xref: /xnu-12377.81.4/bsd/netinet6/udp6_usrreq.c (revision 043036a2b3718f7f0be807e2870f8f47d3fa0796)
1 /*
2  * Copyright (c) 2000-2024 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 
29 /*	$FreeBSD: src/sys/netinet6/udp6_usrreq.c,v 1.6.2.6 2001/07/29 19:32:40 ume Exp $	*/
30 /*	$KAME: udp6_usrreq.c,v 1.27 2001/05/21 05:45:10 jinmei Exp $	*/
31 
32 /*
33  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
34  * All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
39  * 1. Redistributions of source code must retain the above copyright
40  *    notice, this list of conditions and the following disclaimer.
41  * 2. Redistributions in binary form must reproduce the above copyright
42  *    notice, this list of conditions and the following disclaimer in the
43  *    documentation and/or other materials provided with the distribution.
44  * 3. Neither the name of the project nor the names of its contributors
45  *    may be used to endorse or promote products derived from this software
46  *    without specific prior written permission.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58  * SUCH DAMAGE.
59  */
60 
61 /*
62  * Copyright (c) 1982, 1986, 1989, 1993
63  *	The Regents of the University of California.  All rights reserved.
64  *
65  * Redistribution and use in source and binary forms, with or without
66  * modification, are permitted provided that the following conditions
67  * are met:
68  * 1. Redistributions of source code must retain the above copyright
69  *    notice, this list of conditions and the following disclaimer.
70  * 2. Redistributions in binary form must reproduce the above copyright
71  *    notice, this list of conditions and the following disclaimer in the
72  *    documentation and/or other materials provided with the distribution.
73  * 3. All advertising materials mentioning features or use of this software
74  *    must display the following acknowledgement:
75  *	This product includes software developed by the University of
76  *	California, Berkeley and its contributors.
77  * 4. Neither the name of the University nor the names of its contributors
78  *    may be used to endorse or promote products derived from this software
79  *    without specific prior written permission.
80  *
81  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
82  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
83  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
84  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
85  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
86  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
87  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
88  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
89  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
90  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
91  * SUCH DAMAGE.
92  *
93  *	@(#)udp_var.h	8.1 (Berkeley) 6/10/93
94  */
95 #include <sys/kernel.h>
96 #include <sys/malloc.h>
97 #include <sys/mbuf.h>
98 #include <sys/param.h>
99 #include <sys/protosw.h>
100 #include <sys/socket.h>
101 #include <sys/socketvar.h>
102 #include <sys/sysctl.h>
103 #include <sys/errno.h>
104 #include <sys/stat.h>
105 #include <sys/systm.h>
106 #include <sys/syslog.h>
107 #include <sys/proc.h>
108 #include <sys/kauth.h>
109 
110 #include <net/if.h>
111 #include <net/route.h>
112 #include <net/if_types.h>
113 #include <net/ntstat.h>
114 #include <net/dlil.h>
115 #include <net/net_api_stats.h>
116 #include <net/droptap.h>
117 
118 #include <netinet/in.h>
119 #include <netinet/in_systm.h>
120 #include <netinet/ip.h>
121 #include <netinet/in_pcb.h>
122 #include <netinet/in_var.h>
123 #include <netinet/ip_var.h>
124 #include <netinet/udp.h>
125 #include <netinet/udp_var.h>
126 #include <netinet/udp_log.h>
127 
128 #include <netinet/ip6.h>
129 #include <netinet6/ip6_var.h>
130 #include <netinet6/in6_pcb.h>
131 #include <netinet/icmp6.h>
132 #include <netinet6/udp6_var.h>
133 #include <netinet6/ip6protosw.h>
134 
135 #if IPSEC
136 #include <netinet6/ipsec.h>
137 #include <netinet6/ipsec6.h>
138 #include <netinet6/esp6.h>
139 #include <netkey/key.h>
140 extern int ipsec_bypass;
141 extern int esp_udp_encap_port;
142 #endif /* IPSEC */
143 
144 #if NECP
145 #include <net/necp.h>
146 #endif /* NECP */
147 
148 #if FLOW_DIVERT
149 #include <netinet/flow_divert.h>
150 #endif /* FLOW_DIVERT */
151 
152 #if CONTENT_FILTER
153 #include <net/content_filter.h>
154 #endif /* CONTENT_FILTER */
155 
156 #if SKYWALK
157 #include <skywalk/core/skywalk_var.h>
158 #endif /* SKYWALK */
159 
160 #include <net/sockaddr_utils.h>
161 
162 /*
163  * UDP protocol inplementation.
164  * Per RFC 768, August, 1980.
165  */
166 
167 static int udp6_abort(struct socket *);
168 static int udp6_attach(struct socket *, int, struct proc *);
169 static int udp6_bind(struct socket *, struct sockaddr *, struct proc *);
170 static int udp6_connectx(struct socket *, struct sockaddr *,
171     struct sockaddr *, struct proc *, uint32_t, sae_associd_t,
172     sae_connid_t *, uint32_t, void *, uint32_t, struct uio *, user_ssize_t *);
173 static  int udp6_detach(struct socket *);
174 static int udp6_disconnect(struct socket *);
175 static int udp6_disconnectx(struct socket *, sae_associd_t, sae_connid_t);
176 static int udp6_send(struct socket *, int, struct mbuf *, struct sockaddr *,
177     struct mbuf *, struct proc *);
178 static void udp6_append(struct inpcb *, struct ip6_hdr *,
179     struct sockaddr_in6 *, struct mbuf *, int, struct ifnet *);
180 static int udp6_input_checksum(struct mbuf *, struct udphdr *, int, int);
181 static int udp6_defunct(struct socket *);
182 
183 struct pr_usrreqs udp6_usrreqs = {
184 	.pru_abort =            udp6_abort,
185 	.pru_attach =           udp6_attach,
186 	.pru_bind =             udp6_bind,
187 	.pru_connect =          udp6_connect,
188 	.pru_connectx =         udp6_connectx,
189 	.pru_control =          in6_control,
190 	.pru_detach =           udp6_detach,
191 	.pru_disconnect =       udp6_disconnect,
192 	.pru_disconnectx =      udp6_disconnectx,
193 	.pru_peeraddr =         in6_mapped_peeraddr,
194 	.pru_send =             udp6_send,
195 	.pru_shutdown =         udp_shutdown,
196 	.pru_sockaddr =         in6_mapped_sockaddr,
197 	.pru_sosend =           sosend,
198 	.pru_soreceive =        soreceive,
199 	.pru_defunct =          udp6_defunct,
200 };
201 
202 /*
203  * subroutine of udp6_input(), mainly for source code readability.
204  */
205 static void
udp6_append(struct inpcb * last,struct ip6_hdr * ip6,struct sockaddr_in6 * udp_in6,struct mbuf * n,int off,struct ifnet * ifp)206 udp6_append(struct inpcb *last, struct ip6_hdr *ip6,
207     struct sockaddr_in6 *udp_in6, struct mbuf *n, int off, struct ifnet *ifp)
208 {
209 #pragma unused(ip6)
210 	struct mbuf *__single opts = NULL;
211 	int ret = 0;
212 
213 	if ((last->in6p_flags & INP_CONTROLOPTS) != 0 ||
214 	    SOFLOW_ENABLED(last->in6p_socket) ||
215 	    SO_RECV_CONTROL_OPTS(last->in6p_socket)) {
216 		ret = ip6_savecontrol(last, n, &opts);
217 		if (ret != 0) {
218 			UDP_LOG(last, "ip_savecontrol error %d", ret);
219 			m_freem(n);
220 			m_freem(opts);
221 			return;
222 		}
223 	}
224 	m_adj(n, off);
225 	if (nstat_collect) {
226 		stats_functional_type ifnet_count_type = IFNET_COUNT_TYPE(ifp);
227 		INP_ADD_RXSTAT(last, ifnet_count_type, 1, n->m_pkthdr.len);
228 	}
229 	so_recv_data_stat(last->in6p_socket, n, 0);
230 	if (sbappendaddr(&last->in6p_socket->so_rcv,
231 	    SA(udp_in6), n, opts, NULL) == 0) {
232 		UDP_LOG(last, "sbappendaddr full receive socket buffer");
233 		udpstat.udps_fullsock++;
234 	} else {
235 		sorwakeup(last->in6p_socket);
236 	}
237 }
238 
239 int
udp6_input(struct mbuf ** mp,int * offp,int proto)240 udp6_input(struct mbuf **mp, int *offp, int proto)
241 {
242 #pragma unused(proto)
243 	struct mbuf *m = *mp;
244 	struct ifnet *__single ifp;
245 	struct ip6_hdr *ip6;
246 	struct udphdr *uh;
247 	struct inpcb *__single in6p;
248 	struct  mbuf *__single opts = NULL;
249 	int off = *offp;
250 	int plen, ulen, ret = 0;
251 	stats_functional_type ifnet_count_type = stats_functional_type_unclassified;
252 	struct sockaddr_in6 udp_in6;
253 	struct inpcbinfo *__single pcbinfo = &udbinfo;
254 	struct sockaddr_in6 fromsa;
255 	u_int16_t pf_tag = 0;
256 	boolean_t is_wake_pkt = false;
257 	drop_reason_t drop_reason = DROP_REASON_UNSPECIFIED;
258 
259 	IP6_EXTHDR_CHECK(m, off, sizeof(struct udphdr), return IPPROTO_DONE);
260 
261 	/* Expect 32-bit aligned data pointer on strict-align platforms */
262 	MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
263 
264 	ifp = m->m_pkthdr.rcvif;
265 	ip6 = mtod(m, struct ip6_hdr *);
266 
267 	if (m->m_flags & M_PKTHDR) {
268 		pf_tag = m_pftag(m)->pftag_tag;
269 		if (m->m_pkthdr.pkt_flags & PKTF_WAKE_PKT) {
270 			is_wake_pkt = true;
271 		}
272 	}
273 
274 	udpstat.udps_ipackets++;
275 
276 	plen = ntohs(ip6->ip6_plen) - off + sizeof(*ip6);
277 	uh = (struct udphdr *)(void *)((caddr_t)ip6 + off);
278 	ulen = ntohs((u_short)uh->uh_ulen);
279 
280 	if (plen != ulen) {
281 		udpstat.udps_badlen++;
282 		IF_UDP_STATINC(ifp, badlength);
283 		drop_reason = DROP_REASON_IP_BAD_LENGTH;
284 		goto bad;
285 	}
286 
287 	/* destination port of 0 is illegal, based on RFC768. */
288 	if (uh->uh_dport == 0) {
289 		IF_UDP_STATINC(ifp, port0);
290 		drop_reason = DROP_REASON_IP6_ILLEGAL_PORT;
291 		goto bad;
292 	}
293 
294 	/*
295 	 * Checksum extended UDP header and data.
296 	 */
297 	if (udp6_input_checksum(m, uh, off, ulen)) {
298 		drop_reason = DROP_REASON_IP6_BAD_UDP_CHECKSUM;
299 		goto bad;
300 	}
301 
302 	/*
303 	 * Construct sockaddr format source address.
304 	 */
305 	init_sin6(&fromsa, m);
306 	fromsa.sin6_port = uh->uh_sport;
307 
308 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
309 		int reuse_sock = 0, mcast_delivered = 0;
310 		struct ip6_moptions *imo;
311 
312 		/*
313 		 * Deliver a multicast datagram to all sockets
314 		 * for which the local and remote addresses and ports match
315 		 * those of the incoming datagram.  This allows more than
316 		 * one process to receive multicasts on the same port.
317 		 * (This really ought to be done for unicast datagrams as
318 		 * well, but that would cause problems with existing
319 		 * applications that open both address-specific sockets and
320 		 * a wildcard socket listening to the same port -- they would
321 		 * end up receiving duplicates of every unicast datagram.
322 		 * Those applications open the multiple sockets to overcome an
323 		 * inadequacy of the UDP socket interface, but for backwards
324 		 * compatibility we avoid the problem here rather than
325 		 * fixing the interface.  Maybe 4.5BSD will remedy this?)
326 		 */
327 
328 		/*
329 		 * In a case that laddr should be set to the link-local
330 		 * address (this happens in RIPng), the multicast address
331 		 * specified in the received packet does not match with
332 		 * laddr. To cure this situation, the matching is relaxed
333 		 * if the receiving interface is the same as one specified
334 		 * in the socket and if the destination multicast address
335 		 * matches one of the multicast groups specified in the socket.
336 		 */
337 
338 		/*
339 		 * Construct sockaddr format source address.
340 		 */
341 		init_sin6(&udp_in6, m); /* general init */
342 		udp_in6.sin6_port = uh->uh_sport;
343 		/*
344 		 * KAME note: usually we drop udphdr from mbuf here.
345 		 * We need udphdr for IPsec processing so we do that later.
346 		 */
347 
348 		/*
349 		 * Locate pcb(s) for datagram.
350 		 * (Algorithm copied from raw_intr().)
351 		 */
352 		lck_rw_lock_shared(&pcbinfo->ipi_lock);
353 
354 		LIST_FOREACH(in6p, &udb, inp_list) {
355 #if IPSEC
356 			int skipit;
357 #endif /* IPSEC */
358 
359 			if ((in6p->inp_vflag & INP_IPV6) == 0) {
360 				continue;
361 			}
362 
363 			if (inp_restricted_recv(in6p, ifp)) {
364 				continue;
365 			}
366 			/*
367 			 * Skip unbound sockets before taking the lock on the socket as
368 			 * the test with the destination port in the header will fail
369 			 */
370 			if (in6p->in6p_lport == 0) {
371 				continue;
372 			}
373 
374 			if (in_pcb_checkstate(in6p, WNT_ACQUIRE, 0) ==
375 			    WNT_STOPUSING) {
376 				continue;
377 			}
378 
379 			udp_lock(in6p->in6p_socket, 1, 0);
380 
381 			if (in_pcb_checkstate(in6p, WNT_RELEASE, 1) ==
382 			    WNT_STOPUSING) {
383 				udp_unlock(in6p->in6p_socket, 1, 0);
384 				continue;
385 			}
386 			if (in6p->in6p_lport != uh->uh_dport) {
387 				udp_unlock(in6p->in6p_socket, 1, 0);
388 				continue;
389 			}
390 
391 			/*
392 			 * Handle socket delivery policy for any-source
393 			 * and source-specific multicast. [RFC3678]
394 			 */
395 			imo = in6p->in6p_moptions;
396 			if (imo && IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
397 				struct sockaddr_in6 mcaddr;
398 				int blocked;
399 
400 				IM6O_LOCK(imo);
401 				SOCKADDR_ZERO(&mcaddr, sizeof(struct sockaddr_in6));
402 				mcaddr.sin6_len = sizeof(struct sockaddr_in6);
403 				mcaddr.sin6_family = AF_INET6;
404 				mcaddr.sin6_addr = ip6->ip6_dst;
405 
406 				blocked = im6o_mc_filter(imo, ifp,
407 				    &mcaddr, &fromsa);
408 				IM6O_UNLOCK(imo);
409 				if (blocked != MCAST_PASS) {
410 					udp_unlock(in6p->in6p_socket, 1, 0);
411 					if (blocked == MCAST_NOTSMEMBER ||
412 					    blocked == MCAST_MUTED) {
413 						udpstat.udps_filtermcast++;
414 					}
415 					continue;
416 				}
417 			}
418 			if (!IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_faddr) &&
419 			    (!in6_are_addr_equal_scoped(&in6p->in6p_faddr,
420 			    &ip6->ip6_src, in6p->inp_fifscope, ifp->if_index) ||
421 			    in6p->in6p_fport != uh->uh_sport)) {
422 				udp_unlock(in6p->in6p_socket, 1, 0);
423 				continue;
424 			}
425 
426 			reuse_sock = in6p->inp_socket->so_options &
427 			    (SO_REUSEPORT | SO_REUSEADDR);
428 
429 #if NECP
430 			skipit = 0;
431 			if (!necp_socket_is_allowed_to_send_recv_v6(in6p,
432 			    uh->uh_dport, uh->uh_sport, &ip6->ip6_dst,
433 			    &ip6->ip6_src, ifp, pf_tag, NULL, NULL, NULL, NULL)) {
434 				/* do not inject data to pcb */
435 				skipit = 1;
436 				UDP_LOG_DROP_NECP(ip6, uh, in6p, false);
437 			}
438 			if (skipit == 0)
439 #endif /* NECP */
440 			{
441 				struct mbuf *__single n = NULL;
442 				/*
443 				 * KAME NOTE: do not
444 				 * m_copy(m, offset, ...) below.
445 				 * sbappendaddr() expects M_PKTHDR,
446 				 * and m_copy() will copy M_PKTHDR
447 				 * only if offset is 0.
448 				 */
449 				if (reuse_sock) {
450 					n = m_copy(m, 0, M_COPYALL);
451 				}
452 				udp6_append(in6p, ip6, &udp_in6, m,
453 				    off + sizeof(struct udphdr), ifp);
454 				mcast_delivered++;
455 				m = n;
456 			}
457 			if (is_wake_pkt) {
458 				soevent(in6p->in6p_socket,
459 				    SO_FILT_HINT_LOCKED | SO_FILT_HINT_WAKE_PKT);
460 			}
461 			udp_unlock(in6p->in6p_socket, 1, 0);
462 
463 			/*
464 			 * Don't look for additional matches if this one does
465 			 * not have either the SO_REUSEPORT or SO_REUSEADDR
466 			 * socket options set.  This heuristic avoids searching
467 			 * through all pcbs in the common case of a non-shared
468 			 * port.  It assumes that an application will never
469 			 * clear these options after setting them.
470 			 */
471 			if (reuse_sock == 0 || m == NULL) {
472 				break;
473 			}
474 
475 			/*
476 			 * Expect 32-bit aligned data pointer on strict-align
477 			 * platforms.
478 			 */
479 			MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
480 
481 			/*
482 			 * Recompute IP and UDP header pointers for new mbuf
483 			 */
484 			ip6 = mtod(m, struct ip6_hdr *);
485 			uh = (struct udphdr *)(void *)((caddr_t)ip6 + off);
486 		}
487 		lck_rw_done(&pcbinfo->ipi_lock);
488 
489 		if (mcast_delivered == 0) {
490 			/*
491 			 * No matching pcb found; discard datagram.
492 			 * (No need to send an ICMP Port Unreachable
493 			 * for a broadcast or multicast datgram.)
494 			 */
495 			udpstat.udps_noport++;
496 			udpstat.udps_noportmcast++;
497 			IF_UDP_STATINC(ifp, port_unreach);
498 			drop_reason = DROP_REASON_UDP_PORT_UNREACHEABLE;
499 			goto bad;
500 		}
501 
502 		/* free the extra copy of mbuf or skipped by NECP */
503 		if (m != NULL) {
504 			m_freem(m);
505 		}
506 		return IPPROTO_DONE;
507 	}
508 
509 #if IPSEC
510 	/*
511 	 * UDP to port 4500 with a payload where the first four bytes are
512 	 * not zero is a UDP encapsulated IPsec packet. Packets where
513 	 * the payload is one byte and that byte is 0xFF are NAT keepalive
514 	 * packets. Decapsulate the ESP packet and carry on with IPsec input
515 	 * or discard the NAT keep-alive.
516 	 */
517 	if (ipsec_bypass == 0 && (esp_udp_encap_port & 0xFFFF) != 0 &&
518 	    (uh->uh_dport == ntohs((u_short)esp_udp_encap_port) ||
519 	    uh->uh_sport == ntohs((u_short)esp_udp_encap_port))) {
520 		union sockaddr_in_4_6 src = {};
521 		union sockaddr_in_4_6 dst = {};
522 
523 		ipsec_fill_ip6_sockaddr_4_6_with_ifscope(&src, &ip6->ip6_src,
524 		    uh->uh_sport, ip6_input_getsrcifscope(m));
525 		ipsec_fill_ip6_sockaddr_4_6_with_ifscope(&dst, &ip6->ip6_dst,
526 		    uh->uh_dport, ip6_input_getdstifscope(m));
527 
528 		/*
529 		 * Check if ESP or keepalive:
530 		 *      1. If the destination port of the incoming packet is 4500.
531 		 *      2. If the source port of the incoming packet is 4500,
532 		 *         then check the SADB to match IP address and port.
533 		 */
534 		bool check_esp = true;
535 		if (uh->uh_dport != ntohs((u_short)esp_udp_encap_port)) {
536 			check_esp = key_checksa_present(&dst, &src);
537 		}
538 
539 		if (check_esp) {
540 			int payload_len = ulen - sizeof(struct udphdr) > 4 ? 4 :
541 			    ulen - sizeof(struct udphdr);
542 
543 			if (m->m_len < off + sizeof(struct udphdr) + payload_len) {
544 				if ((m = m_pullup(m, off + sizeof(struct udphdr) +
545 				    payload_len)) == NULL) {
546 					udpstat.udps_hdrops++;
547 					drop_reason = DROP_REASON_UDP_PACKET_SHORTER_THAN_HEADER;
548 					goto bad;
549 				}
550 				/*
551 				 * Expect 32-bit aligned data pointer on strict-align
552 				 * platforms.
553 				 */
554 				MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
555 
556 				ip6 = mtod(m, struct ip6_hdr *);
557 				uh = (struct udphdr *)(void *)((caddr_t)ip6 + off);
558 			}
559 			/* Check for NAT keepalive packet */
560 			if (payload_len == 1 && *(u_int8_t*)
561 			    ((caddr_t)uh + sizeof(struct udphdr)) == 0xFF) {
562 				drop_reason = DROP_REASON_UDP_PACKET_SHORTER_THAN_HEADER;
563 				goto bad;
564 			} else if (payload_len == 4 && *(u_int32_t*)(void *)
565 			    ((caddr_t)uh + sizeof(struct udphdr)) != 0) {
566 				/* UDP encapsulated IPsec packet to pass through NAT */
567 				/* preserve the udp header */
568 				*offp = off + sizeof(struct udphdr);
569 				return esp6_input(mp, offp, IPPROTO_UDP);
570 			}
571 		}
572 	}
573 #endif /* IPSEC */
574 
575 	/*
576 	 * Locate pcb for datagram.
577 	 */
578 	in6p = in6_pcblookup_hash(&udbinfo, &ip6->ip6_src, uh->uh_sport, ip6_input_getsrcifscope(m),
579 	    &ip6->ip6_dst, uh->uh_dport, ip6_input_getdstifscope(m), 1, m->m_pkthdr.rcvif);
580 	if (in6p == NULL) {
581 		IF_UDP_STATINC(ifp, port_unreach);
582 
583 		if (udp_log_in_vain) {
584 			char buf[INET6_ADDRSTRLEN];
585 
586 			strlcpy(buf, ip6_sprintf(&ip6->ip6_dst), sizeof(buf));
587 			if (udp_log_in_vain < 3) {
588 				log(LOG_INFO, "Connection attempt to UDP "
589 				    "%s:%d from %s:%d\n", buf,
590 				    ntohs(uh->uh_dport),
591 				    ip6_sprintf(&ip6->ip6_src),
592 				    ntohs(uh->uh_sport));
593 			} else if (!(m->m_flags & (M_BCAST | M_MCAST)) &&
594 			    !in6_are_addr_equal_scoped(&ip6->ip6_dst, &ip6->ip6_src, ip6_input_getdstifscope(m), ip6_input_getsrcifscope(m))) {
595 				log(LOG_INFO, "Connection attempt "
596 				    "to UDP %s:%d from %s:%d\n", buf,
597 				    ntohs(uh->uh_dport),
598 				    ip6_sprintf(&ip6->ip6_src),
599 				    ntohs(uh->uh_sport));
600 			}
601 		}
602 		udpstat.udps_noport++;
603 		if (m->m_flags & M_MCAST) {
604 			printf("UDP6: M_MCAST is set in a unicast packet.\n");
605 			udpstat.udps_noportmcast++;
606 			IF_UDP_STATINC(ifp, badmcast);
607 			drop_reason = DROP_REASON_IP_MULTICAST_NO_PORT;
608 			goto bad;
609 		}
610 
611 		if (udp6_port_unreach_rlc_compress(&ip6->ip6_src, uh->uh_sport,
612 		    &ip6->ip6_dst, uh->uh_dport) == true) {
613 			drop_reason = DROP_REASON_UDP_PORT_UNREACHEABLE;
614 			goto bad;
615 		}
616 		if (if_link_heuristics_enabled(ifp)) {
617 			drop_reason = DROP_REASON_UDP_PORT_UNREACHEABLE;
618 			IF_UDP_STATINC(ifp, linkheur_stealthdrop);
619 			goto bad;
620 		}
621 		icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_NOPORT, 0);
622 		return IPPROTO_DONE;
623 	}
624 
625 	/*
626 	 * Construct sockaddr format source address.
627 	 * Stuff source address and datagram in user buffer.
628 	 */
629 	udp_lock(in6p->in6p_socket, 1, 0);
630 
631 #if NECP
632 	if (!necp_socket_is_allowed_to_send_recv_v6(in6p, uh->uh_dport,
633 	    uh->uh_sport, &ip6->ip6_dst, &ip6->ip6_src, ifp, pf_tag, NULL, NULL, NULL, NULL)) {
634 		in_pcb_checkstate(in6p, WNT_RELEASE, 1);
635 		UDP_LOG_DROP_NECP(ip6, uh, in6p, false);
636 		udp_unlock(in6p->in6p_socket, 1, 0);
637 		IF_UDP_STATINC(ifp, badipsec);
638 		drop_reason = DROP_REASON_IP_NECP_POLICY_DROP;
639 		goto bad;
640 	}
641 #endif /* NECP */
642 
643 	if (in_pcb_checkstate(in6p, WNT_RELEASE, 1) == WNT_STOPUSING) {
644 		udp_unlock(in6p->in6p_socket, 1, 0);
645 		IF_UDP_STATINC(ifp, cleanup);
646 		drop_reason = DROP_REASON_UDP_PCB_GARBAGE_COLLECTED;
647 		goto bad;
648 	}
649 
650 	init_sin6(&udp_in6, m); /* general init */
651 	udp_in6.sin6_port = uh->uh_sport;
652 	if ((in6p->in6p_flags & INP_CONTROLOPTS) != 0 ||
653 	    SOFLOW_ENABLED(in6p->in6p_socket) ||
654 	    SO_RECV_CONTROL_OPTS(in6p->in6p_socket)) {
655 		ret = ip6_savecontrol(in6p, m, &opts);
656 		if (ret != 0) {
657 			UDP_LOG(in6p, "ip_savecontrol error %d", ret);
658 			udp_unlock(in6p->in6p_socket, 1, 0);
659 			drop_reason = DROP_REASON_IP_ENOBUFS;
660 			goto bad;
661 		}
662 	}
663 	m_adj(m, off + sizeof(struct udphdr));
664 	if (nstat_collect) {
665 		ifnet_count_type = IFNET_COUNT_TYPE(ifp);
666 		INP_ADD_RXSTAT(in6p, ifnet_count_type, 1, m->m_pkthdr.len);
667 	}
668 	so_recv_data_stat(in6p->in6p_socket, m, 0);
669 	if (sbappendaddr(&in6p->in6p_socket->so_rcv,
670 	    SA(&udp_in6), m, opts, NULL) == 0) {
671 		UDP_LOG(in6p, "sbappendaddr full receive socket buffer");
672 		m = NULL;
673 		opts = NULL;
674 		udpstat.udps_fullsock++;
675 		udp_unlock(in6p->in6p_socket, 1, 0);
676 		goto bad;
677 	}
678 	if (is_wake_pkt) {
679 		soevent(in6p->in6p_socket, SO_FILT_HINT_LOCKED | SO_FILT_HINT_WAKE_PKT);
680 	}
681 	sorwakeup(in6p->in6p_socket);
682 	udp_unlock(in6p->in6p_socket, 1, 0);
683 	return IPPROTO_DONE;
684 bad:
685 	if (m != NULL) {
686 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, drop_reason, NULL, 0);
687 	}
688 	if (opts != NULL) {
689 		m_freem(opts);
690 	}
691 	return IPPROTO_DONE;
692 }
693 
694 void
udp6_ctlinput(int cmd,struct sockaddr * sa,void * d,__unused struct ifnet * ifp)695 udp6_ctlinput(int cmd, struct sockaddr *sa, void *d, __unused struct ifnet *ifp)
696 {
697 	struct udphdr uh;
698 	struct ip6_hdr *ip6;
699 	struct mbuf *m;
700 	int off = 0;
701 	struct ip6ctlparam *__single ip6cp = NULL;
702 	struct icmp6_hdr *__single icmp6 = NULL;
703 	const struct sockaddr_in6 *__single sa6_src = NULL;
704 	void *__single cmdarg = NULL;
705 	void (*notify)(struct inpcb *, int) = udp_notify;
706 	struct inpcb *__single in6p;
707 	struct udp_portonly {
708 		u_int16_t uh_sport;
709 		u_int16_t uh_dport;
710 	} *uhp;
711 
712 	if (sa->sa_family != AF_INET6 ||
713 	    sa->sa_len != sizeof(struct sockaddr_in6)) {
714 		return;
715 	}
716 
717 	if ((unsigned)cmd >= PRC_NCMDS) {
718 		return;
719 	}
720 	if (PRC_IS_REDIRECT(cmd)) {
721 		notify = in6_rtchange;
722 		d = NULL;
723 	} else if (cmd == PRC_HOSTDEAD) {
724 		d = NULL;
725 	} else if (inet6ctlerrmap[cmd] == 0) {
726 		return;
727 	}
728 
729 	/* if the parameter is from icmp6, decode it. */
730 	if (d != NULL) {
731 		ip6cp = (struct ip6ctlparam *)d;
732 		icmp6 = ip6cp->ip6c_icmp6;
733 		m = ip6cp->ip6c_m;
734 		ip6 = ip6cp->ip6c_ip6;
735 		off = ip6cp->ip6c_off;
736 		cmdarg = ip6cp->ip6c_cmdarg;
737 		sa6_src = ip6cp->ip6c_src;
738 	} else {
739 		m = NULL;
740 		ip6 = NULL;
741 		cmdarg = NULL;
742 		sa6_src = &sa6_any;
743 	}
744 
745 	if (ip6 != NULL) {
746 #if SKYWALK
747 		union sockaddr_in_4_6 sock_laddr;
748 		struct protoctl_ev_val prctl_ev_val;
749 #endif /* SKYWALK */
750 		/*
751 		 * XXX: We assume that when IPV6 is non NULL,
752 		 * M and OFF are valid.
753 		 */
754 		/* check if we can safely examine src and dst ports */
755 		if (m->m_pkthdr.len < off + sizeof(*uhp)) {
756 			return;
757 		}
758 
759 		bzero(&uh, sizeof(uh));
760 		m_copydata(m, off, sizeof(*uhp), (caddr_t)&uh);
761 
762 		in6p = in6_pcblookup_hash(&udbinfo, &ip6->ip6_dst, uh.uh_dport, ip6_input_getdstifscope(m),
763 		    &ip6->ip6_src, uh.uh_sport, ip6_input_getsrcifscope(m), 0, NULL);
764 		if (cmd == PRC_MSGSIZE && in6p != NULL && !uuid_is_null(in6p->necp_client_uuid)) {
765 			uuid_t null_uuid;
766 			uuid_clear(null_uuid);
767 			necp_update_flow_protoctl_event(null_uuid, in6p->necp_client_uuid,
768 			    PRC_MSGSIZE, ntohl(icmp6->icmp6_mtu), 0);
769 			/*
770 			 * Avoid setting so_error when using Network.framework
771 			 * since the notification of PRC_MSGSIZE has been delivered
772 			 * through NECP.
773 			 */
774 			in6_pcbnotify(&udbinfo, sa, uh.uh_dport,
775 			    SA(ip6cp->ip6c_src), uh.uh_sport,
776 			    cmd, cmdarg, NULL);
777 		} else {
778 			in6_pcbnotify(&udbinfo, sa, uh.uh_dport,
779 			    SA(ip6cp->ip6c_src), uh.uh_sport,
780 			    cmd, cmdarg, notify);
781 		}
782 #if SKYWALK
783 		bzero(&prctl_ev_val, sizeof(prctl_ev_val));
784 		bzero(&sock_laddr, sizeof(sock_laddr));
785 
786 		if (cmd == PRC_MSGSIZE && icmp6 != NULL) {
787 			prctl_ev_val.val = ntohl(icmp6->icmp6_mtu);
788 		}
789 		sock_laddr.sin6.sin6_family = AF_INET6;
790 		sock_laddr.sin6.sin6_len = sizeof(sock_laddr.sin6);
791 		sock_laddr.sin6.sin6_addr = ip6->ip6_src;
792 
793 		protoctl_event_enqueue_nwk_wq_entry(ifp,
794 		    SA(&sock_laddr), sa,
795 		    uh.uh_sport, uh.uh_dport, IPPROTO_UDP,
796 		    cmd, &prctl_ev_val);
797 #endif /* SKYWALK */
798 	}
799 	/*
800 	 * XXX The else condition here was broken for a long time.
801 	 * Fixing it made us deliver notification correctly but broke
802 	 * some frameworks that didn't handle it well.
803 	 * For now we have removed it and will revisit it later.
804 	 */
805 }
806 
807 static int
udp6_abort(struct socket * so)808 udp6_abort(struct socket *so)
809 {
810 	struct inpcb *__single inp;
811 
812 	inp = sotoinpcb(so);
813 	if (inp == NULL) {
814 		panic("%s: so=%p null inp", __func__, so);
815 		/* NOTREACHED */
816 	}
817 	soisdisconnected(so);
818 	in6_pcbdetach(inp);
819 	return 0;
820 }
821 
822 static int
udp6_attach(struct socket * so,int proto,struct proc * p)823 udp6_attach(struct socket *so, int proto, struct proc *p)
824 {
825 #pragma unused(proto)
826 	struct inpcb *__single inp;
827 	int error;
828 
829 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
830 		error = soreserve(so, udp_sendspace, udp_recvspace);
831 		if (error) {
832 			return error;
833 		}
834 	}
835 
836 	inp = sotoinpcb(so);
837 	if (inp != NULL) {
838 		return EINVAL;
839 	}
840 
841 	error = in_pcballoc(so, &udbinfo, p);
842 	if (error) {
843 		return error;
844 	}
845 
846 	inp = (struct inpcb *)so->so_pcb;
847 	inp->inp_vflag |= INP_IPV6;
848 	if (ip6_mapped_addr_on) {
849 		inp->inp_vflag |= INP_IPV4;
850 	}
851 	inp->in6p_hops = -1;    /* use kernel default */
852 	inp->in6p_cksum = -1;   /* just to be sure */
853 	/*
854 	 * XXX: ugly!!
855 	 * IPv4 TTL initialization is necessary for an IPv6 socket as well,
856 	 * because the socket may be bound to an IPv6 wildcard address,
857 	 * which may match an IPv4-mapped IPv6 address.
858 	 */
859 	inp->inp_ip_ttl = (u_char)ip_defttl;
860 	if (nstat_collect) {
861 		nstat_udp_new_pcb(inp);
862 	}
863 	return 0;
864 }
865 
866 static int
udp6_bind(struct socket * so,struct sockaddr * nam,struct proc * p)867 udp6_bind(struct socket *so, struct sockaddr *nam, struct proc *p)
868 {
869 	struct inpcb *__single inp;
870 	int error;
871 
872 	inp = sotoinpcb(so);
873 	if (inp == NULL) {
874 		return EINVAL;
875 	}
876 	inp_enter_bind_in_progress(so);
877 
878 	const uint8_t old_flags = inp->inp_vflag;
879 	inp->inp_vflag &= ~INP_IPV4;
880 	inp->inp_vflag |= INP_IPV6;
881 
882 	if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
883 		struct sockaddr_in6 *__single sin6_p;
884 
885 		sin6_p = SIN6(nam);
886 
887 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6_p->sin6_addr)) {
888 			inp->inp_vflag |= INP_IPV4;
889 			inp->inp_vflag &= ~INP_V4MAPPEDV6;
890 		} else if (IN6_IS_ADDR_V4MAPPED(&sin6_p->sin6_addr)) {
891 			struct sockaddr_in sin;
892 
893 			in6_sin6_2_sin(&sin, sin6_p);
894 			inp->inp_vflag |= INP_IPV4;
895 			inp->inp_vflag &= ~INP_IPV6;
896 			inp->inp_vflag |= INP_V4MAPPEDV6;
897 
898 			error = in_pcbbind(inp, SA(&sin), NULL, p);
899 			if (error != 0) {
900 				inp->inp_vflag = old_flags;
901 			}
902 			goto out;
903 		}
904 	}
905 
906 	error = in6_pcbbind(inp, nam, NULL, p);
907 	if (error != 0) {
908 		inp->inp_vflag = old_flags;
909 	}
910 out:
911 	UDP_LOG_BIND(inp, error);
912 
913 	inp_exit_bind_in_progress(so);
914 
915 	return error;
916 }
917 
918 int
udp6_connect(struct socket * so,struct sockaddr * nam,struct proc * p)919 udp6_connect(struct socket *so, struct sockaddr *nam, struct proc *p)
920 {
921 	struct inpcb *__single inp;
922 	int error;
923 	struct sockaddr_in6 *__single sin6_p = SIN6(nam);
924 
925 #if defined(NECP) && defined(FLOW_DIVERT)
926 	int should_use_flow_divert = 0;
927 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
928 
929 	inp = sotoinpcb(so);
930 	if (inp == NULL) {
931 		return EINVAL;
932 	}
933 
934 	inp_enter_bind_in_progress(so);
935 
936 #if defined(NECP) && defined(FLOW_DIVERT)
937 	should_use_flow_divert = necp_socket_should_use_flow_divert(inp);
938 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
939 
940 	/*
941 	 * It is possible that the socket is bound to v4 mapped v6 address.
942 	 * Post that do not allow connect to a v6 endpoint.
943 	 */
944 	if (inp->inp_vflag & INP_V4MAPPEDV6 &&
945 	    !IN6_IS_ADDR_V4MAPPED(&sin6_p->sin6_addr)) {
946 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6_p->sin6_addr)) {
947 			sin6_p->sin6_addr.s6_addr[10] = 0xff;
948 			sin6_p->sin6_addr.s6_addr[11] = 0xff;
949 		} else {
950 			error = EINVAL;
951 			goto done;
952 		}
953 	}
954 
955 	if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
956 		if (IN6_IS_ADDR_V4MAPPED(&sin6_p->sin6_addr)) {
957 			struct sockaddr_in sin;
958 			const uint8_t old_flags = inp->inp_vflag;
959 
960 			if (inp->inp_faddr.s_addr != INADDR_ANY) {
961 				error = EISCONN;
962 				goto done;
963 			}
964 			/*
965 			 * If bound to an IPv6 address, we cannot connect to
966 			 * an IPv4 mapped address
967 			 */
968 			if (inp->inp_vflag == INP_IPV6) {
969 				error = EINVAL;
970 				goto done;
971 			}
972 
973 			if (!(so->so_flags1 & SOF1_CONNECT_COUNTED)) {
974 				so->so_flags1 |= SOF1_CONNECT_COUNTED;
975 				INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_inet_dgram_connected);
976 			}
977 
978 			in6_sin6_2_sin(&sin, sin6_p);
979 #if defined(NECP) && defined(FLOW_DIVERT)
980 			if (should_use_flow_divert) {
981 				goto do_flow_divert;
982 			}
983 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
984 			inp->inp_vflag |= INP_IPV4;
985 			inp->inp_vflag &= ~INP_IPV6;
986 			inp->inp_vflag |= INP_V4MAPPEDV6;
987 
988 			error = in_pcbconnect(inp, SA(&sin), p, IFSCOPE_NONE, NULL);
989 			if (error == 0) {
990 #if NECP
991 				/* Update NECP client with connected five-tuple */
992 				if (!uuid_is_null(inp->necp_client_uuid)) {
993 					socket_unlock(so, 0);
994 					necp_client_assign_from_socket(so->last_pid, inp->necp_client_uuid, inp);
995 					socket_lock(so, 0);
996 				}
997 #endif /* NECP */
998 				soisconnected(so);
999 			} else {
1000 				inp->inp_vflag = old_flags;
1001 			}
1002 			goto done;
1003 		}
1004 	}
1005 
1006 	/*
1007 	 * If bound to an IPv4 mapped address, we cannot connect to
1008 	 * an IPv6 address
1009 	 */
1010 	if (inp->inp_vflag == INP_IPV4) {
1011 		error = EINVAL;
1012 		goto done;
1013 	}
1014 
1015 	if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
1016 		error = EISCONN;
1017 		goto done;
1018 	}
1019 
1020 	if (!(so->so_flags1 & SOF1_CONNECT_COUNTED)) {
1021 		so->so_flags1 |= SOF1_CONNECT_COUNTED;
1022 		INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_inet6_dgram_connected);
1023 	}
1024 
1025 #if defined(NECP) && defined(FLOW_DIVERT)
1026 do_flow_divert:
1027 	if (should_use_flow_divert) {
1028 		error = flow_divert_pcb_init(so);
1029 		if (error == 0) {
1030 			error = flow_divert_connect_out(so, nam, p);
1031 		}
1032 		goto done;
1033 	}
1034 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
1035 
1036 	error = in6_pcbconnect(inp, nam, p);
1037 	if (error == 0) {
1038 		/* should be non mapped addr */
1039 		if (ip6_mapped_addr_on ||
1040 		    (inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
1041 			inp->inp_vflag &= ~INP_IPV4;
1042 			inp->inp_vflag |= INP_IPV6;
1043 		}
1044 #if NECP
1045 		/* Update NECP client with connected five-tuple */
1046 		if (!uuid_is_null(inp->necp_client_uuid)) {
1047 			socket_unlock(so, 0);
1048 			necp_client_assign_from_socket(so->last_pid, inp->necp_client_uuid, inp);
1049 			socket_lock(so, 0);
1050 		}
1051 #endif /* NECP */
1052 		soisconnected(so);
1053 		if (inp->inp_flowhash == 0) {
1054 			inp_calc_flowhash(inp);
1055 			ASSERT(inp->inp_flowhash != 0);
1056 		}
1057 		/* update flowinfo - RFC 6437 */
1058 		if (inp->inp_flow == 0 &&
1059 		    inp->in6p_flags & IN6P_AUTOFLOWLABEL) {
1060 			inp->inp_flow &= ~IPV6_FLOWLABEL_MASK;
1061 			inp->inp_flow |=
1062 			    (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
1063 		}
1064 		inp->inp_connect_timestamp = mach_continuous_time();
1065 	}
1066 done:
1067 	UDP_LOG_CONNECT(inp, error);
1068 
1069 	inp_exit_bind_in_progress(so);
1070 
1071 	return error;
1072 }
1073 
1074 static int
udp6_connectx(struct socket * so,struct sockaddr * src,struct sockaddr * dst,struct proc * p,uint32_t ifscope,sae_associd_t aid,sae_connid_t * pcid,uint32_t flags,void * arg,uint32_t arglen,struct uio * uio,user_ssize_t * bytes_written)1075 udp6_connectx(struct socket *so, struct sockaddr *src,
1076     struct sockaddr *dst, struct proc *p, uint32_t ifscope,
1077     sae_associd_t aid, sae_connid_t *pcid, uint32_t flags, void *arg,
1078     uint32_t arglen, struct uio *uio, user_ssize_t *bytes_written)
1079 {
1080 	return udp_connectx_common(so, AF_INET6, src, dst,
1081 	           p, ifscope, aid, pcid, flags, arg, arglen, uio, bytes_written);
1082 }
1083 
1084 static int
udp6_detach(struct socket * so)1085 udp6_detach(struct socket *so)
1086 {
1087 	struct inpcb *__single inp;
1088 
1089 	inp = sotoinpcb(so);
1090 	if (inp == NULL) {
1091 		return EINVAL;
1092 	}
1093 
1094 	UDP_LOG_CONNECTION_SUMMARY(inp);
1095 
1096 	in6_pcbdetach(inp);
1097 	return 0;
1098 }
1099 
1100 static int
udp6_disconnect(struct socket * so)1101 udp6_disconnect(struct socket *so)
1102 {
1103 	struct inpcb *__single inp;
1104 
1105 	inp = sotoinpcb(so);
1106 	if (inp == NULL
1107 #if NECP
1108 	    || (necp_socket_should_use_flow_divert(inp))
1109 #endif /* NECP */
1110 	    ) {
1111 		return inp == NULL ? EINVAL : EPROTOTYPE;
1112 	}
1113 
1114 	if (inp->inp_vflag & INP_IPV4) {
1115 		struct pr_usrreqs *__single pru;
1116 
1117 		pru = ip_protox[IPPROTO_UDP]->pr_usrreqs;
1118 		return (*pru->pru_disconnect)(so);
1119 	}
1120 
1121 	if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
1122 		return ENOTCONN;
1123 	}
1124 
1125 	UDP_LOG_CONNECTION_SUMMARY(inp);
1126 
1127 	in6_pcbdisconnect(inp);
1128 
1129 	/* reset flow-controlled state, just in case */
1130 	inp_reset_fc_state(inp);
1131 
1132 	inp->in6p_laddr = in6addr_any;
1133 	inp->inp_lifscope = IFSCOPE_NONE;
1134 	inp->in6p_last_outifp = NULL;
1135 #if SKYWALK
1136 	if (NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
1137 		netns_set_ifnet(&inp->inp_netns_token, NULL);
1138 	}
1139 #endif /* SKYWALK */
1140 
1141 	so->so_state &= ~SS_ISCONNECTED;                /* XXX */
1142 	return 0;
1143 }
1144 
1145 static int
udp6_disconnectx(struct socket * so,sae_associd_t aid,sae_connid_t cid)1146 udp6_disconnectx(struct socket *so, sae_associd_t aid, sae_connid_t cid)
1147 {
1148 #pragma unused(cid)
1149 	if (aid != SAE_ASSOCID_ANY && aid != SAE_ASSOCID_ALL) {
1150 		return EINVAL;
1151 	}
1152 
1153 	return udp6_disconnect(so);
1154 }
1155 
1156 static int
udp6_send(struct socket * so,int flags,struct mbuf * m,struct sockaddr * addr,struct mbuf * control,struct proc * p)1157 udp6_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *addr,
1158     struct mbuf *control, struct proc *p)
1159 {
1160 	struct inpcb *__single inp;
1161 	int error = 0;
1162 #if defined(NECP) && defined(FLOW_DIVERT)
1163 	int should_use_flow_divert = 0;
1164 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
1165 #if CONTENT_FILTER
1166 	struct m_tag *__single cfil_tag = NULL;
1167 	struct sockaddr *__single cfil_faddr = NULL;
1168 #endif
1169 
1170 	inp = sotoinpcb(so);
1171 	if (inp == NULL) {
1172 		error = EINVAL;
1173 		goto bad;
1174 	}
1175 
1176 #if CONTENT_FILTER
1177 	/* If socket is subject to UDP Content Filter and unconnected, get addr from tag. */
1178 	if (CFIL_DGRAM_FILTERED(so) && !addr && IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
1179 		cfil_tag = cfil_dgram_get_socket_state(m, NULL, NULL, &cfil_faddr, NULL);
1180 		if (cfil_tag) {
1181 			addr = SA(cfil_faddr);
1182 		}
1183 	}
1184 #endif
1185 
1186 #if defined(NECP) && defined(FLOW_DIVERT)
1187 	should_use_flow_divert = necp_socket_should_use_flow_divert(inp);
1188 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
1189 
1190 	if (addr != NULL) {
1191 		if (addr->sa_len != sizeof(struct sockaddr_in6)) {
1192 			error = EINVAL;
1193 			goto bad;
1194 		}
1195 		if (addr->sa_family != AF_INET6) {
1196 			error = EAFNOSUPPORT;
1197 			goto bad;
1198 		}
1199 	}
1200 
1201 	if (ip6_mapped_addr_on || (inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
1202 		int hasv4addr;
1203 		struct sockaddr_in6 *__single sin6 = NULL;
1204 
1205 		if (addr == NULL) {
1206 			hasv4addr = (inp->inp_vflag & INP_IPV4);
1207 		} else {
1208 			sin6 = SIN6(addr);
1209 			hasv4addr =
1210 			    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ? 1 : 0;
1211 		}
1212 		if (hasv4addr) {
1213 			struct pr_usrreqs *__single pru;
1214 
1215 			if (sin6 != NULL) {
1216 				in6_sin6_2_sin_in_sock(addr);
1217 			}
1218 #if defined(NECP) && defined(FLOW_DIVERT)
1219 			if (should_use_flow_divert) {
1220 				goto do_flow_divert;
1221 			}
1222 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
1223 			pru = ip_protox[IPPROTO_UDP]->pr_usrreqs;
1224 			error = ((*pru->pru_send)(so, flags, m, addr,
1225 			    control, p));
1226 			if (error == EJUSTRETURN) {
1227 				error = 0;
1228 			}
1229 #if CONTENT_FILTER
1230 			if (cfil_tag) {
1231 				m_tag_free(cfil_tag);
1232 			}
1233 #endif
1234 			/* addr will just be freed in sendit(). */
1235 			return error;
1236 		}
1237 	}
1238 
1239 #if defined(NECP) && defined(FLOW_DIVERT)
1240 do_flow_divert:
1241 	if (should_use_flow_divert) {
1242 		/* Implicit connect */
1243 		error = flow_divert_implicit_data_out(so, flags, m, addr, control, p);
1244 #if CONTENT_FILTER
1245 		if (cfil_tag) {
1246 			m_tag_free(cfil_tag);
1247 		}
1248 #endif
1249 		return error;
1250 	}
1251 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
1252 
1253 	so_update_tx_data_stats(so, 1, m->m_pkthdr.len);
1254 
1255 	in_pcb_check_management_entitled(inp);
1256 	in_pcb_check_ultra_constrained_entitled(inp);
1257 
1258 #if SKYWALK
1259 	sk_protect_t __single protect = sk_async_transmit_protect();
1260 #endif /* SKYWALK */
1261 	error = udp6_output(inp, m, addr, control, p);
1262 #if SKYWALK
1263 	sk_async_transmit_unprotect(protect);
1264 #endif /* SKYWALK */
1265 
1266 #if CONTENT_FILTER
1267 	if (cfil_tag) {
1268 		m_tag_free(cfil_tag);
1269 	}
1270 #endif
1271 	return error;
1272 
1273 bad:
1274 	VERIFY(error != 0);
1275 
1276 	if (m != NULL) {
1277 		m_freem(m);
1278 	}
1279 	if (control != NULL) {
1280 		m_freem(control);
1281 	}
1282 #if CONTENT_FILTER
1283 	if (cfil_tag) {
1284 		m_tag_free(cfil_tag);
1285 	}
1286 #endif
1287 	return error;
1288 }
1289 
1290 /*
1291  * Checksum extended UDP header and data.
1292  */
1293 static int
udp6_input_checksum(struct mbuf * m,struct udphdr * uh,int off,int ulen)1294 udp6_input_checksum(struct mbuf *m, struct udphdr *uh, int off, int ulen)
1295 {
1296 	struct ifnet *__single ifp = m->m_pkthdr.rcvif;
1297 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1298 
1299 	if (!(m->m_pkthdr.csum_flags & CSUM_DATA_VALID) &&
1300 	    uh->uh_sum == 0) {
1301 		/* UDP/IPv6 checksum is mandatory (RFC2460) */
1302 
1303 		/*
1304 		 * If checksum was already validated, ignore this check.
1305 		 * This is necessary for transport-mode ESP, which may be
1306 		 * getting UDP payloads without checksums when the network
1307 		 * has a NAT64.
1308 		 */
1309 		udpstat.udps_nosum++;
1310 		goto badsum;
1311 	}
1312 
1313 	if ((hwcksum_rx || (ifp->if_flags & IFF_LOOPBACK) ||
1314 	    (m->m_pkthdr.pkt_flags & PKTF_LOOP)) &&
1315 	    (m->m_pkthdr.csum_flags & CSUM_DATA_VALID)) {
1316 		if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
1317 			uh->uh_sum = m->m_pkthdr.csum_rx_val;
1318 		} else {
1319 			uint32_t sum = m->m_pkthdr.csum_rx_val;
1320 			uint32_t start = m->m_pkthdr.csum_rx_start;
1321 			int32_t trailer = (m_pktlen(m) - (off + ulen));
1322 
1323 			/*
1324 			 * Perform 1's complement adjustment of octets
1325 			 * that got included/excluded in the hardware-
1326 			 * calculated checksum value.  Also take care
1327 			 * of any trailing bytes and subtract out
1328 			 * their partial sum.
1329 			 */
1330 			ASSERT(trailer >= 0);
1331 			if ((m->m_pkthdr.csum_flags & CSUM_PARTIAL) &&
1332 			    (start != off || trailer != 0)) {
1333 				uint32_t swbytes = (uint32_t)trailer;
1334 				uint16_t s = 0, d = 0;
1335 
1336 				if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
1337 					s = ip6->ip6_src.s6_addr16[1];
1338 					ip6->ip6_src.s6_addr16[1] = 0;
1339 				}
1340 				if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
1341 					d = ip6->ip6_dst.s6_addr16[1];
1342 					ip6->ip6_dst.s6_addr16[1] = 0;
1343 				}
1344 
1345 				/* callee folds in sum */
1346 				sum = m_adj_sum16(m, start, off, ulen, sum);
1347 				if (off > start) {
1348 					swbytes += (off - start);
1349 				} else {
1350 					swbytes += (start - off);
1351 				}
1352 
1353 				if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
1354 					ip6->ip6_src.s6_addr16[1] = s;
1355 				}
1356 				if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
1357 					ip6->ip6_dst.s6_addr16[1] = d;
1358 				}
1359 
1360 				if (swbytes != 0) {
1361 					udp_in_cksum_stats(swbytes);
1362 				}
1363 				if (trailer != 0) {
1364 					m_adj(m, -trailer);
1365 				}
1366 			}
1367 
1368 			uh->uh_sum = in6_pseudo(&ip6->ip6_src, &ip6->ip6_dst,
1369 			    sum + htonl(ulen + IPPROTO_UDP));
1370 		}
1371 		uh->uh_sum ^= 0xffff;
1372 	} else {
1373 		udp_in6_cksum_stats(ulen);
1374 		uh->uh_sum = in6_cksum(m, IPPROTO_UDP, off, ulen);
1375 	}
1376 
1377 	if (uh->uh_sum != 0) {
1378 badsum:
1379 		udpstat.udps_badsum++;
1380 		IF_UDP_STATINC(ifp, badchksum);
1381 		return -1;
1382 	}
1383 
1384 	return 0;
1385 }
1386 
1387 int
udp6_defunct(struct socket * so)1388 udp6_defunct(struct socket *so)
1389 {
1390 	struct ip_moptions *__single imo;
1391 	struct ip6_moptions *__single im6o;
1392 	struct inpcb *__single inp;
1393 
1394 	inp = sotoinpcb(so);
1395 	if (inp == NULL) {
1396 		return EINVAL;
1397 	}
1398 
1399 	im6o = inp->in6p_moptions;
1400 	inp->in6p_moptions = NULL;
1401 	if (im6o != NULL) {
1402 		struct proc *p = current_proc();
1403 
1404 		SODEFUNCTLOG("%s[%d, %s]: defuncting so 0x%llu drop ipv6 multicast memberships",
1405 		    __func__, proc_pid(p), proc_best_name(p),
1406 		    so->so_gencnt);
1407 		IM6O_REMREF(im6o);
1408 	}
1409 	imo = inp->inp_moptions;
1410 	if (imo != NULL) {
1411 		struct proc *__single p = current_proc();
1412 
1413 		SODEFUNCTLOG("%s[%d, %s]: defuncting so 0x%llu drop ipv4 multicast memberships",
1414 		    __func__, proc_pid(p), proc_best_name(p),
1415 		    so->so_gencnt);
1416 
1417 		inp->inp_moptions = NULL;
1418 
1419 		IMO_REMREF(imo);
1420 	}
1421 
1422 	return 0;
1423 }
1424