xref: /xnu-12377.1.9/bsd/netinet6/udp6_usrreq.c (revision f6217f891ac0bb64f3d375211650a4c1ff8ca1ea)
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_IP_UNREACHABLE_PORT;
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 		icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_NOPORT, 0);
611 		return IPPROTO_DONE;
612 	}
613 
614 	/*
615 	 * Construct sockaddr format source address.
616 	 * Stuff source address and datagram in user buffer.
617 	 */
618 	udp_lock(in6p->in6p_socket, 1, 0);
619 
620 #if NECP
621 	if (!necp_socket_is_allowed_to_send_recv_v6(in6p, uh->uh_dport,
622 	    uh->uh_sport, &ip6->ip6_dst, &ip6->ip6_src, ifp, pf_tag, NULL, NULL, NULL, NULL)) {
623 		in_pcb_checkstate(in6p, WNT_RELEASE, 1);
624 		UDP_LOG_DROP_NECP(ip6, uh, in6p, false);
625 		udp_unlock(in6p->in6p_socket, 1, 0);
626 		IF_UDP_STATINC(ifp, badipsec);
627 		drop_reason = DROP_REASON_IP_NECP_POLICY_DROP;
628 		goto bad;
629 	}
630 #endif /* NECP */
631 
632 	if (in_pcb_checkstate(in6p, WNT_RELEASE, 1) == WNT_STOPUSING) {
633 		udp_unlock(in6p->in6p_socket, 1, 0);
634 		IF_UDP_STATINC(ifp, cleanup);
635 		drop_reason = DROP_REASON_UDP_PCB_GARBAGE_COLLECTED;
636 		goto bad;
637 	}
638 
639 	init_sin6(&udp_in6, m); /* general init */
640 	udp_in6.sin6_port = uh->uh_sport;
641 	if ((in6p->in6p_flags & INP_CONTROLOPTS) != 0 ||
642 	    SOFLOW_ENABLED(in6p->in6p_socket) ||
643 	    SO_RECV_CONTROL_OPTS(in6p->in6p_socket)) {
644 		ret = ip6_savecontrol(in6p, m, &opts);
645 		if (ret != 0) {
646 			UDP_LOG(in6p, "ip_savecontrol error %d", ret);
647 			udp_unlock(in6p->in6p_socket, 1, 0);
648 			drop_reason = DROP_REASON_IP_ENOBUFS;
649 			goto bad;
650 		}
651 	}
652 	m_adj(m, off + sizeof(struct udphdr));
653 	if (nstat_collect) {
654 		ifnet_count_type = IFNET_COUNT_TYPE(ifp);
655 		INP_ADD_RXSTAT(in6p, ifnet_count_type, 1, m->m_pkthdr.len);
656 	}
657 	so_recv_data_stat(in6p->in6p_socket, m, 0);
658 	if (sbappendaddr(&in6p->in6p_socket->so_rcv,
659 	    SA(&udp_in6), m, opts, NULL) == 0) {
660 		UDP_LOG(in6p, "sbappendaddr full receive socket buffer");
661 		m = NULL;
662 		opts = NULL;
663 		udpstat.udps_fullsock++;
664 		udp_unlock(in6p->in6p_socket, 1, 0);
665 		goto bad;
666 	}
667 	if (is_wake_pkt) {
668 		soevent(in6p->in6p_socket, SO_FILT_HINT_LOCKED | SO_FILT_HINT_WAKE_PKT);
669 	}
670 	sorwakeup(in6p->in6p_socket);
671 	udp_unlock(in6p->in6p_socket, 1, 0);
672 	return IPPROTO_DONE;
673 bad:
674 	if (m != NULL) {
675 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, drop_reason, NULL, 0);
676 	}
677 	if (opts != NULL) {
678 		m_freem(opts);
679 	}
680 	return IPPROTO_DONE;
681 }
682 
683 void
udp6_ctlinput(int cmd,struct sockaddr * sa,void * d,__unused struct ifnet * ifp)684 udp6_ctlinput(int cmd, struct sockaddr *sa, void *d, __unused struct ifnet *ifp)
685 {
686 	struct udphdr uh;
687 	struct ip6_hdr *ip6;
688 	struct mbuf *m;
689 	int off = 0;
690 	struct ip6ctlparam *__single ip6cp = NULL;
691 	struct icmp6_hdr *__single icmp6 = NULL;
692 	const struct sockaddr_in6 *__single sa6_src = NULL;
693 	void *__single cmdarg = NULL;
694 	void (*notify)(struct inpcb *, int) = udp_notify;
695 	struct inpcb *__single in6p;
696 	struct udp_portonly {
697 		u_int16_t uh_sport;
698 		u_int16_t uh_dport;
699 	} *uhp;
700 
701 	if (sa->sa_family != AF_INET6 ||
702 	    sa->sa_len != sizeof(struct sockaddr_in6)) {
703 		return;
704 	}
705 
706 	if ((unsigned)cmd >= PRC_NCMDS) {
707 		return;
708 	}
709 	if (PRC_IS_REDIRECT(cmd)) {
710 		notify = in6_rtchange;
711 		d = NULL;
712 	} else if (cmd == PRC_HOSTDEAD) {
713 		d = NULL;
714 	} else if (inet6ctlerrmap[cmd] == 0) {
715 		return;
716 	}
717 
718 	/* if the parameter is from icmp6, decode it. */
719 	if (d != NULL) {
720 		ip6cp = (struct ip6ctlparam *)d;
721 		icmp6 = ip6cp->ip6c_icmp6;
722 		m = ip6cp->ip6c_m;
723 		ip6 = ip6cp->ip6c_ip6;
724 		off = ip6cp->ip6c_off;
725 		cmdarg = ip6cp->ip6c_cmdarg;
726 		sa6_src = ip6cp->ip6c_src;
727 	} else {
728 		m = NULL;
729 		ip6 = NULL;
730 		cmdarg = NULL;
731 		sa6_src = &sa6_any;
732 	}
733 
734 	if (ip6 != NULL) {
735 #if SKYWALK
736 		union sockaddr_in_4_6 sock_laddr;
737 		struct protoctl_ev_val prctl_ev_val;
738 #endif /* SKYWALK */
739 		/*
740 		 * XXX: We assume that when IPV6 is non NULL,
741 		 * M and OFF are valid.
742 		 */
743 		/* check if we can safely examine src and dst ports */
744 		if (m->m_pkthdr.len < off + sizeof(*uhp)) {
745 			return;
746 		}
747 
748 		bzero(&uh, sizeof(uh));
749 		m_copydata(m, off, sizeof(*uhp), (caddr_t)&uh);
750 
751 		in6p = in6_pcblookup_hash(&udbinfo, &ip6->ip6_dst, uh.uh_dport, ip6_input_getdstifscope(m),
752 		    &ip6->ip6_src, uh.uh_sport, ip6_input_getsrcifscope(m), 0, NULL);
753 		if (cmd == PRC_MSGSIZE && in6p != NULL && !uuid_is_null(in6p->necp_client_uuid)) {
754 			uuid_t null_uuid;
755 			uuid_clear(null_uuid);
756 			necp_update_flow_protoctl_event(null_uuid, in6p->necp_client_uuid,
757 			    PRC_MSGSIZE, ntohl(icmp6->icmp6_mtu), 0);
758 			/*
759 			 * Avoid setting so_error when using Network.framework
760 			 * since the notification of PRC_MSGSIZE has been delivered
761 			 * through NECP.
762 			 */
763 			in6_pcbnotify(&udbinfo, sa, uh.uh_dport,
764 			    SA(ip6cp->ip6c_src), uh.uh_sport,
765 			    cmd, cmdarg, NULL);
766 		} else {
767 			in6_pcbnotify(&udbinfo, sa, uh.uh_dport,
768 			    SA(ip6cp->ip6c_src), uh.uh_sport,
769 			    cmd, cmdarg, notify);
770 		}
771 #if SKYWALK
772 		bzero(&prctl_ev_val, sizeof(prctl_ev_val));
773 		bzero(&sock_laddr, sizeof(sock_laddr));
774 
775 		if (cmd == PRC_MSGSIZE && icmp6 != NULL) {
776 			prctl_ev_val.val = ntohl(icmp6->icmp6_mtu);
777 		}
778 		sock_laddr.sin6.sin6_family = AF_INET6;
779 		sock_laddr.sin6.sin6_len = sizeof(sock_laddr.sin6);
780 		sock_laddr.sin6.sin6_addr = ip6->ip6_src;
781 
782 		protoctl_event_enqueue_nwk_wq_entry(ifp,
783 		    SA(&sock_laddr), sa,
784 		    uh.uh_sport, uh.uh_dport, IPPROTO_UDP,
785 		    cmd, &prctl_ev_val);
786 #endif /* SKYWALK */
787 	}
788 	/*
789 	 * XXX The else condition here was broken for a long time.
790 	 * Fixing it made us deliver notification correctly but broke
791 	 * some frameworks that didn't handle it well.
792 	 * For now we have removed it and will revisit it later.
793 	 */
794 }
795 
796 static int
udp6_abort(struct socket * so)797 udp6_abort(struct socket *so)
798 {
799 	struct inpcb *__single inp;
800 
801 	inp = sotoinpcb(so);
802 	if (inp == NULL) {
803 		panic("%s: so=%p null inp", __func__, so);
804 		/* NOTREACHED */
805 	}
806 	soisdisconnected(so);
807 	in6_pcbdetach(inp);
808 	return 0;
809 }
810 
811 static int
udp6_attach(struct socket * so,int proto,struct proc * p)812 udp6_attach(struct socket *so, int proto, struct proc *p)
813 {
814 #pragma unused(proto)
815 	struct inpcb *__single inp;
816 	int error;
817 
818 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
819 		error = soreserve(so, udp_sendspace, udp_recvspace);
820 		if (error) {
821 			return error;
822 		}
823 	}
824 
825 	inp = sotoinpcb(so);
826 	if (inp != NULL) {
827 		return EINVAL;
828 	}
829 
830 	error = in_pcballoc(so, &udbinfo, p);
831 	if (error) {
832 		return error;
833 	}
834 
835 	inp = (struct inpcb *)so->so_pcb;
836 	inp->inp_vflag |= INP_IPV6;
837 	if (ip6_mapped_addr_on) {
838 		inp->inp_vflag |= INP_IPV4;
839 	}
840 	inp->in6p_hops = -1;    /* use kernel default */
841 	inp->in6p_cksum = -1;   /* just to be sure */
842 	/*
843 	 * XXX: ugly!!
844 	 * IPv4 TTL initialization is necessary for an IPv6 socket as well,
845 	 * because the socket may be bound to an IPv6 wildcard address,
846 	 * which may match an IPv4-mapped IPv6 address.
847 	 */
848 	inp->inp_ip_ttl = (u_char)ip_defttl;
849 	if (nstat_collect) {
850 		nstat_udp_new_pcb(inp);
851 	}
852 	return 0;
853 }
854 
855 static int
udp6_bind(struct socket * so,struct sockaddr * nam,struct proc * p)856 udp6_bind(struct socket *so, struct sockaddr *nam, struct proc *p)
857 {
858 	struct inpcb *__single inp;
859 	int error;
860 
861 	inp = sotoinpcb(so);
862 	if (inp == NULL) {
863 		return EINVAL;
864 	}
865 	inp_enter_bind_in_progress(so);
866 
867 	const uint8_t old_flags = inp->inp_vflag;
868 	inp->inp_vflag &= ~INP_IPV4;
869 	inp->inp_vflag |= INP_IPV6;
870 
871 	if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
872 		struct sockaddr_in6 *__single sin6_p;
873 
874 		sin6_p = SIN6(nam);
875 
876 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6_p->sin6_addr)) {
877 			inp->inp_vflag |= INP_IPV4;
878 			inp->inp_vflag &= ~INP_V4MAPPEDV6;
879 		} else if (IN6_IS_ADDR_V4MAPPED(&sin6_p->sin6_addr)) {
880 			struct sockaddr_in sin;
881 
882 			in6_sin6_2_sin(&sin, sin6_p);
883 			inp->inp_vflag |= INP_IPV4;
884 			inp->inp_vflag &= ~INP_IPV6;
885 			inp->inp_vflag |= INP_V4MAPPEDV6;
886 
887 			error = in_pcbbind(inp, SA(&sin), NULL, p);
888 			if (error != 0) {
889 				inp->inp_vflag = old_flags;
890 			}
891 			goto out;
892 		}
893 	}
894 
895 	error = in6_pcbbind(inp, nam, NULL, p);
896 	if (error != 0) {
897 		inp->inp_vflag = old_flags;
898 	}
899 out:
900 	UDP_LOG_BIND(inp, error);
901 
902 	inp_exit_bind_in_progress(so);
903 
904 	return error;
905 }
906 
907 int
udp6_connect(struct socket * so,struct sockaddr * nam,struct proc * p)908 udp6_connect(struct socket *so, struct sockaddr *nam, struct proc *p)
909 {
910 	struct inpcb *__single inp;
911 	int error;
912 	struct sockaddr_in6 *__single sin6_p = SIN6(nam);
913 
914 #if defined(NECP) && defined(FLOW_DIVERT)
915 	int should_use_flow_divert = 0;
916 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
917 
918 	inp = sotoinpcb(so);
919 	if (inp == NULL) {
920 		return EINVAL;
921 	}
922 
923 	inp_enter_bind_in_progress(so);
924 
925 #if defined(NECP) && defined(FLOW_DIVERT)
926 	should_use_flow_divert = necp_socket_should_use_flow_divert(inp);
927 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
928 
929 	/*
930 	 * It is possible that the socket is bound to v4 mapped v6 address.
931 	 * Post that do not allow connect to a v6 endpoint.
932 	 */
933 	if (inp->inp_vflag & INP_V4MAPPEDV6 &&
934 	    !IN6_IS_ADDR_V4MAPPED(&sin6_p->sin6_addr)) {
935 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6_p->sin6_addr)) {
936 			sin6_p->sin6_addr.s6_addr[10] = 0xff;
937 			sin6_p->sin6_addr.s6_addr[11] = 0xff;
938 		} else {
939 			error = EINVAL;
940 			goto done;
941 		}
942 	}
943 
944 	if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
945 		if (IN6_IS_ADDR_V4MAPPED(&sin6_p->sin6_addr)) {
946 			struct sockaddr_in sin;
947 			const uint8_t old_flags = inp->inp_vflag;
948 
949 			if (inp->inp_faddr.s_addr != INADDR_ANY) {
950 				error = EISCONN;
951 				goto done;
952 			}
953 			/*
954 			 * If bound to an IPv6 address, we cannot connect to
955 			 * an IPv4 mapped address
956 			 */
957 			if (inp->inp_vflag == INP_IPV6) {
958 				error = EINVAL;
959 				goto done;
960 			}
961 
962 			if (!(so->so_flags1 & SOF1_CONNECT_COUNTED)) {
963 				so->so_flags1 |= SOF1_CONNECT_COUNTED;
964 				INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_inet_dgram_connected);
965 			}
966 
967 			in6_sin6_2_sin(&sin, sin6_p);
968 #if defined(NECP) && defined(FLOW_DIVERT)
969 			if (should_use_flow_divert) {
970 				goto do_flow_divert;
971 			}
972 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
973 			inp->inp_vflag |= INP_IPV4;
974 			inp->inp_vflag &= ~INP_IPV6;
975 			inp->inp_vflag |= INP_V4MAPPEDV6;
976 
977 			error = in_pcbconnect(inp, SA(&sin), p, IFSCOPE_NONE, NULL);
978 			if (error == 0) {
979 #if NECP
980 				/* Update NECP client with connected five-tuple */
981 				if (!uuid_is_null(inp->necp_client_uuid)) {
982 					socket_unlock(so, 0);
983 					necp_client_assign_from_socket(so->last_pid, inp->necp_client_uuid, inp);
984 					socket_lock(so, 0);
985 				}
986 #endif /* NECP */
987 				soisconnected(so);
988 			} else {
989 				inp->inp_vflag = old_flags;
990 			}
991 			goto done;
992 		}
993 	}
994 
995 	/*
996 	 * If bound to an IPv4 mapped address, we cannot connect to
997 	 * an IPv6 address
998 	 */
999 	if (inp->inp_vflag == INP_IPV4) {
1000 		error = EINVAL;
1001 		goto done;
1002 	}
1003 
1004 	if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
1005 		error = EISCONN;
1006 		goto done;
1007 	}
1008 
1009 	if (!(so->so_flags1 & SOF1_CONNECT_COUNTED)) {
1010 		so->so_flags1 |= SOF1_CONNECT_COUNTED;
1011 		INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_inet6_dgram_connected);
1012 	}
1013 
1014 #if defined(NECP) && defined(FLOW_DIVERT)
1015 do_flow_divert:
1016 	if (should_use_flow_divert) {
1017 		error = flow_divert_pcb_init(so);
1018 		if (error == 0) {
1019 			error = flow_divert_connect_out(so, nam, p);
1020 		}
1021 		goto done;
1022 	}
1023 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
1024 
1025 	error = in6_pcbconnect(inp, nam, p);
1026 	if (error == 0) {
1027 		/* should be non mapped addr */
1028 		if (ip6_mapped_addr_on ||
1029 		    (inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
1030 			inp->inp_vflag &= ~INP_IPV4;
1031 			inp->inp_vflag |= INP_IPV6;
1032 		}
1033 #if NECP
1034 		/* Update NECP client with connected five-tuple */
1035 		if (!uuid_is_null(inp->necp_client_uuid)) {
1036 			socket_unlock(so, 0);
1037 			necp_client_assign_from_socket(so->last_pid, inp->necp_client_uuid, inp);
1038 			socket_lock(so, 0);
1039 		}
1040 #endif /* NECP */
1041 		soisconnected(so);
1042 		if (inp->inp_flowhash == 0) {
1043 			inp_calc_flowhash(inp);
1044 			ASSERT(inp->inp_flowhash != 0);
1045 		}
1046 		/* update flowinfo - RFC 6437 */
1047 		if (inp->inp_flow == 0 &&
1048 		    inp->in6p_flags & IN6P_AUTOFLOWLABEL) {
1049 			inp->inp_flow &= ~IPV6_FLOWLABEL_MASK;
1050 			inp->inp_flow |=
1051 			    (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
1052 		}
1053 		inp->inp_connect_timestamp = mach_continuous_time();
1054 	}
1055 done:
1056 	UDP_LOG_CONNECT(inp, error);
1057 
1058 	inp_exit_bind_in_progress(so);
1059 
1060 	return error;
1061 }
1062 
1063 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)1064 udp6_connectx(struct socket *so, struct sockaddr *src,
1065     struct sockaddr *dst, struct proc *p, uint32_t ifscope,
1066     sae_associd_t aid, sae_connid_t *pcid, uint32_t flags, void *arg,
1067     uint32_t arglen, struct uio *uio, user_ssize_t *bytes_written)
1068 {
1069 	return udp_connectx_common(so, AF_INET6, src, dst,
1070 	           p, ifscope, aid, pcid, flags, arg, arglen, uio, bytes_written);
1071 }
1072 
1073 static int
udp6_detach(struct socket * so)1074 udp6_detach(struct socket *so)
1075 {
1076 	struct inpcb *__single inp;
1077 
1078 	inp = sotoinpcb(so);
1079 	if (inp == NULL) {
1080 		return EINVAL;
1081 	}
1082 
1083 	UDP_LOG_CONNECTION_SUMMARY(inp);
1084 
1085 	in6_pcbdetach(inp);
1086 	return 0;
1087 }
1088 
1089 static int
udp6_disconnect(struct socket * so)1090 udp6_disconnect(struct socket *so)
1091 {
1092 	struct inpcb *__single inp;
1093 
1094 	inp = sotoinpcb(so);
1095 	if (inp == NULL
1096 #if NECP
1097 	    || (necp_socket_should_use_flow_divert(inp))
1098 #endif /* NECP */
1099 	    ) {
1100 		return inp == NULL ? EINVAL : EPROTOTYPE;
1101 	}
1102 
1103 	if (inp->inp_vflag & INP_IPV4) {
1104 		struct pr_usrreqs *__single pru;
1105 
1106 		pru = ip_protox[IPPROTO_UDP]->pr_usrreqs;
1107 		return (*pru->pru_disconnect)(so);
1108 	}
1109 
1110 	if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
1111 		return ENOTCONN;
1112 	}
1113 
1114 	UDP_LOG_CONNECTION_SUMMARY(inp);
1115 
1116 	in6_pcbdisconnect(inp);
1117 
1118 	/* reset flow-controlled state, just in case */
1119 	inp_reset_fc_state(inp);
1120 
1121 	inp->in6p_laddr = in6addr_any;
1122 	inp->inp_lifscope = IFSCOPE_NONE;
1123 	inp->in6p_last_outifp = NULL;
1124 #if SKYWALK
1125 	if (NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
1126 		netns_set_ifnet(&inp->inp_netns_token, NULL);
1127 	}
1128 #endif /* SKYWALK */
1129 
1130 	so->so_state &= ~SS_ISCONNECTED;                /* XXX */
1131 	return 0;
1132 }
1133 
1134 static int
udp6_disconnectx(struct socket * so,sae_associd_t aid,sae_connid_t cid)1135 udp6_disconnectx(struct socket *so, sae_associd_t aid, sae_connid_t cid)
1136 {
1137 #pragma unused(cid)
1138 	if (aid != SAE_ASSOCID_ANY && aid != SAE_ASSOCID_ALL) {
1139 		return EINVAL;
1140 	}
1141 
1142 	return udp6_disconnect(so);
1143 }
1144 
1145 static int
udp6_send(struct socket * so,int flags,struct mbuf * m,struct sockaddr * addr,struct mbuf * control,struct proc * p)1146 udp6_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *addr,
1147     struct mbuf *control, struct proc *p)
1148 {
1149 	struct inpcb *__single inp;
1150 	int error = 0;
1151 #if defined(NECP) && defined(FLOW_DIVERT)
1152 	int should_use_flow_divert = 0;
1153 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
1154 #if CONTENT_FILTER
1155 	struct m_tag *__single cfil_tag = NULL;
1156 	struct sockaddr *__single cfil_faddr = NULL;
1157 #endif
1158 
1159 	inp = sotoinpcb(so);
1160 	if (inp == NULL) {
1161 		error = EINVAL;
1162 		goto bad;
1163 	}
1164 
1165 #if CONTENT_FILTER
1166 	/* If socket is subject to UDP Content Filter and unconnected, get addr from tag. */
1167 	if (CFIL_DGRAM_FILTERED(so) && !addr && IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
1168 		cfil_tag = cfil_dgram_get_socket_state(m, NULL, NULL, &cfil_faddr, NULL);
1169 		if (cfil_tag) {
1170 			addr = SA(cfil_faddr);
1171 		}
1172 	}
1173 #endif
1174 
1175 #if defined(NECP) && defined(FLOW_DIVERT)
1176 	should_use_flow_divert = necp_socket_should_use_flow_divert(inp);
1177 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
1178 
1179 	if (addr != NULL) {
1180 		if (addr->sa_len != sizeof(struct sockaddr_in6)) {
1181 			error = EINVAL;
1182 			goto bad;
1183 		}
1184 		if (addr->sa_family != AF_INET6) {
1185 			error = EAFNOSUPPORT;
1186 			goto bad;
1187 		}
1188 	}
1189 
1190 	if (ip6_mapped_addr_on || (inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
1191 		int hasv4addr;
1192 		struct sockaddr_in6 *__single sin6 = NULL;
1193 
1194 		if (addr == NULL) {
1195 			hasv4addr = (inp->inp_vflag & INP_IPV4);
1196 		} else {
1197 			sin6 = SIN6(addr);
1198 			hasv4addr =
1199 			    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ? 1 : 0;
1200 		}
1201 		if (hasv4addr) {
1202 			struct pr_usrreqs *__single pru;
1203 
1204 			if (sin6 != NULL) {
1205 				in6_sin6_2_sin_in_sock(addr);
1206 			}
1207 #if defined(NECP) && defined(FLOW_DIVERT)
1208 			if (should_use_flow_divert) {
1209 				goto do_flow_divert;
1210 			}
1211 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
1212 			pru = ip_protox[IPPROTO_UDP]->pr_usrreqs;
1213 			error = ((*pru->pru_send)(so, flags, m, addr,
1214 			    control, p));
1215 #if CONTENT_FILTER
1216 			if (cfil_tag) {
1217 				m_tag_free(cfil_tag);
1218 			}
1219 #endif
1220 			/* addr will just be freed in sendit(). */
1221 			return error;
1222 		}
1223 	}
1224 
1225 #if defined(NECP) && defined(FLOW_DIVERT)
1226 do_flow_divert:
1227 	if (should_use_flow_divert) {
1228 		/* Implicit connect */
1229 		error = flow_divert_implicit_data_out(so, flags, m, addr, control, p);
1230 #if CONTENT_FILTER
1231 		if (cfil_tag) {
1232 			m_tag_free(cfil_tag);
1233 		}
1234 #endif
1235 		return error;
1236 	}
1237 #endif /* defined(NECP) && defined(FLOW_DIVERT) */
1238 
1239 	so_update_tx_data_stats(so, 1, m->m_pkthdr.len);
1240 
1241 	in_pcb_check_management_entitled(inp);
1242 	in_pcb_check_ultra_constrained_entitled(inp);
1243 
1244 #if SKYWALK
1245 	sk_protect_t __single protect = sk_async_transmit_protect();
1246 #endif /* SKYWALK */
1247 	error = udp6_output(inp, m, addr, control, p);
1248 #if SKYWALK
1249 	sk_async_transmit_unprotect(protect);
1250 #endif /* SKYWALK */
1251 
1252 #if CONTENT_FILTER
1253 	if (cfil_tag) {
1254 		m_tag_free(cfil_tag);
1255 	}
1256 #endif
1257 	return error;
1258 
1259 bad:
1260 	VERIFY(error != 0);
1261 
1262 	if (m != NULL) {
1263 		m_freem(m);
1264 	}
1265 	if (control != NULL) {
1266 		m_freem(control);
1267 	}
1268 #if CONTENT_FILTER
1269 	if (cfil_tag) {
1270 		m_tag_free(cfil_tag);
1271 	}
1272 #endif
1273 	return error;
1274 }
1275 
1276 /*
1277  * Checksum extended UDP header and data.
1278  */
1279 static int
udp6_input_checksum(struct mbuf * m,struct udphdr * uh,int off,int ulen)1280 udp6_input_checksum(struct mbuf *m, struct udphdr *uh, int off, int ulen)
1281 {
1282 	struct ifnet *__single ifp = m->m_pkthdr.rcvif;
1283 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1284 
1285 	if (!(m->m_pkthdr.csum_flags & CSUM_DATA_VALID) &&
1286 	    uh->uh_sum == 0) {
1287 		/* UDP/IPv6 checksum is mandatory (RFC2460) */
1288 
1289 		/*
1290 		 * If checksum was already validated, ignore this check.
1291 		 * This is necessary for transport-mode ESP, which may be
1292 		 * getting UDP payloads without checksums when the network
1293 		 * has a NAT64.
1294 		 */
1295 		udpstat.udps_nosum++;
1296 		goto badsum;
1297 	}
1298 
1299 	if ((hwcksum_rx || (ifp->if_flags & IFF_LOOPBACK) ||
1300 	    (m->m_pkthdr.pkt_flags & PKTF_LOOP)) &&
1301 	    (m->m_pkthdr.csum_flags & CSUM_DATA_VALID)) {
1302 		if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
1303 			uh->uh_sum = m->m_pkthdr.csum_rx_val;
1304 		} else {
1305 			uint32_t sum = m->m_pkthdr.csum_rx_val;
1306 			uint32_t start = m->m_pkthdr.csum_rx_start;
1307 			int32_t trailer = (m_pktlen(m) - (off + ulen));
1308 
1309 			/*
1310 			 * Perform 1's complement adjustment of octets
1311 			 * that got included/excluded in the hardware-
1312 			 * calculated checksum value.  Also take care
1313 			 * of any trailing bytes and subtract out
1314 			 * their partial sum.
1315 			 */
1316 			ASSERT(trailer >= 0);
1317 			if ((m->m_pkthdr.csum_flags & CSUM_PARTIAL) &&
1318 			    (start != off || trailer != 0)) {
1319 				uint32_t swbytes = (uint32_t)trailer;
1320 				uint16_t s = 0, d = 0;
1321 
1322 				if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
1323 					s = ip6->ip6_src.s6_addr16[1];
1324 					ip6->ip6_src.s6_addr16[1] = 0;
1325 				}
1326 				if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
1327 					d = ip6->ip6_dst.s6_addr16[1];
1328 					ip6->ip6_dst.s6_addr16[1] = 0;
1329 				}
1330 
1331 				/* callee folds in sum */
1332 				sum = m_adj_sum16(m, start, off, ulen, sum);
1333 				if (off > start) {
1334 					swbytes += (off - start);
1335 				} else {
1336 					swbytes += (start - off);
1337 				}
1338 
1339 				if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
1340 					ip6->ip6_src.s6_addr16[1] = s;
1341 				}
1342 				if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
1343 					ip6->ip6_dst.s6_addr16[1] = d;
1344 				}
1345 
1346 				if (swbytes != 0) {
1347 					udp_in_cksum_stats(swbytes);
1348 				}
1349 				if (trailer != 0) {
1350 					m_adj(m, -trailer);
1351 				}
1352 			}
1353 
1354 			uh->uh_sum = in6_pseudo(&ip6->ip6_src, &ip6->ip6_dst,
1355 			    sum + htonl(ulen + IPPROTO_UDP));
1356 		}
1357 		uh->uh_sum ^= 0xffff;
1358 	} else {
1359 		udp_in6_cksum_stats(ulen);
1360 		uh->uh_sum = in6_cksum(m, IPPROTO_UDP, off, ulen);
1361 	}
1362 
1363 	if (uh->uh_sum != 0) {
1364 badsum:
1365 		udpstat.udps_badsum++;
1366 		IF_UDP_STATINC(ifp, badchksum);
1367 		return -1;
1368 	}
1369 
1370 	return 0;
1371 }
1372 
1373 int
udp6_defunct(struct socket * so)1374 udp6_defunct(struct socket *so)
1375 {
1376 	struct ip_moptions *__single imo;
1377 	struct ip6_moptions *__single im6o;
1378 	struct inpcb *__single inp;
1379 
1380 	inp = sotoinpcb(so);
1381 	if (inp == NULL) {
1382 		return EINVAL;
1383 	}
1384 
1385 	im6o = inp->in6p_moptions;
1386 	inp->in6p_moptions = NULL;
1387 	if (im6o != NULL) {
1388 		struct proc *p = current_proc();
1389 
1390 		SODEFUNCTLOG("%s[%d, %s]: defuncting so 0x%llu drop ipv6 multicast memberships",
1391 		    __func__, proc_pid(p), proc_best_name(p),
1392 		    so->so_gencnt);
1393 		IM6O_REMREF(im6o);
1394 	}
1395 	imo = inp->inp_moptions;
1396 	if (imo != NULL) {
1397 		struct proc *__single p = current_proc();
1398 
1399 		SODEFUNCTLOG("%s[%d, %s]: defuncting so 0x%llu drop ipv4 multicast memberships",
1400 		    __func__, proc_pid(p), proc_best_name(p),
1401 		    so->so_gencnt);
1402 
1403 		inp->inp_moptions = NULL;
1404 
1405 		IMO_REMREF(imo);
1406 	}
1407 
1408 	return 0;
1409 }
1410