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