xref: /xnu-11417.121.6/bsd/netinet6/ip6_input.c (revision a1e26a70f38d1d7daa7b49b258e2f8538ad81650)
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 	_CASSERT(!(offsetof(struct in6_ifstat, f) % sizeof (uint64_t)))
181 
182 #define ICMP6_IFSTAT_REQUIRE_ALIGNED_64(f)      \
183 	_CASSERT(!(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 ip6protosw * pp,struct domain * dp)355 ip6_init(struct ip6protosw *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 	_CASSERT((sizeof(struct ip6_hdr) +
367 	    sizeof(struct icmp6_hdr)) <= _MHLEN);
368 
369 	if (ip6_initialized) {
370 		return;
371 	}
372 	ip6_initialized = 1;
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 
611 	*deliverifp = NULL;
612 
613 	if (m->m_pkthdr.pkt_flags & PKTF_IFAINFO) {
614 		dst_ifscope = m->m_pkthdr.dst_ifindex;
615 	} else {
616 		dst_ifscope = inifp->if_index;
617 	}
618 	/*
619 	 * Check for exact addresses in the hash bucket.
620 	 */
621 	lck_rw_lock_shared(&in6_ifaddr_rwlock);
622 	TAILQ_FOREACH(ia6, IN6ADDR_HASH(&tmp_dst), ia6_hash) {
623 		/*
624 		 * TODO: should we accept loopback
625 		 */
626 		if (in6_are_addr_equal_scoped(&ia6->ia_addr.sin6_addr, &tmp_dst, ia6->ia_ifp->if_index, dst_ifscope)) {
627 			if ((ia6->ia6_flags & IN6_IFF_NOTREADY) != 0) {
628 				continue;
629 			}
630 			best_ia6 = ia6;
631 			if (ia6->ia_ifp == inifp) {
632 				/*
633 				 * TODO: should we also accept locally originated packets
634 				 * or from loopback ???
635 				 */
636 				break;
637 			}
638 			/*
639 			 * Continue the loop in case there's a exact match with another
640 			 * interface
641 			 */
642 		}
643 	}
644 	if (best_ia6 != NULL) {
645 		if (best_ia6->ia_ifp != inifp && ip6_forwarding == 0 &&
646 		    ((ip6_checkinterface == IP6_CHECKINTERFACE_HYBRID_ES &&
647 		    (best_ia6->ia_ifp->if_family == IFNET_FAMILY_IPSEC ||
648 		    best_ia6->ia_ifp->if_family == IFNET_FAMILY_UTUN)) ||
649 		    ip6_checkinterface == IP6_CHECKINTERFACE_STRONG_ES)) {
650 			/*
651 			 * Drop when interface address check is strict and forwarding
652 			 * is disabled
653 			 */
654 			result = IP6_CHECK_IF_DROP;
655 		} else {
656 			result = IP6_CHECK_IF_OURS;
657 			*deliverifp = best_ia6->ia_ifp;
658 			ip6_setdstifaddr_info(m, 0, best_ia6);
659 			ip6_setsrcifaddr_info(m, best_ia6->ia_ifp->if_index, NULL);
660 		}
661 	}
662 	lck_rw_done(&in6_ifaddr_rwlock);
663 
664 	if (result == IP6_CHECK_IF_NONE) {
665 		/*
666 		 * Slow path: route lookup.
667 		 */
668 		struct sockaddr_in6 *__single dst6;
669 
670 		dst6 = SIN6(&rin6->ro_dst);
671 		dst6->sin6_len = sizeof(struct sockaddr_in6);
672 		dst6->sin6_family = AF_INET6;
673 		dst6->sin6_addr = ip6->ip6_dst;
674 		if (!in6_embedded_scope && IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
675 			dst6->sin6_scope_id = dst_ifscope;
676 		}
677 		rtalloc_scoped_ign((struct route *)rin6,
678 		    RTF_PRCLONING, IFSCOPE_NONE);
679 		if (rin6->ro_rt != NULL) {
680 			RT_LOCK_SPIN(rin6->ro_rt);
681 		}
682 
683 #define rt6_key(r) (SIN6(rn_get_key((r)->rt_nodes)))
684 
685 		/*
686 		 * Accept the packet if the forwarding interface to the destination
687 		 * according to the routing table is the loopback interface,
688 		 * unless the associated route has a gateway.
689 		 * Note that this approach causes to accept a packet if there is a
690 		 * route to the loopback interface for the destination of the packet.
691 		 * But we think it's even useful in some situations, e.g. when using
692 		 * a special daemon which wants to intercept the packet.
693 		 *
694 		 * XXX: some OSes automatically make a cloned route for the destination
695 		 * of an outgoing packet.  If the outgoing interface of the packet
696 		 * is a loopback one, the kernel would consider the packet to be
697 		 * accepted, even if we have no such address assinged on the interface.
698 		 * We check the cloned flag of the route entry to reject such cases,
699 		 * assuming that route entries for our own addresses are not made by
700 		 * cloning (it should be true because in6_addloop explicitly installs
701 		 * the host route).  However, we might have to do an explicit check
702 		 * while it would be less efficient.  Or, should we rather install a
703 		 * reject route for such a case?
704 		 */
705 		if (rin6->ro_rt != NULL &&
706 		    (rin6->ro_rt->rt_flags & (RTF_HOST | RTF_GATEWAY)) == RTF_HOST &&
707 #if RTF_WASCLONED
708 		    !(rin6->ro_rt->rt_flags & RTF_WASCLONED) &&
709 #endif
710 		    rin6->ro_rt->rt_ifp->if_type == IFT_LOOP) {
711 			ia6 = ifatoia6(rin6->ro_rt->rt_ifa);
712 			/*
713 			 * Packets to a tentative, duplicated, or somehow invalid
714 			 * address must not be accepted.
715 			 *
716 			 * For performance, test without acquiring the address lock;
717 			 * a lot of things in the address are set once and never
718 			 * changed (e.g. ia_ifp.)
719 			 */
720 			if (!(ia6->ia6_flags & IN6_IFF_NOTREADY)) {
721 				/* this address is ready */
722 				result = IP6_CHECK_IF_OURS;
723 				*deliverifp = ia6->ia_ifp;       /* correct? */
724 				/*
725 				 * record dst address information into mbuf.
726 				 */
727 				(void) ip6_setdstifaddr_info(m, 0, ia6);
728 				(void) ip6_setsrcifaddr_info(m, ia6->ia_ifp->if_index, NULL);
729 			}
730 		}
731 
732 		if (rin6->ro_rt != NULL) {
733 			RT_UNLOCK(rin6->ro_rt);
734 		}
735 	}
736 
737 	if (result == IP6_CHECK_IF_NONE) {
738 		if (ip6_forwarding == 0) {
739 			result = IP6_CHECK_IF_DROP;
740 		} else {
741 			result = IP6_CHECK_IF_FORWARD;
742 			ip6_setdstifaddr_info(m, inifp->if_index, NULL);
743 			ip6_setsrcifaddr_info(m, inifp->if_index, NULL);
744 		}
745 	}
746 
747 	if (result == IP6_CHECK_IF_OURS && *deliverifp != inifp) {
748 		ASSERT(*deliverifp != NULL);
749 		ip6stat.ip6s_rcv_if_weak_match++;
750 
751 		/*  Logging is too noisy when forwarding is enabled */
752 		if (ip6_checkinterface_debug != IP6_CHECKINTERFACE_WEAK_ES && ip6_forwarding != 0) {
753 			char src_str[MAX_IPv6_STR_LEN];
754 			char dst_str[MAX_IPv6_STR_LEN];
755 
756 			inet_ntop(AF_INET6, &ip6->ip6_src, src_str, sizeof(src_str));
757 			inet_ntop(AF_INET6, &ip6->ip6_dst, dst_str, sizeof(dst_str));
758 			os_log_info(OS_LOG_DEFAULT,
759 			    "%s: weak ES interface match to %s for packet from %s to %s proto %u received via %s",
760 			    __func__, (*deliverifp)->if_xname, src_str, dst_str, ip6->ip6_nxt, inifp->if_xname);
761 		}
762 	} else if (result == IP6_CHECK_IF_DROP) {
763 		ip6stat.ip6s_rcv_if_no_match++;
764 		if (ip6_checkinterface_debug > 0) {
765 			char src_str[MAX_IPv6_STR_LEN];
766 			char dst_str[MAX_IPv6_STR_LEN];
767 
768 			inet_ntop(AF_INET6, &ip6->ip6_src, src_str, sizeof(src_str));
769 			inet_ntop(AF_INET6, &ip6->ip6_dst, dst_str, sizeof(dst_str));
770 			os_log(OS_LOG_DEFAULT,
771 			    "%s: no interface match for packet from %s to %s proto %u received via %s",
772 			    __func__, src_str, dst_str, ip6->ip6_nxt, inifp->if_xname);
773 		}
774 	}
775 
776 	return result;
777 }
778 
779 void
ip6_input(struct mbuf * m)780 ip6_input(struct mbuf *m)
781 {
782 	struct ip6_hdr *ip6;
783 	int off = sizeof(struct ip6_hdr), nest;
784 	u_int32_t plen;
785 	u_int32_t rtalert = ~0;
786 	int nxt = 0, ours = 0;
787 	ifnet_ref_t inifp, deliverifp = NULL;
788 	ipfilter_t __single inject_ipfref = NULL;
789 	int seen = 1;
790 #if DUMMYNET
791 	struct m_tag *__single tag;
792 	struct ip_fw_args args = {};
793 #endif /* DUMMYNET */
794 	struct route_in6 rin6 = {};
795 
796 	/*
797 	 * Check if the packet we received is valid after interface filter
798 	 * processing
799 	 */
800 	MBUF_INPUT_CHECK(m, m->m_pkthdr.rcvif);
801 	inifp = m->m_pkthdr.rcvif;
802 	VERIFY(inifp != NULL);
803 
804 	/* Perform IP header alignment fixup, if needed */
805 	IP6_HDR_ALIGNMENT_FIXUP(m, inifp, return );
806 
807 	m->m_pkthdr.pkt_flags &= ~PKTF_FORWARDED;
808 #if IPSEC
809 	/*
810 	 * should the inner packet be considered authentic?
811 	 * see comment in ah4_input().
812 	 */
813 	m->m_flags &= ~M_AUTHIPHDR;
814 	m->m_flags &= ~M_AUTHIPDGM;
815 #endif /* IPSEC */
816 
817 	/*
818 	 * make sure we don't have onion peering information into m_aux.
819 	 */
820 	ip6_delaux(m);
821 
822 #if DUMMYNET
823 	if ((tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID,
824 	    KERNEL_TAG_TYPE_DUMMYNET)) != NULL) {
825 		struct dn_pkt_tag *__single dn_tag;
826 
827 		dn_tag = (struct dn_pkt_tag *)(tag->m_tag_data);
828 
829 		args.fwa_pf_rule = dn_tag->dn_pf_rule;
830 
831 		m_tag_delete(m, tag);
832 	}
833 
834 	if (args.fwa_pf_rule) {
835 		ip6 = mtod(m, struct ip6_hdr *); /* In case PF got disabled */
836 
837 		goto check_with_pf;
838 	}
839 #endif /* DUMMYNET */
840 
841 	/*
842 	 * No need to process packet twice if we've already seen it.
843 	 */
844 	inject_ipfref = ipf_get_inject_filter(m);
845 	if (inject_ipfref != NULL) {
846 		ip6 = mtod(m, struct ip6_hdr *);
847 		nxt = ip6->ip6_nxt;
848 		seen = 0;
849 		goto injectit;
850 	} else {
851 		seen = 1;
852 	}
853 
854 	if (__improbable(m->m_pkthdr.pkt_flags & PKTF_WAKE_PKT)) {
855 		if_ports_used_match_mbuf(inifp, PF_INET6, m);
856 	}
857 
858 	/*
859 	 * mbuf statistics
860 	 */
861 	if (m->m_flags & M_EXT) {
862 		if (m->m_next != NULL) {
863 			ip6stat.ip6s_mext2m++;
864 		} else {
865 			ip6stat.ip6s_mext1++;
866 		}
867 	} else {
868 #define M2MMAX  (sizeof (ip6stat.ip6s_m2m) / sizeof (ip6stat.ip6s_m2m[0]))
869 		if (m->m_next != NULL) {
870 			if (m->m_pkthdr.pkt_flags & PKTF_LOOP) {
871 				/* XXX */
872 				ip6stat.ip6s_m2m[ifnet_index(lo_ifp)]++;
873 			} else if (inifp->if_index < M2MMAX) {
874 				ip6stat.ip6s_m2m[inifp->if_index]++;
875 			} else {
876 				ip6stat.ip6s_m2m[0]++;
877 			}
878 		} else {
879 			ip6stat.ip6s_m1++;
880 		}
881 #undef M2MMAX
882 	}
883 
884 	/*
885 	 * Drop the packet if IPv6 operation is disabled on the interface.
886 	 */
887 	if (inifp->if_eflags & IFEF_IPV6_DISABLED) {
888 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_IF_IPV6_DISABLED, NULL, 0);
889 		goto bad;
890 	}
891 
892 	in6_ifstat_inc_na(inifp, ifs6_in_receive);
893 	ip6stat.ip6s_total++;
894 
895 	/*
896 	 * L2 bridge code and some other code can return mbuf chain
897 	 * that does not conform to KAME requirement.  too bad.
898 	 * XXX: fails to join if interface MTU > MCLBYTES.  jumbogram?
899 	 */
900 	if (m->m_next != NULL && m->m_pkthdr.len < MCLBYTES) {
901 		mbuf_ref_t n;
902 
903 		MGETHDR(n, M_DONTWAIT, MT_HEADER);      /* MAC-OK */
904 		if (n) {
905 			M_COPY_PKTHDR(n, m);
906 		}
907 		if (n && m->m_pkthdr.len > MHLEN) {
908 			MCLGET(n, M_DONTWAIT);
909 			if ((n->m_flags & M_EXT) == 0) {
910 				m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_TOO_SMALL, NULL, 0);
911 				n = NULL;
912 			}
913 		}
914 		if (n == NULL) {
915 			goto bad;
916 		}
917 
918 		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
919 		n->m_len = m->m_pkthdr.len;
920 		m_freem(m);
921 		m = n;
922 	}
923 	IP6_EXTHDR_CHECK(m, 0, sizeof(struct ip6_hdr), { goto done; });
924 
925 	if (m->m_len < sizeof(struct ip6_hdr)) {
926 		if ((m = m_pullup(m, sizeof(struct ip6_hdr))) == 0) {
927 			ip6stat.ip6s_toosmall++;
928 			in6_ifstat_inc(inifp, ifs6_in_hdrerr);
929 			goto done;
930 		}
931 	}
932 
933 	ip6 = mtod(m, struct ip6_hdr *);
934 
935 	if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
936 		ip6stat.ip6s_badvers++;
937 		in6_ifstat_inc(inifp, ifs6_in_hdrerr);
938 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_BAD_VERSION, NULL, 0);
939 		goto bad;
940 	}
941 
942 	ip6stat.ip6s_nxthist[ip6->ip6_nxt]++;
943 
944 	/*
945 	 * Check against address spoofing/corruption.
946 	 */
947 	if (!(m->m_pkthdr.pkt_flags & PKTF_LOOP) &&
948 	    IN6_IS_ADDR_LOOPBACK(&ip6->ip6_src)) {
949 		ip6stat.ip6s_badscope++;
950 		in6_ifstat_inc(inifp, ifs6_in_addrerr);
951 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_SCOPE, NULL, 0);
952 		goto bad;
953 	}
954 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_src) ||
955 	    IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_dst)) {
956 		/*
957 		 * XXX: "badscope" is not very suitable for a multicast source.
958 		 */
959 		ip6stat.ip6s_badscope++;
960 		in6_ifstat_inc(inifp, ifs6_in_addrerr);
961 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_SCOPE, NULL, 0);
962 		goto bad;
963 	}
964 	if (IN6_IS_ADDR_MC_INTFACELOCAL(&ip6->ip6_dst) &&
965 	    !(m->m_pkthdr.pkt_flags & PKTF_LOOP)) {
966 		/*
967 		 * In this case, the packet should come from the loopback
968 		 * interface.  However, we cannot just check the if_flags,
969 		 * because ip6_mloopback() passes the "actual" interface
970 		 * as the outgoing/incoming interface.
971 		 */
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 
978 	/*
979 	 * The following check is not documented in specs.  A malicious
980 	 * party may be able to use IPv4 mapped addr to confuse tcp/udp stack
981 	 * and bypass security checks (act as if it was from 127.0.0.1 by using
982 	 * IPv6 src ::ffff:127.0.0.1).  Be cautious.
983 	 *
984 	 * This check chokes if we are in an SIIT cloud.  As none of BSDs
985 	 * support IPv4-less kernel compilation, we cannot support SIIT
986 	 * environment at all.  So, it makes more sense for us to reject any
987 	 * malicious packets for non-SIIT environment, than try to do a
988 	 * partial support for SIIT environment.
989 	 */
990 	if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
991 	    IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
992 		ip6stat.ip6s_badscope++;
993 		in6_ifstat_inc(inifp, ifs6_in_addrerr);
994 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_SCOPE, NULL, 0);
995 		goto bad;
996 	}
997 
998 	if (((ntohl(ip6->ip6_flow & IPV6_FLOW_ECN_MASK) >> 20) & IPTOS_ECN_ECT1) == IPTOS_ECN_ECT1) {
999 		m->m_pkthdr.pkt_ext_flags |= PKTF_EXT_L4S;
1000 	}
1001 
1002 #if 0
1003 	/*
1004 	 * Reject packets with IPv4 compatible addresses (auto tunnel).
1005 	 *
1006 	 * The code forbids auto tunnel relay case in RFC1933 (the check is
1007 	 * stronger than RFC1933).  We may want to re-enable it if mech-xx
1008 	 * is revised to forbid relaying case.
1009 	 */
1010 	if (IN6_IS_ADDR_V4COMPAT(&ip6->ip6_src) ||
1011 	    IN6_IS_ADDR_V4COMPAT(&ip6->ip6_dst)) {
1012 		ip6stat.ip6s_badscope++;
1013 		in6_ifstat_inc(inifp, ifs6_in_addrerr);
1014 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_SCOPE, NULL, 0);
1015 		goto bad;
1016 	}
1017 #endif
1018 
1019 	/*
1020 	 * Naively assume we can attribute inbound data to the route we would
1021 	 * use to send to this destination. Asymetric routing breaks this
1022 	 * assumption, but it still allows us to account for traffic from
1023 	 * a remote node in the routing table.
1024 	 * this has a very significant performance impact so we bypass
1025 	 * if nstat_collect is disabled. We may also bypass if the
1026 	 * protocol is tcp in the future because tcp will have a route that
1027 	 * we can use to attribute the data to. That does mean we would not
1028 	 * account for forwarded tcp traffic.
1029 	 */
1030 	if (nstat_collect) {
1031 		rtentry_ref_t rte =
1032 		    ifnet_cached_rtlookup_inet6(inifp, &ip6->ip6_src);
1033 		if (rte != NULL) {
1034 			nstat_route_rx(rte, 1, m->m_pkthdr.len, 0);
1035 			rtfree(rte);
1036 		}
1037 	}
1038 
1039 #if DUMMYNET
1040 check_with_pf:
1041 #endif /* DUMMYNET */
1042 #if PF
1043 	/* Invoke inbound packet filter */
1044 	if (PF_IS_ENABLED) {
1045 		int error;
1046 #if DUMMYNET
1047 		error = pf_af_hook(inifp, NULL, &m, AF_INET6, TRUE, &args);
1048 #else /* !DUMMYNET */
1049 		error = pf_af_hook(inifp, NULL, &m, AF_INET6, TRUE, NULL);
1050 #endif /* !DUMMYNET */
1051 		if (error != 0 || m == NULL) {
1052 			if (m != NULL) {
1053 				panic("%s: unexpected packet %p",
1054 				    __func__, m);
1055 				/* NOTREACHED */
1056 			}
1057 			/* Already freed by callee */
1058 			goto done;
1059 		}
1060 		ip6 = mtod(m, struct ip6_hdr *);
1061 	}
1062 #endif /* PF */
1063 
1064 	/* drop packets if interface ID portion is already filled */
1065 	if (!(inifp->if_flags & IFF_LOOPBACK) &&
1066 	    !(m->m_pkthdr.pkt_flags & PKTF_LOOP)) {
1067 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src) &&
1068 		    ip6->ip6_src.s6_addr16[1]) {
1069 			ip6stat.ip6s_badscope++;
1070 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_SCOPE, NULL, 0);
1071 			goto bad;
1072 		}
1073 		if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst) &&
1074 		    ip6->ip6_dst.s6_addr16[1]) {
1075 			ip6stat.ip6s_badscope++;
1076 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_SCOPE, NULL, 0);
1077 			goto bad;
1078 		}
1079 	}
1080 
1081 	if ((m->m_pkthdr.pkt_flags & PKTF_IFAINFO) != 0 && in6_embedded_scope) {
1082 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
1083 			ip6->ip6_src.s6_addr16[1] =
1084 			    htons(m->m_pkthdr.src_ifindex);
1085 		}
1086 		if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
1087 			ip6->ip6_dst.s6_addr16[1] =
1088 			    htons(m->m_pkthdr.dst_ifindex);
1089 		}
1090 	} else if (in6_embedded_scope) {
1091 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
1092 			ip6->ip6_src.s6_addr16[1] = htons(inifp->if_index);
1093 		}
1094 		if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
1095 			ip6->ip6_dst.s6_addr16[1] = htons(inifp->if_index);
1096 		}
1097 	}
1098 
1099 	/*
1100 	 * Multicast check
1101 	 */
1102 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
1103 		struct in6_multi *__single in6m = NULL;
1104 
1105 		in6_ifstat_inc_na(inifp, ifs6_in_mcast);
1106 		/*
1107 		 * See if we belong to the destination multicast group on the
1108 		 * arrival interface.
1109 		 */
1110 		in6_multihead_lock_shared();
1111 		IN6_LOOKUP_MULTI(&ip6->ip6_dst, inifp, in6m);
1112 		in6_multihead_lock_done();
1113 		if (in6m != NULL) {
1114 			IN6M_REMREF(in6m);
1115 			ours = 1;
1116 		} else if (!nd6_prproxy) {
1117 			ip6stat.ip6s_notmember++;
1118 			ip6stat.ip6s_cantforward++;
1119 			in6_ifstat_inc(inifp, ifs6_in_discard);
1120 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_UNKNOWN_MULTICAST_GROUP, NULL, 0);
1121 			goto bad;
1122 		}
1123 		deliverifp = inifp;
1124 		/*
1125 		 * record dst address information into mbuf, if we don't have one yet.
1126 		 * note that we are unable to record it, if the address is not listed
1127 		 * as our interface address (e.g. multicast addresses, etc.)
1128 		 */
1129 		if (deliverifp != NULL) {
1130 			struct in6_ifaddr *__single ia6 = NULL;
1131 
1132 			ia6 = in6_ifawithifp(deliverifp, &ip6->ip6_dst);
1133 			if (ia6 != NULL) {
1134 				(void) ip6_setdstifaddr_info(m, 0, ia6);
1135 				(void) ip6_setsrcifaddr_info(m, ia6->ia_ifp->if_index, NULL);
1136 				ifa_remref(&ia6->ia_ifa);
1137 			} else {
1138 				(void) ip6_setdstifaddr_info(m, inifp->if_index, NULL);
1139 				(void) ip6_setsrcifaddr_info(m, inifp->if_index, NULL);
1140 			}
1141 		}
1142 		goto hbhcheck;
1143 	} else {
1144 		/*
1145 		 * Unicast check
1146 		 */
1147 		ip6_check_if_result_t check_if_result = IP6_CHECK_IF_NONE;
1148 		check_if_result = ip6_input_check_interface(m, ip6, inifp, &rin6, &deliverifp);
1149 		ASSERT(check_if_result != IP6_CHECK_IF_NONE);
1150 		if (check_if_result == IP6_CHECK_IF_OURS) {
1151 			ours = 1;
1152 			goto hbhcheck;
1153 		} else if (check_if_result == IP6_CHECK_IF_DROP) {
1154 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_RCV_IF_NO_MATCH, NULL, 0);
1155 			goto bad;
1156 		}
1157 	}
1158 
1159 	/*
1160 	 * Now there is no reason to process the packet if it's not our own
1161 	 * and we're not a router.
1162 	 */
1163 	if (!ip6_forwarding) {
1164 		ip6stat.ip6s_cantforward++;
1165 		in6_ifstat_inc(inifp, ifs6_in_discard);
1166 		/*
1167 		 * Raise a kernel event if the packet received on cellular
1168 		 * interface is not intended for local host.
1169 		 * For now limit it to ICMPv6 packets.
1170 		 */
1171 		if (inifp->if_type == IFT_CELLULAR &&
1172 		    ip6->ip6_nxt == IPPROTO_ICMPV6) {
1173 			in6_ifstat_inc(inifp, ifs6_cantfoward_icmp6);
1174 		}
1175 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_CANNOT_FORWARD, NULL, 0);
1176 		goto bad;
1177 	}
1178 
1179 hbhcheck:
1180 	/*
1181 	 * Process Hop-by-Hop options header if it's contained.
1182 	 * m may be modified in ip6_hopopts_input().
1183 	 * If a JumboPayload option is included, plen will also be modified.
1184 	 */
1185 	plen = (u_int32_t)ntohs(ip6->ip6_plen);
1186 	if (ip6->ip6_nxt == IPPROTO_HOPOPTS) {
1187 		struct ip6_hbh *__single hbh;
1188 
1189 		/*
1190 		 * Mark the packet to imply that HBH option has been checked.
1191 		 * This can only be true is the packet came in unfragmented
1192 		 * or if the option is in the first fragment
1193 		 */
1194 		m->m_pkthdr.pkt_flags |= PKTF_HBH_CHKED;
1195 		if (ip6_hopopts_input(&plen, &rtalert, &m, &off)) {
1196 #if 0   /* touches NULL pointer */
1197 			in6_ifstat_inc(inifp, ifs6_in_discard);
1198 #endif
1199 			goto done;      /* m have already been freed */
1200 		}
1201 
1202 		/* adjust pointer */
1203 		ip6 = mtod(m, struct ip6_hdr *);
1204 
1205 		/*
1206 		 * if the payload length field is 0 and the next header field
1207 		 * indicates Hop-by-Hop Options header, then a Jumbo Payload
1208 		 * option MUST be included.
1209 		 */
1210 		if (ip6->ip6_plen == 0 && plen == 0) {
1211 			/*
1212 			 * Note that if a valid jumbo payload option is
1213 			 * contained, ip6_hopopts_input() must set a valid
1214 			 * (non-zero) payload length to the variable plen.
1215 			 */
1216 			ip6stat.ip6s_badoptions++;
1217 			in6_ifstat_inc(inifp, ifs6_in_discard);
1218 			in6_ifstat_inc(inifp, ifs6_in_hdrerr);
1219 			icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_HEADER,
1220 			    (int)((caddr_t)&ip6->ip6_plen - (caddr_t)ip6));
1221 			goto done;
1222 		}
1223 		/* ip6_hopopts_input() ensures that mbuf is contiguous */
1224 		hbh = (struct ip6_hbh *)(ip6 + 1);
1225 		nxt = hbh->ip6h_nxt;
1226 
1227 		/*
1228 		 * If we are acting as a router and the packet contains a
1229 		 * router alert option, see if we know the option value.
1230 		 * Currently, we only support the option value for MLD, in which
1231 		 * case we should pass the packet to the multicast routing
1232 		 * daemon.
1233 		 */
1234 		if (rtalert != ~0 && ip6_forwarding) {
1235 			switch (rtalert) {
1236 			case IP6OPT_RTALERT_MLD:
1237 				ours = 1;
1238 				break;
1239 			default:
1240 				/*
1241 				 * RFC2711 requires unrecognized values must be
1242 				 * silently ignored.
1243 				 */
1244 				break;
1245 			}
1246 		}
1247 	} else {
1248 		nxt = ip6->ip6_nxt;
1249 	}
1250 
1251 	/*
1252 	 * Check that the amount of data in the buffers
1253 	 * is as at least much as the IPv6 header would have us expect.
1254 	 * Trim mbufs if longer than we expect.
1255 	 * Drop packet if shorter than we expect.
1256 	 */
1257 	if (m->m_pkthdr.len - sizeof(struct ip6_hdr) < plen) {
1258 		ip6stat.ip6s_tooshort++;
1259 		in6_ifstat_inc(inifp, ifs6_in_truncated);
1260 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_TOO_SHORT, NULL, 0);
1261 		goto bad;
1262 	}
1263 
1264 	if (m->m_pkthdr.len > sizeof(struct ip6_hdr) + plen) {
1265 		ip6_input_adjust(m, ip6, plen, inifp);
1266 	}
1267 
1268 	/*
1269 	 * Forward if desirable.
1270 	 */
1271 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
1272 		if (!ours && nd6_prproxy) {
1273 			/*
1274 			 * If this isn't for us, this might be a Neighbor
1275 			 * Solicitation (dst is solicited-node multicast)
1276 			 * against an address in one of the proxied prefixes;
1277 			 * if so, claim the packet and let icmp6_input()
1278 			 * handle the rest.
1279 			 */
1280 			ours = nd6_prproxy_isours(m, ip6, NULL, IFSCOPE_NONE);
1281 			VERIFY(!ours ||
1282 			    (m->m_pkthdr.pkt_flags & PKTF_PROXY_DST));
1283 		}
1284 		if (!ours) {
1285 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_UNPROXIED_NS, NULL, 0);
1286 			goto bad;
1287 		}
1288 	} else if (!ours) {
1289 		/*
1290 		 * The unicast forwarding function might return the packet
1291 		 * if we are proxying prefix(es), and if the packet is an
1292 		 * ICMPv6 packet that has failed the zone checks, but is
1293 		 * targetted towards a proxied address (this is optimized by
1294 		 * way of RTF_PROXY test.)  If so, claim the packet as ours
1295 		 * and let icmp6_input() handle the rest.  The packet's hop
1296 		 * limit value is kept intact (it's not decremented).  This
1297 		 * is for supporting Neighbor Unreachability Detection between
1298 		 * proxied nodes on different links (src is link-local, dst
1299 		 * is target address.)
1300 		 */
1301 		if ((m = ip6_forward(m, &rin6, 0)) == NULL) {
1302 			goto done;
1303 		}
1304 		VERIFY(rin6.ro_rt != NULL);
1305 		VERIFY(m->m_pkthdr.pkt_flags & PKTF_PROXY_DST);
1306 		deliverifp = rin6.ro_rt->rt_ifp;
1307 		ours = 1;
1308 	}
1309 
1310 	ip6 = mtod(m, struct ip6_hdr *);
1311 
1312 	/*
1313 	 * Malicious party may be able to use IPv4 mapped addr to confuse
1314 	 * tcp/udp stack and bypass security checks (act as if it was from
1315 	 * 127.0.0.1 by using IPv6 src ::ffff:127.0.0.1).  Be cautious.
1316 	 *
1317 	 * For SIIT end node behavior, you may want to disable the check.
1318 	 * However, you will  become vulnerable to attacks using IPv4 mapped
1319 	 * source.
1320 	 */
1321 	if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
1322 	    IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
1323 		ip6stat.ip6s_badscope++;
1324 		in6_ifstat_inc(inifp, ifs6_in_addrerr);
1325 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_SCOPE, NULL, 0);
1326 		goto bad;
1327 	}
1328 
1329 	/*
1330 	 * Tell launch routine the next header
1331 	 */
1332 	ip6stat.ip6s_delivered++;
1333 	in6_ifstat_inc_na(deliverifp, ifs6_in_deliver);
1334 
1335 injectit:
1336 	nest = 0;
1337 
1338 	/*
1339 	 * Perform IP header alignment fixup again, if needed.  Note that
1340 	 * we do it once for the outermost protocol, and we assume each
1341 	 * protocol handler wouldn't mess with the alignment afterwards.
1342 	 */
1343 	IP6_HDR_ALIGNMENT_FIXUP(m, inifp, return );
1344 
1345 	while (nxt != IPPROTO_DONE) {
1346 		struct ipfilter *__single filter;
1347 		int (*pr_input)(struct mbuf **, int *, int);
1348 
1349 		/*
1350 		 * This would imply either IPPROTO_HOPOPTS was not the first
1351 		 * option or it did not come in the first fragment.
1352 		 */
1353 		if (nxt == IPPROTO_HOPOPTS &&
1354 		    (m->m_pkthdr.pkt_flags & PKTF_HBH_CHKED) == 0) {
1355 			/*
1356 			 * This implies that HBH option was not contained
1357 			 * in the first fragment
1358 			 */
1359 			ip6stat.ip6s_badoptions++;
1360 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_OPTION, NULL, 0);
1361 			goto bad;
1362 		}
1363 
1364 		if (ip6_hdrnestlimit && (++nest > ip6_hdrnestlimit)) {
1365 			ip6stat.ip6s_toomanyhdr++;
1366 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_TOO_MANY_OPTIONS, NULL, 0);
1367 			goto bad;
1368 		}
1369 
1370 		/*
1371 		 * protection against faulty packet - there should be
1372 		 * more sanity checks in header chain processing.
1373 		 */
1374 		if (m->m_pkthdr.len < off) {
1375 			ip6stat.ip6s_tooshort++;
1376 			in6_ifstat_inc(inifp, ifs6_in_truncated);
1377 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_TOO_SHORT, NULL, 0);
1378 			goto bad;
1379 		}
1380 
1381 #if IPSEC
1382 		/*
1383 		 * enforce IPsec policy checking if we are seeing last header.
1384 		 * note that we do not visit this with protocols with pcb layer
1385 		 * code - like udp/tcp/raw ip.
1386 		 */
1387 		if ((ipsec_bypass == 0) &&
1388 		    (ip6_protox[nxt]->pr_flags & PR_LASTHDR) != 0) {
1389 			if (ipsec6_in_reject(m, NULL)) {
1390 				IPSEC_STAT_INCREMENT(ipsec6stat.in_polvio);
1391 				m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IPSEC_REJECT, NULL, 0);
1392 				goto bad;
1393 			}
1394 		}
1395 #endif /* IPSEC */
1396 
1397 		/*
1398 		 * Call IP filter
1399 		 */
1400 		if (!TAILQ_EMPTY(&ipv6_filters) && !IFNET_IS_INTCOPROC(inifp)) {
1401 			ipf_ref();
1402 			TAILQ_FOREACH(filter, &ipv6_filters, ipf_link) {
1403 				if (seen == 0) {
1404 					if ((struct ipfilter *)inject_ipfref ==
1405 					    filter) {
1406 						seen = 1;
1407 					}
1408 				} else if (filter->ipf_filter.ipf_input) {
1409 					errno_t result;
1410 
1411 					result = filter->ipf_filter.ipf_input(
1412 						filter->ipf_filter.cookie,
1413 						(mbuf_t *)&m, off, (uint8_t)nxt);
1414 					if (result == EJUSTRETURN) {
1415 						ipf_unref();
1416 						goto done;
1417 					}
1418 					if (result != 0) {
1419 						ipf_unref();
1420 						m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_FILTER_DROP, NULL, 0);
1421 						goto bad;
1422 					}
1423 				}
1424 			}
1425 			ipf_unref();
1426 		}
1427 
1428 		DTRACE_IP6(receive, struct mbuf *, m, struct inpcb *, NULL,
1429 		    struct ip6_hdr *, ip6, struct ifnet *, inifp,
1430 		    struct ip *, NULL, struct ip6_hdr *, ip6);
1431 
1432 		if ((pr_input = ip6_protox[nxt]->pr_input) == NULL) {
1433 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_NO_PROTO, NULL, 0);
1434 			m = NULL;
1435 			nxt = IPPROTO_DONE;
1436 		} else if (!(ip6_protox[nxt]->pr_flags & PR_PROTOLOCK)) {
1437 			lck_mtx_lock(inet6_domain_mutex);
1438 			nxt = pr_input(&m, &off, nxt);
1439 			lck_mtx_unlock(inet6_domain_mutex);
1440 		} else {
1441 			nxt = pr_input(&m, &off, nxt);
1442 		}
1443 	}
1444 done:
1445 	ROUTE_RELEASE(&rin6);
1446 	return;
1447 bad:
1448 	goto done;
1449 }
1450 
1451 void
ip6_setsrcifaddr_info(struct mbuf * m,uint32_t src_idx,struct in6_ifaddr * ia6)1452 ip6_setsrcifaddr_info(struct mbuf *m, uint32_t src_idx, struct in6_ifaddr *ia6)
1453 {
1454 	VERIFY(m->m_flags & M_PKTHDR);
1455 	m->m_pkthdr.pkt_ext_flags &= ~PKTF_EXT_OUTPUT_SCOPE;
1456 	/*
1457 	 * If the source ifaddr is specified, pick up the information
1458 	 * from there; otherwise just grab the passed-in ifindex as the
1459 	 * caller may not have the ifaddr available.
1460 	 */
1461 	if (ia6 != NULL) {
1462 		m->m_pkthdr.pkt_flags |= PKTF_IFAINFO;
1463 		m->m_pkthdr.src_ifindex = ia6->ia_ifp->if_index;
1464 
1465 		/* See IN6_IFF comments in in6_var.h */
1466 		m->m_pkthdr.src_iff = (ia6->ia6_flags & 0xffff);
1467 	} else {
1468 		m->m_pkthdr.src_iff = 0;
1469 		m->m_pkthdr.src_ifindex = (uint16_t)src_idx;
1470 		if (src_idx != 0) {
1471 			m->m_pkthdr.pkt_flags |= PKTF_IFAINFO;
1472 		}
1473 	}
1474 }
1475 
1476 void
ip6_setdstifaddr_info(struct mbuf * m,uint32_t dst_idx,struct in6_ifaddr * ia6)1477 ip6_setdstifaddr_info(struct mbuf *m, uint32_t dst_idx, struct in6_ifaddr *ia6)
1478 {
1479 	VERIFY(m->m_flags & M_PKTHDR);
1480 	m->m_pkthdr.pkt_ext_flags &= ~PKTF_EXT_OUTPUT_SCOPE;
1481 
1482 	/*
1483 	 * If the destination ifaddr is specified, pick up the information
1484 	 * from there; otherwise just grab the passed-in ifindex as the
1485 	 * caller may not have the ifaddr available.
1486 	 */
1487 	if (ia6 != NULL) {
1488 		m->m_pkthdr.pkt_flags |= PKTF_IFAINFO;
1489 		m->m_pkthdr.dst_ifindex = ia6->ia_ifp->if_index;
1490 
1491 		/* See IN6_IFF comments in in6_var.h */
1492 		m->m_pkthdr.dst_iff = (ia6->ia6_flags & 0xffff);
1493 	} else {
1494 		m->m_pkthdr.dst_iff = 0;
1495 		m->m_pkthdr.dst_ifindex = (uint16_t)dst_idx;
1496 		if (dst_idx != 0) {
1497 			m->m_pkthdr.pkt_flags |= PKTF_IFAINFO;
1498 		}
1499 	}
1500 }
1501 
1502 int
ip6_getsrcifaddr_info(struct mbuf * m,uint32_t * src_idx,uint32_t * ia6f)1503 ip6_getsrcifaddr_info(struct mbuf *m, uint32_t *src_idx, uint32_t *ia6f)
1504 {
1505 	VERIFY(m->m_flags & M_PKTHDR);
1506 
1507 	if (!(m->m_pkthdr.pkt_flags & PKTF_IFAINFO)) {
1508 		return -1;
1509 	}
1510 
1511 	if (src_idx != NULL) {
1512 		*src_idx = m->m_pkthdr.src_ifindex;
1513 	}
1514 
1515 	if (ia6f != NULL) {
1516 		*ia6f = m->m_pkthdr.src_iff;
1517 	}
1518 
1519 	return 0;
1520 }
1521 
1522 int
ip6_getdstifaddr_info(struct mbuf * m,uint32_t * dst_idx,uint32_t * ia6f)1523 ip6_getdstifaddr_info(struct mbuf *m, uint32_t *dst_idx, uint32_t *ia6f)
1524 {
1525 	VERIFY(m->m_flags & M_PKTHDR);
1526 
1527 	if (!(m->m_pkthdr.pkt_flags & PKTF_IFAINFO)) {
1528 		return -1;
1529 	}
1530 
1531 	if (dst_idx != NULL) {
1532 		*dst_idx = m->m_pkthdr.dst_ifindex;
1533 	}
1534 
1535 	if (ia6f != NULL) {
1536 		*ia6f = m->m_pkthdr.dst_iff;
1537 	}
1538 
1539 	return 0;
1540 }
1541 
1542 uint32_t
ip6_input_getsrcifscope(struct mbuf * m)1543 ip6_input_getsrcifscope(struct mbuf *m)
1544 {
1545 	VERIFY(m->m_flags & M_PKTHDR);
1546 
1547 	if (m->m_pkthdr.rcvif != NULL) {
1548 		return m->m_pkthdr.rcvif->if_index;
1549 	}
1550 
1551 	uint32_t src_ifscope = IFSCOPE_NONE;
1552 	ip6_getsrcifaddr_info(m, &src_ifscope, NULL);
1553 	return src_ifscope;
1554 }
1555 
1556 uint32_t
ip6_input_getdstifscope(struct mbuf * m)1557 ip6_input_getdstifscope(struct mbuf *m)
1558 {
1559 	VERIFY(m->m_flags & M_PKTHDR);
1560 
1561 	if (m->m_pkthdr.rcvif != NULL) {
1562 		return m->m_pkthdr.rcvif->if_index;
1563 	}
1564 
1565 	uint32_t dst_ifscope = IFSCOPE_NONE;
1566 	ip6_getdstifaddr_info(m, &dst_ifscope, NULL);
1567 	return dst_ifscope;
1568 }
1569 
1570 /*
1571  * Hop-by-Hop options header processing. If a valid jumbo payload option is
1572  * included, the real payload length will be stored in plenp.
1573  */
1574 static int
ip6_hopopts_input(uint32_t * plenp,uint32_t * rtalertp,struct mbuf ** mp,int * offp)1575 ip6_hopopts_input(uint32_t *plenp, uint32_t *rtalertp, struct mbuf **mp,
1576     int *offp)
1577 {
1578 	mbuf_ref_t m = *mp;
1579 	int off = *offp, hbhlen;
1580 	struct ip6_hbh *hbh;
1581 	u_int8_t *opt;
1582 
1583 	/* validation of the length of the header */
1584 	IP6_EXTHDR_CHECK(m, off, sizeof(*hbh), return (-1));
1585 	hbh = (struct ip6_hbh *)(mtod(m, caddr_t) + off);
1586 	hbhlen = (hbh->ip6h_len + 1) << 3;
1587 
1588 	IP6_EXTHDR_CHECK(m, off, hbhlen, return (-1));
1589 	hbh = (struct ip6_hbh *)(mtod(m, caddr_t) + off);
1590 	off += hbhlen;
1591 	hbhlen -= sizeof(struct ip6_hbh);
1592 	opt = (u_int8_t *)hbh + sizeof(struct ip6_hbh);
1593 
1594 	if (ip6_process_hopopts(m, (u_int8_t *)hbh + sizeof(struct ip6_hbh),
1595 	    hbhlen, rtalertp, plenp) < 0) {
1596 		return -1;
1597 	}
1598 
1599 	*offp = off;
1600 	*mp = m;
1601 	return 0;
1602 }
1603 
1604 /*
1605  * Search header for all Hop-by-hop options and process each option.
1606  * This function is separate from ip6_hopopts_input() in order to
1607  * handle a case where the sending node itself process its hop-by-hop
1608  * options header. In such a case, the function is called from ip6_output().
1609  *
1610  * The function assumes that hbh header is located right after the IPv6 header
1611  * (RFC2460 p7), opthead is pointer into data content in m, and opthead to
1612  * opthead + hbhlen is located in continuous memory region.
1613  */
1614 int
ip6_process_hopopts(struct mbuf * m,u_int8_t * __sized_by (inhbhlen)opthead,int inhbhlen,u_int32_t * rtalertp,u_int32_t * plenp)1615 ip6_process_hopopts(struct mbuf *m, u_int8_t *__sized_by(inhbhlen)opthead, int inhbhlen,
1616     u_int32_t *rtalertp, u_int32_t *plenp)
1617 {
1618 	struct ip6_hdr *__single ip6;
1619 	int optlen = 0;
1620 	int hbhlen = inhbhlen;
1621 	u_int8_t *opt = opthead;
1622 	u_int16_t rtalert_val;
1623 	u_int32_t jumboplen;
1624 	const int erroff = sizeof(struct ip6_hdr) + sizeof(struct ip6_hbh);
1625 
1626 	for (; hbhlen > 0; hbhlen -= optlen, opt += optlen) {
1627 		switch (*opt) {
1628 		case IP6OPT_PAD1:
1629 			optlen = 1;
1630 			break;
1631 		case IP6OPT_PADN:
1632 			if (hbhlen < IP6OPT_MINLEN) {
1633 				ip6stat.ip6s_toosmall++;
1634 				m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_TOO_SMALL, NULL, 0);
1635 				goto bad;
1636 			}
1637 			optlen = *(opt + 1) + 2;
1638 			break;
1639 		case IP6OPT_ROUTER_ALERT:
1640 			/* XXX may need check for alignment */
1641 			if (hbhlen < IP6OPT_RTALERT_LEN) {
1642 				ip6stat.ip6s_toosmall++;
1643 				goto bad;
1644 			}
1645 			if (*(opt + 1) != IP6OPT_RTALERT_LEN - 2) {
1646 				/* XXX stat */
1647 				icmp6_error(m, ICMP6_PARAM_PROB,
1648 				    ICMP6_PARAMPROB_HEADER,
1649 				    (int)(erroff + opt + 1 - opthead));
1650 				return -1;
1651 			}
1652 			optlen = IP6OPT_RTALERT_LEN;
1653 			bcopy((caddr_t)(opt + 2), (caddr_t)&rtalert_val, 2);
1654 			*rtalertp = ntohs(rtalert_val);
1655 			break;
1656 		case IP6OPT_JUMBO:
1657 			/* XXX may need check for alignment */
1658 			if (hbhlen < IP6OPT_JUMBO_LEN) {
1659 				ip6stat.ip6s_toosmall++;
1660 				m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_TOO_SMALL, NULL, 0);
1661 				goto bad;
1662 			}
1663 			if (*(opt + 1) != IP6OPT_JUMBO_LEN - 2) {
1664 				/* XXX stat */
1665 				icmp6_error(m, ICMP6_PARAM_PROB,
1666 				    ICMP6_PARAMPROB_HEADER,
1667 				    (int)(erroff + opt + 1 - opthead));
1668 				return -1;
1669 			}
1670 			optlen = IP6OPT_JUMBO_LEN;
1671 
1672 			/*
1673 			 * IPv6 packets that have non 0 payload length
1674 			 * must not contain a jumbo payload option.
1675 			 */
1676 			ip6 = mtod(m, struct ip6_hdr *);
1677 			if (ip6->ip6_plen) {
1678 				ip6stat.ip6s_badoptions++;
1679 				icmp6_error(m, ICMP6_PARAM_PROB,
1680 				    ICMP6_PARAMPROB_HEADER,
1681 				    (int)(erroff + opt - opthead));
1682 				return -1;
1683 			}
1684 
1685 			/*
1686 			 * We may see jumbolen in unaligned location, so
1687 			 * we'd need to perform bcopy().
1688 			 */
1689 			bcopy(opt + 2, &jumboplen, sizeof(jumboplen));
1690 			jumboplen = (u_int32_t)htonl(jumboplen);
1691 
1692 #if 1
1693 			/*
1694 			 * if there are multiple jumbo payload options,
1695 			 * *plenp will be non-zero and the packet will be
1696 			 * rejected.
1697 			 * the behavior may need some debate in ipngwg -
1698 			 * multiple options does not make sense, however,
1699 			 * there's no explicit mention in specification.
1700 			 */
1701 			if (*plenp != 0) {
1702 				ip6stat.ip6s_badoptions++;
1703 				icmp6_error(m, ICMP6_PARAM_PROB,
1704 				    ICMP6_PARAMPROB_HEADER,
1705 				    (int)(erroff + opt + 2 - opthead));
1706 				return -1;
1707 			}
1708 #endif
1709 
1710 			/*
1711 			 * jumbo payload length must be larger than 65535.
1712 			 */
1713 			if (jumboplen <= IPV6_MAXPACKET) {
1714 				ip6stat.ip6s_badoptions++;
1715 				icmp6_error(m, ICMP6_PARAM_PROB,
1716 				    ICMP6_PARAMPROB_HEADER,
1717 				    (int)(erroff + opt + 2 - opthead));
1718 				return -1;
1719 			}
1720 			*plenp = jumboplen;
1721 
1722 			break;
1723 		default:                /* unknown option */
1724 			if (hbhlen < IP6OPT_MINLEN) {
1725 				ip6stat.ip6s_toosmall++;
1726 				m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_TOO_SMALL, NULL, 0);
1727 				goto bad;
1728 			}
1729 			optlen = ip6_unknown_opt(opt, hbhlen, m,
1730 			    erroff + opt - opthead);
1731 			if (optlen == -1) {
1732 				return -1;
1733 			}
1734 			optlen += 2;
1735 			break;
1736 		}
1737 	}
1738 
1739 	return 0;
1740 
1741 bad:
1742 	return -1;
1743 }
1744 
1745 /*
1746  * Unknown option processing.
1747  * The fourth argument `off' is the offset from the IPv6 header to the option,
1748  * which is necessary if the IPv6 header the and option header and IPv6 header
1749  * is not continuous in order to return an ICMPv6 error.
1750  */
1751 int
ip6_unknown_opt(uint8_t * __counted_by (optplen)optp,size_t optplen,struct mbuf * m,size_t off)1752 ip6_unknown_opt(uint8_t *__counted_by(optplen) optp, size_t optplen, struct mbuf *m, size_t off)
1753 {
1754 #pragma unused(optplen)
1755 
1756 	struct ip6_hdr *__single ip6;
1757 
1758 	switch (IP6OPT_TYPE(*optp)) {
1759 	case IP6OPT_TYPE_SKIP: /* ignore the option */
1760 		return (int)*(optp + 1);
1761 
1762 	case IP6OPT_TYPE_DISCARD:       /* silently discard */
1763 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_OPT_DISCARD, NULL, 0);
1764 		return -1;
1765 
1766 	case IP6OPT_TYPE_FORCEICMP: /* send ICMP even if multicasted */
1767 		ip6stat.ip6s_badoptions++;
1768 		icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_OPTION, (int)off);
1769 		return -1;
1770 
1771 	case IP6OPT_TYPE_ICMP: /* send ICMP if not multicasted */
1772 		ip6stat.ip6s_badoptions++;
1773 		ip6 = mtod(m, struct ip6_hdr *);
1774 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1775 		    (m->m_flags & (M_BCAST | M_MCAST))) {
1776 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_OPTION, NULL, 0);
1777 		} else {
1778 			icmp6_error(m, ICMP6_PARAM_PROB,
1779 			    ICMP6_PARAMPROB_OPTION, (int)off);
1780 		}
1781 		return -1;
1782 	}
1783 
1784 	m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_UNSPECIFIED, NULL, 0); /* XXX: NOTREACHED */
1785 	return -1;
1786 }
1787 
1788 /*
1789  * Create the "control" list for this pcb.
1790  * These functions will not modify mbuf chain at all.
1791  *
1792  * With KAME mbuf chain restriction:
1793  * The routine will be called from upper layer handlers like tcp6_input().
1794  * Thus the routine assumes that the caller (tcp6_input) have already
1795  * called IP6_EXTHDR_CHECK() and all the extension headers are located in the
1796  * very first mbuf on the mbuf chain.
1797  *
1798  * ip6_savecontrol_v4 will handle those options that are possible to be
1799  * set on a v4-mapped socket.
1800  * ip6_savecontrol will directly call ip6_savecontrol_v4 to handle those
1801  * options and handle the v6-only ones itself.
1802  */
1803 struct mbuf **
ip6_savecontrol_v4(struct inpcb * inp,struct mbuf * m,struct mbuf ** mp,int * v4only)1804 ip6_savecontrol_v4(struct inpcb *inp, struct mbuf *m, struct mbuf **mp,
1805     int *v4only)
1806 {
1807 	struct ip6_hdr *__single ip6 = mtod(m, struct ip6_hdr *);
1808 
1809 	if ((inp->inp_socket->so_options & SO_TIMESTAMP) != 0) {
1810 		struct timeval tv;
1811 
1812 		getmicrotime(&tv);
1813 		mp = sbcreatecontrol_mbuf((caddr_t)&tv, sizeof(tv),
1814 		    SCM_TIMESTAMP, SOL_SOCKET, mp);
1815 		if (*mp == NULL) {
1816 			return NULL;
1817 		}
1818 	}
1819 	if ((inp->inp_socket->so_options & SO_TIMESTAMP_MONOTONIC) != 0) {
1820 		uint64_t time;
1821 
1822 		time = mach_absolute_time();
1823 		mp = sbcreatecontrol_mbuf((caddr_t)&time, sizeof(time),
1824 		    SCM_TIMESTAMP_MONOTONIC, SOL_SOCKET, mp);
1825 		if (*mp == NULL) {
1826 			return NULL;
1827 		}
1828 	}
1829 	if ((inp->inp_socket->so_options & SO_TIMESTAMP_CONTINUOUS) != 0) {
1830 		uint64_t time;
1831 
1832 		time = mach_continuous_time();
1833 		mp = sbcreatecontrol_mbuf((caddr_t)&time, sizeof(time),
1834 		    SCM_TIMESTAMP_CONTINUOUS, SOL_SOCKET, mp);
1835 		if (*mp == NULL) {
1836 			return NULL;
1837 		}
1838 	}
1839 	if ((inp->inp_socket->so_flags & SOF_RECV_TRAFFIC_CLASS) != 0) {
1840 		int tc = m_get_traffic_class(m);
1841 
1842 		mp = sbcreatecontrol_mbuf((caddr_t)&tc, sizeof(tc),
1843 		    SO_TRAFFIC_CLASS, SOL_SOCKET, mp);
1844 		if (*mp == NULL) {
1845 			return NULL;
1846 		}
1847 	}
1848 
1849 	if ((inp->inp_socket->so_flags & SOF_RECV_WAKE_PKT) &&
1850 	    (m->m_pkthdr.pkt_flags & PKTF_WAKE_PKT)) {
1851 		int flag = 1;
1852 
1853 		mp = sbcreatecontrol_mbuf((caddr_t)&flag, sizeof(flag),
1854 		    SO_RECV_WAKE_PKT, SOL_SOCKET, mp);
1855 		if (*mp == NULL) {
1856 			return NULL;
1857 		}
1858 	}
1859 
1860 #define IS2292(inp, x, y)       (((inp)->inp_flags & IN6P_RFC2292) ? (x) : (y))
1861 	if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
1862 		if (v4only != NULL) {
1863 			*v4only = 1;
1864 		}
1865 
1866 		// Send ECN flags for v4-mapped addresses
1867 		if ((inp->inp_flags & IN6P_TCLASS) != 0) {
1868 			struct ip *__single ip_header = mtod(m, struct ip *);
1869 
1870 			int tclass = (int)(ip_header->ip_tos);
1871 			mp = sbcreatecontrol_mbuf((caddr_t)&tclass, sizeof(tclass),
1872 			    IPV6_TCLASS, IPPROTO_IPV6, mp);
1873 			if (*mp == NULL) {
1874 				return NULL;
1875 			}
1876 		}
1877 
1878 		// Send IN6P_PKTINFO for v4-mapped address
1879 		if ((inp->inp_flags & IN6P_PKTINFO) != 0 || SOFLOW_ENABLED(inp->inp_socket)) {
1880 			struct in6_pktinfo pi6 = {
1881 				.ipi6_addr = IN6ADDR_V4MAPPED_INIT,
1882 				.ipi6_ifindex = (m && m->m_pkthdr.rcvif) ? m->m_pkthdr.rcvif->if_index : 0,
1883 			};
1884 
1885 			struct ip *__single ip_header = mtod(m, struct ip *);
1886 			bcopy(&ip_header->ip_dst, &pi6.ipi6_addr.s6_addr32[3], sizeof(struct in_addr));
1887 
1888 			mp = sbcreatecontrol_mbuf((caddr_t)&pi6,
1889 			    sizeof(struct in6_pktinfo),
1890 			    IS2292(inp, IPV6_2292PKTINFO, IPV6_PKTINFO),
1891 			    IPPROTO_IPV6, mp);
1892 			if (*mp == NULL) {
1893 				return NULL;
1894 			}
1895 		}
1896 		return mp;
1897 	}
1898 
1899 	/* RFC 2292 sec. 5 */
1900 	if ((inp->inp_flags & IN6P_PKTINFO) != 0 || SOFLOW_ENABLED(inp->inp_socket)) {
1901 		struct in6_pktinfo pi6;
1902 
1903 		bcopy(&ip6->ip6_dst, &pi6.ipi6_addr, sizeof(struct in6_addr));
1904 		in6_clearscope(&pi6.ipi6_addr); /* XXX */
1905 		pi6.ipi6_ifindex =
1906 		    (m && m->m_pkthdr.rcvif) ? m->m_pkthdr.rcvif->if_index : 0;
1907 
1908 		mp = sbcreatecontrol_mbuf((caddr_t)&pi6,
1909 		    sizeof(struct in6_pktinfo),
1910 		    IS2292(inp, IPV6_2292PKTINFO, IPV6_PKTINFO),
1911 		    IPPROTO_IPV6, mp);
1912 		if (*mp == NULL) {
1913 			return NULL;
1914 		}
1915 	}
1916 
1917 	if ((inp->inp_flags & IN6P_HOPLIMIT) != 0) {
1918 		int hlim = ip6->ip6_hlim & 0xff;
1919 
1920 		mp = sbcreatecontrol_mbuf((caddr_t)&hlim, sizeof(int),
1921 		    IS2292(inp, IPV6_2292HOPLIMIT, IPV6_HOPLIMIT),
1922 		    IPPROTO_IPV6, mp);
1923 		if (*mp == NULL) {
1924 			return NULL;
1925 		}
1926 	}
1927 
1928 	if (v4only != NULL) {
1929 		*v4only = 0;
1930 	}
1931 	return mp;
1932 }
1933 
1934 int
ip6_savecontrol(struct inpcb * in6p,struct mbuf * m,struct mbuf ** mp)1935 ip6_savecontrol(struct inpcb *in6p, struct mbuf *m, struct mbuf **mp)
1936 {
1937 	struct mbuf **np;
1938 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1939 	int v4only = 0;
1940 
1941 	*mp = NULL;
1942 	np = ip6_savecontrol_v4(in6p, m, mp, &v4only);
1943 	if (np == NULL) {
1944 		goto no_mbufs;
1945 	}
1946 
1947 	mp = np;
1948 	if (v4only) {
1949 		return 0;
1950 	}
1951 
1952 	if ((in6p->inp_flags & IN6P_TCLASS) != 0) {
1953 		u_int32_t flowinfo;
1954 		int tclass;
1955 
1956 		flowinfo = (u_int32_t)ntohl(ip6->ip6_flow & IPV6_FLOWINFO_MASK);
1957 		flowinfo >>= 20;
1958 
1959 		tclass = flowinfo & 0xff;
1960 		mp = sbcreatecontrol_mbuf((caddr_t)&tclass, sizeof(tclass),
1961 		    IPV6_TCLASS, IPPROTO_IPV6, mp);
1962 		if (*mp == NULL) {
1963 			goto no_mbufs;
1964 		}
1965 	}
1966 
1967 	/*
1968 	 * IPV6_HOPOPTS socket option.  Recall that we required super-user
1969 	 * privilege for the option (see ip6_ctloutput), but it might be too
1970 	 * strict, since there might be some hop-by-hop options which can be
1971 	 * returned to normal user.
1972 	 * See also RFC 2292 section 6 (or RFC 3542 section 8).
1973 	 */
1974 	if ((in6p->inp_flags & IN6P_HOPOPTS) != 0) {
1975 		/*
1976 		 * Check if a hop-by-hop options header is contatined in the
1977 		 * received packet, and if so, store the options as ancillary
1978 		 * data. Note that a hop-by-hop options header must be
1979 		 * just after the IPv6 header, which is assured through the
1980 		 * IPv6 input processing.
1981 		 */
1982 		ip6 = mtod(m, struct ip6_hdr *);
1983 		if (ip6->ip6_nxt == IPPROTO_HOPOPTS) {
1984 			struct ip6_hbh *hbh;
1985 			int hbhlen = 0;
1986 			hbh = (struct ip6_hbh *)(ip6 + 1);
1987 			hbhlen = (hbh->ip6h_len + 1) << 3;
1988 
1989 			/*
1990 			 * XXX: We copy the whole header even if a
1991 			 * jumbo payload option is included, the option which
1992 			 * is to be removed before returning according to
1993 			 * RFC2292.
1994 			 * Note: this constraint is removed in RFC3542
1995 			 */
1996 			mp = sbcreatecontrol_mbuf((caddr_t)hbh, hbhlen,
1997 			    IS2292(in6p, IPV6_2292HOPOPTS, IPV6_HOPOPTS),
1998 			    IPPROTO_IPV6, mp);
1999 
2000 			if (*mp == NULL) {
2001 				goto no_mbufs;
2002 			}
2003 		}
2004 	}
2005 
2006 	if ((in6p->inp_flags & (IN6P_RTHDR | IN6P_DSTOPTS)) != 0) {
2007 		int nxt = ip6->ip6_nxt, off = sizeof(struct ip6_hdr);
2008 
2009 		/*
2010 		 * Search for destination options headers or routing
2011 		 * header(s) through the header chain, and stores each
2012 		 * header as ancillary data.
2013 		 * Note that the order of the headers remains in
2014 		 * the chain of ancillary data.
2015 		 */
2016 		while (1) {     /* is explicit loop prevention necessary? */
2017 			struct ip6_ext *ip6e = NULL;
2018 			int elen;
2019 
2020 			/*
2021 			 * if it is not an extension header, don't try to
2022 			 * pull it from the chain.
2023 			 */
2024 			switch (nxt) {
2025 			case IPPROTO_DSTOPTS:
2026 			case IPPROTO_ROUTING:
2027 			case IPPROTO_HOPOPTS:
2028 			case IPPROTO_AH: /* is it possible? */
2029 				break;
2030 			default:
2031 				goto loopend;
2032 			}
2033 
2034 			if (off + sizeof(*ip6e) > m->m_len) {
2035 				goto loopend;
2036 			}
2037 			ip6e = (struct ip6_ext *)(mtod(m, caddr_t) + off);
2038 			if (nxt == IPPROTO_AH) {
2039 				elen = (ip6e->ip6e_len + 2) << 2;
2040 			} else {
2041 				elen = (ip6e->ip6e_len + 1) << 3;
2042 			}
2043 			if (off + elen > m->m_len) {
2044 				goto loopend;
2045 			}
2046 
2047 			switch (nxt) {
2048 			case IPPROTO_DSTOPTS:
2049 				if (!(in6p->inp_flags & IN6P_DSTOPTS)) {
2050 					break;
2051 				}
2052 
2053 				mp = sbcreatecontrol_mbuf((caddr_t)ip6e, elen,
2054 				    IS2292(in6p, IPV6_2292DSTOPTS,
2055 				    IPV6_DSTOPTS), IPPROTO_IPV6, mp);
2056 				if (*mp == NULL) {
2057 					goto no_mbufs;
2058 				}
2059 				break;
2060 			case IPPROTO_ROUTING:
2061 				if (!(in6p->inp_flags & IN6P_RTHDR)) {
2062 					break;
2063 				}
2064 
2065 				mp = sbcreatecontrol_mbuf((caddr_t)ip6e, elen,
2066 				    IS2292(in6p, IPV6_2292RTHDR, IPV6_RTHDR),
2067 				    IPPROTO_IPV6, mp);
2068 				if (*mp == NULL) {
2069 					goto no_mbufs;
2070 				}
2071 				break;
2072 			case IPPROTO_HOPOPTS:
2073 			case IPPROTO_AH: /* is it possible? */
2074 				break;
2075 
2076 			default:
2077 				/*
2078 				 * other cases have been filtered in the above.
2079 				 * none will visit this case.  here we supply
2080 				 * the code just in case (nxt overwritten or
2081 				 * other cases).
2082 				 */
2083 				goto loopend;
2084 			}
2085 
2086 			/* proceed with the next header. */
2087 			off += elen;
2088 			nxt = ip6e->ip6e_nxt;
2089 			ip6e = NULL;
2090 		}
2091 loopend:
2092 		;
2093 	}
2094 	return 0;
2095 no_mbufs:
2096 	ip6stat.ip6s_pktdropcntrl++;
2097 	/* XXX increment a stat to show the failure */
2098 	return ENOBUFS;
2099 }
2100 #undef IS2292
2101 
2102 void
ip6_notify_pmtu(struct inpcb * in6p,struct sockaddr_in6 * dst,u_int32_t * mtu)2103 ip6_notify_pmtu(struct inpcb *in6p, struct sockaddr_in6 *dst, u_int32_t *mtu)
2104 {
2105 	struct socket *__single so;
2106 	mbuf_ref_t m_mtu;
2107 	struct ip6_mtuinfo mtuctl;
2108 
2109 	so =  in6p->inp_socket;
2110 
2111 	if ((in6p->inp_flags & IN6P_MTU) == 0) {
2112 		return;
2113 	}
2114 
2115 	if (mtu == NULL) {
2116 		return;
2117 	}
2118 
2119 	if (IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_faddr) && SOCK_CHECK_PROTO(so, IPPROTO_TCP)) {
2120 		return;
2121 	}
2122 
2123 	if (!IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_faddr) &&
2124 	    !in6_are_addr_equal_scoped(&in6p->in6p_faddr, &dst->sin6_addr, in6p->inp_fifscope, dst->sin6_scope_id)) {
2125 		return;
2126 	}
2127 
2128 	bzero(&mtuctl, sizeof(mtuctl));         /* zero-clear for safety */
2129 	mtuctl.ip6m_mtu = *mtu;
2130 	mtuctl.ip6m_addr = *dst;
2131 	if (!in6_embedded_scope) {
2132 		mtuctl.ip6m_addr.sin6_scope_id = dst->sin6_scope_id;
2133 	}
2134 	if (sa6_recoverscope(&mtuctl.ip6m_addr, TRUE)) {
2135 		return;
2136 	}
2137 
2138 	if ((m_mtu = sbcreatecontrol((caddr_t)&mtuctl, sizeof(mtuctl),
2139 	    IPV6_PATHMTU, IPPROTO_IPV6)) == NULL) {
2140 		return;
2141 	}
2142 
2143 	if (sbappendaddr(&so->so_rcv, SA(dst), NULL, m_mtu, NULL) == 0) {
2144 		return;
2145 	}
2146 	sorwakeup(so);
2147 }
2148 
2149 /*
2150  * Get pointer to the previous header followed by the header
2151  * currently processed.
2152  * XXX: This function supposes that
2153  *	M includes all headers,
2154  *	the next header field and the header length field of each header
2155  *	are valid, and
2156  *	the sum of each header length equals to OFF.
2157  * Because of these assumptions, this function must be called very
2158  * carefully. Moreover, it will not be used in the near future when
2159  * we develop `neater' mechanism to process extension headers.
2160  */
2161 char *
ip6_get_prevhdr(struct mbuf * m,int off)2162 ip6_get_prevhdr(struct mbuf *m, int off)
2163 {
2164 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
2165 
2166 	if (off == sizeof(struct ip6_hdr)) {
2167 		return (char *)&ip6->ip6_nxt;
2168 	} else {
2169 		int len, nxt;
2170 		struct ip6_ext *ip6e = NULL;
2171 
2172 		nxt = ip6->ip6_nxt;
2173 		len = sizeof(struct ip6_hdr);
2174 		while (len < off) {
2175 			ip6e = (struct ip6_ext *)(mtod(m, caddr_t) + len);
2176 
2177 			switch (nxt) {
2178 			case IPPROTO_FRAGMENT:
2179 				len += sizeof(struct ip6_frag);
2180 				break;
2181 			case IPPROTO_AH:
2182 				len += (ip6e->ip6e_len + 2) << 2;
2183 				break;
2184 			default:
2185 				len += (ip6e->ip6e_len + 1) << 3;
2186 				break;
2187 			}
2188 			nxt = ip6e->ip6e_nxt;
2189 		}
2190 		if (ip6e) {
2191 			return (char *)&ip6e->ip6e_nxt;
2192 		} else {
2193 			return NULL;
2194 		}
2195 	}
2196 }
2197 
2198 /*
2199  * get next header offset.  m will be retained.
2200  */
2201 int
ip6_nexthdr(struct mbuf * m,int off,int proto,int * nxtp)2202 ip6_nexthdr(struct mbuf *m, int off, int proto, int *nxtp)
2203 {
2204 	struct ip6_hdr ip6;
2205 	struct ip6_ext ip6e;
2206 	struct ip6_frag fh;
2207 
2208 	/* just in case */
2209 	VERIFY(m != NULL);
2210 	if ((m->m_flags & M_PKTHDR) == 0 || m->m_pkthdr.len < off) {
2211 		return -1;
2212 	}
2213 
2214 	switch (proto) {
2215 	case IPPROTO_IPV6:
2216 		if (m->m_pkthdr.len < off + sizeof(ip6)) {
2217 			return -1;
2218 		}
2219 		m_copydata(m, off, sizeof(ip6), (caddr_t)&ip6);
2220 		if (nxtp) {
2221 			*nxtp = ip6.ip6_nxt;
2222 		}
2223 		off += sizeof(ip6);
2224 		return off;
2225 
2226 	case IPPROTO_FRAGMENT:
2227 		/*
2228 		 * terminate parsing if it is not the first fragment,
2229 		 * it does not make sense to parse through it.
2230 		 */
2231 		if (m->m_pkthdr.len < off + sizeof(fh)) {
2232 			return -1;
2233 		}
2234 		m_copydata(m, off, sizeof(fh), (caddr_t)&fh);
2235 		/* IP6F_OFF_MASK = 0xfff8(BigEndian), 0xf8ff(LittleEndian) */
2236 		if (fh.ip6f_offlg & IP6F_OFF_MASK) {
2237 			return -1;
2238 		}
2239 		if (nxtp) {
2240 			*nxtp = fh.ip6f_nxt;
2241 		}
2242 		off += sizeof(struct ip6_frag);
2243 		return off;
2244 
2245 	case IPPROTO_AH:
2246 		if (m->m_pkthdr.len < off + sizeof(ip6e)) {
2247 			return -1;
2248 		}
2249 		m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
2250 		if (nxtp) {
2251 			*nxtp = ip6e.ip6e_nxt;
2252 		}
2253 		off += (ip6e.ip6e_len + 2) << 2;
2254 		return off;
2255 
2256 	case IPPROTO_HOPOPTS:
2257 	case IPPROTO_ROUTING:
2258 	case IPPROTO_DSTOPTS:
2259 		if (m->m_pkthdr.len < off + sizeof(ip6e)) {
2260 			return -1;
2261 		}
2262 		m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
2263 		if (nxtp) {
2264 			*nxtp = ip6e.ip6e_nxt;
2265 		}
2266 		off += (ip6e.ip6e_len + 1) << 3;
2267 		return off;
2268 
2269 	case IPPROTO_NONE:
2270 	case IPPROTO_ESP:
2271 	case IPPROTO_IPCOMP:
2272 		/* give up */
2273 		return -1;
2274 
2275 	default:
2276 		return -1;
2277 	}
2278 }
2279 
2280 /*
2281  * get offset for the last header in the chain.  m will be kept untainted.
2282  */
2283 int
ip6_lasthdr(struct mbuf * m,int off,int proto,int * nxtp)2284 ip6_lasthdr(struct mbuf *m, int off, int proto, int *nxtp)
2285 {
2286 	int newoff;
2287 	int nxt;
2288 
2289 	if (!nxtp) {
2290 		nxt = -1;
2291 		nxtp = &nxt;
2292 	}
2293 	while (1) {
2294 		newoff = ip6_nexthdr(m, off, proto, nxtp);
2295 		if (newoff < 0) {
2296 			return off;
2297 		} else if (newoff < off) {
2298 			return -1;    /* invalid */
2299 		} else if (newoff == off) {
2300 			return newoff;
2301 		}
2302 
2303 		off = newoff;
2304 		proto = *nxtp;
2305 	}
2306 }
2307 
2308 boolean_t
ip6_pkt_has_ulp(struct mbuf * m)2309 ip6_pkt_has_ulp(struct mbuf *m)
2310 {
2311 	int off = 0, nxt = IPPROTO_NONE;
2312 
2313 	off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
2314 	if (off < 0 || m->m_pkthdr.len < off) {
2315 		return FALSE;
2316 	}
2317 
2318 	switch (nxt) {
2319 	case IPPROTO_TCP:
2320 		if (off + sizeof(struct tcphdr) > m->m_pkthdr.len) {
2321 			return FALSE;
2322 		}
2323 		break;
2324 	case IPPROTO_UDP:
2325 		if (off + sizeof(struct udphdr) > m->m_pkthdr.len) {
2326 			return FALSE;
2327 		}
2328 		break;
2329 	case IPPROTO_ICMPV6:
2330 		if (off + sizeof(uint32_t) > m->m_pkthdr.len) {
2331 			return FALSE;
2332 		}
2333 		break;
2334 	case IPPROTO_NONE:
2335 		return TRUE;
2336 	case IPPROTO_ESP:
2337 		return TRUE;
2338 	case IPPROTO_IPCOMP:
2339 		return TRUE;
2340 	default:
2341 		return FALSE;
2342 	}
2343 	return TRUE;
2344 }
2345 
2346 struct ip6aux *
ip6_addaux(struct mbuf * m)2347 ip6_addaux(struct mbuf *m)
2348 {
2349 	struct m_tag *__single tag;
2350 
2351 	/* Check if one is already allocated */
2352 	tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID,
2353 	    KERNEL_TAG_TYPE_INET6);
2354 	if (tag == NULL) {
2355 		/* Allocate a tag */
2356 		tag = m_tag_create(KERNEL_MODULE_TAG_ID, KERNEL_TAG_TYPE_INET6,
2357 		    sizeof(struct ip6aux), M_DONTWAIT, m);
2358 
2359 		/* Attach it to the mbuf */
2360 		if (tag) {
2361 			m_tag_prepend(m, tag);
2362 		}
2363 	}
2364 
2365 	return tag ? (struct ip6aux *)(tag->m_tag_data) : NULL;
2366 }
2367 
2368 struct ip6aux *
ip6_findaux(struct mbuf * m)2369 ip6_findaux(struct mbuf *m)
2370 {
2371 	struct m_tag *__single tag;
2372 
2373 	tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID,
2374 	    KERNEL_TAG_TYPE_INET6);
2375 
2376 	return tag != NULL ? (struct ip6aux *)(tag->m_tag_data) : NULL;
2377 }
2378 
2379 void
ip6_delaux(struct mbuf * m)2380 ip6_delaux(struct mbuf *m)
2381 {
2382 	struct m_tag *__single tag;
2383 
2384 	tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID,
2385 	    KERNEL_TAG_TYPE_INET6);
2386 	if (tag != NULL) {
2387 		m_tag_delete(m, tag);
2388 	}
2389 }
2390 
2391 struct inet6_tag_container {
2392 	struct m_tag    inet6_m_tag;
2393 	struct ip6aux   inet6_ip6a;
2394 };
2395 
2396 struct m_tag *
m_tag_kalloc_inet6(u_int32_t id,u_int16_t type,uint16_t len,int wait)2397 m_tag_kalloc_inet6(u_int32_t id, u_int16_t type, uint16_t len, int wait)
2398 {
2399 	struct inet6_tag_container *tag_container;
2400 	struct m_tag *tag = NULL;
2401 
2402 	assert3u(id, ==, KERNEL_MODULE_TAG_ID);
2403 	assert3u(type, ==, KERNEL_TAG_TYPE_INET6);
2404 	assert3u(len, ==, sizeof(struct ip6aux));
2405 
2406 	if (len != sizeof(struct ip6aux)) {
2407 		return NULL;
2408 	}
2409 
2410 	tag_container = kalloc_type(struct inet6_tag_container, wait | M_ZERO);
2411 	if (tag_container != NULL) {
2412 		tag =  &tag_container->inet6_m_tag;
2413 
2414 		assert3p(tag, ==, tag_container);
2415 
2416 		M_TAG_INIT(tag, id, type, len, &tag_container->inet6_ip6a, NULL);
2417 	}
2418 
2419 	return tag;
2420 }
2421 
2422 void
m_tag_kfree_inet6(struct m_tag * tag)2423 m_tag_kfree_inet6(struct m_tag *tag)
2424 {
2425 	struct inet6_tag_container *__single tag_container = (struct inet6_tag_container *)tag;
2426 
2427 	assert3u(tag->m_tag_len, ==, sizeof(struct ip6aux));
2428 
2429 	kfree_type(struct inet6_tag_container, tag_container);
2430 }
2431 
2432 void
ip6_register_m_tag(void)2433 ip6_register_m_tag(void)
2434 {
2435 	int error;
2436 
2437 	error = m_register_internal_tag_type(KERNEL_TAG_TYPE_INET6, sizeof(struct ip6aux),
2438 	    m_tag_kalloc_inet6, m_tag_kfree_inet6);
2439 
2440 	assert3u(error, ==, 0);
2441 }
2442 
2443 /*
2444  * Drain callback
2445  */
2446 void
ip6_drain(void)2447 ip6_drain(void)
2448 {
2449 	frag6_drain();          /* fragments */
2450 	in6_rtqdrain();         /* protocol cloned routes */
2451 	nd6_drain(NULL);        /* cloned routes: ND6 */
2452 }
2453 
2454 /*
2455  * System control for IP6
2456  */
2457 
2458 u_char  inet6ctlerrmap[PRC_NCMDS] = {
2459 	0, 0, 0, 0,
2460 	0, EMSGSIZE, EHOSTDOWN, EHOSTUNREACH,
2461 	EHOSTUNREACH, EHOSTUNREACH, ECONNREFUSED, ECONNREFUSED,
2462 	EMSGSIZE, EHOSTUNREACH, 0, 0,
2463 	0, 0, 0, 0,
2464 	ENOPROTOOPT, ECONNREFUSED
2465 };
2466 
2467 static int
2468 sysctl_reset_ip6_input_stats SYSCTL_HANDLER_ARGS
2469 {
2470 #pragma unused(arg1, arg2)
2471 	int error, i;
2472 
2473 	i = ip6_input_measure;
2474 	error = sysctl_handle_int(oidp, &i, 0, req);
2475 	if (error || req->newptr == USER_ADDR_NULL) {
2476 		goto done;
2477 	}
2478 	/* impose bounds */
2479 	if (i < 0 || i > 1) {
2480 		error = EINVAL;
2481 		goto done;
2482 	}
2483 	if (ip6_input_measure != i && i == 1) {
2484 		net_perf_initialize(&net_perf, ip6_input_measure_bins);
2485 	}
2486 	ip6_input_measure = i;
2487 done:
2488 	return error;
2489 }
2490 
2491 static int
2492 sysctl_ip6_input_measure_bins SYSCTL_HANDLER_ARGS
2493 {
2494 #pragma unused(arg1, arg2)
2495 	int error;
2496 	uint64_t i;
2497 
2498 	i = ip6_input_measure_bins;
2499 	error = sysctl_handle_quad(oidp, &i, 0, req);
2500 	if (error || req->newptr == USER_ADDR_NULL) {
2501 		goto done;
2502 	}
2503 	/* validate data */
2504 	if (!net_perf_validate_bins(i)) {
2505 		error = EINVAL;
2506 		goto done;
2507 	}
2508 	ip6_input_measure_bins = i;
2509 done:
2510 	return error;
2511 }
2512 
2513 static int
2514 sysctl_ip6_input_getperf SYSCTL_HANDLER_ARGS
2515 {
2516 #pragma unused(oidp, arg1, arg2)
2517 	if (req->oldptr == USER_ADDR_NULL) {
2518 		req->oldlen = (size_t)sizeof(struct net_perf);
2519 	}
2520 
2521 	return SYSCTL_OUT(req, &net_perf, MIN(sizeof(net_perf), req->oldlen));
2522 }
2523 
2524 
2525 /*
2526  * Initialize IPv6 source address hash table.
2527  */
2528 static void
in6_ifaddrhashtbl_init(void)2529 in6_ifaddrhashtbl_init(void)
2530 {
2531 	int i, k, p;
2532 	uint32_t nhash = 0;
2533 	uint32_t hash_size;
2534 
2535 	if (in6_ifaddrhashtbl != NULL) {
2536 		return;
2537 	}
2538 
2539 	PE_parse_boot_argn("ina6ddr_nhash", &nhash,
2540 	    sizeof(in6addr_nhash));
2541 	if (nhash == 0) {
2542 		nhash = IN6ADDR_NHASH;
2543 	}
2544 
2545 	hash_size = nhash * sizeof(*in6_ifaddrhashtbl);
2546 
2547 	in6_ifaddrhashtbl = zalloc_permanent(
2548 		hash_size,
2549 		ZALIGN_PTR);
2550 	in6addr_nhash = nhash;
2551 
2552 	/*
2553 	 * Generate the next largest prime greater than in6addr_nhash.
2554 	 */
2555 	k = (in6addr_nhash % 2 == 0) ? in6addr_nhash + 1 : in6addr_nhash + 2;
2556 	for (;;) {
2557 		p = 1;
2558 		for (i = 3; i * i <= k; i += 2) {
2559 			if (k % i == 0) {
2560 				p = 0;
2561 			}
2562 		}
2563 		if (p == 1) {
2564 			break;
2565 		}
2566 		k += 2;
2567 	}
2568 	in6addr_hashp = k;
2569 }
2570 
2571 static int
2572 sysctl_ip6_checkinterface SYSCTL_HANDLER_ARGS
2573 {
2574 #pragma unused(arg1, arg2)
2575 	int error, i;
2576 
2577 	i = ip6_checkinterface;
2578 	error = sysctl_handle_int(oidp, &i, 0, req);
2579 	if (error || req->newptr == USER_ADDR_NULL) {
2580 		return error;
2581 	}
2582 
2583 	switch (i) {
2584 	case IP6_CHECKINTERFACE_WEAK_ES:
2585 	case IP6_CHECKINTERFACE_HYBRID_ES:
2586 	case IP6_CHECKINTERFACE_STRONG_ES:
2587 		if (ip6_checkinterface != i) {
2588 			ip6_checkinterface = i;
2589 			os_log(OS_LOG_DEFAULT, "%s: ip6_checkinterface is now %d\n",
2590 			    __func__, ip6_checkinterface);
2591 		}
2592 		break;
2593 	default:
2594 		error = EINVAL;
2595 		break;
2596 	}
2597 	return error;
2598 }
2599