xref: /xnu-10063.101.15/bsd/net/necp_client.c (revision 94d3b452840153a99b38a3a9659680b2a006908e)
1 /*
2  * Copyright (c) 2015-2023 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 #include <string.h>
30 
31 #include <kern/thread_call.h>
32 #include <kern/zalloc.h>
33 
34 #include <net/if.h>
35 #include <net/if_var.h>
36 #include <net/net_api_stats.h>
37 #include <net/necp.h>
38 #include <net/network_agent.h>
39 #include <net/ntstat.h>
40 
41 #include <netinet/in_pcb.h>
42 #include <netinet/in_var.h>
43 #include <netinet/ip.h>
44 #include <netinet/ip6.h>
45 #include <netinet/mp_pcb.h>
46 #include <netinet/tcp_cc.h>
47 #include <netinet/tcp_fsm.h>
48 #include <netinet/tcp_cache.h>
49 #include <netinet6/in6_var.h>
50 
51 #include <sys/domain.h>
52 #include <sys/file_internal.h>
53 #include <sys/kauth.h>
54 #include <sys/kernel.h>
55 #include <sys/malloc.h>
56 #include <sys/poll.h>
57 #include <sys/priv.h>
58 #include <sys/protosw.h>
59 #include <sys/queue.h>
60 #include <sys/socket.h>
61 #include <sys/socketvar.h>
62 #include <sys/sysproto.h>
63 #include <sys/systm.h>
64 #include <sys/types.h>
65 #include <sys/codesign.h>
66 #include <libkern/section_keywords.h>
67 #include <IOKit/IOBSD.h>
68 
69 #include <os/refcnt.h>
70 
71 #include <CodeSignature/Entitlements.h>
72 
73 #if SKYWALK
74 #include <skywalk/os_skywalk_private.h>
75 #include <skywalk/nexus/flowswitch/flow/flow_var.h>
76 #include <skywalk/nexus/flowswitch/nx_flowswitch.h>
77 #endif /* SKYWALK */
78 
79 #if CONFIG_MACF
80 #include <security/mac_framework.h>
81 #endif
82 
83 /*
84  * NECP Client Architecture
85  * ------------------------------------------------
86  * See <net/necp.c> for a discussion on NECP database architecture.
87  *
88  * Each client of NECP provides a set of parameters for a connection or network state
89  * evaluation, on which NECP policy evaluation is run. This produces a policy result
90  * which can be accessed by the originating process, along with events for when policies
91  * results have changed.
92  *
93  * ------------------------------------------------
94  * NECP Client FD
95  * ------------------------------------------------
96  * A process opens an NECP file descriptor using necp_open(). This is a very simple
97  * file descriptor, upon which the process may do the following operations:
98  *   - necp_client_action(...), to add/remove/query clients
99  *   - kqueue, to watch for readable events
100  *   - close(), to close the client session and release all clients
101  *
102  * Client objects are allocated structures that hang off of the file descriptor. Each
103  * client contains:
104  *   - Client ID, a UUID that references the client across the system
105  *   - Parameters, a buffer of TLVs that describe the client's connection parameters,
106  *       such as the remote and local endpoints, interface requirements, etc.
107  *   - Result, a buffer of TLVs containing the current policy evaluation for the client.
108  *       This result will be updated whenever a network change occurs that impacts the
109  *       policy result for that client.
110  *
111  *                   +--------------+
112  *                   |   NECP fd    |
113  *                   +--------------+
114  *                          ||
115  *          ==================================
116  *          ||              ||              ||
117  *  +--------------+ +--------------+ +--------------+
118  *  |   Client ID  | |   Client ID  | |   Client ID  |
119  *  |     ----     | |     ----     | |     ----     |
120  *  |  Parameters  | |  Parameters  | |  Parameters  |
121  *  |     ----     | |     ----     | |     ----     |
122  *  |    Result    | |    Result    | |    Result    |
123  *  +--------------+ +--------------+ +--------------+
124  *
125  * ------------------------------------------------
126  * Client Actions
127  * ------------------------------------------------
128  *   - Add. Input parameters as a buffer of TLVs, and output a client ID. Allocates a
129  *       new client structure on the file descriptor.
130  *   - Remove. Input a client ID. Removes a client structure from the file descriptor.
131  *   - Copy Parameters. Input a client ID, and output parameter TLVs.
132  *   - Copy Result. Input a client ID, and output result TLVs. Alternatively, input empty
133  *       client ID and get next unread client result.
134  *   - Copy List. List all client IDs.
135  *
136  * ------------------------------------------------
137  * Client Policy Evaluation
138  * ------------------------------------------------
139  * Policies are evaluated for clients upon client creation, and upon update events,
140  * which are network/agent/policy changes coalesced by a timer.
141  *
142  * The policy evaluation goes through the following steps:
143  *   1. Parse client parameters.
144  *   2. Select a scoped interface if applicable. This involves using require/prohibit
145  *      parameters, along with the local address, to select the most appropriate interface
146  *      if not explicitly set by the client parameters.
147  *   3. Run NECP application-level policy evalution
148  *   4. Set policy result into client result buffer.
149  *
150  * ------------------------------------------------
151  * Client Observers
152  * ------------------------------------------------
153  * If necp_open() is called with the NECP_OPEN_FLAG_OBSERVER flag, and the process
154  * passes the necessary privilege check, the fd is allowed to use necp_client_action()
155  * to copy client state attached to the file descriptors of other processes, and to
156  * list all client IDs on the system.
157  */
158 
159 extern u_int32_t necp_debug;
160 
161 static int necpop_select(struct fileproc *, int, void *, vfs_context_t);
162 static int necpop_close(struct fileglob *, vfs_context_t);
163 static int necpop_kqfilter(struct fileproc *, struct knote *, struct kevent_qos_s *);
164 
165 // Timer functions
166 static int necp_timeout_microseconds = 1000 * 100; // 100ms
167 static int necp_timeout_leeway_microseconds = 1000 * 50; // 50ms
168 #if SKYWALK
169 static int necp_collect_stats_timeout_microseconds = 1000 * 1000 * 1; // 1s
170 static int necp_collect_stats_timeout_leeway_microseconds = 1000 * 500; // 500ms
171 static int necp_close_arenas_timeout_microseconds = 1000 * 1000 * 10; // 10s
172 static int necp_close_arenas_timeout_leeway_microseconds = 1000 * 1000 * 1; // 1s
173 #endif /* SKYWALK */
174 
175 static int necp_client_fd_count = 0;
176 static int necp_observer_fd_count = 0;
177 static int necp_client_count = 0;
178 static int necp_socket_flow_count = 0;
179 static int necp_if_flow_count = 0;
180 static int necp_observer_message_limit = 256;
181 
182 /*
183  * NECP client tracing control -
184  *
185  * necp_client_tracing_level  : 1 for client trace, 2 for flow trace, 3 for parameter details
186  * necp_client_tracing_pid    : match client with pid
187  */
188 static int necp_client_tracing_level = 0;
189 static int necp_client_tracing_pid = 0;
190 
191 #define NECP_CLIENT_TRACE_LEVEL_CLIENT   1
192 #define NECP_CLIENT_TRACE_LEVEL_FLOW     2
193 #define NECP_CLIENT_TRACE_LEVEL_PARAMS   3
194 
195 #define NECP_CLIENT_TRACE_PID_MATCHED(pid) \
196     (pid == necp_client_tracing_pid)
197 
198 #define NECP_ENABLE_CLIENT_TRACE(level) \
199     ((necp_client_tracing_level >= level && \
200       (!necp_client_tracing_pid || NECP_CLIENT_TRACE_PID_MATCHED(client->proc_pid))) ? necp_client_tracing_level : 0)
201 
202 #define NECP_CLIENT_LOG(client, fmt, ...)                                                                       \
203     if (client && NECP_ENABLE_CLIENT_TRACE(NECP_CLIENT_TRACE_LEVEL_CLIENT)) {                                   \
204 	uuid_string_t client_uuid_str = { };                                                                        \
205 	uuid_unparse_lower(client->client_id, client_uuid_str);                                                     \
206 	NECPLOG(LOG_NOTICE, "NECP_CLIENT_LOG <pid %d %s>: " fmt "\n", client ? client->proc_pid : 0, client_uuid_str, ##__VA_ARGS__); \
207     }
208 
209 #define NECP_CLIENT_FLOW_LOG(client, flow, fmt, ...)                                                            \
210     if (client && flow && NECP_ENABLE_CLIENT_TRACE(NECP_CLIENT_TRACE_LEVEL_FLOW)) {                             \
211 	uuid_string_t client_uuid_str = { };                                                                        \
212 	uuid_unparse_lower(client->client_id, client_uuid_str);                                                     \
213 	uuid_string_t flow_uuid_str = { };                                                                          \
214 	uuid_unparse_lower(flow->registration_id, flow_uuid_str);                                                   \
215 	NECPLOG(LOG_NOTICE, "NECP CLIENT FLOW TRACE <pid %d %s> <flow %s>: " fmt "\n", client ? client->proc_pid : 0, client_uuid_str, flow_uuid_str, ##__VA_ARGS__); \
216     }
217 
218 #define NECP_CLIENT_PARAMS_LOG(client, fmt, ...)                                                                \
219     if (client && NECP_ENABLE_CLIENT_TRACE(NECP_CLIENT_TRACE_LEVEL_PARAMS)) {                                   \
220     uuid_string_t client_uuid_str = { };                                                                        \
221     uuid_unparse_lower(client->client_id, client_uuid_str);                                                     \
222     NECPLOG(LOG_NOTICE, "NECP_CLIENT_PARAMS_LOG <pid %d %s>: " fmt "\n", client ? client->proc_pid : 0, client_uuid_str, ##__VA_ARGS__); \
223     }
224 
225 #define NECP_SOCKET_PID(so) \
226     ((so->so_flags & SOF_DELEGATED) ? so->e_pid : so->last_pid)
227 
228 #define NECP_ENABLE_SOCKET_TRACE(level) \
229     ((necp_client_tracing_level >= level && \
230       (!necp_client_tracing_pid || NECP_CLIENT_TRACE_PID_MATCHED(NECP_SOCKET_PID(so)))) ? necp_client_tracing_level : 0)
231 
232 #define NECP_SOCKET_PARAMS_LOG(so, fmt, ...)                                                                    \
233     if (so && NECP_ENABLE_SOCKET_TRACE(NECP_CLIENT_TRACE_LEVEL_PARAMS)) {                                       \
234     NECPLOG(LOG_NOTICE, "NECP_SOCKET_PARAMS_LOG <pid %d>: " fmt "\n", NECP_SOCKET_PID(so), ##__VA_ARGS__);      \
235     }
236 
237 #define NECP_SOCKET_ATTRIBUTE_LOG(fmt, ...)                                                                     \
238     if (necp_client_tracing_level >= NECP_CLIENT_TRACE_LEVEL_PARAMS) {                                          \
239     NECPLOG(LOG_NOTICE, "NECP_SOCKET_ATTRIBUTE_LOG: " fmt "\n", ##__VA_ARGS__);                                 \
240     }
241 
242 #define NECP_CLIENT_TRACKER_LOG(pid, fmt, ...)                                                                  \
243     if (pid) {                                                                                                  \
244     NECPLOG(LOG_NOTICE, "NECP_CLIENT_TRACKER_LOG <pid %d>: " fmt "\n", pid, ##__VA_ARGS__);                     \
245     }
246 
247 #if SKYWALK
248 static int necp_arena_count = 0;
249 static int necp_sysctl_arena_count = 0;
250 static int necp_nexus_flow_count = 0;
251 
252 /* userspace stats sanity check range, same unit as TCP (see TCP_RTT_SCALE) */
253 static uint32_t necp_client_stats_rtt_floor = 1; // 32us
254 static uint32_t necp_client_stats_rtt_ceiling = 1920000; // 60s
255 const static struct sk_stats_flow ntstat_sk_stats_zero;
256 #endif /* SKYWALK */
257 
258 /*
259  * Global lock to protect socket inp_necp_attributes across updates.
260  * NECP updating these attributes and clients accessing these attributes
261  * must take this lock.
262  */
263 static LCK_GRP_DECLARE(necp_socket_attr_lock_grp, "necpSocketAttrGroup");
264 LCK_MTX_DECLARE(necp_socket_attr_lock, &necp_socket_attr_lock_grp);
265 
266 os_refgrp_decl(static, necp_client_refgrp, "NECPClientRefGroup", NULL);
267 
268 SYSCTL_INT(_net_necp, NECPCTL_CLIENT_FD_COUNT, client_fd_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_client_fd_count, 0, "");
269 SYSCTL_INT(_net_necp, NECPCTL_OBSERVER_FD_COUNT, observer_fd_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_observer_fd_count, 0, "");
270 SYSCTL_INT(_net_necp, NECPCTL_CLIENT_COUNT, client_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_client_count, 0, "");
271 SYSCTL_INT(_net_necp, NECPCTL_SOCKET_FLOW_COUNT, socket_flow_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_socket_flow_count, 0, "");
272 SYSCTL_INT(_net_necp, NECPCTL_IF_FLOW_COUNT, if_flow_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_if_flow_count, 0, "");
273 SYSCTL_INT(_net_necp, NECPCTL_OBSERVER_MESSAGE_LIMIT, observer_message_limit, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_observer_message_limit, 256, "");
274 SYSCTL_INT(_net_necp, NECPCTL_CLIENT_TRACING_LEVEL, necp_client_tracing_level, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_client_tracing_level, 0, "");
275 SYSCTL_INT(_net_necp, NECPCTL_CLIENT_TRACING_PID, necp_client_tracing_pid, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_client_tracing_pid, 0, "");
276 
277 #if SKYWALK
278 SYSCTL_INT(_net_necp, NECPCTL_ARENA_COUNT, arena_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_arena_count, 0, "");
279 SYSCTL_INT(_net_necp, NECPCTL_SYSCTL_ARENA_COUNT, sysctl_arena_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_sysctl_arena_count, 0, "");
280 SYSCTL_INT(_net_necp, NECPCTL_NEXUS_FLOW_COUNT, nexus_flow_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_nexus_flow_count, 0, "");
281 #if (DEVELOPMENT || DEBUG)
282 SYSCTL_UINT(_net_necp, OID_AUTO, collect_stats_interval_us, CTLFLAG_RW | CTLFLAG_LOCKED, &necp_collect_stats_timeout_microseconds, 0, "");
283 SYSCTL_UINT(_net_necp, OID_AUTO, necp_client_stats_rtt_floor, CTLFLAG_RW | CTLFLAG_LOCKED, &necp_client_stats_rtt_floor, 0, "");
284 SYSCTL_UINT(_net_necp, OID_AUTO, necp_client_stats_rtt_ceiling, CTLFLAG_RW | CTLFLAG_LOCKED, &necp_client_stats_rtt_ceiling, 0, "");
285 #endif /* (DEVELOPMENT || DEBUG) */
286 #endif /* SKYWALK */
287 
288 #define NECP_MAX_CLIENT_LIST_SIZE               1024 * 1024 // 1MB
289 #define NECP_MAX_AGENT_ACTION_SIZE              10 * 1024 // 10K
290 
291 extern int tvtohz(struct timeval *);
292 extern unsigned int get_maxmtu(struct rtentry *);
293 
294 // Parsed parameters
295 #define NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR                         0x00001
296 #define NECP_PARSED_PARAMETERS_FIELD_REMOTE_ADDR                        0x00002
297 #define NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IF                        0x00004
298 #define NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IF                      0x00008
299 #define NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE            0x00010
300 #define NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IFTYPE          0x00020
301 #define NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT                     0x00040
302 #define NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT           0x00080
303 #define NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT            0x00100
304 #define NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT                      0x00200
305 #define NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE        0x00400
306 #define NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT_TYPE      0x00800
307 #define NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT_TYPE       0x01000
308 #define NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT_TYPE         0x02000
309 #define NECP_PARSED_PARAMETERS_FIELD_FLAGS                                      0x04000
310 #define NECP_PARSED_PARAMETERS_FIELD_IP_PROTOCOL                        0x08000
311 #define NECP_PARSED_PARAMETERS_FIELD_EFFECTIVE_PID                      0x10000
312 #define NECP_PARSED_PARAMETERS_FIELD_EFFECTIVE_UUID                     0x20000
313 #define NECP_PARSED_PARAMETERS_FIELD_TRAFFIC_CLASS                      0x40000
314 #define NECP_PARSED_PARAMETERS_FIELD_LOCAL_PORT                         0x80000
315 #define NECP_PARSED_PARAMETERS_FIELD_DELEGATED_UPID                     0x100000
316 #define NECP_PARSED_PARAMETERS_FIELD_ETHERTYPE                          0x200000
317 #define NECP_PARSED_PARAMETERS_FIELD_TRANSPORT_PROTOCOL                 0x400000
318 #define NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR_PREFERENCE              0x800000
319 #define NECP_PARSED_PARAMETERS_FIELD_ATTRIBUTED_BUNDLE_IDENTIFIER       0x1000000
320 #define NECP_PARSED_PARAMETERS_FIELD_PARENT_UUID                        0x2000000
321 #define NECP_PARSED_PARAMETERS_FIELD_FLOW_DEMUX_PATTERN                 0x4000000
322 #define NECP_PARSED_PARAMETERS_FIELD_UID                                0x8000000
323 #define NECP_PARSED_PARAMETERS_FIELD_PERSONA_ID                         0x10000000
324 
325 
326 #define NECP_MAX_INTERFACE_PARAMETERS 16
327 #define NECP_MAX_AGENT_PARAMETERS 4
328 struct necp_client_parsed_parameters {
329 	u_int32_t valid_fields;
330 	u_int32_t flags;
331 	u_int64_t delegated_upid;
332 	union necp_sockaddr_union local_addr;
333 	union necp_sockaddr_union remote_addr;
334 	u_int32_t required_interface_index;
335 	char prohibited_interfaces[NECP_MAX_INTERFACE_PARAMETERS][IFXNAMSIZ];
336 	u_int8_t required_interface_type;
337 	u_int8_t local_address_preference;
338 	u_int8_t prohibited_interface_types[NECP_MAX_INTERFACE_PARAMETERS];
339 	struct necp_client_parameter_netagent_type required_netagent_types[NECP_MAX_AGENT_PARAMETERS];
340 	struct necp_client_parameter_netagent_type prohibited_netagent_types[NECP_MAX_AGENT_PARAMETERS];
341 	struct necp_client_parameter_netagent_type preferred_netagent_types[NECP_MAX_AGENT_PARAMETERS];
342 	struct necp_client_parameter_netagent_type avoided_netagent_types[NECP_MAX_AGENT_PARAMETERS];
343 	uuid_t required_netagents[NECP_MAX_AGENT_PARAMETERS];
344 	uuid_t prohibited_netagents[NECP_MAX_AGENT_PARAMETERS];
345 	uuid_t preferred_netagents[NECP_MAX_AGENT_PARAMETERS];
346 	uuid_t avoided_netagents[NECP_MAX_AGENT_PARAMETERS];
347 	u_int8_t ip_protocol;
348 	u_int8_t transport_protocol;
349 	u_int16_t ethertype;
350 	pid_t effective_pid;
351 	uuid_t effective_uuid;
352 	uuid_t parent_uuid;
353 	u_int32_t traffic_class;
354 	struct necp_demux_pattern demux_patterns[NECP_MAX_DEMUX_PATTERNS];
355 	u_int8_t demux_pattern_count;
356 	uid_t uid;
357 	uid_t persona_id;
358 };
359 
360 static bool
361 necp_find_matching_interface_index(struct necp_client_parsed_parameters *parsed_parameters,
362     u_int *return_ifindex, bool *validate_agents);
363 
364 static bool
365 necp_ifnet_matches_local_address(struct ifnet *ifp, struct sockaddr *sa);
366 
367 static bool
368 necp_ifnet_matches_parameters(struct ifnet *ifp,
369     struct necp_client_parsed_parameters *parsed_parameters,
370     u_int32_t override_flags,
371     u_int32_t *preferred_count,
372     bool secondary_interface,
373     bool require_scoped_field);
374 
375 static const struct fileops necp_fd_ops = {
376 	.fo_type     = DTYPE_NETPOLICY,
377 	.fo_read     = fo_no_read,
378 	.fo_write    = fo_no_write,
379 	.fo_ioctl    = fo_no_ioctl,
380 	.fo_select   = necpop_select,
381 	.fo_close    = necpop_close,
382 	.fo_drain    = fo_no_drain,
383 	.fo_kqfilter = necpop_kqfilter,
384 };
385 
386 struct necp_client_assertion {
387 	LIST_ENTRY(necp_client_assertion) assertion_chain;
388 	uuid_t asserted_netagent;
389 };
390 
391 struct necp_client_flow_header {
392 	struct necp_tlv_header outer_header;
393 	struct necp_tlv_header flow_id_tlv_header;
394 	uuid_t flow_id;
395 	struct necp_tlv_header flags_tlv_header;
396 	u_int32_t flags_value;
397 	struct necp_tlv_header interface_tlv_header;
398 	struct necp_client_result_interface interface_value;
399 } __attribute__((__packed__));
400 
401 struct necp_client_flow_protoctl_event_header {
402 	struct necp_tlv_header protoctl_tlv_header;
403 	struct necp_client_flow_protoctl_event protoctl_event;
404 } __attribute__((__packed__));
405 
406 struct necp_client_nexus_flow_header {
407 	struct necp_client_flow_header flow_header;
408 	struct necp_tlv_header agent_tlv_header;
409 	struct necp_client_result_netagent agent_value;
410 	struct necp_tlv_header tfo_cookie_tlv_header;
411 	u_int8_t tfo_cookie_value[NECP_TFO_COOKIE_LEN_MAX];
412 } __attribute__((__packed__));
413 
414 #if SKYWALK
415 struct necp_arena_info;
416 #endif
417 
418 struct necp_client_flow {
419 	LIST_ENTRY(necp_client_flow) flow_chain;
420 	unsigned invalid : 1;
421 	unsigned nexus : 1; // If true, flow is a nexus; if false, flow is attached to socket
422 	unsigned socket : 1;
423 	unsigned viable : 1;
424 	unsigned assigned : 1;
425 	unsigned has_protoctl_event : 1;
426 	unsigned check_tcp_heuristics : 1;
427 	unsigned _reserved : 1;
428 	union {
429 		uuid_t nexus_agent;
430 		struct {
431 			void *socket_handle;
432 			necp_client_flow_cb cb;
433 		};
434 	} u;
435 	uint32_t interface_index;
436 	u_short  delegated_interface_index;
437 	uint32_t interface_flags;
438 	uint32_t necp_flow_flags;
439 	struct necp_client_flow_protoctl_event protoctl_event;
440 	union necp_sockaddr_union local_addr;
441 	union necp_sockaddr_union remote_addr;
442 
443 	size_t assigned_results_length;
444 	u_int8_t *assigned_results;
445 };
446 
447 struct necp_client_flow_registration {
448 	RB_ENTRY(necp_client_flow_registration) fd_link;
449 	RB_ENTRY(necp_client_flow_registration) global_link;
450 	RB_ENTRY(necp_client_flow_registration) client_link;
451 	LIST_ENTRY(necp_client_flow_registration) collect_stats_chain;
452 	uuid_t registration_id;
453 	u_int32_t flags;
454 	unsigned flow_result_read : 1;
455 	unsigned defunct : 1;
456 	void *interface_handle;
457 	necp_client_flow_cb interface_cb;
458 	struct necp_client *client;
459 	LIST_HEAD(_necp_registration_flow_list, necp_client_flow) flow_list;
460 #if SKYWALK
461 	struct necp_arena_info *stats_arena;    /* arena where the stats objects came from */
462 	void * kstats_kaddr;    /* kernel snapshot of untrusted userspace stats, for calculating delta */
463 	mach_vm_address_t ustats_uaddr; /* userspace stats (untrusted) */
464 	nstat_userland_context stats_handler_context;
465 	struct flow_stats *nexus_stats; /* shared stats objects between necp_client and skywalk */
466 #endif /* !SKYWALK */
467 	u_int64_t last_interface_details __attribute__((aligned(sizeof(u_int64_t))));
468 };
469 
470 static int necp_client_flow_id_cmp(struct necp_client_flow_registration *flow0, struct necp_client_flow_registration *flow1);
471 
472 RB_HEAD(_necp_client_flow_tree, necp_client_flow_registration);
473 RB_PROTOTYPE_PREV(_necp_client_flow_tree, necp_client_flow_registration, client_link, necp_client_flow_id_cmp);
474 RB_GENERATE_PREV(_necp_client_flow_tree, necp_client_flow_registration, client_link, necp_client_flow_id_cmp);
475 
476 #define NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT 4
477 #define NECP_CLIENT_MAX_INTERFACE_OPTIONS 32
478 
479 #define NECP_CLIENT_INTERFACE_OPTION_EXTRA_COUNT (NECP_CLIENT_MAX_INTERFACE_OPTIONS - NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT)
480 
481 struct necp_client {
482 	RB_ENTRY(necp_client) link;
483 	RB_ENTRY(necp_client) global_link;
484 
485 	decl_lck_mtx_data(, lock);
486 	decl_lck_mtx_data(, route_lock);
487 	os_refcnt_t reference_count;
488 
489 	uuid_t client_id;
490 	unsigned result_read : 1;
491 	unsigned group_members_read : 1;
492 	unsigned allow_multiple_flows : 1;
493 	unsigned legacy_client_is_flow : 1;
494 
495 	unsigned platform_binary : 1;
496 	unsigned validated_parent : 1;
497 
498 	size_t result_length;
499 	u_int8_t result[NECP_BASE_CLIENT_RESULT_SIZE];
500 
501 	necp_policy_id policy_id;
502 	necp_policy_id skip_policy_id;
503 
504 	u_int8_t ip_protocol;
505 	int proc_pid;
506 
507 	u_int64_t delegated_upid;
508 
509 	struct _necp_client_flow_tree flow_registrations;
510 	LIST_HEAD(_necp_client_assertion_list, necp_client_assertion) assertion_list;
511 
512 	size_t assigned_group_members_length;
513 	u_int8_t *assigned_group_members;
514 
515 	struct rtentry *current_route;
516 
517 	struct necp_client_interface_option interface_options[NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT];
518 	struct necp_client_interface_option *extra_interface_options;
519 	u_int8_t interface_option_count; // Number in interface_options + extra_interface_options
520 
521 	struct necp_client_result_netagent failed_trigger_agent;
522 
523 	void *agent_handle;
524 
525 	uuid_t override_euuid;
526 
527 #if SKYWALK
528 	netns_token port_reservation;
529 	nstat_context nstat_context;
530 	uuid_t latest_flow_registration_id;
531 	uuid_t parent_client_id;
532 	struct necp_client *original_parameters_source;
533 #endif /* !SKYWALK */
534 
535 	size_t parameters_length;
536 	u_int8_t *parameters;
537 };
538 
539 #define NECP_CLIENT_LOCK(_c) lck_mtx_lock(&_c->lock)
540 #define NECP_CLIENT_UNLOCK(_c) lck_mtx_unlock(&_c->lock)
541 #define NECP_CLIENT_ASSERT_LOCKED(_c) LCK_MTX_ASSERT(&_c->lock, LCK_MTX_ASSERT_OWNED)
542 #define NECP_CLIENT_ASSERT_UNLOCKED(_c) LCK_MTX_ASSERT(&_c->lock, LCK_MTX_ASSERT_NOTOWNED)
543 
544 #define NECP_CLIENT_ROUTE_LOCK(_c) lck_mtx_lock(&_c->route_lock)
545 #define NECP_CLIENT_ROUTE_UNLOCK(_c) lck_mtx_unlock(&_c->route_lock)
546 
547 static void necp_client_retain_locked(struct necp_client *client);
548 static void necp_client_retain(struct necp_client *client);
549 
550 static bool necp_client_release_locked(struct necp_client *client);
551 static bool necp_client_release(struct necp_client *client);
552 
553 static void
554 necp_client_add_assertion(struct necp_client *client, uuid_t netagent_uuid);
555 
556 static bool
557 necp_client_remove_assertion(struct necp_client *client, uuid_t netagent_uuid);
558 
559 static int
560 necp_client_copy_parameters_locked(struct necp_client *client,
561     struct necp_client_nexus_parameters *parameters);
562 
563 LIST_HEAD(_necp_flow_registration_list, necp_client_flow_registration);
564 static struct _necp_flow_registration_list necp_collect_stats_flow_list;
565 
566 struct necp_flow_defunct {
567 	LIST_ENTRY(necp_flow_defunct) chain;
568 
569 	uuid_t flow_id;
570 	uuid_t nexus_agent;
571 	void *agent_handle;
572 	int proc_pid;
573 	u_int32_t flags;
574 	struct necp_client_agent_parameters close_parameters;
575 	bool has_close_parameters;
576 };
577 
578 LIST_HEAD(_necp_flow_defunct_list, necp_flow_defunct);
579 
580 static int necp_client_id_cmp(struct necp_client *client0, struct necp_client *client1);
581 
582 RB_HEAD(_necp_client_tree, necp_client);
583 RB_PROTOTYPE_PREV(_necp_client_tree, necp_client, link, necp_client_id_cmp);
584 RB_GENERATE_PREV(_necp_client_tree, necp_client, link, necp_client_id_cmp);
585 
586 RB_HEAD(_necp_client_global_tree, necp_client);
587 RB_PROTOTYPE_PREV(_necp_client_global_tree, necp_client, global_link, necp_client_id_cmp);
588 RB_GENERATE_PREV(_necp_client_global_tree, necp_client, global_link, necp_client_id_cmp);
589 
590 RB_HEAD(_necp_fd_flow_tree, necp_client_flow_registration);
591 RB_PROTOTYPE_PREV(_necp_fd_flow_tree, necp_client_flow_registration, fd_link, necp_client_flow_id_cmp);
592 RB_GENERATE_PREV(_necp_fd_flow_tree, necp_client_flow_registration, fd_link, necp_client_flow_id_cmp);
593 
594 RB_HEAD(_necp_client_flow_global_tree, necp_client_flow_registration);
595 RB_PROTOTYPE_PREV(_necp_client_flow_global_tree, necp_client_flow_registration, global_link, necp_client_flow_id_cmp);
596 RB_GENERATE_PREV(_necp_client_flow_global_tree, necp_client_flow_registration, global_link, necp_client_flow_id_cmp);
597 
598 static struct _necp_client_global_tree necp_client_global_tree;
599 static struct _necp_client_flow_global_tree necp_client_flow_global_tree;
600 
601 struct necp_client_update {
602 	TAILQ_ENTRY(necp_client_update) chain;
603 
604 	uuid_t client_id;
605 
606 	size_t update_length;
607 	struct necp_client_observer_update *update;
608 };
609 
610 #if SKYWALK
611 struct necp_arena_info {
612 	LIST_ENTRY(necp_arena_info) nai_chain;
613 	u_int32_t nai_flags;
614 	pid_t nai_proc_pid;
615 	struct skmem_arena *nai_arena;
616 	struct skmem_arena_mmap_info nai_mmap;
617 	mach_vm_offset_t nai_roff;
618 	u_int32_t nai_use_count;
619 };
620 #endif /* !SKYWALK */
621 
622 #define NAIF_ATTACHED   0x1     // arena is attached to list
623 #define NAIF_REDIRECT   0x2     // arena mmap has been redirected
624 #define NAIF_DEFUNCT    0x4     // arena is now defunct
625 
626 #define NECP_FD_REPORTED_AGENT_COUNT 2
627 
628 struct necp_fd_reported_agents {
629 	uuid_t agent_uuid[NECP_FD_REPORTED_AGENT_COUNT];
630 };
631 
632 struct necp_fd_data {
633 	u_int8_t necp_fd_type;
634 	LIST_ENTRY(necp_fd_data) chain;
635 	struct _necp_client_tree clients;
636 	struct _necp_fd_flow_tree flows;
637 	TAILQ_HEAD(_necp_client_update_list, necp_client_update) update_list;
638 	int update_count;
639 	int flags;
640 
641 	unsigned background : 1;
642 	unsigned request_in_process_flow_divert : 1;
643 
644 	int proc_pid;
645 	decl_lck_mtx_data(, fd_lock);
646 	struct selinfo si;
647 
648 	struct necp_fd_reported_agents reported_agents;
649 #if SKYWALK
650 	// Arenas and their mmap info for per-process stats.  Stats objects are allocated from an active arena
651 	// that is not redirected/defunct.  The stats_arena_active keeps track of such an arena, and it also
652 	// holds a reference count on the object.  Each flow allocating a stats object also holds a reference
653 	// the necp_arena_info (where the object got allocated from).  During defunct, we redirect the mapping
654 	// of the arena such that any attempt to access (read/write) will result in getting zero-filled pages.
655 	// We then go thru all of the flows for the process and free the stats objects associated with them,
656 	// followed by destroying the skmem region(s) associated with the arena.  The stats_arena_list keeps
657 	// track of all current and defunct stats arenas; there could be more than one arena created for the
658 	// process as the arena destruction happens when its reference count drops to 0.
659 	struct necp_arena_info *stats_arena_active;
660 	LIST_HEAD(_necp_arena_info_list, necp_arena_info) stats_arena_list;
661 	u_int32_t stats_arena_gencnt;
662 
663 	struct skmem_arena *sysctl_arena;
664 	struct skmem_arena_mmap_info sysctl_mmap;
665 	mach_vm_offset_t system_sysctls_roff;
666 #endif /* !SKYWALK */
667 };
668 
669 #define NECP_FD_LOCK(_f) lck_mtx_lock(&_f->fd_lock)
670 #define NECP_FD_UNLOCK(_f) lck_mtx_unlock(&_f->fd_lock)
671 #define NECP_FD_ASSERT_LOCKED(_f) LCK_MTX_ASSERT(&_f->fd_lock, LCK_MTX_ASSERT_OWNED)
672 #define NECP_FD_ASSERT_UNLOCKED(_f) LCK_MTX_ASSERT(&_f->fd_lock, LCK_MTX_ASSERT_NOTOWNED)
673 
674 static LIST_HEAD(_necp_fd_list, necp_fd_data) necp_fd_list;
675 static LIST_HEAD(_necp_fd_observer_list, necp_fd_data) necp_fd_observer_list;
676 
677 #if SKYWALK
678 static KALLOC_TYPE_DEFINE(necp_arena_info_zone, struct necp_arena_info, NET_KT_DEFAULT);
679 #endif /* !SKYWALK */
680 
681 static LCK_ATTR_DECLARE(necp_fd_mtx_attr, 0, 0);
682 static LCK_GRP_DECLARE(necp_fd_mtx_grp, "necp_fd");
683 
684 static LCK_RW_DECLARE_ATTR(necp_fd_lock, &necp_fd_mtx_grp, &necp_fd_mtx_attr);
685 static LCK_RW_DECLARE_ATTR(necp_observer_lock, &necp_fd_mtx_grp, &necp_fd_mtx_attr);
686 static LCK_RW_DECLARE_ATTR(necp_client_tree_lock, &necp_fd_mtx_grp, &necp_fd_mtx_attr);
687 static LCK_RW_DECLARE_ATTR(necp_flow_tree_lock, &necp_fd_mtx_grp, &necp_fd_mtx_attr);
688 static LCK_RW_DECLARE_ATTR(necp_collect_stats_list_lock, &necp_fd_mtx_grp, &necp_fd_mtx_attr);
689 
690 
691 #define NECP_STATS_LIST_LOCK_EXCLUSIVE() lck_rw_lock_exclusive(&necp_collect_stats_list_lock)
692 #define NECP_STATS_LIST_LOCK_SHARED() lck_rw_lock_shared(&necp_collect_stats_list_lock)
693 #define NECP_STATS_LIST_UNLOCK() lck_rw_done(&necp_collect_stats_list_lock)
694 
695 #define NECP_CLIENT_TREE_LOCK_EXCLUSIVE() lck_rw_lock_exclusive(&necp_client_tree_lock)
696 #define NECP_CLIENT_TREE_LOCK_SHARED() lck_rw_lock_shared(&necp_client_tree_lock)
697 #define NECP_CLIENT_TREE_UNLOCK() lck_rw_done(&necp_client_tree_lock)
698 #define NECP_CLIENT_TREE_ASSERT_LOCKED() LCK_RW_ASSERT(&necp_client_tree_lock, LCK_RW_ASSERT_HELD)
699 
700 #define NECP_FLOW_TREE_LOCK_EXCLUSIVE() lck_rw_lock_exclusive(&necp_flow_tree_lock)
701 #define NECP_FLOW_TREE_LOCK_SHARED() lck_rw_lock_shared(&necp_flow_tree_lock)
702 #define NECP_FLOW_TREE_UNLOCK() lck_rw_done(&necp_flow_tree_lock)
703 #define NECP_FLOW_TREE_ASSERT_LOCKED() LCK_RW_ASSERT(&necp_flow_tree_lock, LCK_RW_ASSERT_HELD)
704 
705 #define NECP_FD_LIST_LOCK_EXCLUSIVE() lck_rw_lock_exclusive(&necp_fd_lock)
706 #define NECP_FD_LIST_LOCK_SHARED() lck_rw_lock_shared(&necp_fd_lock)
707 #define NECP_FD_LIST_UNLOCK() lck_rw_done(&necp_fd_lock)
708 #define NECP_FD_LIST_ASSERT_LOCKED() LCK_RW_ASSERT(&necp_fd_lock, LCK_RW_ASSERT_HELD)
709 
710 #define NECP_OBSERVER_LIST_LOCK_EXCLUSIVE() lck_rw_lock_exclusive(&necp_observer_lock)
711 #define NECP_OBSERVER_LIST_LOCK_SHARED() lck_rw_lock_shared(&necp_observer_lock)
712 #define NECP_OBSERVER_LIST_UNLOCK() lck_rw_done(&necp_observer_lock)
713 
714 // Locking Notes
715 
716 // Take NECP_FD_LIST_LOCK when accessing or modifying the necp_fd_list
717 // Take NECP_CLIENT_TREE_LOCK when accessing or modifying the necp_client_global_tree
718 // Take NECP_FLOW_TREE_LOCK when accessing or modifying the necp_client_flow_global_tree
719 // Take NECP_STATS_LIST_LOCK when accessing or modifying the necp_collect_stats_flow_list
720 // Take NECP_FD_LOCK when accessing or modifying an necp_fd_data entry
721 // Take NECP_CLIENT_LOCK when accessing or modifying a single necp_client
722 // Take NECP_CLIENT_ROUTE_LOCK when accessing or modifying a client's route
723 
724 // Precedence, where 1 is the first lock that must be taken
725 // 1. NECP_FD_LIST_LOCK
726 // 2. NECP_FD_LOCK (any)
727 // 3. NECP_CLIENT_TREE_LOCK
728 // 4. NECP_CLIENT_LOCK (any)
729 // 5. NECP_FLOW_TREE_LOCK
730 // 6. NECP_STATS_LIST_LOCK
731 // 7. NECP_CLIENT_ROUTE_LOCK (any)
732 
733 static thread_call_t necp_client_update_tcall;
734 static uint32_t necp_update_all_clients_sched_cnt = 0;
735 static uint64_t necp_update_all_clients_sched_abstime = 0;
736 static LCK_RW_DECLARE_ATTR(necp_update_all_clients_lock, &necp_fd_mtx_grp, &necp_fd_mtx_attr);
737 #define NECP_UPDATE_ALL_CLIENTS_LOCK_EXCLUSIVE() lck_rw_lock_exclusive(&necp_update_all_clients_lock)
738 #define NECP_UPDATE_ALL_CLIENTS_SHARED_TO_EXCLUSIVE() lck_rw_lock_shared_to_exclusive(&necp_update_all_clients_lock)
739 #define NECP_UPDATE_ALL_CLIENTS_SHARED() lck_rw_lock_shared(&necp_update_all_clients_lock)
740 #define NECP_UPDATE_ALL_CLIENTS_UNLOCK() lck_rw_done(&necp_update_all_clients_lock)
741 
742 // Array of PIDs that will trigger in-process flow divert, protected by NECP_FD_LIST_LOCK
743 #define NECP_MAX_FLOW_DIVERT_NEEDED_PIDS 4
744 static pid_t necp_flow_divert_needed_pids[NECP_MAX_FLOW_DIVERT_NEEDED_PIDS];
745 
746 #if SKYWALK
747 static thread_call_t necp_client_collect_stats_tcall;
748 static thread_call_t necp_close_empty_arenas_tcall;
749 
750 static void necp_fd_insert_stats_arena(struct necp_fd_data *fd_data, struct necp_arena_info *nai);
751 static void necp_fd_remove_stats_arena(struct necp_fd_data *fd_data, struct necp_arena_info *nai);
752 static struct necp_arena_info *necp_fd_mredirect_stats_arena(struct necp_fd_data *fd_data, struct proc *proc);
753 
754 static void necp_arena_info_retain(struct necp_arena_info *nai);
755 static void necp_arena_info_release(struct necp_arena_info *nai);
756 static struct necp_arena_info *necp_arena_info_alloc(void);
757 static void necp_arena_info_free(struct necp_arena_info *nai);
758 
759 static int necp_arena_initialize(struct necp_fd_data *fd_data, bool locked);
760 static int necp_stats_initialize(struct necp_fd_data *fd_data, struct necp_client *client,
761     struct necp_client_flow_registration *flow_registration, struct necp_stats_bufreq *bufreq);
762 static int necp_arena_create(struct necp_fd_data *fd_data, size_t obj_size, size_t obj_cnt, struct proc *p);
763 static int necp_arena_stats_obj_alloc(struct necp_fd_data *fd_data, mach_vm_offset_t *off, struct necp_arena_info **stats_arena, void **kstats_kaddr, boolean_t cansleep);
764 static void necp_arena_stats_obj_free(struct necp_fd_data *fd_data, struct necp_arena_info *stats_arena, void **kstats_kaddr, mach_vm_address_t *ustats_uaddr);
765 static void necp_stats_arenas_destroy(struct necp_fd_data *fd_data, boolean_t closing);
766 
767 static int necp_sysctl_arena_initialize(struct necp_fd_data *fd_data, bool locked);
768 static void necp_sysctl_arena_destroy(struct necp_fd_data *fd_data);
769 static void *necp_arena_sysctls_obj(struct necp_fd_data *fd_data, mach_vm_offset_t *off, size_t *size);
770 #endif /* !SKYWALK */
771 
772 void necp_copy_inp_domain_info(struct inpcb *, struct socket *, nstat_domain_info *);
773 void necp_with_inp_domain_name(struct socket *so, void *ctx, void (*with_func)(char *domain_name, void *ctx));
774 
775 static void
necp_lock_socket_attributes(void)776 necp_lock_socket_attributes(void)
777 {
778 	lck_mtx_lock(&necp_socket_attr_lock);
779 }
780 
781 static void
necp_unlock_socket_attributes(void)782 necp_unlock_socket_attributes(void)
783 {
784 	lck_mtx_unlock(&necp_socket_attr_lock);
785 }
786 
787 /// NECP file descriptor functions
788 
789 static void
necp_fd_notify(struct necp_fd_data * fd_data,bool locked)790 necp_fd_notify(struct necp_fd_data *fd_data, bool locked)
791 {
792 	struct selinfo *si = &fd_data->si;
793 
794 	if (!locked) {
795 		NECP_FD_LOCK(fd_data);
796 	}
797 
798 	selwakeup(si);
799 
800 	// use a non-zero hint to tell the notification from the
801 	// call done in kqueue_scan() which uses 0
802 	KNOTE(&si->si_note, 1); // notification
803 
804 	if (!locked) {
805 		NECP_FD_UNLOCK(fd_data);
806 	}
807 }
808 
809 static inline bool
necp_client_has_unread_flows(struct necp_client * client)810 necp_client_has_unread_flows(struct necp_client *client)
811 {
812 	NECP_CLIENT_ASSERT_LOCKED(client);
813 	struct necp_client_flow_registration *flow_registration = NULL;
814 	RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
815 		if (!flow_registration->flow_result_read) {
816 			return true;
817 		}
818 	}
819 	return false;
820 }
821 
822 static int
necp_fd_poll(struct necp_fd_data * fd_data,int events,void * wql,struct proc * p,int is_kevent)823 necp_fd_poll(struct necp_fd_data *fd_data, int events, void *wql, struct proc *p, int is_kevent)
824 {
825 #pragma unused(wql, p, is_kevent)
826 	u_int revents = 0;
827 
828 	u_int want_rx = events & (POLLIN | POLLRDNORM);
829 	if (want_rx) {
830 		if (fd_data->flags & NECP_OPEN_FLAG_PUSH_OBSERVER) {
831 			// Push-mode observers are readable when they have a new update
832 			if (!TAILQ_EMPTY(&fd_data->update_list)) {
833 				revents |= want_rx;
834 			}
835 		} else {
836 			// Standard fds are readable when some client is unread
837 			struct necp_client *client = NULL;
838 			bool has_unread_clients = FALSE;
839 			RB_FOREACH(client, _necp_client_tree, &fd_data->clients) {
840 				NECP_CLIENT_LOCK(client);
841 				if (!client->result_read || !client->group_members_read || necp_client_has_unread_flows(client)) {
842 					has_unread_clients = TRUE;
843 				}
844 				NECP_CLIENT_UNLOCK(client);
845 				if (has_unread_clients) {
846 					break;
847 				}
848 			}
849 
850 			if (has_unread_clients || fd_data->request_in_process_flow_divert) {
851 				revents |= want_rx;
852 			}
853 		}
854 	}
855 
856 	return revents;
857 }
858 
859 static inline void
necp_generate_client_id(uuid_t client_id,bool is_flow)860 necp_generate_client_id(uuid_t client_id, bool is_flow)
861 {
862 	uuid_generate_random(client_id);
863 
864 	if (is_flow) {
865 		client_id[9] |= 0x01;
866 	} else {
867 		client_id[9] &= ~0x01;
868 	}
869 }
870 
871 static inline bool
necp_client_id_is_flow(uuid_t client_id)872 necp_client_id_is_flow(uuid_t client_id)
873 {
874 	return client_id[9] & 0x01;
875 }
876 
877 static struct necp_client *
necp_find_client_and_lock(uuid_t client_id)878 necp_find_client_and_lock(uuid_t client_id)
879 {
880 	NECP_CLIENT_TREE_ASSERT_LOCKED();
881 
882 	struct necp_client *client = NULL;
883 
884 	if (necp_client_id_is_flow(client_id)) {
885 		NECP_FLOW_TREE_LOCK_SHARED();
886 		struct necp_client_flow_registration find;
887 		uuid_copy(find.registration_id, client_id);
888 		struct necp_client_flow_registration *flow = RB_FIND(_necp_client_flow_global_tree, &necp_client_flow_global_tree, &find);
889 		if (flow != NULL) {
890 			client = flow->client;
891 		}
892 		NECP_FLOW_TREE_UNLOCK();
893 	} else {
894 		struct necp_client find;
895 		uuid_copy(find.client_id, client_id);
896 		client = RB_FIND(_necp_client_global_tree, &necp_client_global_tree, &find);
897 	}
898 
899 	if (client != NULL) {
900 		NECP_CLIENT_LOCK(client);
901 	}
902 
903 	return client;
904 }
905 
906 static struct necp_client_flow_registration *
necp_client_find_flow(struct necp_client * client,uuid_t flow_id)907 necp_client_find_flow(struct necp_client *client, uuid_t flow_id)
908 {
909 	NECP_CLIENT_ASSERT_LOCKED(client);
910 	struct necp_client_flow_registration *flow = NULL;
911 
912 	if (necp_client_id_is_flow(flow_id)) {
913 		struct necp_client_flow_registration find;
914 		uuid_copy(find.registration_id, flow_id);
915 		flow = RB_FIND(_necp_client_flow_tree, &client->flow_registrations, &find);
916 	} else {
917 		flow = RB_ROOT(&client->flow_registrations);
918 	}
919 
920 	return flow;
921 }
922 
923 static struct necp_client *
necp_client_fd_find_client_unlocked(struct necp_fd_data * client_fd,uuid_t client_id)924 necp_client_fd_find_client_unlocked(struct necp_fd_data *client_fd, uuid_t client_id)
925 {
926 	NECP_FD_ASSERT_LOCKED(client_fd);
927 	struct necp_client *client = NULL;
928 
929 	if (necp_client_id_is_flow(client_id)) {
930 		struct necp_client_flow_registration find;
931 		uuid_copy(find.registration_id, client_id);
932 		struct necp_client_flow_registration *flow = RB_FIND(_necp_fd_flow_tree, &client_fd->flows, &find);
933 		if (flow != NULL) {
934 			client = flow->client;
935 		}
936 	} else {
937 		struct necp_client find;
938 		uuid_copy(find.client_id, client_id);
939 		client = RB_FIND(_necp_client_tree, &client_fd->clients, &find);
940 	}
941 
942 	return client;
943 }
944 
945 static struct necp_client *
necp_client_fd_find_client_and_lock(struct necp_fd_data * client_fd,uuid_t client_id)946 necp_client_fd_find_client_and_lock(struct necp_fd_data *client_fd, uuid_t client_id)
947 {
948 	struct necp_client *client = necp_client_fd_find_client_unlocked(client_fd, client_id);
949 	if (client != NULL) {
950 		NECP_CLIENT_LOCK(client);
951 	}
952 
953 	return client;
954 }
955 
956 static inline int
necp_client_id_cmp(struct necp_client * client0,struct necp_client * client1)957 necp_client_id_cmp(struct necp_client *client0, struct necp_client *client1)
958 {
959 	return uuid_compare(client0->client_id, client1->client_id);
960 }
961 
962 static inline int
necp_client_flow_id_cmp(struct necp_client_flow_registration * flow0,struct necp_client_flow_registration * flow1)963 necp_client_flow_id_cmp(struct necp_client_flow_registration *flow0, struct necp_client_flow_registration *flow1)
964 {
965 	return uuid_compare(flow0->registration_id, flow1->registration_id);
966 }
967 
968 static int
necpop_select(struct fileproc * fp,int which,void * wql,vfs_context_t ctx)969 necpop_select(struct fileproc *fp, int which, void *wql, vfs_context_t ctx)
970 {
971 #pragma unused(fp, which, wql, ctx)
972 	return 0;
973 	struct necp_fd_data *fd_data = NULL;
974 	int revents = 0;
975 	int events = 0;
976 	proc_t procp;
977 
978 	fd_data = (struct necp_fd_data *)fp_get_data(fp);
979 	if (fd_data == NULL) {
980 		return 0;
981 	}
982 
983 	procp = vfs_context_proc(ctx);
984 
985 	switch (which) {
986 	case FREAD: {
987 		events = POLLIN;
988 		break;
989 	}
990 
991 	default: {
992 		return 1;
993 	}
994 	}
995 
996 	NECP_FD_LOCK(fd_data);
997 	revents = necp_fd_poll(fd_data, events, wql, procp, 0);
998 	NECP_FD_UNLOCK(fd_data);
999 
1000 	return (events & revents) ? 1 : 0;
1001 }
1002 
1003 static void
necp_fd_knrdetach(struct knote * kn)1004 necp_fd_knrdetach(struct knote *kn)
1005 {
1006 	struct necp_fd_data *fd_data = (struct necp_fd_data *)knote_kn_hook_get_raw(kn);
1007 	struct selinfo *si = &fd_data->si;
1008 
1009 	NECP_FD_LOCK(fd_data);
1010 	KNOTE_DETACH(&si->si_note, kn);
1011 	NECP_FD_UNLOCK(fd_data);
1012 }
1013 
1014 static int
necp_fd_knread(struct knote * kn,long hint)1015 necp_fd_knread(struct knote *kn, long hint)
1016 {
1017 #pragma unused(kn, hint)
1018 	return 1; /* assume we are ready */
1019 }
1020 
1021 static int
necp_fd_knrprocess(struct knote * kn,struct kevent_qos_s * kev)1022 necp_fd_knrprocess(struct knote *kn, struct kevent_qos_s *kev)
1023 {
1024 	struct necp_fd_data *fd_data;
1025 	int revents;
1026 	int res;
1027 
1028 	fd_data = (struct necp_fd_data *)knote_kn_hook_get_raw(kn);
1029 
1030 	NECP_FD_LOCK(fd_data);
1031 	revents = necp_fd_poll(fd_data, POLLIN, NULL, current_proc(), 1);
1032 	res = ((revents & POLLIN) != 0);
1033 	if (res) {
1034 		knote_fill_kevent(kn, kev, 0);
1035 	}
1036 	NECP_FD_UNLOCK(fd_data);
1037 	return res;
1038 }
1039 
1040 static int
necp_fd_knrtouch(struct knote * kn,struct kevent_qos_s * kev)1041 necp_fd_knrtouch(struct knote *kn, struct kevent_qos_s *kev)
1042 {
1043 #pragma unused(kev)
1044 	struct necp_fd_data *fd_data;
1045 	int revents;
1046 
1047 	fd_data = (struct necp_fd_data *)knote_kn_hook_get_raw(kn);
1048 
1049 	NECP_FD_LOCK(fd_data);
1050 	revents = necp_fd_poll(fd_data, POLLIN, NULL, current_proc(), 1);
1051 	NECP_FD_UNLOCK(fd_data);
1052 
1053 	return (revents & POLLIN) != 0;
1054 }
1055 
1056 SECURITY_READ_ONLY_EARLY(struct filterops) necp_fd_rfiltops = {
1057 	.f_isfd = 1,
1058 	.f_detach = necp_fd_knrdetach,
1059 	.f_event = necp_fd_knread,
1060 	.f_touch = necp_fd_knrtouch,
1061 	.f_process = necp_fd_knrprocess,
1062 };
1063 
1064 static int
necpop_kqfilter(struct fileproc * fp,struct knote * kn,__unused struct kevent_qos_s * kev)1065 necpop_kqfilter(struct fileproc *fp, struct knote *kn,
1066     __unused struct kevent_qos_s *kev)
1067 {
1068 	struct necp_fd_data *fd_data = NULL;
1069 	int revents;
1070 
1071 	if (kn->kn_filter != EVFILT_READ) {
1072 		NECPLOG(LOG_ERR, "bad filter request %d", kn->kn_filter);
1073 		knote_set_error(kn, EINVAL);
1074 		return 0;
1075 	}
1076 
1077 	fd_data = (struct necp_fd_data *)fp_get_data(fp);
1078 	if (fd_data == NULL) {
1079 		NECPLOG0(LOG_ERR, "No channel for kqfilter");
1080 		knote_set_error(kn, ENOENT);
1081 		return 0;
1082 	}
1083 
1084 	NECP_FD_LOCK(fd_data);
1085 	kn->kn_filtid = EVFILTID_NECP_FD;
1086 	knote_kn_hook_set_raw(kn, fd_data);
1087 	KNOTE_ATTACH(&fd_data->si.si_note, kn);
1088 
1089 	revents = necp_fd_poll(fd_data, POLLIN, NULL, current_proc(), 1);
1090 
1091 	NECP_FD_UNLOCK(fd_data);
1092 
1093 	return (revents & POLLIN) != 0;
1094 }
1095 
1096 #define INTERFACE_FLAGS_SHIFT   32
1097 #define INTERFACE_FLAGS_MASK    0xffffffff
1098 #define INTERFACE_INDEX_SHIFT   0
1099 #define INTERFACE_INDEX_MASK    0xffffffff
1100 
1101 static uint64_t
combine_interface_details(uint32_t interface_index,uint32_t interface_flags)1102 combine_interface_details(uint32_t interface_index, uint32_t interface_flags)
1103 {
1104 	return ((uint64_t)interface_flags & INTERFACE_FLAGS_MASK) << INTERFACE_FLAGS_SHIFT |
1105 	       ((uint64_t)interface_index & INTERFACE_INDEX_MASK) << INTERFACE_INDEX_SHIFT;
1106 }
1107 
1108 #if SKYWALK
1109 
1110 static void
split_interface_details(uint64_t combined_details,uint32_t * interface_index,uint32_t * interface_flags)1111 split_interface_details(uint64_t combined_details, uint32_t *interface_index, uint32_t *interface_flags)
1112 {
1113 	*interface_index = (combined_details >> INTERFACE_INDEX_SHIFT) & INTERFACE_INDEX_MASK;
1114 	*interface_flags = (combined_details >> INTERFACE_FLAGS_SHIFT) & INTERFACE_FLAGS_MASK;
1115 }
1116 
1117 static void
necp_flow_save_current_interface_details(struct necp_client_flow_registration * flow_registration)1118 necp_flow_save_current_interface_details(struct necp_client_flow_registration *flow_registration)
1119 {
1120 	struct necp_client_flow *flow = NULL;
1121 	LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
1122 		if (flow->nexus) {
1123 			uint64_t combined_details = combine_interface_details(flow->interface_index, flow->interface_flags);
1124 			os_atomic_store(&flow_registration->last_interface_details, combined_details, release);
1125 			break;
1126 		}
1127 	}
1128 }
1129 
1130 static void
necp_client_collect_interface_stats(struct necp_client_flow_registration * flow_registration,struct ifnet_stats_per_flow * ifs)1131 necp_client_collect_interface_stats(struct necp_client_flow_registration *flow_registration, struct ifnet_stats_per_flow *ifs)
1132 {
1133 	struct necp_client_flow *flow = NULL;
1134 
1135 	if (ifs == NULL || ifs->txpackets == 0 || ifs->rxpackets == 0) {
1136 		return; // App might have crashed without publishing ifs
1137 	}
1138 
1139 	// Do malicious stats detection here
1140 
1141 	// Fold userspace stats into (trusted) kernel stats (stored in ifp).
1142 	LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
1143 		uint32_t if_idx = flow->interface_index;
1144 		ifnet_t ifp = NULL;
1145 		ifnet_head_lock_shared();
1146 		if (if_idx != IFSCOPE_NONE && if_idx <= (uint32_t)if_index) {
1147 			ifp = ifindex2ifnet[if_idx];
1148 			ifnet_update_stats_per_flow(ifs, ifp);
1149 		}
1150 		ifnet_head_done();
1151 
1152 		// Currently there is only one flow that uses the shared necp
1153 		// stats region, so this loop should exit after updating an ifp
1154 		break;
1155 	}
1156 }
1157 
1158 static void
necp_client_collect_stats(struct necp_client_flow_registration * flow_registration)1159 necp_client_collect_stats(struct necp_client_flow_registration *flow_registration)
1160 {
1161 	struct necp_all_kstats *kstats = (struct necp_all_kstats *)flow_registration->kstats_kaddr;
1162 	if (kstats == NULL) {
1163 		return;
1164 	}
1165 
1166 	// Grab userspace stats delta (untrusted).
1167 	struct necp_tcp_stats *curr_tcpstats = (struct necp_tcp_stats *)kstats->necp_stats_ustats;
1168 	struct necp_tcp_stats *prev_tcpstats = (struct necp_tcp_stats *)&kstats->necp_stats_comm;
1169 #define diff_n_update(field)    \
1170 	u_int32_t d_##field = (curr_tcpstats->necp_tcp_counts.necp_stat_##field - prev_tcpstats->necp_tcp_counts.necp_stat_##field);    \
1171 	prev_tcpstats->necp_tcp_counts.necp_stat_##field += d_##field;
1172 	diff_n_update(rxpackets);
1173 	diff_n_update(txpackets);
1174 	if (d_rxpackets == 0 && d_txpackets == 0) {
1175 		return; // no activity since last collection, stop here
1176 	}
1177 	diff_n_update(rxbytes);
1178 	diff_n_update(txbytes);
1179 	diff_n_update(rxduplicatebytes);
1180 	diff_n_update(rxoutoforderbytes);
1181 	diff_n_update(txretransmit);
1182 	diff_n_update(connectattempts);
1183 	diff_n_update(connectsuccesses);
1184 	uint32_t rtt = prev_tcpstats->necp_tcp_counts.necp_stat_avg_rtt = curr_tcpstats->necp_tcp_counts.necp_stat_avg_rtt;
1185 	uint32_t rtt_var = prev_tcpstats->necp_tcp_counts.necp_stat_var_rtt = curr_tcpstats->necp_tcp_counts.necp_stat_var_rtt;
1186 #undef diff_n_update
1187 
1188 	// Do malicious stats detection with the deltas here.
1189 	// RTT check (not necessarily attacks, might just be not measured since we report stats async periodically).
1190 	if (rtt < necp_client_stats_rtt_floor || rtt > necp_client_stats_rtt_ceiling) {
1191 		rtt = rtt_var = 0;      // nstat_route_update to skip 0 rtt
1192 	}
1193 
1194 	// Fold userspace stats into (trusted) kernel stats (stored in route).
1195 	NECP_CLIENT_ROUTE_LOCK(flow_registration->client);
1196 	struct rtentry *route = flow_registration->client->current_route;
1197 	if (route != NULL) {
1198 		nstat_route_update(route, d_connectattempts, d_connectsuccesses, d_rxpackets, d_rxbytes, d_rxduplicatebytes,
1199 		    d_rxoutoforderbytes, d_txpackets, d_txbytes, d_txretransmit, rtt, rtt_var);
1200 	}
1201 	NECP_CLIENT_ROUTE_UNLOCK(flow_registration->client);
1202 }
1203 
1204 // This is called from various places; "closing" here implies the client being closed/removed if true, otherwise being
1205 // defunct.  In the former, we expect the caller to not hold the lock; for the latter it must have acquired it.
1206 static void
necp_destroy_flow_stats(struct necp_fd_data * fd_data,struct necp_client_flow_registration * flow_registration,struct ifnet_stats_per_flow * flow_ifnet_stats,boolean_t closing)1207 necp_destroy_flow_stats(struct necp_fd_data *fd_data,
1208     struct necp_client_flow_registration *flow_registration,
1209     struct ifnet_stats_per_flow *flow_ifnet_stats,
1210     boolean_t closing)
1211 {
1212 	NECP_FD_ASSERT_LOCKED(fd_data);
1213 
1214 	struct necp_client *client = flow_registration->client;
1215 
1216 	if (closing) {
1217 		NECP_CLIENT_ASSERT_UNLOCKED(client);
1218 		NECP_CLIENT_LOCK(client);
1219 	} else {
1220 		NECP_CLIENT_ASSERT_LOCKED(client);
1221 	}
1222 
1223 	// the interface stats are independent of the flow stats, hence we check here
1224 	if (flow_ifnet_stats != NULL) {
1225 		necp_client_collect_interface_stats(flow_registration, flow_ifnet_stats);
1226 	}
1227 
1228 	if (flow_registration->kstats_kaddr != NULL) {
1229 		NECP_STATS_LIST_LOCK_EXCLUSIVE();
1230 		necp_client_collect_stats(flow_registration);
1231 		const bool destroyed = necp_client_release_locked(client); // Drop the reference held by the stats list
1232 		ASSERT(!destroyed);
1233 		(void)destroyed;
1234 		LIST_REMOVE(flow_registration, collect_stats_chain);
1235 		NECP_STATS_LIST_UNLOCK();
1236 		if (flow_registration->stats_handler_context != NULL) {
1237 			ntstat_userland_stats_close(flow_registration->stats_handler_context);
1238 			flow_registration->stats_handler_context = NULL;
1239 		}
1240 		necp_arena_stats_obj_free(fd_data, flow_registration->stats_arena, &flow_registration->kstats_kaddr, &flow_registration->ustats_uaddr);
1241 		ASSERT(flow_registration->kstats_kaddr == NULL);
1242 		ASSERT(flow_registration->ustats_uaddr == 0);
1243 	}
1244 
1245 	if (flow_registration->nexus_stats != NULL) {
1246 		flow_stats_release(flow_registration->nexus_stats);
1247 		flow_registration->nexus_stats = NULL;
1248 	}
1249 
1250 	if (closing) {
1251 		NECP_CLIENT_UNLOCK(client);
1252 	}
1253 }
1254 
1255 static void
necp_schedule_collect_stats_clients(bool recur)1256 necp_schedule_collect_stats_clients(bool recur)
1257 {
1258 	if (necp_client_collect_stats_tcall == NULL ||
1259 	    (!recur && thread_call_isactive(necp_client_collect_stats_tcall))) {
1260 		return;
1261 	}
1262 
1263 	uint64_t deadline = 0;
1264 	uint64_t leeway = 0;
1265 	clock_interval_to_deadline(necp_collect_stats_timeout_microseconds, NSEC_PER_USEC, &deadline);
1266 	clock_interval_to_absolutetime_interval(necp_collect_stats_timeout_leeway_microseconds, NSEC_PER_USEC, &leeway);
1267 
1268 	thread_call_enter_delayed_with_leeway(necp_client_collect_stats_tcall, NULL,
1269 	    deadline, leeway, THREAD_CALL_DELAY_LEEWAY);
1270 }
1271 
1272 static void
necp_collect_stats_client_callout(__unused thread_call_param_t dummy,__unused thread_call_param_t arg)1273 necp_collect_stats_client_callout(__unused thread_call_param_t dummy,
1274     __unused thread_call_param_t arg)
1275 {
1276 	struct necp_client_flow_registration *flow_registration;
1277 
1278 	net_update_uptime();
1279 	NECP_STATS_LIST_LOCK_SHARED();
1280 	if (LIST_EMPTY(&necp_collect_stats_flow_list)) {
1281 		NECP_STATS_LIST_UNLOCK();
1282 		return;
1283 	}
1284 	LIST_FOREACH(flow_registration, &necp_collect_stats_flow_list, collect_stats_chain) {
1285 		// Collecting stats should be cheap (atomic increments)
1286 		// Values like flow_registration->kstats_kaddr are guaranteed to be valid
1287 		// as long as the flow_registration is in the stats list
1288 		necp_client_collect_stats(flow_registration);
1289 	}
1290 	NECP_STATS_LIST_UNLOCK();
1291 
1292 	necp_schedule_collect_stats_clients(TRUE); // recurring collection
1293 }
1294 
1295 #endif /* !SKYWALK */
1296 
1297 static void
necp_defunct_flow_registration(struct necp_client * client,struct necp_client_flow_registration * flow_registration,struct _necp_flow_defunct_list * defunct_list)1298 necp_defunct_flow_registration(struct necp_client *client,
1299     struct necp_client_flow_registration *flow_registration,
1300     struct _necp_flow_defunct_list *defunct_list)
1301 {
1302 	NECP_CLIENT_ASSERT_LOCKED(client);
1303 
1304 	if (!flow_registration->defunct) {
1305 		bool needs_defunct = false;
1306 		struct necp_client_flow *search_flow = NULL;
1307 		LIST_FOREACH(search_flow, &flow_registration->flow_list, flow_chain) {
1308 			if (search_flow->nexus &&
1309 			    !uuid_is_null(search_flow->u.nexus_agent)) {
1310 				// Save defunct values for the nexus
1311 				if (defunct_list != NULL) {
1312 					// Sleeping alloc won't fail; copy only what's necessary
1313 					struct necp_flow_defunct *flow_defunct = kalloc_type(struct necp_flow_defunct,
1314 					    Z_WAITOK | Z_ZERO);
1315 					uuid_copy(flow_defunct->nexus_agent, search_flow->u.nexus_agent);
1316 					uuid_copy(flow_defunct->flow_id, ((flow_registration->flags & NECP_CLIENT_FLOW_FLAGS_USE_CLIENT_ID) ?
1317 					    client->client_id :
1318 					    flow_registration->registration_id));
1319 					flow_defunct->proc_pid = client->proc_pid;
1320 					flow_defunct->agent_handle = client->agent_handle;
1321 					flow_defunct->flags = flow_registration->flags;
1322 #if SKYWALK
1323 					if (flow_registration->kstats_kaddr != NULL) {
1324 						struct necp_all_stats *ustats_kaddr = ((struct necp_all_kstats *)flow_registration->kstats_kaddr)->necp_stats_ustats;
1325 						struct necp_quic_stats *quicstats = (struct necp_quic_stats *)ustats_kaddr;
1326 						if (quicstats != NULL) {
1327 							memcpy(flow_defunct->close_parameters.u.close_token, quicstats->necp_quic_extra.ssr_token, sizeof(flow_defunct->close_parameters.u.close_token));
1328 							flow_defunct->has_close_parameters = true;
1329 						}
1330 					}
1331 #endif /* SKYWALK */
1332 					// Add to the list provided by caller
1333 					LIST_INSERT_HEAD(defunct_list, flow_defunct, chain);
1334 				}
1335 
1336 				needs_defunct = true;
1337 			}
1338 		}
1339 
1340 		if (needs_defunct) {
1341 #if SKYWALK
1342 			// Close the stats early
1343 			if (flow_registration->stats_handler_context != NULL) {
1344 				ntstat_userland_stats_event(flow_registration->stats_handler_context,
1345 				    NECP_CLIENT_STATISTICS_EVENT_TIME_WAIT);
1346 			}
1347 #endif /* SKYWALK */
1348 
1349 			// Only set defunct if there was some assigned flow
1350 			flow_registration->defunct = true;
1351 		}
1352 	}
1353 }
1354 
1355 static void
necp_defunct_client_for_policy(struct necp_client * client,struct _necp_flow_defunct_list * defunct_list)1356 necp_defunct_client_for_policy(struct necp_client *client,
1357     struct _necp_flow_defunct_list *defunct_list)
1358 {
1359 	NECP_CLIENT_ASSERT_LOCKED(client);
1360 
1361 	struct necp_client_flow_registration *flow_registration = NULL;
1362 	RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
1363 		necp_defunct_flow_registration(client, flow_registration, defunct_list);
1364 	}
1365 }
1366 
1367 static void
necp_client_free(struct necp_client * client)1368 necp_client_free(struct necp_client *client)
1369 {
1370 	NECP_CLIENT_ASSERT_UNLOCKED(client);
1371 
1372 	kfree_data(client->extra_interface_options,
1373 	    sizeof(struct necp_client_interface_option) * NECP_CLIENT_INTERFACE_OPTION_EXTRA_COUNT);
1374 	client->extra_interface_options = NULL;
1375 
1376 	kfree_data(client->parameters, client->parameters_length);
1377 	client->parameters = NULL;
1378 
1379 	kfree_data(client->assigned_group_members, client->assigned_group_members_length);
1380 	client->assigned_group_members = NULL;
1381 
1382 	lck_mtx_destroy(&client->route_lock, &necp_fd_mtx_grp);
1383 	lck_mtx_destroy(&client->lock, &necp_fd_mtx_grp);
1384 
1385 	kfree_type(struct necp_client, client);
1386 }
1387 
1388 static void
necp_client_retain_locked(struct necp_client * client)1389 necp_client_retain_locked(struct necp_client *client)
1390 {
1391 	NECP_CLIENT_ASSERT_LOCKED(client);
1392 
1393 	os_ref_retain_locked(&client->reference_count);
1394 }
1395 
1396 static void
necp_client_retain(struct necp_client * client)1397 necp_client_retain(struct necp_client *client)
1398 {
1399 	NECP_CLIENT_LOCK(client);
1400 	necp_client_retain_locked(client);
1401 	NECP_CLIENT_UNLOCK(client);
1402 }
1403 
1404 static bool
necp_client_release_locked(struct necp_client * client)1405 necp_client_release_locked(struct necp_client *client)
1406 {
1407 	NECP_CLIENT_ASSERT_LOCKED(client);
1408 
1409 	os_ref_count_t count = os_ref_release_locked(&client->reference_count);
1410 	if (count == 0) {
1411 		NECP_CLIENT_UNLOCK(client);
1412 		necp_client_free(client);
1413 	}
1414 
1415 	return count == 0;
1416 }
1417 
1418 static bool
necp_client_release(struct necp_client * client)1419 necp_client_release(struct necp_client *client)
1420 {
1421 	bool last_ref;
1422 
1423 	NECP_CLIENT_LOCK(client);
1424 	if (!(last_ref = necp_client_release_locked(client))) {
1425 		NECP_CLIENT_UNLOCK(client);
1426 	}
1427 
1428 	return last_ref;
1429 }
1430 
1431 static struct necp_client_update *
necp_client_update_alloc(const void * data,size_t length)1432 necp_client_update_alloc(const void *data, size_t length)
1433 {
1434 	struct necp_client_update *client_update;
1435 	struct necp_client_observer_update *buffer;
1436 	size_t alloc_size;
1437 
1438 	if (os_add_overflow(length, sizeof(*buffer), &alloc_size)) {
1439 		return NULL;
1440 	}
1441 	buffer = kalloc_data(alloc_size, Z_WAITOK);
1442 	if (buffer == NULL) {
1443 		return NULL;
1444 	}
1445 
1446 	client_update = kalloc_type(struct necp_client_update,
1447 	    Z_WAITOK | Z_ZERO | Z_NOFAIL);
1448 	client_update->update_length = alloc_size;
1449 	client_update->update = buffer;
1450 	memcpy(buffer->tlv_buffer, data, length);
1451 	return client_update;
1452 }
1453 
1454 static void
necp_client_update_free(struct necp_client_update * client_update)1455 necp_client_update_free(struct necp_client_update *client_update)
1456 {
1457 	kfree_data(client_update->update, client_update->update_length);
1458 	kfree_type(struct necp_client_update, client_update);
1459 }
1460 
1461 static void
necp_client_update_observer_add_internal(struct necp_fd_data * observer_fd,struct necp_client * client)1462 necp_client_update_observer_add_internal(struct necp_fd_data *observer_fd, struct necp_client *client)
1463 {
1464 	struct necp_client_update *client_update;
1465 
1466 	NECP_FD_LOCK(observer_fd);
1467 
1468 	if (observer_fd->update_count >= necp_observer_message_limit) {
1469 		NECP_FD_UNLOCK(observer_fd);
1470 		return;
1471 	}
1472 
1473 	client_update = necp_client_update_alloc(client->parameters, client->parameters_length);
1474 	if (client_update != NULL) {
1475 		uuid_copy(client_update->client_id, client->client_id);
1476 		client_update->update->update_type = NECP_CLIENT_UPDATE_TYPE_PARAMETERS;
1477 		TAILQ_INSERT_TAIL(&observer_fd->update_list, client_update, chain);
1478 		observer_fd->update_count++;
1479 
1480 		necp_fd_notify(observer_fd, true);
1481 	}
1482 
1483 	NECP_FD_UNLOCK(observer_fd);
1484 }
1485 
1486 static void
necp_client_update_observer_update_internal(struct necp_fd_data * observer_fd,struct necp_client * client)1487 necp_client_update_observer_update_internal(struct necp_fd_data *observer_fd, struct necp_client *client)
1488 {
1489 	NECP_FD_LOCK(observer_fd);
1490 
1491 	if (observer_fd->update_count >= necp_observer_message_limit) {
1492 		NECP_FD_UNLOCK(observer_fd);
1493 		return;
1494 	}
1495 
1496 	struct necp_client_update *client_update = necp_client_update_alloc(client->result, client->result_length);
1497 	if (client_update != NULL) {
1498 		uuid_copy(client_update->client_id, client->client_id);
1499 		client_update->update->update_type = NECP_CLIENT_UPDATE_TYPE_RESULT;
1500 		TAILQ_INSERT_TAIL(&observer_fd->update_list, client_update, chain);
1501 		observer_fd->update_count++;
1502 
1503 		necp_fd_notify(observer_fd, true);
1504 	}
1505 
1506 	NECP_FD_UNLOCK(observer_fd);
1507 }
1508 
1509 static void
necp_client_update_observer_remove_internal(struct necp_fd_data * observer_fd,struct necp_client * client)1510 necp_client_update_observer_remove_internal(struct necp_fd_data *observer_fd, struct necp_client *client)
1511 {
1512 	NECP_FD_LOCK(observer_fd);
1513 
1514 	if (observer_fd->update_count >= necp_observer_message_limit) {
1515 		NECP_FD_UNLOCK(observer_fd);
1516 		return;
1517 	}
1518 
1519 	struct necp_client_update *client_update = necp_client_update_alloc(NULL, 0);
1520 	if (client_update != NULL) {
1521 		uuid_copy(client_update->client_id, client->client_id);
1522 		client_update->update->update_type = NECP_CLIENT_UPDATE_TYPE_REMOVE;
1523 		TAILQ_INSERT_TAIL(&observer_fd->update_list, client_update, chain);
1524 		observer_fd->update_count++;
1525 
1526 		necp_fd_notify(observer_fd, true);
1527 	}
1528 
1529 	NECP_FD_UNLOCK(observer_fd);
1530 }
1531 
1532 static void
necp_client_update_observer_add(struct necp_client * client)1533 necp_client_update_observer_add(struct necp_client *client)
1534 {
1535 	NECP_OBSERVER_LIST_LOCK_SHARED();
1536 
1537 	if (LIST_EMPTY(&necp_fd_observer_list)) {
1538 		// No observers, bail
1539 		NECP_OBSERVER_LIST_UNLOCK();
1540 		return;
1541 	}
1542 
1543 	struct necp_fd_data *observer_fd = NULL;
1544 	LIST_FOREACH(observer_fd, &necp_fd_observer_list, chain) {
1545 		necp_client_update_observer_add_internal(observer_fd, client);
1546 	}
1547 
1548 	NECP_OBSERVER_LIST_UNLOCK();
1549 }
1550 
1551 static void
necp_client_update_observer_update(struct necp_client * client)1552 necp_client_update_observer_update(struct necp_client *client)
1553 {
1554 	NECP_OBSERVER_LIST_LOCK_SHARED();
1555 
1556 	if (LIST_EMPTY(&necp_fd_observer_list)) {
1557 		// No observers, bail
1558 		NECP_OBSERVER_LIST_UNLOCK();
1559 		return;
1560 	}
1561 
1562 	struct necp_fd_data *observer_fd = NULL;
1563 	LIST_FOREACH(observer_fd, &necp_fd_observer_list, chain) {
1564 		necp_client_update_observer_update_internal(observer_fd, client);
1565 	}
1566 
1567 	NECP_OBSERVER_LIST_UNLOCK();
1568 }
1569 
1570 static void
necp_client_update_observer_remove(struct necp_client * client)1571 necp_client_update_observer_remove(struct necp_client *client)
1572 {
1573 	NECP_OBSERVER_LIST_LOCK_SHARED();
1574 
1575 	if (LIST_EMPTY(&necp_fd_observer_list)) {
1576 		// No observers, bail
1577 		NECP_OBSERVER_LIST_UNLOCK();
1578 		return;
1579 	}
1580 
1581 	struct necp_fd_data *observer_fd = NULL;
1582 	LIST_FOREACH(observer_fd, &necp_fd_observer_list, chain) {
1583 		necp_client_update_observer_remove_internal(observer_fd, client);
1584 	}
1585 
1586 	NECP_OBSERVER_LIST_UNLOCK();
1587 }
1588 
1589 static void
necp_destroy_client_flow_registration(struct necp_client * client,struct necp_client_flow_registration * flow_registration,pid_t pid,bool abort)1590 necp_destroy_client_flow_registration(struct necp_client *client,
1591     struct necp_client_flow_registration *flow_registration,
1592     pid_t pid, bool abort)
1593 {
1594 	NECP_CLIENT_ASSERT_LOCKED(client);
1595 
1596 	bool has_close_parameters = false;
1597 	struct necp_client_agent_parameters close_parameters = {};
1598 	memset(close_parameters.u.close_token, 0, sizeof(close_parameters.u.close_token));
1599 #if SKYWALK
1600 	if (flow_registration->kstats_kaddr != NULL) {
1601 		struct necp_all_stats *ustats_kaddr = ((struct necp_all_kstats *)flow_registration->kstats_kaddr)->necp_stats_ustats;
1602 		struct necp_quic_stats *quicstats = (struct necp_quic_stats *)ustats_kaddr;
1603 		if (quicstats != NULL &&
1604 		    quicstats->necp_quic_udp_stats.necp_udp_hdr.necp_stats_type == NECP_CLIENT_STATISTICS_TYPE_QUIC) {
1605 			memcpy(close_parameters.u.close_token, quicstats->necp_quic_extra.ssr_token, sizeof(close_parameters.u.close_token));
1606 			has_close_parameters = true;
1607 		}
1608 	}
1609 
1610 	// Release reference held on the stats arena
1611 	if (flow_registration->stats_arena != NULL) {
1612 		necp_arena_info_release(flow_registration->stats_arena);
1613 		flow_registration->stats_arena = NULL;
1614 	}
1615 #endif /* SKYWALK */
1616 
1617 	struct necp_client_flow *search_flow = NULL;
1618 	struct necp_client_flow *temp_flow = NULL;
1619 	LIST_FOREACH_SAFE(search_flow, &flow_registration->flow_list, flow_chain, temp_flow) {
1620 		if (search_flow->nexus &&
1621 		    !uuid_is_null(search_flow->u.nexus_agent)) {
1622 			// Don't unregister for defunct flows
1623 			if (!flow_registration->defunct) {
1624 				u_int8_t message_type = (abort ? NETAGENT_MESSAGE_TYPE_ABORT_NEXUS :
1625 				    NETAGENT_MESSAGE_TYPE_CLOSE_NEXUS);
1626 				if (((flow_registration->flags & NECP_CLIENT_FLOW_FLAGS_BROWSE) ||
1627 				    (flow_registration->flags & NECP_CLIENT_FLOW_FLAGS_RESOLVE)) &&
1628 				    !(flow_registration->flags & NECP_CLIENT_FLOW_FLAGS_ALLOW_NEXUS)) {
1629 					message_type = NETAGENT_MESSAGE_TYPE_CLIENT_UNASSERT;
1630 				}
1631 				int netagent_error = netagent_client_message_with_params(search_flow->u.nexus_agent,
1632 				    ((flow_registration->flags & NECP_CLIENT_FLOW_FLAGS_USE_CLIENT_ID) ?
1633 				    client->client_id :
1634 				    flow_registration->registration_id),
1635 				    pid, client->agent_handle,
1636 				    message_type,
1637 				    has_close_parameters ? &close_parameters : NULL,
1638 				    NULL, 0);
1639 				if (netagent_error != 0 && netagent_error != ENOENT) {
1640 					NECPLOG(LOG_ERR, "necp_client_remove close nexus error (%d) MESSAGE TYPE %u", netagent_error, message_type);
1641 				}
1642 			}
1643 			uuid_clear(search_flow->u.nexus_agent);
1644 		}
1645 		if (search_flow->assigned_results != NULL) {
1646 			kfree_data(search_flow->assigned_results, search_flow->assigned_results_length);
1647 			search_flow->assigned_results = NULL;
1648 		}
1649 		LIST_REMOVE(search_flow, flow_chain);
1650 #if SKYWALK
1651 		if (search_flow->nexus) {
1652 			OSDecrementAtomic(&necp_nexus_flow_count);
1653 		} else
1654 #endif /* SKYWALK */
1655 		if (search_flow->socket) {
1656 			OSDecrementAtomic(&necp_socket_flow_count);
1657 		} else {
1658 			OSDecrementAtomic(&necp_if_flow_count);
1659 		}
1660 		kfree_type(struct necp_client_flow, search_flow);
1661 	}
1662 
1663 	RB_REMOVE(_necp_client_flow_tree, &client->flow_registrations, flow_registration);
1664 	flow_registration->client = NULL;
1665 
1666 	kfree_type(struct necp_client_flow_registration, flow_registration);
1667 }
1668 
1669 static void
necp_destroy_client(struct necp_client * client,pid_t pid,bool abort)1670 necp_destroy_client(struct necp_client *client, pid_t pid, bool abort)
1671 {
1672 	NECP_CLIENT_ASSERT_UNLOCKED(client);
1673 
1674 #if SKYWALK
1675 	if (client->nstat_context != NULL) {
1676 		// This is a catch-all that should be rarely used.
1677 		nstat_provider_stats_close(client->nstat_context);
1678 		client->nstat_context = NULL;
1679 	}
1680 	if (client->original_parameters_source != NULL) {
1681 		necp_client_release(client->original_parameters_source);
1682 		client->original_parameters_source = NULL;
1683 	}
1684 #endif /* SKYWALK */
1685 	necp_client_update_observer_remove(client);
1686 
1687 	NECP_CLIENT_LOCK(client);
1688 
1689 	// Free route
1690 	NECP_CLIENT_ROUTE_LOCK(client);
1691 	if (client->current_route != NULL) {
1692 		rtfree(client->current_route);
1693 		client->current_route = NULL;
1694 	}
1695 	NECP_CLIENT_ROUTE_UNLOCK(client);
1696 
1697 	// Remove flow assignments
1698 	struct necp_client_flow_registration *flow_registration = NULL;
1699 	struct necp_client_flow_registration *temp_flow_registration = NULL;
1700 	RB_FOREACH_SAFE(flow_registration, _necp_client_flow_tree, &client->flow_registrations, temp_flow_registration) {
1701 		necp_destroy_client_flow_registration(client, flow_registration, pid, abort);
1702 	}
1703 
1704 #if SKYWALK
1705 	// Remove port reservation
1706 	if (NETNS_TOKEN_VALID(&client->port_reservation)) {
1707 		netns_release(&client->port_reservation);
1708 	}
1709 #endif /* !SKYWALK */
1710 
1711 	// Remove agent assertions
1712 	struct necp_client_assertion *search_assertion = NULL;
1713 	struct necp_client_assertion *temp_assertion = NULL;
1714 	LIST_FOREACH_SAFE(search_assertion, &client->assertion_list, assertion_chain, temp_assertion) {
1715 		int netagent_error = netagent_client_message(search_assertion->asserted_netagent, client->client_id, pid,
1716 		    client->agent_handle, NETAGENT_MESSAGE_TYPE_CLIENT_UNASSERT);
1717 		if (netagent_error != 0) {
1718 			NECPLOG((netagent_error == ENOENT ? LOG_DEBUG : LOG_ERR),
1719 			    "necp_client_remove unassert agent error (%d)", netagent_error);
1720 		}
1721 		LIST_REMOVE(search_assertion, assertion_chain);
1722 		kfree_type(struct necp_client_assertion, search_assertion);
1723 	}
1724 
1725 	if (!necp_client_release_locked(client)) {
1726 		NECP_CLIENT_UNLOCK(client);
1727 	}
1728 
1729 	OSDecrementAtomic(&necp_client_count);
1730 }
1731 
1732 static bool
1733 necp_defunct_client_fd_locked_inner(struct necp_fd_data *client_fd, struct _necp_flow_defunct_list *defunct_list, bool destroy_stats);
1734 
1735 static void
necp_process_defunct_list(struct _necp_flow_defunct_list * defunct_list)1736 necp_process_defunct_list(struct _necp_flow_defunct_list *defunct_list)
1737 {
1738 	if (!LIST_EMPTY(defunct_list)) {
1739 		struct necp_flow_defunct *flow_defunct = NULL;
1740 		struct necp_flow_defunct *temp_flow_defunct = NULL;
1741 
1742 		// For each newly defunct client, send a message to the nexus to remove the flow
1743 		LIST_FOREACH_SAFE(flow_defunct, defunct_list, chain, temp_flow_defunct) {
1744 			if (!uuid_is_null(flow_defunct->nexus_agent)) {
1745 				u_int8_t message_type = NETAGENT_MESSAGE_TYPE_ABORT_NEXUS;
1746 				if (((flow_defunct->flags & NECP_CLIENT_FLOW_FLAGS_BROWSE) ||
1747 				    (flow_defunct->flags & NECP_CLIENT_FLOW_FLAGS_RESOLVE)) &&
1748 				    !(flow_defunct->flags & NECP_CLIENT_FLOW_FLAGS_ALLOW_NEXUS)) {
1749 					message_type = NETAGENT_MESSAGE_TYPE_CLIENT_UNASSERT;
1750 				}
1751 				int netagent_error = netagent_client_message_with_params(flow_defunct->nexus_agent,
1752 				    flow_defunct->flow_id,
1753 				    flow_defunct->proc_pid,
1754 				    flow_defunct->agent_handle,
1755 				    message_type,
1756 				    flow_defunct->has_close_parameters ? &flow_defunct->close_parameters : NULL,
1757 				    NULL, 0);
1758 				if (netagent_error != 0) {
1759 					char namebuf[MAXCOMLEN + 1];
1760 					(void) strlcpy(namebuf, "unknown", sizeof(namebuf));
1761 					proc_name(flow_defunct->proc_pid, namebuf, sizeof(namebuf));
1762 					NECPLOG((netagent_error == ENOENT ? LOG_DEBUG : LOG_ERR), "necp_update_client abort nexus error (%d) for pid %d %s", netagent_error, flow_defunct->proc_pid, namebuf);
1763 				}
1764 			}
1765 			LIST_REMOVE(flow_defunct, chain);
1766 			kfree_type(struct necp_flow_defunct, flow_defunct);
1767 		}
1768 	}
1769 	ASSERT(LIST_EMPTY(defunct_list));
1770 }
1771 
1772 static int
necpop_close(struct fileglob * fg,vfs_context_t ctx)1773 necpop_close(struct fileglob *fg, vfs_context_t ctx)
1774 {
1775 #pragma unused(ctx)
1776 	struct necp_fd_data *fd_data = NULL;
1777 	int error = 0;
1778 
1779 	fd_data = (struct necp_fd_data *)fg_get_data(fg);
1780 	fg_set_data(fg, NULL);
1781 
1782 	if (fd_data != NULL) {
1783 		struct _necp_client_tree clients_to_close;
1784 		RB_INIT(&clients_to_close);
1785 
1786 		// Remove from list quickly
1787 		if (fd_data->flags & NECP_OPEN_FLAG_PUSH_OBSERVER) {
1788 			NECP_OBSERVER_LIST_LOCK_EXCLUSIVE();
1789 			LIST_REMOVE(fd_data, chain);
1790 			NECP_OBSERVER_LIST_UNLOCK();
1791 		} else {
1792 			NECP_FD_LIST_LOCK_EXCLUSIVE();
1793 			LIST_REMOVE(fd_data, chain);
1794 			NECP_FD_LIST_UNLOCK();
1795 		}
1796 
1797 		NECP_FD_LOCK(fd_data);
1798 		pid_t pid = fd_data->proc_pid;
1799 
1800 		struct _necp_flow_defunct_list defunct_list;
1801 		LIST_INIT(&defunct_list);
1802 
1803 		(void)necp_defunct_client_fd_locked_inner(fd_data, &defunct_list, false);
1804 
1805 		struct necp_client_flow_registration *flow_registration = NULL;
1806 		struct necp_client_flow_registration *temp_flow_registration = NULL;
1807 		RB_FOREACH_SAFE(flow_registration, _necp_fd_flow_tree, &fd_data->flows, temp_flow_registration) {
1808 #if SKYWALK
1809 			necp_destroy_flow_stats(fd_data, flow_registration, NULL, TRUE);
1810 #endif /* SKYWALK */
1811 			NECP_FLOW_TREE_LOCK_EXCLUSIVE();
1812 			RB_REMOVE(_necp_client_flow_global_tree, &necp_client_flow_global_tree, flow_registration);
1813 			NECP_FLOW_TREE_UNLOCK();
1814 			RB_REMOVE(_necp_fd_flow_tree, &fd_data->flows, flow_registration);
1815 		}
1816 
1817 		struct necp_client *client = NULL;
1818 		struct necp_client *temp_client = NULL;
1819 		RB_FOREACH_SAFE(client, _necp_client_tree, &fd_data->clients, temp_client) {
1820 			// Clear out the agent_handle to avoid dangling pointers back to fd_data
1821 			NECP_CLIENT_LOCK(client);
1822 			client->agent_handle = NULL;
1823 			NECP_CLIENT_UNLOCK(client);
1824 
1825 			NECP_CLIENT_TREE_LOCK_EXCLUSIVE();
1826 			RB_REMOVE(_necp_client_global_tree, &necp_client_global_tree, client);
1827 			NECP_CLIENT_TREE_UNLOCK();
1828 			RB_REMOVE(_necp_client_tree, &fd_data->clients, client);
1829 			RB_INSERT(_necp_client_tree, &clients_to_close, client);
1830 		}
1831 
1832 		struct necp_client_update *client_update = NULL;
1833 		struct necp_client_update *temp_update = NULL;
1834 		TAILQ_FOREACH_SAFE(client_update, &fd_data->update_list, chain, temp_update) {
1835 			// Flush pending updates
1836 			TAILQ_REMOVE(&fd_data->update_list, client_update, chain);
1837 			necp_client_update_free(client_update);
1838 		}
1839 		fd_data->update_count = 0;
1840 
1841 #if SKYWALK
1842 		// Cleanup stats arena(s); indicate that we're closing
1843 		necp_stats_arenas_destroy(fd_data, TRUE);
1844 		ASSERT(fd_data->stats_arena_active == NULL);
1845 		ASSERT(LIST_EMPTY(&fd_data->stats_arena_list));
1846 
1847 		// Cleanup systctl arena
1848 		necp_sysctl_arena_destroy(fd_data);
1849 		ASSERT(fd_data->sysctl_arena == NULL);
1850 #endif /* SKYWALK */
1851 
1852 		NECP_FD_UNLOCK(fd_data);
1853 
1854 		selthreadclear(&fd_data->si);
1855 
1856 		lck_mtx_destroy(&fd_data->fd_lock, &necp_fd_mtx_grp);
1857 
1858 		if (fd_data->flags & NECP_OPEN_FLAG_PUSH_OBSERVER) {
1859 			OSDecrementAtomic(&necp_observer_fd_count);
1860 		} else {
1861 			OSDecrementAtomic(&necp_client_fd_count);
1862 		}
1863 
1864 		kfree_type(struct necp_fd_data, fd_data);
1865 
1866 		RB_FOREACH_SAFE(client, _necp_client_tree, &clients_to_close, temp_client) {
1867 			RB_REMOVE(_necp_client_tree, &clients_to_close, client);
1868 			necp_destroy_client(client, pid, true);
1869 		}
1870 
1871 		necp_process_defunct_list(&defunct_list);
1872 	}
1873 
1874 	return error;
1875 }
1876 
1877 /// NECP client utilities
1878 
1879 static inline bool
necp_address_is_wildcard(const union necp_sockaddr_union * const addr)1880 necp_address_is_wildcard(const union necp_sockaddr_union * const addr)
1881 {
1882 	return (addr->sa.sa_family == AF_INET && addr->sin.sin_addr.s_addr == INADDR_ANY) ||
1883 	       (addr->sa.sa_family == AF_INET6 && IN6_IS_ADDR_UNSPECIFIED(&addr->sin6.sin6_addr));
1884 }
1885 
1886 static int
necp_find_fd_data(struct proc * p,int fd,struct fileproc ** fpp,struct necp_fd_data ** fd_data)1887 necp_find_fd_data(struct proc *p, int fd,
1888     struct fileproc **fpp, struct necp_fd_data **fd_data)
1889 {
1890 	struct fileproc *fp;
1891 	int error = fp_get_ftype(p, fd, DTYPE_NETPOLICY, ENODEV, &fp);
1892 
1893 	if (error == 0) {
1894 		*fd_data = (struct necp_fd_data *)fp_get_data(fp);
1895 		*fpp = fp;
1896 
1897 		if ((*fd_data)->necp_fd_type != necp_fd_type_client) {
1898 			// Not a client fd, ignore
1899 			fp_drop(p, fd, fp, 0);
1900 			error = EINVAL;
1901 		}
1902 	}
1903 	return error;
1904 }
1905 
1906 static void
necp_client_add_nexus_flow(struct necp_client_flow_registration * flow_registration,uuid_t nexus_agent,uint32_t interface_index,uint32_t interface_flags)1907 necp_client_add_nexus_flow(struct necp_client_flow_registration *flow_registration,
1908     uuid_t nexus_agent,
1909     uint32_t interface_index,
1910     uint32_t interface_flags)
1911 {
1912 	struct necp_client_flow *new_flow = kalloc_type(struct necp_client_flow, Z_WAITOK | Z_ZERO | Z_NOFAIL);
1913 
1914 	new_flow->nexus = TRUE;
1915 	uuid_copy(new_flow->u.nexus_agent, nexus_agent);
1916 	new_flow->interface_index = interface_index;
1917 	new_flow->interface_flags = interface_flags;
1918 	new_flow->check_tcp_heuristics = TRUE;
1919 
1920 #if SKYWALK
1921 	OSIncrementAtomic(&necp_nexus_flow_count);
1922 #endif /* SKYWALK */
1923 
1924 	LIST_INSERT_HEAD(&flow_registration->flow_list, new_flow, flow_chain);
1925 
1926 #if SKYWALK
1927 	necp_flow_save_current_interface_details(flow_registration);
1928 #endif /* SKYWALK */
1929 }
1930 
1931 static void
necp_client_add_nexus_flow_if_needed(struct necp_client_flow_registration * flow_registration,uuid_t nexus_agent,uint32_t interface_index)1932 necp_client_add_nexus_flow_if_needed(struct necp_client_flow_registration *flow_registration,
1933     uuid_t nexus_agent,
1934     uint32_t interface_index)
1935 {
1936 	struct necp_client_flow *flow = NULL;
1937 	LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
1938 		if (flow->nexus &&
1939 		    uuid_compare(flow->u.nexus_agent, nexus_agent) == 0) {
1940 			return;
1941 		}
1942 	}
1943 
1944 	uint32_t interface_flags = 0;
1945 	ifnet_t ifp = NULL;
1946 	ifnet_head_lock_shared();
1947 	if (interface_index != IFSCOPE_NONE && interface_index <= (u_int32_t)if_index) {
1948 		ifp = ifindex2ifnet[interface_index];
1949 		if (ifp != NULL) {
1950 			ifnet_lock_shared(ifp);
1951 			interface_flags = nstat_ifnet_to_flags(ifp);
1952 			ifnet_lock_done(ifp);
1953 		}
1954 	}
1955 	ifnet_head_done();
1956 	necp_client_add_nexus_flow(flow_registration, nexus_agent, interface_index, interface_flags);
1957 }
1958 
1959 static struct necp_client_flow *
necp_client_add_interface_flow(struct necp_client_flow_registration * flow_registration,uint32_t interface_index)1960 necp_client_add_interface_flow(struct necp_client_flow_registration *flow_registration,
1961     uint32_t interface_index)
1962 {
1963 	struct necp_client_flow *new_flow = kalloc_type(struct necp_client_flow, Z_WAITOK | Z_ZERO | Z_NOFAIL);
1964 
1965 	// Neither nexus nor socket
1966 	new_flow->interface_index = interface_index;
1967 	new_flow->u.socket_handle = flow_registration->interface_handle;
1968 	new_flow->u.cb = flow_registration->interface_cb;
1969 
1970 	OSIncrementAtomic(&necp_if_flow_count);
1971 
1972 	LIST_INSERT_HEAD(&flow_registration->flow_list, new_flow, flow_chain);
1973 
1974 	return new_flow;
1975 }
1976 
1977 static struct necp_client_flow *
necp_client_add_interface_flow_if_needed(struct necp_client * client,struct necp_client_flow_registration * flow_registration,uint32_t interface_index)1978 necp_client_add_interface_flow_if_needed(struct necp_client *client,
1979     struct necp_client_flow_registration *flow_registration,
1980     uint32_t interface_index)
1981 {
1982 	if (!client->allow_multiple_flows ||
1983 	    interface_index == IFSCOPE_NONE) {
1984 		// Interface not set, or client not allowed to use this mode
1985 		return NULL;
1986 	}
1987 
1988 	struct necp_client_flow *flow = NULL;
1989 	LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
1990 		if (!flow->nexus && !flow->socket && flow->interface_index == interface_index) {
1991 			// Already have the flow
1992 			flow->invalid = FALSE;
1993 			flow->u.socket_handle = flow_registration->interface_handle;
1994 			flow->u.cb = flow_registration->interface_cb;
1995 			return NULL;
1996 		}
1997 	}
1998 	return necp_client_add_interface_flow(flow_registration, interface_index);
1999 }
2000 
2001 static void
necp_client_add_interface_option_if_needed(struct necp_client * client,uint32_t interface_index,uint32_t interface_generation,uuid_t * nexus_agent,bool network_provider)2002 necp_client_add_interface_option_if_needed(struct necp_client *client,
2003     uint32_t interface_index,
2004     uint32_t interface_generation,
2005     uuid_t *nexus_agent,
2006     bool network_provider)
2007 {
2008 	if ((interface_index == IFSCOPE_NONE && !network_provider) ||
2009 	    (client->interface_option_count != 0 && !client->allow_multiple_flows)) {
2010 		// Interface not set, or client not allowed to use this mode
2011 		return;
2012 	}
2013 
2014 	if (client->interface_option_count >= NECP_CLIENT_MAX_INTERFACE_OPTIONS) {
2015 		// Cannot take any more interface options
2016 		return;
2017 	}
2018 
2019 	// Check if already present
2020 	for (u_int32_t option_i = 0; option_i < client->interface_option_count; option_i++) {
2021 		if (option_i < NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT) {
2022 			struct necp_client_interface_option *option = &client->interface_options[option_i];
2023 			if (option->interface_index == interface_index) {
2024 				if (nexus_agent == NULL) {
2025 					return;
2026 				}
2027 				if (uuid_compare(option->nexus_agent, *nexus_agent) == 0) {
2028 					return;
2029 				}
2030 				if (uuid_is_null(option->nexus_agent)) {
2031 					uuid_copy(option->nexus_agent, *nexus_agent);
2032 					return;
2033 				}
2034 				// If we get to this point, this is a new nexus flow
2035 			}
2036 		} else {
2037 			struct necp_client_interface_option *option = &client->extra_interface_options[option_i - NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT];
2038 			if (option->interface_index == interface_index) {
2039 				if (nexus_agent == NULL) {
2040 					return;
2041 				}
2042 				if (uuid_compare(option->nexus_agent, *nexus_agent) == 0) {
2043 					return;
2044 				}
2045 				if (uuid_is_null(option->nexus_agent)) {
2046 					uuid_copy(option->nexus_agent, *nexus_agent);
2047 					return;
2048 				}
2049 				// If we get to this point, this is a new nexus flow
2050 			}
2051 		}
2052 	}
2053 
2054 	// Add a new entry
2055 	if (client->interface_option_count < NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT) {
2056 		// Add to static
2057 		struct necp_client_interface_option *option = &client->interface_options[client->interface_option_count];
2058 		option->interface_index = interface_index;
2059 		option->interface_generation = interface_generation;
2060 		if (nexus_agent != NULL) {
2061 			uuid_copy(option->nexus_agent, *nexus_agent);
2062 		} else {
2063 			uuid_clear(option->nexus_agent);
2064 		}
2065 		client->interface_option_count++;
2066 	} else {
2067 		// Add to extra
2068 		if (client->extra_interface_options == NULL) {
2069 			client->extra_interface_options = (struct necp_client_interface_option *)kalloc_data(
2070 				sizeof(struct necp_client_interface_option) * NECP_CLIENT_INTERFACE_OPTION_EXTRA_COUNT, Z_WAITOK | Z_ZERO);
2071 		}
2072 		if (client->extra_interface_options != NULL) {
2073 			struct necp_client_interface_option *option = &client->extra_interface_options[client->interface_option_count - NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT];
2074 			option->interface_index = interface_index;
2075 			option->interface_generation = interface_generation;
2076 			if (nexus_agent != NULL) {
2077 				uuid_copy(option->nexus_agent, *nexus_agent);
2078 			} else {
2079 				uuid_clear(option->nexus_agent);
2080 			}
2081 			client->interface_option_count++;
2082 		}
2083 	}
2084 }
2085 
2086 static bool
necp_client_flow_is_viable(proc_t proc,struct necp_client * client,struct necp_client_flow * flow)2087 necp_client_flow_is_viable(proc_t proc, struct necp_client *client,
2088     struct necp_client_flow *flow)
2089 {
2090 	struct necp_aggregate_result result;
2091 	bool ignore_address = (client->allow_multiple_flows && !flow->nexus && !flow->socket);
2092 
2093 	flow->necp_flow_flags = 0;
2094 	int error = necp_application_find_policy_match_internal(proc, client->parameters,
2095 	    (u_int32_t)client->parameters_length,
2096 	    &result, &flow->necp_flow_flags, NULL,
2097 	    flow->interface_index,
2098 	    &flow->local_addr, &flow->remote_addr, NULL, NULL,
2099 	    NULL, ignore_address, true, NULL);
2100 
2101 	// Check for blocking agents
2102 	for (int i = 0; i < NECP_MAX_NETAGENTS; i++) {
2103 		if (uuid_is_null(result.netagents[i])) {
2104 			// Passed end of valid agents
2105 			break;
2106 		}
2107 		if (result.netagent_use_flags[i] & NECP_AGENT_USE_FLAG_REMOVE) {
2108 			// A removed agent, ignore
2109 			continue;
2110 		}
2111 		u_int32_t flags = netagent_get_flags(result.netagents[i]);
2112 		if ((flags & NETAGENT_FLAG_REGISTERED) &&
2113 		    !(flags & NETAGENT_FLAG_VOLUNTARY) &&
2114 		    !(flags & NETAGENT_FLAG_ACTIVE) &&
2115 		    !(flags & NETAGENT_FLAG_SPECIFIC_USE_ONLY)) {
2116 			// A required agent is not active, cause the flow to be marked non-viable
2117 			return false;
2118 		}
2119 	}
2120 
2121 	if (flow->interface_index != IFSCOPE_NONE) {
2122 		ifnet_head_lock_shared();
2123 
2124 		struct ifnet *ifp = ifindex2ifnet[flow->interface_index];
2125 		if (ifp && ifp->if_delegated.ifp != IFSCOPE_NONE) {
2126 			flow->delegated_interface_index = ifp->if_delegated.ifp->if_index;
2127 		}
2128 
2129 		ifnet_head_done();
2130 	}
2131 
2132 	return error == 0 &&
2133 	       result.routed_interface_index != IFSCOPE_NONE &&
2134 	       result.routing_result != NECP_KERNEL_POLICY_RESULT_DROP;
2135 }
2136 
2137 static void
necp_flow_add_interface_flows(proc_t proc,struct necp_client * client,struct necp_client_flow_registration * flow_registration,bool send_initial)2138 necp_flow_add_interface_flows(proc_t proc,
2139     struct necp_client *client,
2140     struct necp_client_flow_registration *flow_registration,
2141     bool send_initial)
2142 {
2143 	// Traverse all interfaces and add a tracking flow if needed
2144 	for (u_int32_t option_i = 0; option_i < client->interface_option_count; option_i++) {
2145 		if (option_i < NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT) {
2146 			struct necp_client_interface_option *option = &client->interface_options[option_i];
2147 			struct necp_client_flow *flow = necp_client_add_interface_flow_if_needed(client, flow_registration, option->interface_index);
2148 			if (flow != NULL && send_initial) {
2149 				flow->viable = necp_client_flow_is_viable(proc, client, flow);
2150 				if (flow->viable && flow->u.cb) {
2151 					bool viable = flow->viable;
2152 					flow->u.cb(flow_registration->interface_handle, NECP_CLIENT_CBACTION_INITIAL, flow->interface_index, flow->necp_flow_flags, &viable);
2153 					flow->viable = viable;
2154 				}
2155 			}
2156 		} else {
2157 			struct necp_client_interface_option *option = &client->extra_interface_options[option_i - NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT];
2158 			struct necp_client_flow *flow = necp_client_add_interface_flow_if_needed(client, flow_registration, option->interface_index);
2159 			if (flow != NULL && send_initial) {
2160 				flow->viable = necp_client_flow_is_viable(proc, client, flow);
2161 				if (flow->viable && flow->u.cb) {
2162 					bool viable = flow->viable;
2163 					flow->u.cb(flow_registration->interface_handle, NECP_CLIENT_CBACTION_INITIAL, flow->interface_index, flow->necp_flow_flags, &viable);
2164 					flow->viable = viable;
2165 				}
2166 			}
2167 		}
2168 	}
2169 }
2170 
2171 static bool
necp_client_update_flows(proc_t proc,struct necp_client * client,struct _necp_flow_defunct_list * defunct_list)2172 necp_client_update_flows(proc_t proc,
2173     struct necp_client *client,
2174     struct _necp_flow_defunct_list *defunct_list)
2175 {
2176 	NECP_CLIENT_ASSERT_LOCKED(client);
2177 
2178 	bool any_client_updated = FALSE;
2179 	struct necp_client_flow *flow = NULL;
2180 	struct necp_client_flow *temp_flow = NULL;
2181 	struct necp_client_flow_registration *flow_registration = NULL;
2182 	RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
2183 		if (flow_registration->interface_cb != NULL) {
2184 			// Add any interface flows that are not already tracked
2185 			necp_flow_add_interface_flows(proc, client, flow_registration, false);
2186 		}
2187 
2188 		LIST_FOREACH_SAFE(flow, &flow_registration->flow_list, flow_chain, temp_flow) {
2189 			bool client_updated = FALSE;
2190 
2191 			// Check policy result for flow
2192 			u_short old_delegated_ifindex = flow->delegated_interface_index;
2193 
2194 			int old_flags = flow->necp_flow_flags;
2195 			bool viable = necp_client_flow_is_viable(proc, client, flow);
2196 
2197 			// TODO: Defunct nexus flows that are blocked by policy
2198 
2199 			if (flow->viable != viable) {
2200 				flow->viable = viable;
2201 				client_updated = TRUE;
2202 			}
2203 
2204 			if ((old_flags & NECP_CLIENT_RESULT_FLAG_FORCE_UPDATE) !=
2205 			    (flow->necp_flow_flags & NECP_CLIENT_RESULT_FLAG_FORCE_UPDATE)) {
2206 				client_updated = TRUE;
2207 			}
2208 
2209 			if (flow->delegated_interface_index != old_delegated_ifindex) {
2210 				client_updated = TRUE;
2211 			}
2212 
2213 			if (flow->viable && client_updated && (flow->socket || (!flow->socket && !flow->nexus)) && flow->u.cb) {
2214 				bool flow_viable = flow->viable;
2215 				flow->u.cb(flow->u.socket_handle, NECP_CLIENT_CBACTION_VIABLE, flow->interface_index, flow->necp_flow_flags, &flow_viable);
2216 				flow->viable = flow_viable;
2217 			}
2218 
2219 			if (!flow->viable || flow->invalid) {
2220 				if (client_updated && (flow->socket || (!flow->socket && !flow->nexus)) && flow->u.cb) {
2221 					bool flow_viable = flow->viable;
2222 					flow->u.cb(flow->u.socket_handle, NECP_CLIENT_CBACTION_NONVIABLE, flow->interface_index, flow->necp_flow_flags, &flow_viable);
2223 					flow->viable = flow_viable;
2224 				}
2225 				// The callback might change the viable-flag of the
2226 				// flow depending on its policy. Thus, we need to
2227 				// check the flags again after the callback.
2228 			}
2229 
2230 #if SKYWALK
2231 			if (defunct_list != NULL) {
2232 				if (flow->invalid && flow->nexus && flow->assigned && !uuid_is_null(flow->u.nexus_agent)) {
2233 					// This is a nexus flow that was assigned, but not found on path
2234 					u_int32_t flags = netagent_get_flags(flow->u.nexus_agent);
2235 					if (!(flags & NETAGENT_FLAG_REGISTERED)) {
2236 						// The agent is no longer registered! Mark defunct.
2237 						necp_defunct_flow_registration(client, flow_registration, defunct_list);
2238 						client_updated = TRUE;
2239 					}
2240 				}
2241 			}
2242 #else /* !SKYWALK */
2243 			(void)defunct_list;
2244 #endif /* !SKYWALK */
2245 
2246 			// Handle flows that no longer match
2247 			if (!flow->viable || flow->invalid) {
2248 				// Drop them as long as they aren't assigned data
2249 				if (!flow->nexus && !flow->assigned) {
2250 					if (flow->assigned_results != NULL) {
2251 						kfree_data(flow->assigned_results, flow->assigned_results_length);
2252 						flow->assigned_results = NULL;
2253 						client_updated = TRUE;
2254 					}
2255 					LIST_REMOVE(flow, flow_chain);
2256 #if SKYWALK
2257 					if (flow->nexus) {
2258 						OSDecrementAtomic(&necp_nexus_flow_count);
2259 					} else
2260 #endif /* SKYWALK */
2261 					if (flow->socket) {
2262 						OSDecrementAtomic(&necp_socket_flow_count);
2263 					} else {
2264 						OSDecrementAtomic(&necp_if_flow_count);
2265 					}
2266 					kfree_type(struct necp_client_flow, flow);
2267 				}
2268 			}
2269 
2270 			any_client_updated |= client_updated;
2271 		}
2272 #if SKYWALK
2273 		necp_flow_save_current_interface_details(flow_registration);
2274 #endif /* SKYWALK */
2275 	}
2276 
2277 	return any_client_updated;
2278 }
2279 
2280 static void
necp_client_mark_all_nonsocket_flows_as_invalid(struct necp_client * client)2281 necp_client_mark_all_nonsocket_flows_as_invalid(struct necp_client *client)
2282 {
2283 	struct necp_client_flow_registration *flow_registration = NULL;
2284 	struct necp_client_flow *flow = NULL;
2285 	RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
2286 		LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
2287 			if (!flow->socket) { // Socket flows are not marked as invalid
2288 				flow->invalid = TRUE;
2289 			}
2290 		}
2291 	}
2292 
2293 	// Reset option count every update
2294 	client->interface_option_count = 0;
2295 }
2296 
2297 static inline bool
necp_netagent_is_requested(const struct necp_client_parsed_parameters * parameters,uuid_t * netagent_uuid)2298 necp_netagent_is_requested(const struct necp_client_parsed_parameters *parameters,
2299     uuid_t *netagent_uuid)
2300 {
2301 	// Specific use agents only apply when requested
2302 	bool requested = false;
2303 	if (parameters != NULL) {
2304 		// Check required agent UUIDs
2305 		for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
2306 			if (uuid_is_null(parameters->required_netagents[i])) {
2307 				break;
2308 			}
2309 			if (uuid_compare(parameters->required_netagents[i], *netagent_uuid) == 0) {
2310 				requested = true;
2311 				break;
2312 			}
2313 		}
2314 
2315 		if (!requested) {
2316 			// Check required agent types
2317 			bool fetched_type = false;
2318 			char netagent_domain[NETAGENT_DOMAINSIZE];
2319 			char netagent_type[NETAGENT_TYPESIZE];
2320 			memset(&netagent_domain, 0, NETAGENT_DOMAINSIZE);
2321 			memset(&netagent_type, 0, NETAGENT_TYPESIZE);
2322 
2323 			for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
2324 				if (strlen(parameters->required_netagent_types[i].netagent_domain) == 0 ||
2325 				    strlen(parameters->required_netagent_types[i].netagent_type) == 0) {
2326 					break;
2327 				}
2328 
2329 				if (!fetched_type) {
2330 					if (netagent_get_agent_domain_and_type(*netagent_uuid, netagent_domain, netagent_type)) {
2331 						fetched_type = TRUE;
2332 					} else {
2333 						break;
2334 					}
2335 				}
2336 
2337 				if ((strlen(parameters->required_netagent_types[i].netagent_domain) == 0 ||
2338 				    strncmp(netagent_domain, parameters->required_netagent_types[i].netagent_domain, NETAGENT_DOMAINSIZE) == 0) &&
2339 				    (strlen(parameters->required_netagent_types[i].netagent_type) == 0 ||
2340 				    strncmp(netagent_type, parameters->required_netagent_types[i].netagent_type, NETAGENT_TYPESIZE) == 0)) {
2341 					requested = true;
2342 					break;
2343 				}
2344 			}
2345 		}
2346 
2347 		// Check preferred agent UUIDs
2348 		for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
2349 			if (uuid_is_null(parameters->preferred_netagents[i])) {
2350 				break;
2351 			}
2352 			if (uuid_compare(parameters->preferred_netagents[i], *netagent_uuid) == 0) {
2353 				requested = true;
2354 				break;
2355 			}
2356 		}
2357 
2358 		if (!requested) {
2359 			// Check preferred agent types
2360 			bool fetched_type = false;
2361 			char netagent_domain[NETAGENT_DOMAINSIZE];
2362 			char netagent_type[NETAGENT_TYPESIZE];
2363 			memset(&netagent_domain, 0, NETAGENT_DOMAINSIZE);
2364 			memset(&netagent_type, 0, NETAGENT_TYPESIZE);
2365 
2366 			for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
2367 				if (strlen(parameters->preferred_netagent_types[i].netagent_domain) == 0 ||
2368 				    strlen(parameters->preferred_netagent_types[i].netagent_type) == 0) {
2369 					break;
2370 				}
2371 
2372 				if (!fetched_type) {
2373 					if (netagent_get_agent_domain_and_type(*netagent_uuid, netagent_domain, netagent_type)) {
2374 						fetched_type = TRUE;
2375 					} else {
2376 						break;
2377 					}
2378 				}
2379 
2380 				if ((strlen(parameters->preferred_netagent_types[i].netagent_domain) == 0 ||
2381 				    strncmp(netagent_domain, parameters->preferred_netagent_types[i].netagent_domain, NETAGENT_DOMAINSIZE) == 0) &&
2382 				    (strlen(parameters->preferred_netagent_types[i].netagent_type) == 0 ||
2383 				    strncmp(netagent_type, parameters->preferred_netagent_types[i].netagent_type, NETAGENT_TYPESIZE) == 0)) {
2384 					requested = true;
2385 					break;
2386 				}
2387 			}
2388 		}
2389 	}
2390 
2391 	return requested;
2392 }
2393 
2394 static bool
necp_netagent_applies_to_client(struct necp_client * client,const struct necp_client_parsed_parameters * parameters,uuid_t * netagent_uuid,bool allow_nexus,uint32_t interface_index,uint32_t interface_generation)2395 necp_netagent_applies_to_client(struct necp_client *client,
2396     const struct necp_client_parsed_parameters *parameters,
2397     uuid_t *netagent_uuid, bool allow_nexus,
2398     uint32_t interface_index, uint32_t interface_generation)
2399 {
2400 #pragma unused(interface_index, interface_generation)
2401 	bool applies = FALSE;
2402 	u_int32_t flags = netagent_get_flags(*netagent_uuid);
2403 	if (!(flags & NETAGENT_FLAG_REGISTERED)) {
2404 		// Unregistered agents never apply
2405 		return applies;
2406 	}
2407 
2408 	const bool is_nexus_agent = ((flags & NETAGENT_FLAG_NEXUS_PROVIDER) ||
2409 	    (flags & NETAGENT_FLAG_NEXUS_LISTENER) ||
2410 	    (flags & NETAGENT_FLAG_CUSTOM_ETHER_NEXUS) ||
2411 	    (flags & NETAGENT_FLAG_CUSTOM_IP_NEXUS) ||
2412 	    (flags & NETAGENT_FLAG_INTERPOSE_NEXUS));
2413 	if (is_nexus_agent) {
2414 		if (!allow_nexus) {
2415 			// Hide nexus providers unless allowed
2416 			// Direct interfaces and direct policies are allowed to use a nexus
2417 			// Delegate interfaces or re-scoped interfaces are not allowed
2418 			return applies;
2419 		}
2420 
2421 		if ((parameters->flags & NECP_CLIENT_PARAMETER_FLAG_CUSTOM_ETHER) &&
2422 		    !(flags & NETAGENT_FLAG_CUSTOM_ETHER_NEXUS)) {
2423 			// Client requested a custom ether nexus, but this nexus isn't one
2424 			return applies;
2425 		}
2426 
2427 		if ((parameters->flags & NECP_CLIENT_PARAMETER_FLAG_CUSTOM_IP) &&
2428 		    !(flags & NETAGENT_FLAG_CUSTOM_IP_NEXUS)) {
2429 			// Client requested a custom IP nexus, but this nexus isn't one
2430 			return applies;
2431 		}
2432 
2433 		if ((parameters->flags & NECP_CLIENT_PARAMETER_FLAG_INTERPOSE) &&
2434 		    !(flags & NETAGENT_FLAG_INTERPOSE_NEXUS)) {
2435 			// Client requested an interpose nexus, but this nexus isn't one
2436 			return applies;
2437 		}
2438 
2439 		if (!(parameters->flags & NECP_CLIENT_PARAMETER_FLAG_CUSTOM_ETHER) &&
2440 		    !(parameters->flags & NECP_CLIENT_PARAMETER_FLAG_CUSTOM_IP) &&
2441 		    !(parameters->flags & NECP_CLIENT_PARAMETER_FLAG_INTERPOSE) &&
2442 		    !(flags & NETAGENT_FLAG_NEXUS_PROVIDER)) {
2443 			// Client requested default parameters, but this nexus isn't generic
2444 			return applies;
2445 		}
2446 	}
2447 
2448 	if (uuid_compare(client->failed_trigger_agent.netagent_uuid, *netagent_uuid) == 0) {
2449 		if (client->failed_trigger_agent.generation == netagent_get_generation(*netagent_uuid)) {
2450 			// If this agent was triggered, and failed, and hasn't changed, keep hiding it
2451 			return applies;
2452 		} else {
2453 			// Mismatch generation, clear out old trigger
2454 			uuid_clear(client->failed_trigger_agent.netagent_uuid);
2455 			client->failed_trigger_agent.generation = 0;
2456 		}
2457 	}
2458 
2459 	if (flags & NETAGENT_FLAG_SPECIFIC_USE_ONLY) {
2460 		// Specific use agents only apply when requested
2461 		applies = necp_netagent_is_requested(parameters, netagent_uuid);
2462 	} else {
2463 		applies = TRUE;
2464 	}
2465 
2466 #if SKYWALK
2467 	// Add nexus agent if it is a nexus, and either is not a listener, or the nexus supports listeners
2468 	if (applies && is_nexus_agent &&
2469 	    !(parameters->flags & NECP_CLIENT_PARAMETER_FLAG_BROWSE) &&     // Don't add for browse paths
2470 	    ((flags & NETAGENT_FLAG_NEXUS_LISTENER) || !(parameters->flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER))) {
2471 		necp_client_add_interface_option_if_needed(client, interface_index,
2472 		    interface_generation, netagent_uuid,
2473 		    (flags & NETAGENT_FLAG_NETWORK_PROVIDER));
2474 	}
2475 #endif /* SKYWALK */
2476 
2477 	return applies;
2478 }
2479 
2480 static void
necp_client_add_agent_interface_options(struct necp_client * client,const struct necp_client_parsed_parameters * parsed_parameters,ifnet_t ifp)2481 necp_client_add_agent_interface_options(struct necp_client *client,
2482     const struct necp_client_parsed_parameters *parsed_parameters,
2483     ifnet_t ifp)
2484 {
2485 	if (ifp != NULL && ifp->if_agentids != NULL) {
2486 		for (u_int32_t i = 0; i < ifp->if_agentcount; i++) {
2487 			if (uuid_is_null(ifp->if_agentids[i])) {
2488 				continue;
2489 			}
2490 			// Relies on the side effect that nexus agents that apply will create flows
2491 			(void)necp_netagent_applies_to_client(client, parsed_parameters, &ifp->if_agentids[i], TRUE,
2492 			    ifp->if_index, ifnet_get_generation(ifp));
2493 		}
2494 	}
2495 }
2496 
2497 static void
necp_client_add_browse_interface_options(struct necp_client * client,const struct necp_client_parsed_parameters * parsed_parameters,ifnet_t ifp)2498 necp_client_add_browse_interface_options(struct necp_client *client,
2499     const struct necp_client_parsed_parameters *parsed_parameters,
2500     ifnet_t ifp)
2501 {
2502 	if (ifp != NULL && ifp->if_agentids != NULL) {
2503 		for (u_int32_t i = 0; i < ifp->if_agentcount; i++) {
2504 			if (uuid_is_null(ifp->if_agentids[i])) {
2505 				continue;
2506 			}
2507 
2508 			u_int32_t flags = netagent_get_flags(ifp->if_agentids[i]);
2509 			if ((flags & NETAGENT_FLAG_REGISTERED) &&
2510 			    (flags & NETAGENT_FLAG_ACTIVE) &&
2511 			    (flags & NETAGENT_FLAG_SUPPORTS_BROWSE) &&
2512 			    (!(flags & NETAGENT_FLAG_SPECIFIC_USE_ONLY) ||
2513 			    necp_netagent_is_requested(parsed_parameters, &ifp->if_agentids[i]))) {
2514 				necp_client_add_interface_option_if_needed(client, ifp->if_index, ifnet_get_generation(ifp), &ifp->if_agentids[i], (flags & NETAGENT_FLAG_NETWORK_PROVIDER));
2515 
2516 				// Finding one is enough
2517 				break;
2518 			}
2519 		}
2520 	}
2521 }
2522 
2523 static inline bool
_necp_client_address_is_valid(struct sockaddr * address)2524 _necp_client_address_is_valid(struct sockaddr *address)
2525 {
2526 	if (address->sa_family == AF_INET) {
2527 		return address->sa_len == sizeof(struct sockaddr_in);
2528 	} else if (address->sa_family == AF_INET6) {
2529 		return address->sa_len == sizeof(struct sockaddr_in6);
2530 	} else {
2531 		return FALSE;
2532 	}
2533 }
2534 
2535 #define necp_client_address_is_valid(S) _necp_client_address_is_valid(SA(S))
2536 
2537 static inline bool
necp_client_endpoint_is_unspecified(struct necp_client_endpoint * endpoint)2538 necp_client_endpoint_is_unspecified(struct necp_client_endpoint *endpoint)
2539 {
2540 	if (necp_client_address_is_valid(&endpoint->u.sa)) {
2541 		if (endpoint->u.sa.sa_family == AF_INET) {
2542 			return endpoint->u.sin.sin_addr.s_addr == INADDR_ANY;
2543 		} else if (endpoint->u.sa.sa_family == AF_INET6) {
2544 			return IN6_IS_ADDR_UNSPECIFIED(&endpoint->u.sin6.sin6_addr);
2545 		} else {
2546 			return TRUE;
2547 		}
2548 	} else {
2549 		return TRUE;
2550 	}
2551 }
2552 
2553 #if SKYWALK
2554 static void
necp_client_update_local_port_parameters(u_int8_t * parameters,u_int32_t parameters_size,uint16_t local_port)2555 necp_client_update_local_port_parameters(u_int8_t *parameters,
2556     u_int32_t parameters_size,
2557     uint16_t local_port)
2558 {
2559 	size_t offset = 0;
2560 	while ((offset + sizeof(struct necp_tlv_header)) <= parameters_size) {
2561 		u_int8_t type = necp_buffer_get_tlv_type(parameters, offset);
2562 		u_int32_t length = necp_buffer_get_tlv_length(parameters, offset);
2563 
2564 		if (length > (parameters_size - (offset + sizeof(struct necp_tlv_header)))) {
2565 			// If the length is larger than what can fit in the remaining parameters size, bail
2566 			NECPLOG(LOG_ERR, "Invalid TLV length (%u)", length);
2567 			break;
2568 		}
2569 
2570 		if (length > 0) {
2571 			u_int8_t *value = necp_buffer_get_tlv_value(parameters, offset, NULL);
2572 			if (value != NULL) {
2573 				switch (type) {
2574 				case NECP_CLIENT_PARAMETER_LOCAL_ADDRESS: {
2575 					if (length >= sizeof(struct necp_policy_condition_addr)) {
2576 						struct necp_policy_condition_addr *address_struct = (struct necp_policy_condition_addr *)(void *)value;
2577 						if (necp_client_address_is_valid(&address_struct->address.sa)) {
2578 							if (address_struct->address.sa.sa_family == AF_INET) {
2579 								address_struct->address.sin.sin_port = local_port;
2580 							} else if (address_struct->address.sa.sa_family == AF_INET6) {
2581 								address_struct->address.sin6.sin6_port = local_port;
2582 							}
2583 						}
2584 					}
2585 					break;
2586 				}
2587 				case NECP_CLIENT_PARAMETER_LOCAL_ENDPOINT: {
2588 					if (length >= sizeof(struct necp_client_endpoint)) {
2589 						struct necp_client_endpoint *endpoint = (struct necp_client_endpoint *)(void *)value;
2590 						if (necp_client_address_is_valid(&endpoint->u.sa)) {
2591 							if (endpoint->u.sa.sa_family == AF_INET) {
2592 								endpoint->u.sin.sin_port = local_port;
2593 							} else if (endpoint->u.sa.sa_family == AF_INET6) {
2594 								endpoint->u.sin6.sin6_port = local_port;
2595 							}
2596 						}
2597 					}
2598 					break;
2599 				}
2600 				default: {
2601 					break;
2602 				}
2603 				}
2604 			}
2605 		}
2606 
2607 		offset += sizeof(struct necp_tlv_header) + length;
2608 	}
2609 }
2610 #endif /* !SKYWALK */
2611 
2612 #define NECP_MAX_SOCKET_ATTRIBUTE_STRING_LENGTH 253
2613 
2614 static void
necp_client_trace_parameter_parsing(struct necp_client * client,u_int8_t type,u_int8_t * value,u_int32_t length)2615 necp_client_trace_parameter_parsing(struct necp_client *client, u_int8_t type, u_int8_t *value, u_int32_t length)
2616 {
2617 	uint64_t num = 0;
2618 	uint16_t shortBuf;
2619 	uint32_t intBuf;
2620 	char buffer[NECP_MAX_SOCKET_ATTRIBUTE_STRING_LENGTH + 1];
2621 
2622 	if (value != NULL && length > 0) {
2623 		switch (length) {
2624 		case 1:
2625 			num = *value;
2626 			break;
2627 		case 2:
2628 			memcpy(&shortBuf, value, sizeof(shortBuf));
2629 			num = shortBuf;
2630 			break;
2631 		case 4:
2632 			memcpy(&intBuf, value, sizeof(intBuf));
2633 			num = intBuf;
2634 			break;
2635 		case 8:
2636 			memcpy(&num, value, sizeof(num));
2637 			break;
2638 		default:
2639 			num = 0;
2640 			break;
2641 		}
2642 		int len = NECP_MAX_SOCKET_ATTRIBUTE_STRING_LENGTH < length ? NECP_MAX_SOCKET_ATTRIBUTE_STRING_LENGTH : length;
2643 		memcpy(buffer, value, len);
2644 		buffer[len] = 0;
2645 		NECP_CLIENT_PARAMS_LOG(client, "Parsing param - type %d length %d value <%llu (%llX)> %s", type, length, num, num, buffer);
2646 	} else {
2647 		NECP_CLIENT_PARAMS_LOG(client, "Parsing param - type %d length %d", type, length);
2648 	}
2649 }
2650 
2651 static void
necp_client_trace_parsed_parameters(struct necp_client * client,struct necp_client_parsed_parameters * parsed_parameters)2652 necp_client_trace_parsed_parameters(struct necp_client *client, struct necp_client_parsed_parameters *parsed_parameters)
2653 {
2654 	int i;
2655 	char local_buffer[64] = { };
2656 	char remote_buffer[64] = { };
2657 	uuid_string_t uuid_str = { };
2658 	uuid_unparse_lower(parsed_parameters->effective_uuid, uuid_str);
2659 
2660 	switch (parsed_parameters->local_addr.sa.sa_family) {
2661 	case AF_INET:
2662 		if (parsed_parameters->local_addr.sa.sa_len == sizeof(struct sockaddr_in)) {
2663 			struct sockaddr_in *addr = &parsed_parameters->local_addr.sin;
2664 			inet_ntop(AF_INET, &(addr->sin_addr), local_buffer, sizeof(local_buffer));
2665 		}
2666 		break;
2667 	case AF_INET6:
2668 		if (parsed_parameters->local_addr.sa.sa_len == sizeof(struct sockaddr_in6)) {
2669 			struct sockaddr_in6 *addr6 = &parsed_parameters->local_addr.sin6;
2670 			inet_ntop(AF_INET6, &(addr6->sin6_addr), local_buffer, sizeof(local_buffer));
2671 		}
2672 		break;
2673 	default:
2674 		break;
2675 	}
2676 
2677 	switch (parsed_parameters->remote_addr.sa.sa_family) {
2678 	case AF_INET:
2679 		if (parsed_parameters->remote_addr.sa.sa_len == sizeof(struct sockaddr_in)) {
2680 			struct sockaddr_in *addr = &parsed_parameters->remote_addr.sin;
2681 			inet_ntop(AF_INET, &(addr->sin_addr), remote_buffer, sizeof(remote_buffer));
2682 		}
2683 		break;
2684 	case AF_INET6:
2685 		if (parsed_parameters->remote_addr.sa.sa_len == sizeof(struct sockaddr_in6)) {
2686 			struct sockaddr_in6 *addr6 = &parsed_parameters->remote_addr.sin6;
2687 			inet_ntop(AF_INET6, &(addr6->sin6_addr), remote_buffer, sizeof(remote_buffer));
2688 		}
2689 		break;
2690 	default:
2691 		break;
2692 	}
2693 
2694 	NECP_CLIENT_PARAMS_LOG(client, "Parsed params - valid_fields %X flags %X delegated_upid %llu local_addr %s remote_addr %s "
2695 	    "required_interface_index %u required_interface_type %d local_address_preference %d "
2696 	    "ip_protocol %d transport_protocol %d ethertype %d effective_pid %d effective_uuid %s uid %d persona_id %d traffic_class %d",
2697 	    parsed_parameters->valid_fields,
2698 	    parsed_parameters->flags,
2699 	    parsed_parameters->delegated_upid,
2700 	    local_buffer, remote_buffer,
2701 	    parsed_parameters->required_interface_index,
2702 	    parsed_parameters->required_interface_type,
2703 	    parsed_parameters->local_address_preference,
2704 	    parsed_parameters->ip_protocol,
2705 	    parsed_parameters->transport_protocol,
2706 	    parsed_parameters->ethertype,
2707 	    parsed_parameters->effective_pid,
2708 	    uuid_str,
2709 	    parsed_parameters->uid,
2710 	    parsed_parameters->persona_id,
2711 	    parsed_parameters->traffic_class);
2712 
2713 	NECP_CLIENT_PARAMS_LOG(client, "Parsed params - tracker flags <known-tracker %X> <non-app-initiated %X> <silent %X> <app-approved %X>",
2714 	    parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_KNOWN_TRACKER,
2715 	    parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_NON_APP_INITIATED,
2716 	    parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_SILENT,
2717 	    parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_APPROVED_APP_DOMAIN);
2718 
2719 	for (i = 0; i < NECP_MAX_INTERFACE_PARAMETERS && parsed_parameters->prohibited_interfaces[i][0]; i++) {
2720 		NECP_CLIENT_PARAMS_LOG(client, "Parsed prohibited_interfaces[%d] <%s>", i, parsed_parameters->prohibited_interfaces[i]);
2721 	}
2722 
2723 	for (i = 0; i < NECP_MAX_AGENT_PARAMETERS && parsed_parameters->required_netagent_types[i].netagent_domain[0]; i++) {
2724 		NECP_CLIENT_PARAMS_LOG(client, "Parsed required_netagent_types[%d] <%s> <%s>", i,
2725 		    parsed_parameters->required_netagent_types[i].netagent_domain,
2726 		    parsed_parameters->required_netagent_types[i].netagent_type);
2727 	}
2728 	for (i = 0; i < NECP_MAX_AGENT_PARAMETERS && parsed_parameters->prohibited_netagent_types[i].netagent_domain[0]; i++) {
2729 		NECP_CLIENT_PARAMS_LOG(client, "Parsed prohibited_netagent_types[%d] <%s> <%s>", i,
2730 		    parsed_parameters->prohibited_netagent_types[i].netagent_domain,
2731 		    parsed_parameters->prohibited_netagent_types[i].netagent_type);
2732 	}
2733 	for (i = 0; i < NECP_MAX_AGENT_PARAMETERS && parsed_parameters->preferred_netagent_types[i].netagent_domain[0]; i++) {
2734 		NECP_CLIENT_PARAMS_LOG(client, "Parsed preferred_netagent_types[%d] <%s> <%s>", i,
2735 		    parsed_parameters->preferred_netagent_types[i].netagent_domain,
2736 		    parsed_parameters->preferred_netagent_types[i].netagent_type);
2737 	}
2738 	for (i = 0; i < NECP_MAX_AGENT_PARAMETERS && parsed_parameters->avoided_netagent_types[i].netagent_domain[0]; i++) {
2739 		NECP_CLIENT_PARAMS_LOG(client, "Parsed avoided_netagent_types[%d] <%s> <%s>", i,
2740 		    parsed_parameters->avoided_netagent_types[i].netagent_domain,
2741 		    parsed_parameters->avoided_netagent_types[i].netagent_type);
2742 	}
2743 
2744 	for (i = 0; i < NECP_MAX_AGENT_PARAMETERS && !uuid_is_null(parsed_parameters->required_netagents[i]); i++) {
2745 		uuid_unparse_lower(parsed_parameters->required_netagents[i], uuid_str);
2746 		NECP_CLIENT_PARAMS_LOG(client, "Parsed required_netagents[%d] <%s>", i, uuid_str);
2747 	}
2748 	for (i = 0; i < NECP_MAX_AGENT_PARAMETERS && !uuid_is_null(parsed_parameters->prohibited_netagents[i]); i++) {
2749 		uuid_unparse_lower(parsed_parameters->prohibited_netagents[i], uuid_str);
2750 		NECP_CLIENT_PARAMS_LOG(client, "Parsed prohibited_netagents[%d] <%s>", i, uuid_str);
2751 	}
2752 	for (i = 0; i < NECP_MAX_AGENT_PARAMETERS && !uuid_is_null(parsed_parameters->preferred_netagents[i]); i++) {
2753 		uuid_unparse_lower(parsed_parameters->preferred_netagents[i], uuid_str);
2754 		NECP_CLIENT_PARAMS_LOG(client, "Parsed preferred_netagents[%d] <%s>", i, uuid_str);
2755 	}
2756 	for (i = 0; i < NECP_MAX_AGENT_PARAMETERS && !uuid_is_null(parsed_parameters->avoided_netagents[i]); i++) {
2757 		uuid_unparse_lower(parsed_parameters->avoided_netagents[i], uuid_str);
2758 		NECP_CLIENT_PARAMS_LOG(client, "Parsed avoided_netagents[%d] <%s>", i, uuid_str);
2759 	}
2760 }
2761 
2762 static bool
necp_client_strings_are_equal(const char * string1,size_t string1_length,const char * string2,size_t string2_length)2763 necp_client_strings_are_equal(const char *string1, size_t string1_length,
2764     const char *string2, size_t string2_length)
2765 {
2766 	if (string1 == NULL || string2 == NULL) {
2767 		return false;
2768 	}
2769 	const size_t string1_actual_length = strnlen(string1, string1_length);
2770 	const size_t string2_actual_length = strnlen(string2, string2_length);
2771 	if (string1_actual_length != string2_actual_length) {
2772 		return false;
2773 	}
2774 	return strncmp(string1, string2, string1_actual_length) == 0;
2775 }
2776 
2777 static int
necp_client_parse_parameters(struct necp_client * client,u_int8_t * parameters,u_int32_t parameters_size,struct necp_client_parsed_parameters * parsed_parameters)2778 necp_client_parse_parameters(struct necp_client *client, u_int8_t *parameters,
2779     u_int32_t parameters_size,
2780     struct necp_client_parsed_parameters *parsed_parameters)
2781 {
2782 	int error = 0;
2783 	size_t offset = 0;
2784 
2785 	u_int32_t num_prohibited_interfaces = 0;
2786 	u_int32_t num_prohibited_interface_types = 0;
2787 	u_int32_t num_required_agents = 0;
2788 	u_int32_t num_prohibited_agents = 0;
2789 	u_int32_t num_preferred_agents = 0;
2790 	u_int32_t num_avoided_agents = 0;
2791 	u_int32_t num_required_agent_types = 0;
2792 	u_int32_t num_prohibited_agent_types = 0;
2793 	u_int32_t num_preferred_agent_types = 0;
2794 	u_int32_t num_avoided_agent_types = 0;
2795 	u_int8_t *resolver_tag = NULL;
2796 	u_int32_t resolver_tag_length = 0;
2797 	u_int8_t *client_hostname = NULL;
2798 	u_int32_t hostname_length = 0;
2799 	uuid_t parent_id = {};
2800 
2801 	if (parsed_parameters == NULL) {
2802 		return EINVAL;
2803 	}
2804 
2805 	memset(parsed_parameters, 0, sizeof(struct necp_client_parsed_parameters));
2806 
2807 	while ((offset + sizeof(struct necp_tlv_header)) <= parameters_size) {
2808 		u_int8_t type = necp_buffer_get_tlv_type(parameters, offset);
2809 		u_int32_t length = necp_buffer_get_tlv_length(parameters, offset);
2810 
2811 		if (length > (parameters_size - (offset + sizeof(struct necp_tlv_header)))) {
2812 			// If the length is larger than what can fit in the remaining parameters size, bail
2813 			NECPLOG(LOG_ERR, "Invalid TLV length (%u)", length);
2814 			break;
2815 		}
2816 
2817 		if (length > 0) {
2818 			u_int8_t *value = necp_buffer_get_tlv_value(parameters, offset, NULL);
2819 			if (value != NULL) {
2820 				switch (type) {
2821 				case NECP_CLIENT_PARAMETER_BOUND_INTERFACE: {
2822 					if (length <= IFXNAMSIZ && length > 0) {
2823 						ifnet_t bound_interface = NULL;
2824 						char interface_name[IFXNAMSIZ];
2825 						memcpy(interface_name, value, length);
2826 						interface_name[length - 1] = 0;         // Make sure the string is NULL terminated
2827 						if (ifnet_find_by_name(interface_name, &bound_interface) == 0) {
2828 							parsed_parameters->required_interface_index = bound_interface->if_index;
2829 							parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IF;
2830 							ifnet_release(bound_interface);
2831 						}
2832 					}
2833 					break;
2834 				}
2835 				case NECP_CLIENT_PARAMETER_LOCAL_ADDRESS: {
2836 					if (length >= sizeof(struct necp_policy_condition_addr)) {
2837 						struct necp_policy_condition_addr *address_struct = (struct necp_policy_condition_addr *)(void *)value;
2838 						if (necp_client_address_is_valid(&address_struct->address.sa)) {
2839 							memcpy(&parsed_parameters->local_addr, &address_struct->address, sizeof(address_struct->address));
2840 							if (!necp_address_is_wildcard(&parsed_parameters->local_addr)) {
2841 								parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR;
2842 							}
2843 							if ((parsed_parameters->local_addr.sa.sa_family == AF_INET && parsed_parameters->local_addr.sin.sin_port) ||
2844 							    (parsed_parameters->local_addr.sa.sa_family == AF_INET6 && parsed_parameters->local_addr.sin6.sin6_port)) {
2845 								parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_LOCAL_PORT;
2846 							}
2847 						}
2848 					}
2849 					break;
2850 				}
2851 				case NECP_CLIENT_PARAMETER_LOCAL_ENDPOINT: {
2852 					if (length >= sizeof(struct necp_client_endpoint)) {
2853 						struct necp_client_endpoint *endpoint = (struct necp_client_endpoint *)(void *)value;
2854 						if (necp_client_address_is_valid(&endpoint->u.sa)) {
2855 							memcpy(&parsed_parameters->local_addr, &endpoint->u.sa, sizeof(union necp_sockaddr_union));
2856 							if (!necp_address_is_wildcard(&parsed_parameters->local_addr)) {
2857 								parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR;
2858 							}
2859 							if ((parsed_parameters->local_addr.sa.sa_family == AF_INET && parsed_parameters->local_addr.sin.sin_port) ||
2860 							    (parsed_parameters->local_addr.sa.sa_family == AF_INET6 && parsed_parameters->local_addr.sin6.sin6_port)) {
2861 								parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_LOCAL_PORT;
2862 							}
2863 						}
2864 					}
2865 					break;
2866 				}
2867 				case NECP_CLIENT_PARAMETER_REMOTE_ADDRESS: {
2868 					if (length >= sizeof(struct necp_policy_condition_addr)) {
2869 						struct necp_policy_condition_addr *address_struct = (struct necp_policy_condition_addr *)(void *)value;
2870 						if (necp_client_address_is_valid(&address_struct->address.sa)) {
2871 							memcpy(&parsed_parameters->remote_addr, &address_struct->address, sizeof(address_struct->address));
2872 							parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REMOTE_ADDR;
2873 						}
2874 					}
2875 					break;
2876 				}
2877 				case NECP_CLIENT_PARAMETER_REMOTE_ENDPOINT: {
2878 					if (length >= sizeof(struct necp_client_endpoint)) {
2879 						struct necp_client_endpoint *endpoint = (struct necp_client_endpoint *)(void *)value;
2880 						if (necp_client_address_is_valid(&endpoint->u.sa)) {
2881 							memcpy(&parsed_parameters->remote_addr, &endpoint->u.sa, sizeof(union necp_sockaddr_union));
2882 							parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REMOTE_ADDR;
2883 						}
2884 					}
2885 					break;
2886 				}
2887 				case NECP_CLIENT_PARAMETER_PROHIBIT_INTERFACE: {
2888 					if (num_prohibited_interfaces >= NECP_MAX_INTERFACE_PARAMETERS) {
2889 						break;
2890 					}
2891 					if (length <= IFXNAMSIZ && length > 0) {
2892 						memcpy(parsed_parameters->prohibited_interfaces[num_prohibited_interfaces], value, length);
2893 						parsed_parameters->prohibited_interfaces[num_prohibited_interfaces][length - 1] = 0;         // Make sure the string is NULL terminated
2894 						num_prohibited_interfaces++;
2895 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IF;
2896 					}
2897 					break;
2898 				}
2899 				case NECP_CLIENT_PARAMETER_REQUIRE_IF_TYPE: {
2900 					if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE) {
2901 						break;
2902 					}
2903 					if (length >= sizeof(u_int8_t)) {
2904 						memcpy(&parsed_parameters->required_interface_type, value, sizeof(u_int8_t));
2905 						if (parsed_parameters->required_interface_type) {
2906 							parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE;
2907 						}
2908 					}
2909 					break;
2910 				}
2911 				case NECP_CLIENT_PARAMETER_PROHIBIT_IF_TYPE: {
2912 					if (num_prohibited_interface_types >= NECP_MAX_INTERFACE_PARAMETERS) {
2913 						break;
2914 					}
2915 					if (length >= sizeof(u_int8_t)) {
2916 						memcpy(&parsed_parameters->prohibited_interface_types[num_prohibited_interface_types], value, sizeof(u_int8_t));
2917 						num_prohibited_interface_types++;
2918 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IFTYPE;
2919 					}
2920 					break;
2921 				}
2922 				case NECP_CLIENT_PARAMETER_REQUIRE_AGENT: {
2923 					if (num_required_agents >= NECP_MAX_AGENT_PARAMETERS) {
2924 						break;
2925 					}
2926 					if (length >= sizeof(uuid_t)) {
2927 						memcpy(&parsed_parameters->required_netagents[num_required_agents], value, sizeof(uuid_t));
2928 						num_required_agents++;
2929 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT;
2930 					}
2931 					break;
2932 				}
2933 				case NECP_CLIENT_PARAMETER_PROHIBIT_AGENT: {
2934 					if (num_prohibited_agents >= NECP_MAX_AGENT_PARAMETERS) {
2935 						break;
2936 					}
2937 					if (length >= sizeof(uuid_t)) {
2938 						memcpy(&parsed_parameters->prohibited_netagents[num_prohibited_agents], value, sizeof(uuid_t));
2939 						num_prohibited_agents++;
2940 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT;
2941 					}
2942 					break;
2943 				}
2944 				case NECP_CLIENT_PARAMETER_PREFER_AGENT: {
2945 					if (num_preferred_agents >= NECP_MAX_AGENT_PARAMETERS) {
2946 						break;
2947 					}
2948 					if (length >= sizeof(uuid_t)) {
2949 						memcpy(&parsed_parameters->preferred_netagents[num_preferred_agents], value, sizeof(uuid_t));
2950 						num_preferred_agents++;
2951 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT;
2952 					}
2953 					break;
2954 				}
2955 				case NECP_CLIENT_PARAMETER_AVOID_AGENT: {
2956 					if (num_avoided_agents >= NECP_MAX_AGENT_PARAMETERS) {
2957 						break;
2958 					}
2959 					if (length >= sizeof(uuid_t)) {
2960 						memcpy(&parsed_parameters->avoided_netagents[num_avoided_agents], value, sizeof(uuid_t));
2961 						num_avoided_agents++;
2962 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT;
2963 					}
2964 					break;
2965 				}
2966 				case NECP_CLIENT_PARAMETER_REQUIRE_AGENT_TYPE: {
2967 					if (num_required_agent_types >= NECP_MAX_AGENT_PARAMETERS) {
2968 						break;
2969 					}
2970 					if (length >= sizeof(struct necp_client_parameter_netagent_type)) {
2971 						memcpy(&parsed_parameters->required_netagent_types[num_required_agent_types], value, sizeof(struct necp_client_parameter_netagent_type));
2972 						num_required_agent_types++;
2973 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE;
2974 					}
2975 					break;
2976 				}
2977 				case NECP_CLIENT_PARAMETER_PROHIBIT_AGENT_TYPE: {
2978 					if (num_prohibited_agent_types >= NECP_MAX_AGENT_PARAMETERS) {
2979 						break;
2980 					}
2981 					if (length >= sizeof(struct necp_client_parameter_netagent_type)) {
2982 						memcpy(&parsed_parameters->prohibited_netagent_types[num_prohibited_agent_types], value, sizeof(struct necp_client_parameter_netagent_type));
2983 						num_prohibited_agent_types++;
2984 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT_TYPE;
2985 					}
2986 					break;
2987 				}
2988 				case NECP_CLIENT_PARAMETER_PREFER_AGENT_TYPE: {
2989 					if (num_preferred_agent_types >= NECP_MAX_AGENT_PARAMETERS) {
2990 						break;
2991 					}
2992 					if (length >= sizeof(struct necp_client_parameter_netagent_type)) {
2993 						memcpy(&parsed_parameters->preferred_netagent_types[num_preferred_agent_types], value, sizeof(struct necp_client_parameter_netagent_type));
2994 						num_preferred_agent_types++;
2995 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT_TYPE;
2996 					}
2997 					break;
2998 				}
2999 				case NECP_CLIENT_PARAMETER_AVOID_AGENT_TYPE: {
3000 					if (num_avoided_agent_types >= NECP_MAX_AGENT_PARAMETERS) {
3001 						break;
3002 					}
3003 					if (length >= sizeof(struct necp_client_parameter_netagent_type)) {
3004 						memcpy(&parsed_parameters->avoided_netagent_types[num_avoided_agent_types], value, sizeof(struct necp_client_parameter_netagent_type));
3005 						num_avoided_agent_types++;
3006 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT_TYPE;
3007 					}
3008 					break;
3009 				}
3010 				case NECP_CLIENT_PARAMETER_FLAGS: {
3011 					if (length >= sizeof(u_int32_t)) {
3012 						memcpy(&parsed_parameters->flags, value, sizeof(parsed_parameters->flags));
3013 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_FLAGS;
3014 					}
3015 					break;
3016 				}
3017 				case NECP_CLIENT_PARAMETER_IP_PROTOCOL: {
3018 					if (length == sizeof(u_int16_t)) {
3019 						u_int16_t large_ip_protocol = 0;
3020 						memcpy(&large_ip_protocol, value, sizeof(large_ip_protocol));
3021 						parsed_parameters->ip_protocol = (u_int8_t)large_ip_protocol;
3022 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_IP_PROTOCOL;
3023 					} else if (length >= sizeof(parsed_parameters->ip_protocol)) {
3024 						memcpy(&parsed_parameters->ip_protocol, value, sizeof(parsed_parameters->ip_protocol));
3025 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_IP_PROTOCOL;
3026 					}
3027 					break;
3028 				}
3029 				case NECP_CLIENT_PARAMETER_TRANSPORT_PROTOCOL: {
3030 					if (length >= sizeof(parsed_parameters->transport_protocol)) {
3031 						memcpy(&parsed_parameters->transport_protocol, value, sizeof(parsed_parameters->transport_protocol));
3032 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_TRANSPORT_PROTOCOL;
3033 					}
3034 					break;
3035 				}
3036 				case NECP_CLIENT_PARAMETER_PID: {
3037 					if (length >= sizeof(parsed_parameters->effective_pid)) {
3038 						memcpy(&parsed_parameters->effective_pid, value, sizeof(parsed_parameters->effective_pid));
3039 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_EFFECTIVE_PID;
3040 					}
3041 					break;
3042 				}
3043 				case NECP_CLIENT_PARAMETER_DELEGATED_UPID: {
3044 					if (length >= sizeof(parsed_parameters->delegated_upid)) {
3045 						memcpy(&parsed_parameters->delegated_upid, value, sizeof(parsed_parameters->delegated_upid));
3046 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_DELEGATED_UPID;
3047 					}
3048 					break;
3049 				}
3050 				case NECP_CLIENT_PARAMETER_ETHERTYPE: {
3051 					if (length >= sizeof(parsed_parameters->ethertype)) {
3052 						memcpy(&parsed_parameters->ethertype, value, sizeof(parsed_parameters->ethertype));
3053 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_ETHERTYPE;
3054 					}
3055 					break;
3056 				}
3057 				case NECP_CLIENT_PARAMETER_APPLICATION: {
3058 					if (length >= sizeof(parsed_parameters->effective_uuid)) {
3059 						memcpy(&parsed_parameters->effective_uuid, value, sizeof(parsed_parameters->effective_uuid));
3060 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_EFFECTIVE_UUID;
3061 					}
3062 					break;
3063 				}
3064 				case NECP_CLIENT_PARAMETER_TRAFFIC_CLASS: {
3065 					if (length >= sizeof(parsed_parameters->traffic_class)) {
3066 						memcpy(&parsed_parameters->traffic_class, value, sizeof(parsed_parameters->traffic_class));
3067 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_TRAFFIC_CLASS;
3068 					}
3069 					break;
3070 				}
3071 				case NECP_CLIENT_PARAMETER_RESOLVER_TAG: {
3072 					if (length > 0) {
3073 						if (resolver_tag != NULL) {
3074 							// Multiple resolver tags is invalid
3075 							NECPLOG0(LOG_ERR, "Multiple resolver tags are not supported");
3076 							error = EINVAL;
3077 						} else {
3078 							resolver_tag = (u_int8_t *)value;
3079 							resolver_tag_length = length;
3080 						}
3081 					}
3082 					break;
3083 				}
3084 				case NECP_CLIENT_PARAMETER_DOMAIN: {
3085 					if (length > 0) {
3086 						client_hostname = (u_int8_t *)value;
3087 						hostname_length = length;
3088 					}
3089 					break;
3090 				}
3091 				case NECP_CLIENT_PARAMETER_PARENT_ID: {
3092 					if (length == sizeof(parent_id)) {
3093 						uuid_copy(parent_id, value);
3094 						memcpy(&parsed_parameters->parent_uuid, value, sizeof(parsed_parameters->parent_uuid));
3095 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PARENT_UUID;
3096 					}
3097 					break;
3098 				}
3099 				case NECP_CLIENT_PARAMETER_LOCAL_ADDRESS_PREFERENCE: {
3100 					if (length >= sizeof(parsed_parameters->local_address_preference)) {
3101 						memcpy(&parsed_parameters->local_address_preference, value, sizeof(parsed_parameters->local_address_preference));
3102 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR_PREFERENCE;
3103 					}
3104 					break;
3105 				}
3106 				case NECP_CLIENT_PARAMETER_ATTRIBUTED_BUNDLE_IDENTIFIER: {
3107 					if (length > 0) {
3108 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_ATTRIBUTED_BUNDLE_IDENTIFIER;
3109 					}
3110 					break;
3111 				}
3112 				case NECP_CLIENT_PARAMETER_FLOW_DEMUX_PATTERN: {
3113 					if (parsed_parameters->demux_pattern_count >= NECP_MAX_DEMUX_PATTERNS) {
3114 						break;
3115 					}
3116 					if (length >= sizeof(struct necp_demux_pattern)) {
3117 						memcpy(&parsed_parameters->demux_patterns[parsed_parameters->demux_pattern_count], value, sizeof(struct necp_demux_pattern));
3118 						parsed_parameters->demux_pattern_count++;
3119 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_FLOW_DEMUX_PATTERN;
3120 					}
3121 					break;
3122 				}
3123 				case NECP_CLIENT_PARAMETER_APPLICATION_ID: {
3124 					if (length >= sizeof(necp_application_id_t)) {
3125 						necp_application_id_t *application_id = (necp_application_id_t *)(void *)value;
3126 						// UID
3127 						parsed_parameters->uid = application_id->uid;
3128 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_UID;
3129 						// EUUID
3130 						uuid_copy(parsed_parameters->effective_uuid, application_id->effective_uuid);
3131 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_EFFECTIVE_UUID;
3132 						// PERSONA
3133 						parsed_parameters->persona_id = application_id->persona_id;
3134 						parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PERSONA_ID;
3135 					}
3136 					break;
3137 				}
3138 				default: {
3139 					break;
3140 				}
3141 				}
3142 			}
3143 
3144 			if (NECP_ENABLE_CLIENT_TRACE(NECP_CLIENT_TRACE_LEVEL_PARAMS)) {
3145 				necp_client_trace_parameter_parsing(client, type, value, length);
3146 			}
3147 		}
3148 
3149 		offset += sizeof(struct necp_tlv_header) + length;
3150 	}
3151 
3152 	if (resolver_tag != NULL) {
3153 		struct necp_client_validatable *validatable = (struct necp_client_validatable *)resolver_tag;
3154 		if (resolver_tag_length <= sizeof(struct necp_client_validatable)) {
3155 			error = EINVAL;
3156 			NECPLOG(LOG_ERR, "Resolver tag length too short: %u", resolver_tag_length);
3157 		} else {
3158 			bool matches = true;
3159 
3160 			// Check the client UUID for client-specific results
3161 			if (validatable->signable.sign_type == NECP_CLIENT_SIGN_TYPE_RESOLVER_ANSWER ||
3162 			    validatable->signable.sign_type == NECP_CLIENT_SIGN_TYPE_BROWSE_RESULT ||
3163 			    validatable->signable.sign_type == NECP_CLIENT_SIGN_TYPE_SERVICE_RESOLVER_ANSWER) {
3164 				if (uuid_compare(parent_id, validatable->signable.client_id) != 0 &&
3165 				    uuid_compare(client->client_id, validatable->signable.client_id) != 0) {
3166 					NECPLOG0(LOG_ERR, "Resolver tag invalid client ID");
3167 					matches = false;
3168 				}
3169 			}
3170 
3171 			size_t data_length = resolver_tag_length - sizeof(struct necp_client_validatable);
3172 			switch (validatable->signable.sign_type) {
3173 			case NECP_CLIENT_SIGN_TYPE_RESOLVER_ANSWER:
3174 			case NECP_CLIENT_SIGN_TYPE_SYSTEM_RESOLVER_ANSWER: {
3175 				if (data_length < (sizeof(struct necp_client_host_resolver_answer) - sizeof(struct necp_client_signable))) {
3176 					NECPLOG0(LOG_ERR, "Resolver tag invalid length for resolver answer");
3177 					matches = false;
3178 				} else {
3179 					struct necp_client_host_resolver_answer *answer_struct = (struct necp_client_host_resolver_answer *)&validatable->signable;
3180 					if (data_length != (sizeof(struct necp_client_host_resolver_answer) + answer_struct->hostname_length - sizeof(struct necp_client_signable))) {
3181 						NECPLOG0(LOG_ERR, "Resolver tag invalid length for resolver answer");
3182 						matches = false;
3183 					} else {
3184 						if (answer_struct->hostname_length != 0 && // If the hostname on the signed answer is empty, ignore
3185 						    !necp_client_strings_are_equal((const char *)client_hostname, hostname_length,
3186 						    answer_struct->hostname, answer_struct->hostname_length)) {
3187 							NECPLOG0(LOG_ERR, "Resolver tag hostname does not match");
3188 							matches = false;
3189 						} else if (answer_struct->address_answer.sa.sa_family != parsed_parameters->remote_addr.sa.sa_family ||
3190 						    answer_struct->address_answer.sa.sa_len != parsed_parameters->remote_addr.sa.sa_len) {
3191 							NECPLOG0(LOG_ERR, "Resolver tag address type does not match");
3192 							matches = false;
3193 						} else if (answer_struct->address_answer.sin.sin_port != 0 && // If the port on the signed answer is empty, ignore
3194 						    answer_struct->address_answer.sin.sin_port != parsed_parameters->remote_addr.sin.sin_port) {
3195 							NECPLOG0(LOG_ERR, "Resolver tag port does not match");
3196 							matches = false;
3197 						} else if ((answer_struct->address_answer.sa.sa_family == AF_INET &&
3198 						    answer_struct->address_answer.sin.sin_addr.s_addr != parsed_parameters->remote_addr.sin.sin_addr.s_addr) ||
3199 						    (answer_struct->address_answer.sa.sa_family == AF_INET6 &&
3200 						    memcmp(&answer_struct->address_answer.sin6.sin6_addr, &parsed_parameters->remote_addr.sin6.sin6_addr, sizeof(struct in6_addr)) != 0)) {
3201 							NECPLOG0(LOG_ERR, "Resolver tag address does not match");
3202 							matches = false;
3203 						}
3204 					}
3205 				}
3206 				break;
3207 			}
3208 			case NECP_CLIENT_SIGN_TYPE_BROWSE_RESULT:
3209 			case NECP_CLIENT_SIGN_TYPE_SYSTEM_BROWSE_RESULT: {
3210 				if (data_length < (sizeof(struct necp_client_browse_result) - sizeof(struct necp_client_signable))) {
3211 					NECPLOG0(LOG_ERR, "Resolver tag invalid length for browse result");
3212 					matches = false;
3213 				} else {
3214 					struct necp_client_browse_result *answer_struct = (struct necp_client_browse_result *)&validatable->signable;
3215 					if (data_length != (sizeof(struct necp_client_browse_result) + answer_struct->service_length - sizeof(struct necp_client_signable))) {
3216 						NECPLOG0(LOG_ERR, "Resolver tag invalid length for browse result");
3217 						matches = false;
3218 					}
3219 				}
3220 				break;
3221 			}
3222 			case NECP_CLIENT_SIGN_TYPE_SERVICE_RESOLVER_ANSWER:
3223 			case NECP_CLIENT_SIGN_TYPE_SYSTEM_SERVICE_RESOLVER_ANSWER: {
3224 				if (data_length < (sizeof(struct necp_client_service_resolver_answer) - sizeof(struct necp_client_signable))) {
3225 					NECPLOG0(LOG_ERR, "Resolver tag invalid length for service resolver answer");
3226 					matches = false;
3227 				} else {
3228 					struct necp_client_service_resolver_answer *answer_struct = (struct necp_client_service_resolver_answer *)&validatable->signable;
3229 					if (data_length != (sizeof(struct necp_client_service_resolver_answer) + answer_struct->service_length + answer_struct->hostname_length - sizeof(struct necp_client_signable))) {
3230 						NECPLOG0(LOG_ERR, "Resolver tag invalid length for service resolver answer");
3231 						matches = false;
3232 					}
3233 				}
3234 				break;
3235 			}
3236 			default: {
3237 				NECPLOG(LOG_ERR, "Resolver tag unknown sign type: %u", validatable->signable.sign_type);
3238 				matches = false;
3239 				break;
3240 			}
3241 			}
3242 			if (!matches) {
3243 				error = EAUTH;
3244 			} else {
3245 				const bool validated = necp_validate_resolver_answer(validatable->signable.client_id,
3246 				    validatable->signable.sign_type,
3247 				    validatable->signable.signable_data, data_length,
3248 				    validatable->signature.signed_tag, sizeof(validatable->signature.signed_tag));
3249 				if (!validated) {
3250 					error = EAUTH;
3251 					NECPLOG0(LOG_ERR, "Failed to validate resolve answer");
3252 				}
3253 			}
3254 		}
3255 	}
3256 
3257 	if (NECP_ENABLE_CLIENT_TRACE(NECP_CLIENT_TRACE_LEVEL_PARAMS)) {
3258 		necp_client_trace_parsed_parameters(client, parsed_parameters);
3259 	}
3260 
3261 	return error;
3262 }
3263 
3264 static int
necp_client_parse_result(u_int8_t * result,u_int32_t result_size,union necp_sockaddr_union * local_address,union necp_sockaddr_union * remote_address,void ** flow_stats)3265 necp_client_parse_result(u_int8_t *result,
3266     u_int32_t result_size,
3267     union necp_sockaddr_union *local_address,
3268     union necp_sockaddr_union *remote_address,
3269     void **flow_stats)
3270 {
3271 #pragma unused(flow_stats)
3272 	int error = 0;
3273 	size_t offset = 0;
3274 
3275 	while ((offset + sizeof(struct necp_tlv_header)) <= result_size) {
3276 		u_int8_t type = necp_buffer_get_tlv_type(result, offset);
3277 		u_int32_t length = necp_buffer_get_tlv_length(result, offset);
3278 
3279 		if (length > 0 && (offset + sizeof(struct necp_tlv_header) + length) <= result_size) {
3280 			u_int8_t *value = necp_buffer_get_tlv_value(result, offset, NULL);
3281 			if (value != NULL) {
3282 				switch (type) {
3283 				case NECP_CLIENT_RESULT_LOCAL_ENDPOINT: {
3284 					if (length >= sizeof(struct necp_client_endpoint)) {
3285 						struct necp_client_endpoint *endpoint = (struct necp_client_endpoint *)(void *)value;
3286 						if (local_address != NULL && necp_client_address_is_valid(&endpoint->u.sa)) {
3287 							memcpy(local_address, &endpoint->u.sa, endpoint->u.sa.sa_len);
3288 						}
3289 					}
3290 					break;
3291 				}
3292 				case NECP_CLIENT_RESULT_REMOTE_ENDPOINT: {
3293 					if (length >= sizeof(struct necp_client_endpoint)) {
3294 						struct necp_client_endpoint *endpoint = (struct necp_client_endpoint *)(void *)value;
3295 						if (remote_address != NULL && necp_client_address_is_valid(&endpoint->u.sa)) {
3296 							memcpy(remote_address, &endpoint->u.sa, endpoint->u.sa.sa_len);
3297 						}
3298 					}
3299 					break;
3300 				}
3301 #if SKYWALK
3302 				case NECP_CLIENT_RESULT_NEXUS_FLOW_STATS: {
3303 					// this TLV contains flow_stats pointer which is refcnt'ed.
3304 					if (flow_stats != NULL && length >= sizeof(struct sk_stats_flow *)) {
3305 						struct flow_stats *fs = *(void **)(void *)value;
3306 						// transfer the refcnt to flow_stats pointer
3307 						*flow_stats = fs;
3308 					}
3309 					memset(value, 0, length); // nullify TLV always
3310 					break;
3311 				}
3312 #endif /* SKYWALK */
3313 				default: {
3314 					break;
3315 				}
3316 				}
3317 			}
3318 		}
3319 
3320 		offset += sizeof(struct necp_tlv_header) + length;
3321 	}
3322 
3323 	return error;
3324 }
3325 
3326 static struct necp_client_flow_registration *
necp_client_create_flow_registration(struct necp_fd_data * fd_data,struct necp_client * client)3327 necp_client_create_flow_registration(struct necp_fd_data *fd_data, struct necp_client *client)
3328 {
3329 	NECP_FD_ASSERT_LOCKED(fd_data);
3330 	NECP_CLIENT_ASSERT_LOCKED(client);
3331 
3332 	struct necp_client_flow_registration *new_registration = kalloc_type(struct necp_client_flow_registration, Z_WAITOK | Z_ZERO | Z_NOFAIL);
3333 
3334 	new_registration->last_interface_details = combine_interface_details(IFSCOPE_NONE, NSTAT_IFNET_IS_UNKNOWN_TYPE);
3335 
3336 	necp_generate_client_id(new_registration->registration_id, true);
3337 	LIST_INIT(&new_registration->flow_list);
3338 
3339 	// Add registration to client list
3340 	RB_INSERT(_necp_client_flow_tree, &client->flow_registrations, new_registration);
3341 
3342 	// Add registration to fd list
3343 	RB_INSERT(_necp_fd_flow_tree, &fd_data->flows, new_registration);
3344 
3345 	// Add registration to global tree for lookup
3346 	NECP_FLOW_TREE_LOCK_EXCLUSIVE();
3347 	RB_INSERT(_necp_client_flow_global_tree, &necp_client_flow_global_tree, new_registration);
3348 	NECP_FLOW_TREE_UNLOCK();
3349 
3350 	new_registration->client = client;
3351 
3352 #if SKYWALK
3353 	{
3354 		// The uuid caching here is something of a hack, but saves a dynamic lookup with attendant lock hierarchy issues
3355 		uint64_t stats_event_type = (uuid_is_null(client->latest_flow_registration_id)) ? NSTAT_EVENT_SRC_FLOW_UUID_ASSIGNED : NSTAT_EVENT_SRC_FLOW_UUID_CHANGED;
3356 		uuid_copy(client->latest_flow_registration_id, new_registration->registration_id);
3357 
3358 		// With the flow uuid known, push a new statistics update to ensure the uuid gets known by any clients before the flow can close
3359 		if (client->nstat_context != NULL) {
3360 			nstat_provider_stats_event(client->nstat_context, stats_event_type);
3361 		}
3362 	}
3363 #endif /* !SKYWALK */
3364 
3365 	// Start out assuming there is nothing to read from the flow
3366 	new_registration->flow_result_read = true;
3367 
3368 	return new_registration;
3369 }
3370 
3371 static void
necp_client_add_socket_flow(struct necp_client_flow_registration * flow_registration,struct inpcb * inp)3372 necp_client_add_socket_flow(struct necp_client_flow_registration *flow_registration,
3373     struct inpcb *inp)
3374 {
3375 	struct necp_client_flow *new_flow = kalloc_type(struct necp_client_flow, Z_WAITOK | Z_ZERO | Z_NOFAIL);
3376 
3377 	new_flow->socket = TRUE;
3378 	new_flow->u.socket_handle = inp;
3379 	new_flow->u.cb = inp->necp_cb;
3380 
3381 	OSIncrementAtomic(&necp_socket_flow_count);
3382 
3383 	LIST_INSERT_HEAD(&flow_registration->flow_list, new_flow, flow_chain);
3384 }
3385 
3386 static int
necp_client_register_socket_inner(pid_t pid,uuid_t client_id,struct inpcb * inp,bool is_listener)3387 necp_client_register_socket_inner(pid_t pid, uuid_t client_id, struct inpcb *inp, bool is_listener)
3388 {
3389 	int error = 0;
3390 	struct necp_fd_data *client_fd = NULL;
3391 	bool found_client = FALSE;
3392 
3393 	NECP_FD_LIST_LOCK_SHARED();
3394 	LIST_FOREACH(client_fd, &necp_fd_list, chain) {
3395 		NECP_FD_LOCK(client_fd);
3396 		struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
3397 		if (client != NULL) {
3398 			if (!pid || client->proc_pid == pid) {
3399 				if (is_listener) {
3400 					found_client = TRUE;
3401 #if SKYWALK
3402 					// Check netns token for registration
3403 					if (!NETNS_TOKEN_VALID(&client->port_reservation)) {
3404 						error = EINVAL;
3405 					}
3406 #endif /* !SKYWALK */
3407 				} else {
3408 					// Find client flow and assign from socket
3409 					struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
3410 					if (flow_registration != NULL) {
3411 						// Found the right client and flow registration, add a new flow
3412 						found_client = TRUE;
3413 						necp_client_add_socket_flow(flow_registration, inp);
3414 					} else if (RB_EMPTY(&client->flow_registrations) && !necp_client_id_is_flow(client_id)) {
3415 						// No flows yet on this client, add a new registration
3416 						flow_registration = necp_client_create_flow_registration(client_fd, client);
3417 						if (flow_registration == NULL) {
3418 							error = ENOMEM;
3419 						} else {
3420 							// Add a new flow
3421 							found_client = TRUE;
3422 							necp_client_add_socket_flow(flow_registration, inp);
3423 						}
3424 					}
3425 				}
3426 			}
3427 
3428 			NECP_CLIENT_UNLOCK(client);
3429 		}
3430 		NECP_FD_UNLOCK(client_fd);
3431 
3432 		if (found_client) {
3433 			break;
3434 		}
3435 	}
3436 	NECP_FD_LIST_UNLOCK();
3437 
3438 	if (!found_client) {
3439 		error = ENOENT;
3440 	} else {
3441 		// Count the sockets that have the NECP client UUID set
3442 		struct socket *so = inp->inp_socket;
3443 		if (!(so->so_flags1 & SOF1_HAS_NECP_CLIENT_UUID)) {
3444 			so->so_flags1 |= SOF1_HAS_NECP_CLIENT_UUID;
3445 			INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_necp_clientuuid_total);
3446 		}
3447 	}
3448 
3449 	return error;
3450 }
3451 
3452 int
necp_client_register_socket_flow(pid_t pid,uuid_t client_id,struct inpcb * inp)3453 necp_client_register_socket_flow(pid_t pid, uuid_t client_id, struct inpcb *inp)
3454 {
3455 	return necp_client_register_socket_inner(pid, client_id, inp, false);
3456 }
3457 
3458 int
necp_client_register_socket_listener(pid_t pid,uuid_t client_id,struct inpcb * inp)3459 necp_client_register_socket_listener(pid_t pid, uuid_t client_id, struct inpcb *inp)
3460 {
3461 	return necp_client_register_socket_inner(pid, client_id, inp, true);
3462 }
3463 
3464 #if SKYWALK
3465 int
necp_client_get_netns_flow_info(uuid_t client_id,struct ns_flow_info * flow_info)3466 necp_client_get_netns_flow_info(uuid_t client_id, struct ns_flow_info *flow_info)
3467 {
3468 	int error = 0;
3469 	struct necp_fd_data *client_fd = NULL;
3470 	bool found_client = FALSE;
3471 
3472 	NECP_FD_LIST_LOCK_SHARED();
3473 	LIST_FOREACH(client_fd, &necp_fd_list, chain) {
3474 		NECP_FD_LOCK(client_fd);
3475 		struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
3476 		if (client != NULL) {
3477 			found_client = TRUE;
3478 			if (!NETNS_TOKEN_VALID(&client->port_reservation)) {
3479 				error = EINVAL;
3480 			} else {
3481 				error = netns_get_flow_info(&client->port_reservation, flow_info);
3482 			}
3483 
3484 			NECP_CLIENT_UNLOCK(client);
3485 		}
3486 		NECP_FD_UNLOCK(client_fd);
3487 
3488 		if (found_client) {
3489 			break;
3490 		}
3491 	}
3492 	NECP_FD_LIST_UNLOCK();
3493 
3494 	if (!found_client) {
3495 		error = ENOENT;
3496 	}
3497 
3498 	return error;
3499 }
3500 #endif /* !SKYWALK */
3501 
3502 static void
necp_client_add_multipath_interface_flows(struct necp_client_flow_registration * flow_registration,struct necp_client * client,struct mppcb * mpp)3503 necp_client_add_multipath_interface_flows(struct necp_client_flow_registration *flow_registration,
3504     struct necp_client *client,
3505     struct mppcb *mpp)
3506 {
3507 	flow_registration->interface_handle = mpp;
3508 	flow_registration->interface_cb = mpp->necp_cb;
3509 
3510 	proc_t proc = proc_find(client->proc_pid);
3511 	if (proc == PROC_NULL) {
3512 		return;
3513 	}
3514 
3515 	// Traverse all interfaces and add a tracking flow if needed
3516 	necp_flow_add_interface_flows(proc, client, flow_registration, true);
3517 
3518 	proc_rele(proc);
3519 	proc = PROC_NULL;
3520 }
3521 
3522 int
necp_client_register_multipath_cb(pid_t pid,uuid_t client_id,struct mppcb * mpp)3523 necp_client_register_multipath_cb(pid_t pid, uuid_t client_id, struct mppcb *mpp)
3524 {
3525 	int error = 0;
3526 	struct necp_fd_data *client_fd = NULL;
3527 	bool found_client = FALSE;
3528 
3529 	NECP_FD_LIST_LOCK_SHARED();
3530 	LIST_FOREACH(client_fd, &necp_fd_list, chain) {
3531 		NECP_FD_LOCK(client_fd);
3532 		struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
3533 		if (client != NULL) {
3534 			if (!pid || client->proc_pid == pid) {
3535 				struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
3536 				if (flow_registration != NULL) {
3537 					// Found the right client and flow registration, add a new flow
3538 					found_client = TRUE;
3539 					necp_client_add_multipath_interface_flows(flow_registration, client, mpp);
3540 				} else if (RB_EMPTY(&client->flow_registrations) && !necp_client_id_is_flow(client_id)) {
3541 					// No flows yet on this client, add a new registration
3542 					flow_registration = necp_client_create_flow_registration(client_fd, client);
3543 					if (flow_registration == NULL) {
3544 						error = ENOMEM;
3545 					} else {
3546 						// Add a new flow
3547 						found_client = TRUE;
3548 						necp_client_add_multipath_interface_flows(flow_registration, client, mpp);
3549 					}
3550 				}
3551 			}
3552 
3553 			NECP_CLIENT_UNLOCK(client);
3554 		}
3555 		NECP_FD_UNLOCK(client_fd);
3556 
3557 		if (found_client) {
3558 			break;
3559 		}
3560 	}
3561 	NECP_FD_LIST_UNLOCK();
3562 
3563 	if (!found_client && error == 0) {
3564 		error = ENOENT;
3565 	}
3566 
3567 	return error;
3568 }
3569 
3570 #define NETAGENT_DOMAIN_RADIO_MANAGER   "WirelessRadioManager"
3571 #define NETAGENT_TYPE_RADIO_MANAGER     "WirelessRadioManager:BB Manager"
3572 
3573 static int
necp_client_lookup_bb_radio_manager(struct necp_client * client,uuid_t netagent_uuid)3574 necp_client_lookup_bb_radio_manager(struct necp_client *client,
3575     uuid_t netagent_uuid)
3576 {
3577 	char netagent_domain[NETAGENT_DOMAINSIZE];
3578 	char netagent_type[NETAGENT_TYPESIZE];
3579 	struct necp_aggregate_result result;
3580 	proc_t proc;
3581 	int error;
3582 
3583 	proc = proc_find(client->proc_pid);
3584 	if (proc == PROC_NULL) {
3585 		return ESRCH;
3586 	}
3587 
3588 	error = necp_application_find_policy_match_internal(proc, client->parameters, (u_int32_t)client->parameters_length,
3589 	    &result, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, true, true, NULL);
3590 
3591 	proc_rele(proc);
3592 	proc = PROC_NULL;
3593 
3594 	if (error) {
3595 		return error;
3596 	}
3597 
3598 	for (int i = 0; i < NECP_MAX_NETAGENTS; i++) {
3599 		if (uuid_is_null(result.netagents[i])) {
3600 			// Passed end of valid agents
3601 			break;
3602 		}
3603 
3604 		memset(&netagent_domain, 0, NETAGENT_DOMAINSIZE);
3605 		memset(&netagent_type, 0, NETAGENT_TYPESIZE);
3606 		if (netagent_get_agent_domain_and_type(result.netagents[i], netagent_domain, netagent_type) == FALSE) {
3607 			continue;
3608 		}
3609 
3610 		if (strncmp(netagent_domain, NETAGENT_DOMAIN_RADIO_MANAGER, NETAGENT_DOMAINSIZE) != 0) {
3611 			continue;
3612 		}
3613 
3614 		if (strncmp(netagent_type, NETAGENT_TYPE_RADIO_MANAGER, NETAGENT_TYPESIZE) != 0) {
3615 			continue;
3616 		}
3617 
3618 		uuid_copy(netagent_uuid, result.netagents[i]);
3619 
3620 		break;
3621 	}
3622 
3623 	return 0;
3624 }
3625 
3626 static int
necp_client_assert_bb_radio_manager_common(struct necp_client * client,bool assert)3627 necp_client_assert_bb_radio_manager_common(struct necp_client *client, bool assert)
3628 {
3629 	uuid_t netagent_uuid;
3630 	uint8_t assert_type;
3631 	int error;
3632 
3633 	error = necp_client_lookup_bb_radio_manager(client, netagent_uuid);
3634 	if (error) {
3635 		NECPLOG0(LOG_ERR, "BB radio manager agent not found");
3636 		return error;
3637 	}
3638 
3639 	// Before unasserting, verify that the assertion was already taken
3640 	if (assert == FALSE) {
3641 		assert_type = NETAGENT_MESSAGE_TYPE_CLIENT_UNASSERT;
3642 
3643 		if (!necp_client_remove_assertion(client, netagent_uuid)) {
3644 			return EINVAL;
3645 		}
3646 	} else {
3647 		assert_type = NETAGENT_MESSAGE_TYPE_CLIENT_ASSERT;
3648 	}
3649 
3650 	error = netagent_client_message(netagent_uuid, client->client_id, client->proc_pid, client->agent_handle, assert_type);
3651 	if (error) {
3652 		NECPLOG0(LOG_ERR, "netagent_client_message failed");
3653 		return error;
3654 	}
3655 
3656 	// Only save the assertion if the action succeeded
3657 	if (assert == TRUE) {
3658 		necp_client_add_assertion(client, netagent_uuid);
3659 	}
3660 
3661 	return 0;
3662 }
3663 
3664 int
necp_client_assert_bb_radio_manager(uuid_t client_id,bool assert)3665 necp_client_assert_bb_radio_manager(uuid_t client_id, bool assert)
3666 {
3667 	struct necp_client *client;
3668 	int error = 0;
3669 
3670 	NECP_CLIENT_TREE_LOCK_SHARED();
3671 
3672 	client = necp_find_client_and_lock(client_id);
3673 
3674 	if (client) {
3675 		// Found the right client!
3676 		error = necp_client_assert_bb_radio_manager_common(client, assert);
3677 
3678 		NECP_CLIENT_UNLOCK(client);
3679 	} else {
3680 		NECPLOG0(LOG_ERR, "Couldn't find client");
3681 		error = ENOENT;
3682 	}
3683 
3684 	NECP_CLIENT_TREE_UNLOCK();
3685 
3686 	return error;
3687 }
3688 
3689 static int
necp_client_unregister_socket_flow(uuid_t client_id,void * handle)3690 necp_client_unregister_socket_flow(uuid_t client_id, void *handle)
3691 {
3692 	int error = 0;
3693 	struct necp_fd_data *client_fd = NULL;
3694 	bool found_client = FALSE;
3695 	bool client_updated = FALSE;
3696 
3697 	NECP_FD_LIST_LOCK_SHARED();
3698 	LIST_FOREACH(client_fd, &necp_fd_list, chain) {
3699 		NECP_FD_LOCK(client_fd);
3700 
3701 		struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
3702 		if (client != NULL) {
3703 			struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
3704 			if (flow_registration != NULL) {
3705 				// Found the right client and flow!
3706 				found_client = TRUE;
3707 
3708 				// Remove flow assignment
3709 				struct necp_client_flow *search_flow = NULL;
3710 				struct necp_client_flow *temp_flow = NULL;
3711 				LIST_FOREACH_SAFE(search_flow, &flow_registration->flow_list, flow_chain, temp_flow) {
3712 					if (search_flow->socket && search_flow->u.socket_handle == handle) {
3713 						if (search_flow->assigned_results != NULL) {
3714 							kfree_data(search_flow->assigned_results, search_flow->assigned_results_length);
3715 							search_flow->assigned_results = NULL;
3716 						}
3717 						client_updated = TRUE;
3718 						flow_registration->flow_result_read = FALSE;
3719 						LIST_REMOVE(search_flow, flow_chain);
3720 						OSDecrementAtomic(&necp_socket_flow_count);
3721 						kfree_type(struct necp_client_flow, search_flow);
3722 					}
3723 				}
3724 			}
3725 
3726 			NECP_CLIENT_UNLOCK(client);
3727 		}
3728 
3729 		if (client_updated) {
3730 			necp_fd_notify(client_fd, true);
3731 		}
3732 		NECP_FD_UNLOCK(client_fd);
3733 
3734 		if (found_client) {
3735 			break;
3736 		}
3737 	}
3738 	NECP_FD_LIST_UNLOCK();
3739 
3740 	if (!found_client) {
3741 		error = ENOENT;
3742 	}
3743 
3744 	return error;
3745 }
3746 
3747 static int
necp_client_unregister_multipath_cb(uuid_t client_id,void * handle)3748 necp_client_unregister_multipath_cb(uuid_t client_id, void *handle)
3749 {
3750 	int error = 0;
3751 	bool found_client = FALSE;
3752 
3753 	NECP_CLIENT_TREE_LOCK_SHARED();
3754 
3755 	struct necp_client *client = necp_find_client_and_lock(client_id);
3756 	if (client != NULL) {
3757 		struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
3758 		if (flow_registration != NULL) {
3759 			// Found the right client and flow!
3760 			found_client = TRUE;
3761 
3762 			// Remove flow assignment
3763 			struct necp_client_flow *search_flow = NULL;
3764 			struct necp_client_flow *temp_flow = NULL;
3765 			LIST_FOREACH_SAFE(search_flow, &flow_registration->flow_list, flow_chain, temp_flow) {
3766 				if (!search_flow->socket && !search_flow->nexus &&
3767 				    search_flow->u.socket_handle == handle) {
3768 					search_flow->u.socket_handle = NULL;
3769 					search_flow->u.cb = NULL;
3770 				}
3771 			}
3772 
3773 			flow_registration->interface_handle = NULL;
3774 			flow_registration->interface_cb = NULL;
3775 		}
3776 
3777 		NECP_CLIENT_UNLOCK(client);
3778 	}
3779 
3780 	NECP_CLIENT_TREE_UNLOCK();
3781 
3782 	if (!found_client) {
3783 		error = ENOENT;
3784 	}
3785 
3786 	return error;
3787 }
3788 
3789 int
necp_client_assign_from_socket(pid_t pid,uuid_t client_id,struct inpcb * inp)3790 necp_client_assign_from_socket(pid_t pid, uuid_t client_id, struct inpcb *inp)
3791 {
3792 	int error = 0;
3793 	struct necp_fd_data *client_fd = NULL;
3794 	bool found_client = FALSE;
3795 	bool client_updated = FALSE;
3796 
3797 	NECP_FD_LIST_LOCK_SHARED();
3798 	LIST_FOREACH(client_fd, &necp_fd_list, chain) {
3799 		if (pid && client_fd->proc_pid != pid) {
3800 			continue;
3801 		}
3802 
3803 		proc_t proc = proc_find(client_fd->proc_pid);
3804 		if (proc == PROC_NULL) {
3805 			continue;
3806 		}
3807 
3808 		NECP_FD_LOCK(client_fd);
3809 
3810 		struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
3811 		if (client != NULL) {
3812 			struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
3813 			if (flow_registration == NULL && RB_EMPTY(&client->flow_registrations) && !necp_client_id_is_flow(client_id)) {
3814 				// No flows yet on this client, add a new registration
3815 				flow_registration = necp_client_create_flow_registration(client_fd, client);
3816 				if (flow_registration == NULL) {
3817 					error = ENOMEM;
3818 				}
3819 			}
3820 			if (flow_registration != NULL) {
3821 				// Found the right client and flow!
3822 				found_client = TRUE;
3823 
3824 				struct necp_client_flow *flow = NULL;
3825 				LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
3826 					if (flow->socket && flow->u.socket_handle == inp) {
3827 						// Release prior results and route
3828 						if (flow->assigned_results != NULL) {
3829 							kfree_data(flow->assigned_results, flow->assigned_results_length);
3830 							flow->assigned_results = NULL;
3831 						}
3832 
3833 						ifnet_t ifp = NULL;
3834 						if ((inp->inp_flags & INP_BOUND_IF) && inp->inp_boundifp) {
3835 							ifp = inp->inp_boundifp;
3836 						} else {
3837 							ifp = inp->inp_last_outifp;
3838 						}
3839 
3840 						if (ifp != NULL) {
3841 							flow->interface_index = ifp->if_index;
3842 						} else {
3843 							flow->interface_index = IFSCOPE_NONE;
3844 						}
3845 
3846 						if (inp->inp_vflag & INP_IPV4) {
3847 							flow->local_addr.sin.sin_family = AF_INET;
3848 							flow->local_addr.sin.sin_len = sizeof(struct sockaddr_in);
3849 							flow->local_addr.sin.sin_port = inp->inp_lport;
3850 							memcpy(&flow->local_addr.sin.sin_addr, &inp->inp_laddr, sizeof(struct in_addr));
3851 
3852 							flow->remote_addr.sin.sin_family = AF_INET;
3853 							flow->remote_addr.sin.sin_len = sizeof(struct sockaddr_in);
3854 							flow->remote_addr.sin.sin_port = inp->inp_fport;
3855 							memcpy(&flow->remote_addr.sin.sin_addr, &inp->inp_faddr, sizeof(struct in_addr));
3856 						} else if (inp->inp_vflag & INP_IPV6) {
3857 							in6_ip6_to_sockaddr(&inp->in6p_laddr, inp->inp_lport, inp->inp_lifscope, &flow->local_addr.sin6, sizeof(flow->local_addr));
3858 							in6_ip6_to_sockaddr(&inp->in6p_faddr, inp->inp_fport, inp->inp_fifscope, &flow->remote_addr.sin6, sizeof(flow->remote_addr));
3859 						}
3860 
3861 						flow->viable = necp_client_flow_is_viable(proc, client, flow);
3862 
3863 						uuid_t empty_uuid;
3864 						uuid_clear(empty_uuid);
3865 						flow->assigned = TRUE;
3866 						flow->assigned_results = necp_create_nexus_assign_message(empty_uuid, 0, NULL, 0,
3867 						    (struct necp_client_endpoint *)&flow->local_addr,
3868 						    (struct necp_client_endpoint *)&flow->remote_addr,
3869 						    NULL, 0, NULL, &flow->assigned_results_length);
3870 						flow_registration->flow_result_read = FALSE;
3871 						client_updated = TRUE;
3872 						break;
3873 					}
3874 				}
3875 			}
3876 
3877 			NECP_CLIENT_UNLOCK(client);
3878 		}
3879 		if (client_updated) {
3880 			necp_fd_notify(client_fd, true);
3881 		}
3882 		NECP_FD_UNLOCK(client_fd);
3883 
3884 		proc_rele(proc);
3885 		proc = PROC_NULL;
3886 
3887 		if (found_client) {
3888 			break;
3889 		}
3890 	}
3891 	NECP_FD_LIST_UNLOCK();
3892 
3893 	if (error == 0) {
3894 		if (!found_client) {
3895 			error = ENOENT;
3896 		} else if (!client_updated) {
3897 			error = EINVAL;
3898 		}
3899 	}
3900 
3901 	return error;
3902 }
3903 
3904 bool
necp_socket_is_allowed_to_recv_on_interface(struct inpcb * inp,ifnet_t interface)3905 necp_socket_is_allowed_to_recv_on_interface(struct inpcb *inp, ifnet_t interface)
3906 {
3907 	if (interface == NULL ||
3908 	    inp == NULL ||
3909 	    !(inp->inp_flags2 & INP2_EXTERNAL_PORT) ||
3910 	    uuid_is_null(inp->necp_client_uuid)) {
3911 		// If there's no interface or client ID to check,
3912 		// or if this is not a listener, pass.
3913 		// Outbound connections will have already been
3914 		// validated for policy.
3915 		return TRUE;
3916 	}
3917 
3918 	// Only filter out listener sockets (no remote address specified)
3919 	if ((inp->inp_vflag & INP_IPV4) &&
3920 	    inp->inp_faddr.s_addr != INADDR_ANY) {
3921 		return TRUE;
3922 	}
3923 	if ((inp->inp_vflag & INP_IPV6) &&
3924 	    !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
3925 		return TRUE;
3926 	}
3927 
3928 	bool allowed = TRUE;
3929 
3930 	NECP_CLIENT_TREE_LOCK_SHARED();
3931 
3932 	struct necp_client *client = necp_find_client_and_lock(inp->necp_client_uuid);
3933 	if (client != NULL) {
3934 		struct necp_client_parsed_parameters *parsed_parameters = NULL;
3935 
3936 		parsed_parameters = kalloc_type(struct necp_client_parsed_parameters,
3937 		    Z_WAITOK | Z_ZERO | Z_NOFAIL);
3938 		int error = necp_client_parse_parameters(client, client->parameters, (u_int32_t)client->parameters_length, parsed_parameters);
3939 		if (error == 0) {
3940 			if (!necp_ifnet_matches_parameters(interface, parsed_parameters, 0, NULL, true, false)) {
3941 				allowed = FALSE;
3942 			}
3943 		}
3944 		kfree_type(struct necp_client_parsed_parameters, parsed_parameters);
3945 
3946 		NECP_CLIENT_UNLOCK(client);
3947 	}
3948 
3949 	NECP_CLIENT_TREE_UNLOCK();
3950 
3951 	return allowed;
3952 }
3953 
3954 int
necp_update_flow_protoctl_event(uuid_t netagent_uuid,uuid_t client_id,uint32_t protoctl_event_code,uint32_t protoctl_event_val,uint32_t protoctl_event_tcp_seq_number)3955 necp_update_flow_protoctl_event(uuid_t netagent_uuid, uuid_t client_id,
3956     uint32_t protoctl_event_code, uint32_t protoctl_event_val,
3957     uint32_t protoctl_event_tcp_seq_number)
3958 {
3959 	int error = 0;
3960 	struct necp_fd_data *client_fd = NULL;
3961 	bool found_client = FALSE;
3962 	bool client_updated = FALSE;
3963 
3964 	NECP_FD_LIST_LOCK_SHARED();
3965 	LIST_FOREACH(client_fd, &necp_fd_list, chain) {
3966 		proc_t proc = proc_find(client_fd->proc_pid);
3967 		if (proc == PROC_NULL) {
3968 			continue;
3969 		}
3970 
3971 		NECP_FD_LOCK(client_fd);
3972 
3973 		struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
3974 		if (client != NULL) {
3975 			struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
3976 			if (flow_registration != NULL) {
3977 				// Found the right client and flow!
3978 				found_client = TRUE;
3979 
3980 				struct necp_client_flow *flow = NULL;
3981 				LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
3982 					// Verify that the client nexus agent matches
3983 					if ((flow->nexus && uuid_compare(flow->u.nexus_agent, netagent_uuid) == 0) ||
3984 					    flow->socket) {
3985 						flow->has_protoctl_event = TRUE;
3986 						flow->protoctl_event.protoctl_event_code = protoctl_event_code;
3987 						flow->protoctl_event.protoctl_event_val = protoctl_event_val;
3988 						flow->protoctl_event.protoctl_event_tcp_seq_num = protoctl_event_tcp_seq_number;
3989 						flow_registration->flow_result_read = FALSE;
3990 						client_updated = TRUE;
3991 						break;
3992 					}
3993 				}
3994 			}
3995 
3996 			NECP_CLIENT_UNLOCK(client);
3997 		}
3998 
3999 		if (client_updated) {
4000 			necp_fd_notify(client_fd, true);
4001 		}
4002 
4003 		NECP_FD_UNLOCK(client_fd);
4004 		proc_rele(proc);
4005 		proc = PROC_NULL;
4006 
4007 		if (found_client) {
4008 			break;
4009 		}
4010 	}
4011 	NECP_FD_LIST_UNLOCK();
4012 
4013 	if (!found_client) {
4014 		error = ENOENT;
4015 	} else if (!client_updated) {
4016 		error = EINVAL;
4017 	}
4018 	return error;
4019 }
4020 
4021 static bool
necp_assign_client_result_locked(struct proc * proc,struct necp_fd_data * client_fd,struct necp_client * client,struct necp_client_flow_registration * flow_registration,uuid_t netagent_uuid,u_int8_t * assigned_results,size_t assigned_results_length,bool notify_fd,bool assigned_from_userspace_agent)4022 necp_assign_client_result_locked(struct proc *proc,
4023     struct necp_fd_data *client_fd,
4024     struct necp_client *client,
4025     struct necp_client_flow_registration *flow_registration,
4026     uuid_t netagent_uuid,
4027     u_int8_t *assigned_results,
4028     size_t assigned_results_length,
4029     bool notify_fd,
4030     bool assigned_from_userspace_agent)
4031 {
4032 	bool client_updated = FALSE;
4033 
4034 	NECP_FD_ASSERT_LOCKED(client_fd);
4035 	NECP_CLIENT_ASSERT_LOCKED(client);
4036 
4037 	struct necp_client_flow *flow = NULL;
4038 	LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
4039 		// Verify that the client nexus agent matches
4040 		if (flow->nexus &&
4041 		    uuid_compare(flow->u.nexus_agent, netagent_uuid) == 0) {
4042 			// Release prior results and route
4043 			if (flow->assigned_results != NULL) {
4044 				kfree_data(flow->assigned_results, flow->assigned_results_length);
4045 				flow->assigned_results = NULL;
4046 			}
4047 
4048 			void *nexus_stats = NULL;
4049 			if (assigned_results != NULL && assigned_results_length > 0) {
4050 				int error = necp_client_parse_result(assigned_results, (u_int32_t)assigned_results_length,
4051 				    &flow->local_addr, &flow->remote_addr,
4052 				    assigned_from_userspace_agent ? NULL : &nexus_stats); // Only assign stats from kernel agents
4053 				VERIFY(error == 0);
4054 			}
4055 
4056 			flow->viable = necp_client_flow_is_viable(proc, client, flow);
4057 
4058 			flow->assigned = TRUE;
4059 			flow->assigned_results = assigned_results;
4060 			flow->assigned_results_length = assigned_results_length;
4061 			flow_registration->flow_result_read = FALSE;
4062 #if SKYWALK
4063 			if (nexus_stats != NULL) {
4064 				if (flow_registration->nexus_stats != NULL) {
4065 					flow_stats_release(flow_registration->nexus_stats);
4066 				}
4067 				flow_registration->nexus_stats = nexus_stats;
4068 			}
4069 #endif /* SKYWALK */
4070 			client_updated = TRUE;
4071 			break;
4072 		}
4073 	}
4074 
4075 	if (client_updated && notify_fd) {
4076 		necp_fd_notify(client_fd, true);
4077 	}
4078 
4079 	// if not updated, client must free assigned_results
4080 	return client_updated;
4081 }
4082 
4083 int
necp_assign_client_result(uuid_t netagent_uuid,uuid_t client_id,u_int8_t * assigned_results,size_t assigned_results_length)4084 necp_assign_client_result(uuid_t netagent_uuid, uuid_t client_id,
4085     u_int8_t *assigned_results, size_t assigned_results_length)
4086 {
4087 	int error = 0;
4088 	struct necp_fd_data *client_fd = NULL;
4089 	bool found_client = FALSE;
4090 	bool client_updated = FALSE;
4091 
4092 	NECP_FD_LIST_LOCK_SHARED();
4093 
4094 	LIST_FOREACH(client_fd, &necp_fd_list, chain) {
4095 		proc_t proc = proc_find(client_fd->proc_pid);
4096 		if (proc == PROC_NULL) {
4097 			continue;
4098 		}
4099 
4100 		NECP_FD_LOCK(client_fd);
4101 		struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
4102 		if (client != NULL) {
4103 			struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
4104 			if (flow_registration != NULL) {
4105 				// Found the right client and flow!
4106 				found_client = TRUE;
4107 				if (necp_assign_client_result_locked(proc, client_fd, client, flow_registration, netagent_uuid,
4108 				    assigned_results, assigned_results_length, true, true)) {
4109 					client_updated = TRUE;
4110 				}
4111 			}
4112 
4113 			NECP_CLIENT_UNLOCK(client);
4114 		}
4115 		NECP_FD_UNLOCK(client_fd);
4116 
4117 		proc_rele(proc);
4118 		proc = PROC_NULL;
4119 
4120 		if (found_client) {
4121 			break;
4122 		}
4123 	}
4124 
4125 	NECP_FD_LIST_UNLOCK();
4126 
4127 	// upon error, client must free assigned_results
4128 	if (!found_client) {
4129 		error = ENOENT;
4130 	} else if (!client_updated) {
4131 		error = EINVAL;
4132 	}
4133 
4134 	return error;
4135 }
4136 
4137 int
necp_assign_client_group_members(uuid_t netagent_uuid,uuid_t client_id,u_int8_t * assigned_group_members,size_t assigned_group_members_length)4138 necp_assign_client_group_members(uuid_t netagent_uuid, uuid_t client_id,
4139     u_int8_t *assigned_group_members, size_t assigned_group_members_length)
4140 {
4141 #pragma unused(netagent_uuid)
4142 	int error = 0;
4143 	struct necp_fd_data *client_fd = NULL;
4144 	bool found_client = false;
4145 	bool client_updated = false;
4146 
4147 	NECP_FD_LIST_LOCK_SHARED();
4148 
4149 	LIST_FOREACH(client_fd, &necp_fd_list, chain) {
4150 		proc_t proc = proc_find(client_fd->proc_pid);
4151 		if (proc == PROC_NULL) {
4152 			continue;
4153 		}
4154 
4155 		NECP_FD_LOCK(client_fd);
4156 		struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
4157 		if (client != NULL) {
4158 			found_client = true;
4159 			// Release prior results
4160 			if (client->assigned_group_members != NULL) {
4161 				kfree_data(client->assigned_group_members, client->assigned_group_members_length);
4162 				client->assigned_group_members = NULL;
4163 			}
4164 
4165 			// Save new results
4166 			client->assigned_group_members = assigned_group_members;
4167 			client->assigned_group_members_length = assigned_group_members_length;
4168 			client->group_members_read = false;
4169 
4170 			client_updated = true;
4171 			necp_fd_notify(client_fd, true);
4172 
4173 			NECP_CLIENT_UNLOCK(client);
4174 		}
4175 		NECP_FD_UNLOCK(client_fd);
4176 
4177 		proc_rele(proc);
4178 		proc = PROC_NULL;
4179 
4180 		if (found_client) {
4181 			break;
4182 		}
4183 	}
4184 
4185 	NECP_FD_LIST_UNLOCK();
4186 
4187 	// upon error, client must free assigned_results
4188 	if (!found_client) {
4189 		error = ENOENT;
4190 	} else if (!client_updated) {
4191 		error = EINVAL;
4192 	}
4193 
4194 	return error;
4195 }
4196 
4197 /// Client updating
4198 
4199 static bool
necp_update_parsed_parameters(struct necp_client_parsed_parameters * parsed_parameters,struct necp_aggregate_result * result)4200 necp_update_parsed_parameters(struct necp_client_parsed_parameters *parsed_parameters,
4201     struct necp_aggregate_result *result)
4202 {
4203 	if (parsed_parameters == NULL ||
4204 	    result == NULL) {
4205 		return false;
4206 	}
4207 
4208 	bool updated = false;
4209 	for (int i = 0; i < NECP_MAX_NETAGENTS; i++) {
4210 		if (uuid_is_null(result->netagents[i])) {
4211 			// Passed end of valid agents
4212 			break;
4213 		}
4214 
4215 		if (!(result->netagent_use_flags[i] & NECP_AGENT_USE_FLAG_SCOPE)) {
4216 			// Not a scoped agent, ignore
4217 			continue;
4218 		}
4219 
4220 		// This is a scoped agent. Add it to the required agents.
4221 		if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT) {
4222 			// Already some required agents, add this at the end
4223 			for (int j = 0; j < NECP_MAX_AGENT_PARAMETERS; j++) {
4224 				if (uuid_compare(parsed_parameters->required_netagents[j], result->netagents[i]) == 0) {
4225 					// Already required, break
4226 					break;
4227 				}
4228 				if (uuid_is_null(parsed_parameters->required_netagents[j])) {
4229 					// Add here
4230 					memcpy(&parsed_parameters->required_netagents[j], result->netagents[i], sizeof(uuid_t));
4231 					updated = true;
4232 					break;
4233 				}
4234 			}
4235 		} else {
4236 			// No required agents yet, add this one
4237 			parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT;
4238 			memcpy(&parsed_parameters->required_netagents[0], result->netagents[i], sizeof(uuid_t));
4239 			updated = true;
4240 		}
4241 
4242 		// Remove requirements for agents of the same type
4243 		if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE) {
4244 			char remove_agent_domain[NETAGENT_DOMAINSIZE] = { 0 };
4245 			char remove_agent_type[NETAGENT_TYPESIZE] = { 0 };
4246 			if (netagent_get_agent_domain_and_type(result->netagents[i], remove_agent_domain, remove_agent_type)) {
4247 				for (int j = 0; j < NECP_MAX_AGENT_PARAMETERS; j++) {
4248 					if (strlen(parsed_parameters->required_netagent_types[j].netagent_domain) == 0 &&
4249 					    strlen(parsed_parameters->required_netagent_types[j].netagent_type) == 0) {
4250 						break;
4251 					}
4252 
4253 					if (strncmp(parsed_parameters->required_netagent_types[j].netagent_domain, remove_agent_domain, NETAGENT_DOMAINSIZE) == 0 &&
4254 					    strncmp(parsed_parameters->required_netagent_types[j].netagent_type, remove_agent_type, NETAGENT_TYPESIZE) == 0) {
4255 						updated = true;
4256 
4257 						if (j == NECP_MAX_AGENT_PARAMETERS - 1) {
4258 							// Last field, just clear and break
4259 							memset(&parsed_parameters->required_netagent_types[NECP_MAX_AGENT_PARAMETERS - 1], 0, sizeof(struct necp_client_parameter_netagent_type));
4260 							break;
4261 						} else {
4262 							// Move the parameters down, clear the last entry
4263 							memmove(&parsed_parameters->required_netagent_types[j],
4264 							    &parsed_parameters->required_netagent_types[j + 1],
4265 							    sizeof(struct necp_client_parameter_netagent_type) * (NECP_MAX_AGENT_PARAMETERS - (j + 1)));
4266 							memset(&parsed_parameters->required_netagent_types[NECP_MAX_AGENT_PARAMETERS - 1], 0, sizeof(struct necp_client_parameter_netagent_type));
4267 							// Continue, don't increment but look at the new shifted item instead
4268 							continue;
4269 						}
4270 					}
4271 
4272 					// Increment j to look at the next agent type parameter
4273 					j++;
4274 				}
4275 			}
4276 		}
4277 	}
4278 
4279 	if (updated &&
4280 	    parsed_parameters->required_interface_index != IFSCOPE_NONE &&
4281 	    (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IF) == 0) {
4282 		// A required interface index was added after the fact. Clear it.
4283 		parsed_parameters->required_interface_index = IFSCOPE_NONE;
4284 	}
4285 
4286 
4287 	return updated;
4288 }
4289 
4290 static inline bool
necp_agent_types_match(const char * agent_domain1,const char * agent_type1,const char * agent_domain2,const char * agent_type2)4291 necp_agent_types_match(const char *agent_domain1, const char *agent_type1,
4292     const char *agent_domain2, const char *agent_type2)
4293 {
4294 	return (strlen(agent_domain1) == 0 ||
4295 	       strncmp(agent_domain2, agent_domain1, NETAGENT_DOMAINSIZE) == 0) &&
4296 	       (strlen(agent_type1) == 0 ||
4297 	       strncmp(agent_type2, agent_type1, NETAGENT_TYPESIZE) == 0);
4298 }
4299 
4300 static inline bool
necp_calculate_client_result(proc_t proc,struct necp_client * client,struct necp_client_parsed_parameters * parsed_parameters,struct necp_aggregate_result * result,u_int32_t * flags,u_int32_t * reason,struct necp_client_endpoint * v4_gateway,struct necp_client_endpoint * v6_gateway,uuid_t * override_euuid)4301 necp_calculate_client_result(proc_t proc,
4302     struct necp_client *client,
4303     struct necp_client_parsed_parameters *parsed_parameters,
4304     struct necp_aggregate_result *result,
4305     u_int32_t *flags,
4306     u_int32_t *reason,
4307     struct necp_client_endpoint *v4_gateway,
4308     struct necp_client_endpoint *v6_gateway,
4309     uuid_t *override_euuid)
4310 {
4311 	struct rtentry *route = NULL;
4312 
4313 	// Check parameters to find best interface
4314 	bool validate_agents = false;
4315 	u_int matching_if_index = 0;
4316 	if (necp_find_matching_interface_index(parsed_parameters, &matching_if_index, &validate_agents)) {
4317 		if (matching_if_index != 0) {
4318 			parsed_parameters->required_interface_index = matching_if_index;
4319 		}
4320 		// Interface found or not needed, match policy.
4321 		memset(result, 0, sizeof(*result));
4322 		int error = necp_application_find_policy_match_internal(proc, client->parameters,
4323 		    (u_int32_t)client->parameters_length,
4324 		    result, flags, reason, matching_if_index,
4325 		    NULL, NULL,
4326 		    v4_gateway, v6_gateway,
4327 		    &route, false, true,
4328 		    override_euuid);
4329 		if (error != 0) {
4330 			if (route != NULL) {
4331 				rtfree(route);
4332 			}
4333 			return FALSE;
4334 		}
4335 
4336 		if (validate_agents) {
4337 			bool requirement_failed = FALSE;
4338 			if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT) {
4339 				for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
4340 					if (uuid_is_null(parsed_parameters->required_netagents[i])) {
4341 						break;
4342 					}
4343 
4344 					bool requirement_found = FALSE;
4345 					for (int j = 0; j < NECP_MAX_NETAGENTS; j++) {
4346 						if (uuid_is_null(result->netagents[j])) {
4347 							break;
4348 						}
4349 
4350 						if (result->netagent_use_flags[j] & NECP_AGENT_USE_FLAG_REMOVE) {
4351 							// A removed agent, ignore
4352 							continue;
4353 						}
4354 
4355 						if (uuid_compare(parsed_parameters->required_netagents[i], result->netagents[j]) == 0) {
4356 							requirement_found = TRUE;
4357 							break;
4358 						}
4359 					}
4360 
4361 					if (!requirement_found) {
4362 						requirement_failed = TRUE;
4363 						break;
4364 					}
4365 				}
4366 			}
4367 
4368 			if (!requirement_failed && parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE) {
4369 				for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
4370 					if (strlen(parsed_parameters->required_netagent_types[i].netagent_domain) == 0 &&
4371 					    strlen(parsed_parameters->required_netagent_types[i].netagent_type) == 0) {
4372 						break;
4373 					}
4374 
4375 					bool requirement_found = FALSE;
4376 					for (int j = 0; j < NECP_MAX_NETAGENTS; j++) {
4377 						if (uuid_is_null(result->netagents[j])) {
4378 							break;
4379 						}
4380 
4381 						if (result->netagent_use_flags[j] & NECP_AGENT_USE_FLAG_REMOVE) {
4382 							// A removed agent, ignore
4383 							continue;
4384 						}
4385 
4386 						char policy_agent_domain[NETAGENT_DOMAINSIZE] = { 0 };
4387 						char policy_agent_type[NETAGENT_TYPESIZE] = { 0 };
4388 
4389 						if (netagent_get_agent_domain_and_type(result->netagents[j], policy_agent_domain, policy_agent_type)) {
4390 							if (necp_agent_types_match(parsed_parameters->required_netagent_types[i].netagent_domain,
4391 							    parsed_parameters->required_netagent_types[i].netagent_type,
4392 							    policy_agent_domain, policy_agent_type)) {
4393 								requirement_found = TRUE;
4394 								break;
4395 							}
4396 						}
4397 					}
4398 
4399 					if (!requirement_found) {
4400 						requirement_failed = TRUE;
4401 						break;
4402 					}
4403 				}
4404 			}
4405 
4406 			if (requirement_failed) {
4407 				// Agent requirement failed. Clear out the whole result, make everything fail.
4408 				memset(result, 0, sizeof(*result));
4409 				if (route != NULL) {
4410 					rtfree(route);
4411 				}
4412 				return TRUE;
4413 			}
4414 		}
4415 
4416 		// Reset current route
4417 		NECP_CLIENT_ROUTE_LOCK(client);
4418 		if (client->current_route != NULL) {
4419 			rtfree(client->current_route);
4420 		}
4421 		client->current_route = route;
4422 		NECP_CLIENT_ROUTE_UNLOCK(client);
4423 	} else {
4424 		// Interface not found. Clear out the whole result, make everything fail.
4425 		memset(result, 0, sizeof(*result));
4426 	}
4427 
4428 	return TRUE;
4429 }
4430 
4431 #define NECP_PARSED_PARAMETERS_REQUIRED_FIELDS (NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IF |             \
4432 	                                                                                        NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE |          \
4433 	                                                                                        NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT |           \
4434 	                                                                                        NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE)
4435 
4436 static bool
necp_update_client_result(proc_t proc,struct necp_fd_data * client_fd,struct necp_client * client,struct _necp_flow_defunct_list * defunct_list)4437 necp_update_client_result(proc_t proc,
4438     struct necp_fd_data *client_fd,
4439     struct necp_client *client,
4440     struct _necp_flow_defunct_list *defunct_list)
4441 {
4442 	struct necp_client_result_netagent netagent;
4443 	struct necp_aggregate_result result;
4444 	struct necp_client_parsed_parameters *parsed_parameters = NULL;
4445 	u_int32_t flags = 0;
4446 	u_int32_t reason = 0;
4447 
4448 	NECP_CLIENT_ASSERT_LOCKED(client);
4449 
4450 	parsed_parameters = kalloc_type(struct necp_client_parsed_parameters,
4451 	    Z_WAITOK | Z_ZERO | Z_NOFAIL);
4452 
4453 	// Nexus flows will be brought back if they are still valid
4454 	necp_client_mark_all_nonsocket_flows_as_invalid(client);
4455 
4456 	int error = necp_client_parse_parameters(client, client->parameters, (u_int32_t)client->parameters_length, parsed_parameters);
4457 	if (error != 0) {
4458 		kfree_type(struct necp_client_parsed_parameters, parsed_parameters);
4459 		return FALSE;
4460 	}
4461 
4462 	// Update saved IP protocol
4463 	client->ip_protocol = parsed_parameters->ip_protocol;
4464 
4465 	// Calculate the policy result
4466 	struct necp_client_endpoint v4_gateway = {};
4467 	struct necp_client_endpoint v6_gateway = {};
4468 	uuid_t override_euuid;
4469 	uuid_clear(override_euuid);
4470 	if (!necp_calculate_client_result(proc, client, parsed_parameters, &result, &flags, &reason, &v4_gateway, &v6_gateway, &override_euuid)) {
4471 		kfree_type(struct necp_client_parsed_parameters, parsed_parameters);
4472 		return FALSE;
4473 	}
4474 
4475 	if (necp_update_parsed_parameters(parsed_parameters, &result)) {
4476 		// Changed the parameters based on result, try again (only once)
4477 		if (!necp_calculate_client_result(proc, client, parsed_parameters, &result, &flags, &reason, &v4_gateway, &v6_gateway, &override_euuid)) {
4478 			kfree_type(struct necp_client_parsed_parameters, parsed_parameters);
4479 			return FALSE;
4480 		}
4481 	}
4482 
4483 	if ((parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) &&
4484 	    parsed_parameters->required_interface_index != IFSCOPE_NONE &&
4485 	    (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IF) == 0) {
4486 		// Listener should not apply required interface index if
4487 		parsed_parameters->required_interface_index = IFSCOPE_NONE;
4488 	}
4489 
4490 	// Save the last policy id on the client
4491 	client->policy_id = result.policy_id;
4492 	client->skip_policy_id = result.skip_policy_id;
4493 	uuid_copy(client->override_euuid, override_euuid);
4494 
4495 	if ((parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_MULTIPATH) ||
4496 	    (parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_BROWSE) ||
4497 	    ((parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) &&
4498 	    result.routing_result != NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED)) {
4499 		client->allow_multiple_flows = TRUE;
4500 	} else {
4501 		client->allow_multiple_flows = FALSE;
4502 	}
4503 
4504 	// If the original request was scoped, and the policy result matches, make sure the result is scoped
4505 	if ((result.routing_result == NECP_KERNEL_POLICY_RESULT_NONE ||
4506 	    result.routing_result == NECP_KERNEL_POLICY_RESULT_PASS) &&
4507 	    result.routed_interface_index != IFSCOPE_NONE &&
4508 	    parsed_parameters->required_interface_index == result.routed_interface_index) {
4509 		result.routing_result = NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED;
4510 		result.routing_result_parameter.scoped_interface_index = result.routed_interface_index;
4511 	}
4512 
4513 	if (defunct_list != NULL &&
4514 	    result.routing_result == NECP_KERNEL_POLICY_RESULT_DROP) {
4515 		// If we are forced to drop the client, defunct it if it has flows
4516 		necp_defunct_client_for_policy(client, defunct_list);
4517 	}
4518 
4519 	// Recalculate flags
4520 	if (parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) {
4521 		// Listeners are valid as long as they aren't dropped
4522 		if (result.routing_result != NECP_KERNEL_POLICY_RESULT_DROP) {
4523 			flags |= NECP_CLIENT_RESULT_FLAG_SATISFIED;
4524 		}
4525 	} else if (result.routed_interface_index != 0) {
4526 		// Clients without flows determine viability based on having some routable interface
4527 		flags |= NECP_CLIENT_RESULT_FLAG_SATISFIED;
4528 	}
4529 
4530 	bool updated = FALSE;
4531 	u_int8_t *cursor = client->result;
4532 	cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_FLAGS, sizeof(flags), &flags, &updated, client->result, sizeof(client->result));
4533 	if (reason != 0) {
4534 		cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_REASON, sizeof(reason), &reason, &updated, client->result, sizeof(client->result));
4535 	}
4536 	cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_CLIENT_ID, sizeof(uuid_t), client->client_id, &updated,
4537 	    client->result, sizeof(client->result));
4538 	cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_POLICY_RESULT, sizeof(result.routing_result), &result.routing_result, &updated,
4539 	    client->result, sizeof(client->result));
4540 	if (result.routing_result_parameter.tunnel_interface_index != 0) {
4541 		cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_POLICY_RESULT_PARAMETER,
4542 		    sizeof(result.routing_result_parameter), &result.routing_result_parameter, &updated,
4543 		    client->result, sizeof(client->result));
4544 	}
4545 	if (result.filter_control_unit != 0) {
4546 		cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_FILTER_CONTROL_UNIT,
4547 		    sizeof(result.filter_control_unit), &result.filter_control_unit, &updated,
4548 		    client->result, sizeof(client->result));
4549 	}
4550 	if (result.flow_divert_aggregate_unit != 0) {
4551 		cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_FLOW_DIVERT_AGGREGATE_UNIT,
4552 		    sizeof(result.flow_divert_aggregate_unit), &result.flow_divert_aggregate_unit, &updated,
4553 		    client->result, sizeof(client->result));
4554 	}
4555 	if (result.routed_interface_index != 0) {
4556 		u_int routed_interface_index = result.routed_interface_index;
4557 		if (result.routing_result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL &&
4558 		    (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_REQUIRED_FIELDS) &&
4559 		    parsed_parameters->required_interface_index != IFSCOPE_NONE &&
4560 		    parsed_parameters->required_interface_index != result.routed_interface_index) {
4561 			routed_interface_index = parsed_parameters->required_interface_index;
4562 		}
4563 
4564 		cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE_INDEX,
4565 		    sizeof(routed_interface_index), &routed_interface_index, &updated,
4566 		    client->result, sizeof(client->result));
4567 	}
4568 	if (client_fd && client_fd->flags & NECP_OPEN_FLAG_BACKGROUND) {
4569 		u_int32_t effective_traffic_class = SO_TC_BK_SYS;
4570 		cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_EFFECTIVE_TRAFFIC_CLASS,
4571 		    sizeof(effective_traffic_class), &effective_traffic_class, &updated,
4572 		    client->result, sizeof(client->result));
4573 	}
4574 
4575 	if (client_fd->background) {
4576 		bool has_assigned_flow = FALSE;
4577 		struct necp_client_flow_registration *flow_registration = NULL;
4578 		struct necp_client_flow *search_flow = NULL;
4579 		RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
4580 			LIST_FOREACH(search_flow, &flow_registration->flow_list, flow_chain) {
4581 				if (search_flow->assigned) {
4582 					has_assigned_flow = TRUE;
4583 					break;
4584 				}
4585 			}
4586 		}
4587 
4588 		if (has_assigned_flow) {
4589 			u_int32_t background = client_fd->background;
4590 			cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_TRAFFIC_MGMT_BG,
4591 			    sizeof(background), &background, &updated,
4592 			    client->result, sizeof(client->result));
4593 		}
4594 	}
4595 
4596 	bool write_v4_gateway = !necp_client_endpoint_is_unspecified(&v4_gateway);
4597 	bool write_v6_gateway = !necp_client_endpoint_is_unspecified(&v6_gateway);
4598 
4599 	NECP_CLIENT_ROUTE_LOCK(client);
4600 	if (client->current_route != NULL) {
4601 		const u_int32_t route_mtu = get_maxmtu(client->current_route);
4602 		if (route_mtu != 0) {
4603 			cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_EFFECTIVE_MTU,
4604 			    sizeof(route_mtu), &route_mtu, &updated,
4605 			    client->result, sizeof(client->result));
4606 		}
4607 		bool has_remote_addr = parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REMOTE_ADDR;
4608 		if (has_remote_addr && client->current_route->rt_gateway != NULL) {
4609 			if (client->current_route->rt_gateway->sa_family == AF_INET) {
4610 				write_v6_gateway = false;
4611 			} else if (client->current_route->rt_gateway->sa_family == AF_INET6) {
4612 				write_v4_gateway = false;
4613 			}
4614 		}
4615 	}
4616 	NECP_CLIENT_ROUTE_UNLOCK(client);
4617 
4618 	if (write_v4_gateway) {
4619 		cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_GATEWAY,
4620 		    sizeof(struct necp_client_endpoint), &v4_gateway, &updated,
4621 		    client->result, sizeof(client->result));
4622 	}
4623 
4624 	if (write_v6_gateway) {
4625 		cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_GATEWAY,
4626 		    sizeof(struct necp_client_endpoint), &v6_gateway, &updated,
4627 		    client->result, sizeof(client->result));
4628 	}
4629 
4630 	for (int i = 0; i < NAT64_MAX_NUM_PREFIXES; i++) {
4631 		if (result.nat64_prefixes[i].prefix_len != 0) {
4632 			cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_NAT64,
4633 			    sizeof(result.nat64_prefixes), result.nat64_prefixes, &updated,
4634 			    client->result, sizeof(client->result));
4635 			break;
4636 		}
4637 	}
4638 
4639 	if (result.mss_recommended != 0) {
4640 		cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_RECOMMENDED_MSS,
4641 		    sizeof(result.mss_recommended), &result.mss_recommended, &updated,
4642 		    client->result, sizeof(client->result));
4643 	}
4644 
4645 	for (int i = 0; i < NECP_MAX_NETAGENTS; i++) {
4646 		if (uuid_is_null(result.netagents[i])) {
4647 			break;
4648 		}
4649 		if (result.netagent_use_flags[i] & NECP_AGENT_USE_FLAG_REMOVE) {
4650 			// A removed agent, ignore
4651 			continue;
4652 		}
4653 		uuid_copy(netagent.netagent_uuid, result.netagents[i]);
4654 		netagent.generation = netagent_get_generation(netagent.netagent_uuid);
4655 		if (necp_netagent_applies_to_client(client, parsed_parameters, &netagent.netagent_uuid, TRUE, 0, 0)) {
4656 			cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_NETAGENT, sizeof(netagent), &netagent, &updated,
4657 			    client->result, sizeof(client->result));
4658 		}
4659 	}
4660 
4661 	ifnet_head_lock_shared();
4662 	ifnet_t direct_interface = NULL;
4663 	ifnet_t delegate_interface = NULL;
4664 	ifnet_t original_scoped_interface = NULL;
4665 
4666 	if (result.routed_interface_index != IFSCOPE_NONE && result.routed_interface_index <= (u_int32_t)if_index) {
4667 		direct_interface = ifindex2ifnet[result.routed_interface_index];
4668 	} else if (parsed_parameters->required_interface_index != IFSCOPE_NONE &&
4669 	    parsed_parameters->required_interface_index <= (u_int32_t)if_index) {
4670 		// If the request was scoped, but the route didn't match, still grab the agents
4671 		direct_interface = ifindex2ifnet[parsed_parameters->required_interface_index];
4672 	} else if (result.routed_interface_index == IFSCOPE_NONE &&
4673 	    result.routing_result == NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED &&
4674 	    result.routing_result_parameter.scoped_interface_index != IFSCOPE_NONE) {
4675 		direct_interface = ifindex2ifnet[result.routing_result_parameter.scoped_interface_index];
4676 	}
4677 	if (direct_interface != NULL) {
4678 		delegate_interface = direct_interface->if_delegated.ifp;
4679 	}
4680 	if (result.routing_result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL &&
4681 	    (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_REQUIRED_FIELDS) &&
4682 	    parsed_parameters->required_interface_index != IFSCOPE_NONE &&
4683 	    parsed_parameters->required_interface_index != result.routing_result_parameter.tunnel_interface_index &&
4684 	    parsed_parameters->required_interface_index <= (u_int32_t)if_index) {
4685 		original_scoped_interface = ifindex2ifnet[parsed_parameters->required_interface_index];
4686 	}
4687 	// Add interfaces
4688 	if (original_scoped_interface != NULL) {
4689 		struct necp_client_result_interface interface_struct;
4690 		interface_struct.index = original_scoped_interface->if_index;
4691 		interface_struct.generation = ifnet_get_generation(original_scoped_interface);
4692 		cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE, sizeof(interface_struct), &interface_struct, &updated,
4693 		    client->result, sizeof(client->result));
4694 	}
4695 	if (direct_interface != NULL) {
4696 		struct necp_client_result_interface interface_struct;
4697 		interface_struct.index = direct_interface->if_index;
4698 		interface_struct.generation = ifnet_get_generation(direct_interface);
4699 		cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE, sizeof(interface_struct), &interface_struct, &updated,
4700 		    client->result, sizeof(client->result));
4701 
4702 		// Set the delta time since interface up/down
4703 		struct timeval updown_delta = {};
4704 		if (ifnet_updown_delta(direct_interface, &updown_delta) == 0) {
4705 			u_int32_t delta = updown_delta.tv_sec;
4706 			bool ignore_updated = FALSE;
4707 			cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE_TIME_DELTA,
4708 			    sizeof(delta), &delta, &ignore_updated,
4709 			    client->result, sizeof(client->result));
4710 		}
4711 	}
4712 	if (delegate_interface != NULL) {
4713 		struct necp_client_result_interface interface_struct;
4714 		interface_struct.index = delegate_interface->if_index;
4715 		interface_struct.generation = ifnet_get_generation(delegate_interface);
4716 		cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE, sizeof(interface_struct), &interface_struct, &updated,
4717 		    client->result, sizeof(client->result));
4718 	}
4719 
4720 	// Update multipath/listener interface flows
4721 	if (parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_MULTIPATH) {
4722 		// Add the interface option for the routed interface first
4723 		if (direct_interface != NULL) {
4724 			// Add nexus agent
4725 			necp_client_add_agent_interface_options(client, parsed_parameters, direct_interface);
4726 
4727 			// Add interface option in case it is not a nexus
4728 			necp_client_add_interface_option_if_needed(client, direct_interface->if_index,
4729 			    ifnet_get_generation(direct_interface), NULL, false);
4730 		}
4731 		if (parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_INBOUND) {
4732 			// For inbound multipath, add from the global list (like a listener)
4733 			struct ifnet *multi_interface = NULL;
4734 			TAILQ_FOREACH(multi_interface, &ifnet_head, if_link) {
4735 				if ((multi_interface->if_flags & (IFF_UP | IFF_RUNNING)) &&
4736 				    necp_ifnet_matches_parameters(multi_interface, parsed_parameters, 0, NULL, true, false)) {
4737 					// Add nexus agents for inbound multipath
4738 					necp_client_add_agent_interface_options(client, parsed_parameters, multi_interface);
4739 				}
4740 			}
4741 		} else {
4742 			// Get other multipath interface options from ordered list
4743 			struct ifnet *multi_interface = NULL;
4744 			TAILQ_FOREACH(multi_interface, &ifnet_ordered_head, if_ordered_link) {
4745 				if (multi_interface != direct_interface &&
4746 				    necp_ifnet_matches_parameters(multi_interface, parsed_parameters, 0, NULL, true, false)) {
4747 					// Add nexus agents for multipath
4748 					necp_client_add_agent_interface_options(client, parsed_parameters, multi_interface);
4749 
4750 					// Add multipath interface flows for kernel MPTCP
4751 					necp_client_add_interface_option_if_needed(client, multi_interface->if_index,
4752 					    ifnet_get_generation(multi_interface), NULL, false);
4753 				}
4754 			}
4755 		}
4756 	} else if (parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) {
4757 		if (result.routing_result == NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED) {
4758 			if (direct_interface != NULL) {
4759 				// If scoped, only listen on that interface
4760 				// Add nexus agents for listeners
4761 				necp_client_add_agent_interface_options(client, parsed_parameters, direct_interface);
4762 
4763 				// Add interface option in case it is not a nexus
4764 				necp_client_add_interface_option_if_needed(client, direct_interface->if_index,
4765 				    ifnet_get_generation(direct_interface), NULL, false);
4766 			}
4767 		} else {
4768 			// Get listener interface options from global list
4769 			struct ifnet *listen_interface = NULL;
4770 			TAILQ_FOREACH(listen_interface, &ifnet_head, if_link) {
4771 				if ((listen_interface->if_flags & (IFF_UP | IFF_RUNNING)) &&
4772 				    necp_ifnet_matches_parameters(listen_interface, parsed_parameters, 0, NULL, true, false)) {
4773 					// Add nexus agents for listeners
4774 					necp_client_add_agent_interface_options(client, parsed_parameters, listen_interface);
4775 				}
4776 			}
4777 		}
4778 	} else if (parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_BROWSE) {
4779 		if (result.routing_result == NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED) {
4780 			if (direct_interface != NULL) {
4781 				// Add browse option if it has an agent
4782 				necp_client_add_browse_interface_options(client, parsed_parameters, direct_interface);
4783 			}
4784 		} else {
4785 			// Get browse interface options from global list
4786 			struct ifnet *browse_interface = NULL;
4787 			TAILQ_FOREACH(browse_interface, &ifnet_head, if_link) {
4788 				if (necp_ifnet_matches_parameters(browse_interface, parsed_parameters, 0, NULL, true, false)) {
4789 					necp_client_add_browse_interface_options(client, parsed_parameters, browse_interface);
4790 				}
4791 			}
4792 		}
4793 	}
4794 
4795 	struct necp_client_result_estimated_throughput throughput = {
4796 		.up = 0,
4797 		.down = 0,
4798 	};
4799 
4800 	// Add agents
4801 	if (original_scoped_interface != NULL) {
4802 		ifnet_lock_shared(original_scoped_interface);
4803 		if (original_scoped_interface->if_agentids != NULL) {
4804 			for (u_int32_t i = 0; i < original_scoped_interface->if_agentcount; i++) {
4805 				if (uuid_is_null(original_scoped_interface->if_agentids[i])) {
4806 					continue;
4807 				}
4808 				bool skip_agent = false;
4809 				for (int j = 0; j < NECP_MAX_NETAGENTS; j++) {
4810 					if (uuid_is_null(result.netagents[j])) {
4811 						break;
4812 					}
4813 					if ((result.netagent_use_flags[j] & NECP_AGENT_USE_FLAG_REMOVE) &&
4814 					    uuid_compare(original_scoped_interface->if_agentids[i], result.netagents[j]) == 0) {
4815 						skip_agent = true;
4816 						break;
4817 					}
4818 				}
4819 				if (skip_agent) {
4820 					continue;
4821 				}
4822 				uuid_copy(netagent.netagent_uuid, original_scoped_interface->if_agentids[i]);
4823 				netagent.generation = netagent_get_generation(netagent.netagent_uuid);
4824 				if (necp_netagent_applies_to_client(client, parsed_parameters, &netagent.netagent_uuid, FALSE,
4825 				    original_scoped_interface->if_index, ifnet_get_generation(original_scoped_interface))) {
4826 					cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_NETAGENT, sizeof(netagent), &netagent, &updated,
4827 					    client->result, sizeof(client->result));
4828 				}
4829 			}
4830 		}
4831 		ifnet_lock_done(original_scoped_interface);
4832 	}
4833 	if (direct_interface != NULL) {
4834 		ifnet_lock_shared(direct_interface);
4835 		throughput.up = direct_interface->if_estimated_up_bucket;
4836 		throughput.down = direct_interface->if_estimated_down_bucket;
4837 		if (direct_interface->if_agentids != NULL) {
4838 			for (u_int32_t i = 0; i < direct_interface->if_agentcount; i++) {
4839 				if (uuid_is_null(direct_interface->if_agentids[i])) {
4840 					continue;
4841 				}
4842 				bool skip_agent = false;
4843 				for (int j = 0; j < NECP_MAX_NETAGENTS; j++) {
4844 					if (uuid_is_null(result.netagents[j])) {
4845 						break;
4846 					}
4847 					if ((result.netagent_use_flags[j] & NECP_AGENT_USE_FLAG_REMOVE) &&
4848 					    uuid_compare(direct_interface->if_agentids[i], result.netagents[j]) == 0) {
4849 						skip_agent = true;
4850 						break;
4851 					}
4852 				}
4853 				if (skip_agent) {
4854 					continue;
4855 				}
4856 				uuid_copy(netagent.netagent_uuid, direct_interface->if_agentids[i]);
4857 				netagent.generation = netagent_get_generation(netagent.netagent_uuid);
4858 				if (necp_netagent_applies_to_client(client, parsed_parameters, &netagent.netagent_uuid, TRUE,
4859 				    direct_interface->if_index, ifnet_get_generation(direct_interface))) {
4860 					cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_NETAGENT, sizeof(netagent), &netagent, &updated,
4861 					    client->result, sizeof(client->result));
4862 				}
4863 			}
4864 		}
4865 		ifnet_lock_done(direct_interface);
4866 	}
4867 	if (delegate_interface != NULL) {
4868 		ifnet_lock_shared(delegate_interface);
4869 		if (throughput.up == 0 && throughput.down == 0) {
4870 			throughput.up = delegate_interface->if_estimated_up_bucket;
4871 			throughput.down = delegate_interface->if_estimated_down_bucket;
4872 		}
4873 		if (delegate_interface->if_agentids != NULL) {
4874 			for (u_int32_t i = 0; i < delegate_interface->if_agentcount; i++) {
4875 				if (uuid_is_null(delegate_interface->if_agentids[i])) {
4876 					continue;
4877 				}
4878 				bool skip_agent = false;
4879 				for (int j = 0; j < NECP_MAX_NETAGENTS; j++) {
4880 					if (uuid_is_null(result.netagents[j])) {
4881 						break;
4882 					}
4883 					if ((result.netagent_use_flags[j] & NECP_AGENT_USE_FLAG_REMOVE) &&
4884 					    uuid_compare(delegate_interface->if_agentids[i], result.netagents[j]) == 0) {
4885 						skip_agent = true;
4886 						break;
4887 					}
4888 				}
4889 				if (skip_agent) {
4890 					continue;
4891 				}
4892 				uuid_copy(netagent.netagent_uuid, delegate_interface->if_agentids[i]);
4893 				netagent.generation = netagent_get_generation(netagent.netagent_uuid);
4894 				if (necp_netagent_applies_to_client(client, parsed_parameters, &netagent.netagent_uuid, FALSE,
4895 				    delegate_interface->if_index, ifnet_get_generation(delegate_interface))) {
4896 					cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_NETAGENT, sizeof(netagent), &netagent, &updated,
4897 					    client->result, sizeof(client->result));
4898 				}
4899 			}
4900 		}
4901 		ifnet_lock_done(delegate_interface);
4902 	}
4903 	ifnet_head_done();
4904 
4905 	if (throughput.up != 0 || throughput.down != 0) {
4906 		cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_ESTIMATED_THROUGHPUT,
4907 		    sizeof(throughput), &throughput, &updated, client->result, sizeof(client->result));
4908 	}
4909 
4910 	// Add interface options
4911 	for (u_int32_t option_i = 0; option_i < client->interface_option_count; option_i++) {
4912 		if (option_i < NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT) {
4913 			struct necp_client_interface_option *option = &client->interface_options[option_i];
4914 			cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE_OPTION, sizeof(*option), option, &updated,
4915 			    client->result, sizeof(client->result));
4916 		} else {
4917 			struct necp_client_interface_option *option = &client->extra_interface_options[option_i - NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT];
4918 			cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE_OPTION, sizeof(*option), option, &updated,
4919 			    client->result, sizeof(client->result));
4920 		}
4921 	}
4922 
4923 	size_t new_result_length = (cursor - client->result);
4924 	if (new_result_length != client->result_length) {
4925 		client->result_length = new_result_length;
4926 		updated = TRUE;
4927 	}
4928 
4929 	// Update flow viability/flags
4930 	if (necp_client_update_flows(proc, client, defunct_list)) {
4931 		updated = TRUE;
4932 	}
4933 
4934 	if (updated) {
4935 		client->result_read = FALSE;
4936 		necp_client_update_observer_update(client);
4937 	}
4938 
4939 	kfree_type(struct necp_client_parsed_parameters, parsed_parameters);
4940 	return updated;
4941 }
4942 
4943 static bool
necp_defunct_client_fd_locked_inner(struct necp_fd_data * client_fd,struct _necp_flow_defunct_list * defunct_list,bool destroy_stats)4944 necp_defunct_client_fd_locked_inner(struct necp_fd_data *client_fd, struct _necp_flow_defunct_list *defunct_list, bool destroy_stats)
4945 {
4946 	bool updated_result = FALSE;
4947 	struct necp_client *client = NULL;
4948 
4949 	NECP_FD_ASSERT_LOCKED(client_fd);
4950 
4951 	RB_FOREACH(client, _necp_client_tree, &client_fd->clients) {
4952 		struct necp_client_flow_registration *flow_registration = NULL;
4953 
4954 		NECP_CLIENT_LOCK(client);
4955 
4956 		// Prepare close events to be sent to the nexus to effectively remove the flows
4957 		struct necp_client_flow *search_flow = NULL;
4958 		RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
4959 			LIST_FOREACH(search_flow, &flow_registration->flow_list, flow_chain) {
4960 				if (search_flow->nexus &&
4961 				    !uuid_is_null(search_flow->u.nexus_agent)) {
4962 					// Sleeping alloc won't fail; copy only what's necessary
4963 					struct necp_flow_defunct *flow_defunct = kalloc_type(struct necp_flow_defunct, Z_WAITOK | Z_ZERO);
4964 					uuid_copy(flow_defunct->nexus_agent, search_flow->u.nexus_agent);
4965 					uuid_copy(flow_defunct->flow_id, ((flow_registration->flags & NECP_CLIENT_FLOW_FLAGS_USE_CLIENT_ID) ?
4966 					    client->client_id :
4967 					    flow_registration->registration_id));
4968 					flow_defunct->proc_pid = client->proc_pid;
4969 					flow_defunct->agent_handle = client->agent_handle;
4970 					flow_defunct->flags = flow_registration->flags;
4971 #if SKYWALK
4972 					if (flow_registration->kstats_kaddr != NULL) {
4973 						struct necp_all_stats *ustats_kaddr = ((struct necp_all_kstats *)flow_registration->kstats_kaddr)->necp_stats_ustats;
4974 						struct necp_quic_stats *quicstats = (struct necp_quic_stats *)ustats_kaddr;
4975 						if (quicstats != NULL &&
4976 						    quicstats->necp_quic_udp_stats.necp_udp_hdr.necp_stats_type == NECP_CLIENT_STATISTICS_TYPE_QUIC) {
4977 							memcpy(flow_defunct->close_parameters.u.close_token, quicstats->necp_quic_extra.ssr_token, sizeof(flow_defunct->close_parameters.u.close_token));
4978 							flow_defunct->has_close_parameters = true;
4979 						}
4980 					}
4981 #endif /* SKYWALK */
4982 					// Add to the list provided by caller
4983 					LIST_INSERT_HEAD(defunct_list, flow_defunct, chain);
4984 
4985 					flow_registration->defunct = true;
4986 					flow_registration->flow_result_read = false;
4987 					updated_result = true;
4988 				}
4989 			}
4990 		}
4991 		if (destroy_stats) {
4992 #if SKYWALK
4993 			// Free any remaining stats objects back to the arena where they came from;
4994 			// do this independent of the above defunct check, as the client may have
4995 			// been marked as defunct separately via necp_defunct_client_for_policy().
4996 			RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
4997 				necp_destroy_flow_stats(client_fd, flow_registration, NULL, FALSE);
4998 			}
4999 #endif /* SKYWALK */
5000 		}
5001 		NECP_CLIENT_UNLOCK(client);
5002 	}
5003 
5004 	return updated_result;
5005 }
5006 
5007 static inline void
necp_defunct_client_fd_locked(struct necp_fd_data * client_fd,struct _necp_flow_defunct_list * defunct_list,struct proc * proc)5008 necp_defunct_client_fd_locked(struct necp_fd_data *client_fd, struct _necp_flow_defunct_list *defunct_list, struct proc *proc)
5009 {
5010 #pragma unused(proc)
5011 	bool updated_result = FALSE;
5012 
5013 	NECP_FD_ASSERT_LOCKED(client_fd);
5014 #if SKYWALK
5015 	// redirect regions of currently-active stats arena to zero-filled pages
5016 	struct necp_arena_info *nai = necp_fd_mredirect_stats_arena(client_fd, proc);
5017 #endif /* SKYWALK */
5018 
5019 	updated_result = necp_defunct_client_fd_locked_inner(client_fd, defunct_list, true);
5020 
5021 #if SKYWALK
5022 	// and tear down the currently-active arena's regions now that the redirection and freeing are done
5023 	if (nai != NULL) {
5024 		ASSERT((nai->nai_flags & (NAIF_REDIRECT | NAIF_DEFUNCT)) == NAIF_REDIRECT);
5025 		ASSERT(nai->nai_arena != NULL);
5026 		ASSERT(nai->nai_mmap.ami_mapref != NULL);
5027 
5028 		int err = skmem_arena_defunct(nai->nai_arena);
5029 		VERIFY(err == 0);
5030 
5031 		nai->nai_flags |= NAIF_DEFUNCT;
5032 	}
5033 #endif /* SKYWALK */
5034 
5035 	if (updated_result) {
5036 		necp_fd_notify(client_fd, true);
5037 	}
5038 }
5039 
5040 static inline void
necp_update_client_fd_locked(struct necp_fd_data * client_fd,proc_t proc,struct _necp_flow_defunct_list * defunct_list)5041 necp_update_client_fd_locked(struct necp_fd_data *client_fd,
5042     proc_t proc,
5043     struct _necp_flow_defunct_list *defunct_list)
5044 {
5045 	struct necp_client *client = NULL;
5046 	bool updated_result = FALSE;
5047 	NECP_FD_ASSERT_LOCKED(client_fd);
5048 	RB_FOREACH(client, _necp_client_tree, &client_fd->clients) {
5049 		NECP_CLIENT_LOCK(client);
5050 		if (necp_update_client_result(proc, client_fd, client, defunct_list)) {
5051 			updated_result = TRUE;
5052 		}
5053 		NECP_CLIENT_UNLOCK(client);
5054 	}
5055 
5056 	// Check if this PID needs to request in-process flow divert
5057 	NECP_FD_LIST_ASSERT_LOCKED();
5058 	for (int i = 0; i < NECP_MAX_FLOW_DIVERT_NEEDED_PIDS; i++) {
5059 		if (necp_flow_divert_needed_pids[i] == 0) {
5060 			break;
5061 		}
5062 		if (necp_flow_divert_needed_pids[i] == client_fd->proc_pid) {
5063 			client_fd->request_in_process_flow_divert = true;
5064 			break;
5065 		}
5066 	}
5067 
5068 	if (updated_result || client_fd->request_in_process_flow_divert) {
5069 		necp_fd_notify(client_fd, true);
5070 	}
5071 }
5072 
5073 #if SKYWALK
5074 static void
necp_close_empty_arenas_callout(__unused thread_call_param_t dummy,__unused thread_call_param_t arg)5075 necp_close_empty_arenas_callout(__unused thread_call_param_t dummy,
5076     __unused thread_call_param_t arg)
5077 {
5078 	struct necp_fd_data *client_fd = NULL;
5079 
5080 	NECP_FD_LIST_LOCK_SHARED();
5081 
5082 	LIST_FOREACH(client_fd, &necp_fd_list, chain) {
5083 		NECP_FD_LOCK(client_fd);
5084 		necp_stats_arenas_destroy(client_fd, FALSE);
5085 		NECP_FD_UNLOCK(client_fd);
5086 	}
5087 
5088 	NECP_FD_LIST_UNLOCK();
5089 }
5090 #endif /* SKYWALK */
5091 
5092 static void
necp_update_all_clients_callout(__unused thread_call_param_t dummy,__unused thread_call_param_t arg)5093 necp_update_all_clients_callout(__unused thread_call_param_t dummy,
5094     __unused thread_call_param_t arg)
5095 {
5096 	struct necp_fd_data *client_fd = NULL;
5097 
5098 	NECP_UPDATE_ALL_CLIENTS_LOCK_EXCLUSIVE();
5099 	uint32_t count = necp_update_all_clients_sched_cnt;
5100 	necp_update_all_clients_sched_cnt = 0;
5101 	necp_update_all_clients_sched_abstime = 0;
5102 	NECP_UPDATE_ALL_CLIENTS_UNLOCK();
5103 
5104 	if (necp_debug > 0) {
5105 		NECPLOG(LOG_DEBUG,
5106 		    "necp_update_all_clients_callout running for coalesced %u updates",
5107 		    count);
5108 	}
5109 
5110 	struct _necp_flow_defunct_list defunct_list;
5111 	LIST_INIT(&defunct_list);
5112 
5113 	NECP_FD_LIST_LOCK_SHARED();
5114 
5115 	LIST_FOREACH(client_fd, &necp_fd_list, chain) {
5116 		proc_t proc = proc_find(client_fd->proc_pid);
5117 		if (proc == PROC_NULL) {
5118 			continue;
5119 		}
5120 
5121 		// Update all clients on one fd
5122 		NECP_FD_LOCK(client_fd);
5123 		necp_update_client_fd_locked(client_fd, proc, &defunct_list);
5124 		NECP_FD_UNLOCK(client_fd);
5125 
5126 		proc_rele(proc);
5127 		proc = PROC_NULL;
5128 	}
5129 
5130 	// Reset the necp_flow_divert_needed_pids list
5131 	for (int i = 0; i < NECP_MAX_FLOW_DIVERT_NEEDED_PIDS; i++) {
5132 		necp_flow_divert_needed_pids[i] = 0;
5133 	}
5134 
5135 	NECP_FD_LIST_UNLOCK();
5136 
5137 	// Handle the case in which some clients became newly defunct
5138 	necp_process_defunct_list(&defunct_list);
5139 }
5140 
5141 void
necp_update_all_clients(void)5142 necp_update_all_clients(void)
5143 {
5144 	necp_update_all_clients_immediately_if_needed(false);
5145 }
5146 
5147 void
necp_update_all_clients_immediately_if_needed(bool should_update_immediately)5148 necp_update_all_clients_immediately_if_needed(bool should_update_immediately)
5149 {
5150 	if (necp_client_update_tcall == NULL) {
5151 		// Don't try to update clients if the module is not initialized
5152 		return;
5153 	}
5154 
5155 	uint64_t deadline = 0;
5156 	uint64_t leeway = 0;
5157 
5158 	uint32_t timeout_to_use = necp_timeout_microseconds;
5159 	uint32_t leeway_to_use = necp_timeout_leeway_microseconds;
5160 	if (should_update_immediately) {
5161 		timeout_to_use = 1000 * 10; // 10ms
5162 		leeway_to_use = 1000 * 10; // 10ms;
5163 	}
5164 
5165 	clock_interval_to_deadline(timeout_to_use, NSEC_PER_USEC, &deadline);
5166 	clock_interval_to_absolutetime_interval(leeway_to_use, NSEC_PER_USEC, &leeway);
5167 
5168 	NECP_UPDATE_ALL_CLIENTS_LOCK_EXCLUSIVE();
5169 	bool need_cancel = false;
5170 	bool need_schedule = true;
5171 	uint64_t sched_abstime;
5172 
5173 	clock_absolutetime_interval_to_deadline(deadline + leeway, &sched_abstime);
5174 
5175 	/*
5176 	 * Do not push the timer if it is already scheduled
5177 	 */
5178 	if (necp_update_all_clients_sched_abstime != 0) {
5179 		need_schedule = false;
5180 
5181 		if (should_update_immediately) {
5182 			/*
5183 			 * To update immediately we may have to cancel the current timer
5184 			 * if it's scheduled too far out.
5185 			 */
5186 			if (necp_update_all_clients_sched_abstime > sched_abstime) {
5187 				need_cancel = true;
5188 				need_schedule = true;
5189 			}
5190 		}
5191 	}
5192 
5193 	/*
5194 	 * Record the time of the deadline with leeway
5195 	 */
5196 	if (need_schedule) {
5197 		necp_update_all_clients_sched_abstime = sched_abstime;
5198 	}
5199 
5200 	necp_update_all_clients_sched_cnt += 1;
5201 	uint32_t count = necp_update_all_clients_sched_cnt;
5202 	NECP_UPDATE_ALL_CLIENTS_UNLOCK();
5203 
5204 	if (need_schedule) {
5205 		/*
5206 		 * Wait if the thread call is currently executing to make sure the
5207 		 * next update will be delivered to all clients
5208 		 */
5209 		if (need_cancel) {
5210 			(void) thread_call_cancel_wait(necp_client_update_tcall);
5211 		}
5212 
5213 		(void) thread_call_enter_delayed_with_leeway(necp_client_update_tcall, NULL,
5214 		    deadline, leeway, THREAD_CALL_DELAY_LEEWAY);
5215 	}
5216 	if (necp_debug > 0) {
5217 		NECPLOG(LOG_DEBUG,
5218 		    "necp_update_all_clients immediate %s update %u",
5219 		    should_update_immediately ? "true" : "false", count);
5220 	}
5221 }
5222 
5223 bool
necp_set_client_as_background(proc_t proc,struct fileproc * fp,bool background)5224 necp_set_client_as_background(proc_t proc,
5225     struct fileproc *fp,
5226     bool background)
5227 {
5228 	if (proc == PROC_NULL) {
5229 		NECPLOG0(LOG_ERR, "NULL proc");
5230 		return FALSE;
5231 	}
5232 
5233 	if (fp == NULL) {
5234 		NECPLOG0(LOG_ERR, "NULL fp");
5235 		return FALSE;
5236 	}
5237 
5238 	struct necp_fd_data *client_fd = (struct necp_fd_data *)fp_get_data(fp);
5239 	if (client_fd == NULL) {
5240 		NECPLOG0(LOG_ERR, "Could not find client structure for backgrounded client");
5241 		return FALSE;
5242 	}
5243 
5244 	if (client_fd->necp_fd_type != necp_fd_type_client) {
5245 		// Not a client fd, ignore
5246 		NECPLOG0(LOG_ERR, "Not a client fd, ignore");
5247 		return FALSE;
5248 	}
5249 
5250 	client_fd->background = background;
5251 
5252 	return TRUE;
5253 }
5254 
5255 void
necp_fd_memstatus(proc_t proc,uint32_t status,struct necp_fd_data * client_fd)5256 necp_fd_memstatus(proc_t proc, uint32_t status,
5257     struct necp_fd_data *client_fd)
5258 {
5259 #pragma unused(proc, status, client_fd)
5260 	ASSERT(proc != PROC_NULL);
5261 	ASSERT(client_fd != NULL);
5262 
5263 	// Nothing to reap for the process or client for now,
5264 	// but this is where we would trigger that in future.
5265 }
5266 
5267 void
necp_fd_defunct(proc_t proc,struct necp_fd_data * client_fd)5268 necp_fd_defunct(proc_t proc, struct necp_fd_data *client_fd)
5269 {
5270 	struct _necp_flow_defunct_list defunct_list;
5271 
5272 	ASSERT(proc != PROC_NULL);
5273 	ASSERT(client_fd != NULL);
5274 
5275 	if (client_fd->necp_fd_type != necp_fd_type_client) {
5276 		// Not a client fd, ignore
5277 		return;
5278 	}
5279 
5280 	// Our local temporary list
5281 	LIST_INIT(&defunct_list);
5282 
5283 	// Need to hold lock so ntstats defunct the same set of clients
5284 	NECP_FD_LOCK(client_fd);
5285 #if SKYWALK
5286 	// Shut down statistics
5287 	nstats_userland_stats_defunct_for_process(proc_getpid(proc));
5288 #endif /* SKYWALK */
5289 	necp_defunct_client_fd_locked(client_fd, &defunct_list, proc);
5290 	NECP_FD_UNLOCK(client_fd);
5291 
5292 	necp_process_defunct_list(&defunct_list);
5293 }
5294 
5295 void
necp_client_request_in_process_flow_divert(pid_t pid)5296 necp_client_request_in_process_flow_divert(pid_t pid)
5297 {
5298 	if (pid == 0) {
5299 		return;
5300 	}
5301 
5302 	// Add to the list of pids that should get an update. These will
5303 	// get picked up on the next thread call to update client paths.
5304 	NECP_FD_LIST_LOCK_SHARED();
5305 	for (int i = 0; i < NECP_MAX_FLOW_DIVERT_NEEDED_PIDS; i++) {
5306 		if (necp_flow_divert_needed_pids[i] == 0) {
5307 			necp_flow_divert_needed_pids[i] = pid;
5308 			break;
5309 		}
5310 	}
5311 	NECP_FD_LIST_UNLOCK();
5312 }
5313 
5314 static void
necp_client_remove_agent_from_result(struct necp_client * client,uuid_t netagent_uuid)5315 necp_client_remove_agent_from_result(struct necp_client *client, uuid_t netagent_uuid)
5316 {
5317 	size_t offset = 0;
5318 
5319 	u_int8_t *result_buffer = client->result;
5320 	while ((offset + sizeof(struct necp_tlv_header)) <= client->result_length) {
5321 		u_int8_t type = necp_buffer_get_tlv_type(result_buffer, offset);
5322 		u_int32_t length = necp_buffer_get_tlv_length(result_buffer, offset);
5323 
5324 		size_t tlv_total_length = (sizeof(struct necp_tlv_header) + length);
5325 		if (type == NECP_CLIENT_RESULT_NETAGENT &&
5326 		    length == sizeof(struct necp_client_result_netagent) &&
5327 		    (offset + tlv_total_length) <= client->result_length) {
5328 			struct necp_client_result_netagent *value = ((struct necp_client_result_netagent *)(void *)
5329 			    necp_buffer_get_tlv_value(result_buffer, offset, NULL));
5330 			if (uuid_compare(value->netagent_uuid, netagent_uuid) == 0) {
5331 				// Found a netagent to remove
5332 				// Shift bytes down to remove the tlv, and adjust total length
5333 				// Don't adjust the current offset
5334 				memmove(result_buffer + offset,
5335 				    result_buffer + offset + tlv_total_length,
5336 				    client->result_length - (offset + tlv_total_length));
5337 				client->result_length -= tlv_total_length;
5338 				memset(result_buffer + client->result_length, 0, sizeof(client->result) - client->result_length);
5339 				continue;
5340 			}
5341 		}
5342 
5343 		offset += tlv_total_length;
5344 	}
5345 }
5346 
5347 void
necp_force_update_client(uuid_t client_id,uuid_t remove_netagent_uuid,u_int32_t agent_generation)5348 necp_force_update_client(uuid_t client_id, uuid_t remove_netagent_uuid, u_int32_t agent_generation)
5349 {
5350 	struct necp_fd_data *client_fd = NULL;
5351 
5352 	NECP_FD_LIST_LOCK_SHARED();
5353 
5354 	LIST_FOREACH(client_fd, &necp_fd_list, chain) {
5355 		bool updated_result = FALSE;
5356 		NECP_FD_LOCK(client_fd);
5357 		struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
5358 		if (client != NULL) {
5359 			client->failed_trigger_agent.generation = agent_generation;
5360 			uuid_copy(client->failed_trigger_agent.netagent_uuid, remove_netagent_uuid);
5361 			if (!uuid_is_null(remove_netagent_uuid)) {
5362 				necp_client_remove_agent_from_result(client, remove_netagent_uuid);
5363 			}
5364 			client->result_read = FALSE;
5365 			// Found the client, break
5366 			updated_result = TRUE;
5367 			NECP_CLIENT_UNLOCK(client);
5368 		}
5369 		if (updated_result) {
5370 			necp_fd_notify(client_fd, true);
5371 		}
5372 		NECP_FD_UNLOCK(client_fd);
5373 		if (updated_result) {
5374 			// Found the client, break
5375 			break;
5376 		}
5377 	}
5378 
5379 	NECP_FD_LIST_UNLOCK();
5380 }
5381 
5382 #if SKYWALK
5383 void
necp_client_early_close(uuid_t client_id)5384 necp_client_early_close(uuid_t client_id)
5385 {
5386 	NECP_CLIENT_TREE_LOCK_SHARED();
5387 
5388 	struct necp_client *client = necp_find_client_and_lock(client_id);
5389 	if (client != NULL) {
5390 		struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
5391 		if (flow_registration != NULL) {
5392 			// Found the right client and flow, mark the stats as over
5393 			if (flow_registration->stats_handler_context != NULL) {
5394 				ntstat_userland_stats_event(flow_registration->stats_handler_context,
5395 				    NECP_CLIENT_STATISTICS_EVENT_TIME_WAIT);
5396 			}
5397 		}
5398 		NECP_CLIENT_UNLOCK(client);
5399 	}
5400 
5401 	NECP_CLIENT_TREE_UNLOCK();
5402 }
5403 #endif /* SKYWALK */
5404 
5405 /// Interface matching
5406 
5407 #define NECP_PARSED_PARAMETERS_INTERESTING_IFNET_FIELDS (NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR |                              \
5408 	                                                                                                         NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IF |                   \
5409 	                                                                                                         NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE |                 \
5410 	                                                                                                         NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IFTYPE |               \
5411 	                                                                                                         NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT |                  \
5412 	                                                                                                         NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT |                \
5413 	                                                                                                         NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT |                 \
5414 	                                                                                                         NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT |                   \
5415 	                                                                                                         NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE |             \
5416 	                                                                                                         NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT_TYPE |   \
5417 	                                                                                                         NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT_TYPE |    \
5418 	                                                                                                         NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT_TYPE)
5419 
5420 #define NECP_PARSED_PARAMETERS_SCOPED_FIELDS (NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR |                 \
5421 	                                                                                  NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE |                \
5422 	                                                                                  NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT |         \
5423 	                                                                                  NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT |                \
5424 	                                                                                  NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE |    \
5425 	                                                                                  NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT_TYPE)
5426 
5427 #define NECP_PARSED_PARAMETERS_SCOPED_IFNET_FIELDS (NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR |           \
5428 	                                                                                                NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE)
5429 
5430 #define NECP_PARSED_PARAMETERS_PREFERRED_FIELDS (NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT |                 \
5431 	                                                                                         NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT |                   \
5432 	                                                                                         NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT_TYPE |    \
5433 	                                                                                         NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT_TYPE)
5434 
5435 static bool
necp_ifnet_matches_type(struct ifnet * ifp,u_int8_t interface_type,bool check_delegates)5436 necp_ifnet_matches_type(struct ifnet *ifp, u_int8_t interface_type, bool check_delegates)
5437 {
5438 	struct ifnet *check_ifp = ifp;
5439 	while (check_ifp) {
5440 		if (if_functional_type(check_ifp, TRUE) == interface_type) {
5441 			return TRUE;
5442 		}
5443 		if (!check_delegates) {
5444 			break;
5445 		}
5446 		check_ifp = check_ifp->if_delegated.ifp;
5447 	}
5448 	return FALSE;
5449 }
5450 
5451 static bool
necp_ifnet_matches_name(struct ifnet * ifp,const char * interface_name,bool check_delegates)5452 necp_ifnet_matches_name(struct ifnet *ifp, const char *interface_name, bool check_delegates)
5453 {
5454 	struct ifnet *check_ifp = ifp;
5455 	while (check_ifp) {
5456 		if (strncmp(check_ifp->if_xname, interface_name, IFXNAMSIZ) == 0) {
5457 			return TRUE;
5458 		}
5459 		if (!check_delegates) {
5460 			break;
5461 		}
5462 		check_ifp = check_ifp->if_delegated.ifp;
5463 	}
5464 	return FALSE;
5465 }
5466 
5467 static bool
necp_ifnet_matches_agent(struct ifnet * ifp,uuid_t * agent_uuid,bool check_delegates)5468 necp_ifnet_matches_agent(struct ifnet *ifp, uuid_t *agent_uuid, bool check_delegates)
5469 {
5470 	struct ifnet *check_ifp = ifp;
5471 
5472 	while (check_ifp != NULL) {
5473 		ifnet_lock_shared(check_ifp);
5474 		if (check_ifp->if_agentids != NULL) {
5475 			for (u_int32_t index = 0; index < check_ifp->if_agentcount; index++) {
5476 				if (uuid_compare(check_ifp->if_agentids[index], *agent_uuid) == 0) {
5477 					ifnet_lock_done(check_ifp);
5478 					return TRUE;
5479 				}
5480 			}
5481 		}
5482 		ifnet_lock_done(check_ifp);
5483 
5484 		if (!check_delegates) {
5485 			break;
5486 		}
5487 		check_ifp = check_ifp->if_delegated.ifp;
5488 	}
5489 	return FALSE;
5490 }
5491 
5492 static bool
necp_ifnet_matches_agent_type(struct ifnet * ifp,const char * agent_domain,const char * agent_type,bool check_delegates)5493 necp_ifnet_matches_agent_type(struct ifnet *ifp, const char *agent_domain, const char *agent_type, bool check_delegates)
5494 {
5495 	struct ifnet *check_ifp = ifp;
5496 
5497 	while (check_ifp != NULL) {
5498 		ifnet_lock_shared(check_ifp);
5499 		if (check_ifp->if_agentids != NULL) {
5500 			for (u_int32_t index = 0; index < check_ifp->if_agentcount; index++) {
5501 				if (uuid_is_null(check_ifp->if_agentids[index])) {
5502 					continue;
5503 				}
5504 
5505 				char if_agent_domain[NETAGENT_DOMAINSIZE] = { 0 };
5506 				char if_agent_type[NETAGENT_TYPESIZE] = { 0 };
5507 
5508 				if (netagent_get_agent_domain_and_type(check_ifp->if_agentids[index], if_agent_domain, if_agent_type)) {
5509 					if (necp_agent_types_match(agent_domain, agent_type, if_agent_domain, if_agent_type)) {
5510 						ifnet_lock_done(check_ifp);
5511 						return TRUE;
5512 					}
5513 				}
5514 			}
5515 		}
5516 		ifnet_lock_done(check_ifp);
5517 
5518 		if (!check_delegates) {
5519 			break;
5520 		}
5521 		check_ifp = check_ifp->if_delegated.ifp;
5522 	}
5523 	return FALSE;
5524 }
5525 
5526 static bool
necp_ifnet_matches_local_address(struct ifnet * ifp,struct sockaddr * sa)5527 necp_ifnet_matches_local_address(struct ifnet *ifp, struct sockaddr *sa)
5528 {
5529 	struct ifaddr *ifa = NULL;
5530 	bool matched_local_address = FALSE;
5531 
5532 	// Transform sa into the ifaddr form
5533 	// IPv6 Scope IDs are always embedded in the ifaddr list
5534 	struct sockaddr_storage address;
5535 	u_int ifscope = IFSCOPE_NONE;
5536 	(void)sa_copy(sa, &address, &ifscope);
5537 	SIN(&address)->sin_port = 0;
5538 	if (address.ss_family == AF_INET6) {
5539 		if (in6_embedded_scope ||
5540 		    !IN6_IS_SCOPE_EMBED(&SIN6(&address)->sin6_addr)) {
5541 			SIN6(&address)->sin6_scope_id = 0;
5542 		}
5543 	}
5544 
5545 	ifa = ifa_ifwithaddr_scoped_locked((struct sockaddr *)&address, ifp->if_index);
5546 	matched_local_address = (ifa != NULL);
5547 
5548 	if (ifa) {
5549 		ifaddr_release(ifa);
5550 	}
5551 
5552 	return matched_local_address;
5553 }
5554 
5555 static bool
necp_interface_type_should_match_unranked_interfaces(u_int8_t interface_type)5556 necp_interface_type_should_match_unranked_interfaces(u_int8_t interface_type)
5557 {
5558 	switch (interface_type) {
5559 	// These are the interface types we allow a client to request even if the matching
5560 	// interface isn't currently eligible to be primary (has default route, dns, etc)
5561 	case IFRTYPE_FUNCTIONAL_WIFI_AWDL:
5562 	case IFRTYPE_FUNCTIONAL_INTCOPROC:
5563 	case IFRTYPE_FUNCTIONAL_COMPANIONLINK:
5564 		return true;
5565 	default:
5566 		break;
5567 	}
5568 	return false;
5569 }
5570 
5571 #define NECP_IFP_IS_ON_ORDERED_LIST(_ifp) ((_ifp)->if_ordered_link.tqe_next != NULL || (_ifp)->if_ordered_link.tqe_prev != NULL)
5572 
5573 // Secondary interface flag indicates that the interface is being
5574 // used for multipath or a listener as an extra path
5575 static bool
necp_ifnet_matches_parameters(struct ifnet * ifp,struct necp_client_parsed_parameters * parsed_parameters,u_int32_t override_flags,u_int32_t * preferred_count,bool secondary_interface,bool require_scoped_field)5576 necp_ifnet_matches_parameters(struct ifnet *ifp,
5577     struct necp_client_parsed_parameters *parsed_parameters,
5578     u_int32_t override_flags,
5579     u_int32_t *preferred_count,
5580     bool secondary_interface,
5581     bool require_scoped_field)
5582 {
5583 	bool matched_some_scoped_field = FALSE;
5584 
5585 	if (preferred_count) {
5586 		*preferred_count = 0;
5587 	}
5588 
5589 	if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IF) {
5590 		if (parsed_parameters->required_interface_index != ifp->if_index) {
5591 			return FALSE;
5592 		}
5593 	}
5594 #if SKYWALK
5595 	else {
5596 		if (ifnet_is_low_latency(ifp)) {
5597 			return FALSE;
5598 		}
5599 	}
5600 #endif /* SKYWALK */
5601 
5602 	if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR) {
5603 		if (!necp_ifnet_matches_local_address(ifp, SA(&parsed_parameters->local_addr.sa))) {
5604 			return FALSE;
5605 		}
5606 		if (require_scoped_field) {
5607 			matched_some_scoped_field = TRUE;
5608 		}
5609 	}
5610 
5611 	if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_FLAGS) {
5612 		if (override_flags != 0) {
5613 			if ((override_flags & NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_EXPENSIVE) &&
5614 			    IFNET_IS_EXPENSIVE(ifp)) {
5615 				return FALSE;
5616 			}
5617 			if ((override_flags & NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_CONSTRAINED) &&
5618 			    IFNET_IS_CONSTRAINED(ifp)) {
5619 				return FALSE;
5620 			}
5621 		} else {
5622 			if ((parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_EXPENSIVE) &&
5623 			    IFNET_IS_EXPENSIVE(ifp)) {
5624 				return FALSE;
5625 			}
5626 			if ((parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_CONSTRAINED) &&
5627 			    IFNET_IS_CONSTRAINED(ifp)) {
5628 				return FALSE;
5629 			}
5630 		}
5631 	}
5632 
5633 	if ((!secondary_interface || // Enforce interface type if this is the primary interface
5634 	    !(parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_FLAGS) ||      // or if there are no flags
5635 	    !(parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_ONLY_PRIMARY_REQUIRES_TYPE)) &&      // or if the flags don't give an exception
5636 	    (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE) &&
5637 	    !necp_ifnet_matches_type(ifp, parsed_parameters->required_interface_type, FALSE)) {
5638 		return FALSE;
5639 	}
5640 
5641 	if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE) {
5642 		if (require_scoped_field) {
5643 			matched_some_scoped_field = TRUE;
5644 		}
5645 	}
5646 
5647 	if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IFTYPE) {
5648 		for (int i = 0; i < NECP_MAX_INTERFACE_PARAMETERS; i++) {
5649 			if (parsed_parameters->prohibited_interface_types[i] == 0) {
5650 				break;
5651 			}
5652 
5653 			if (necp_ifnet_matches_type(ifp, parsed_parameters->prohibited_interface_types[i], TRUE)) {
5654 				return FALSE;
5655 			}
5656 		}
5657 	}
5658 
5659 	if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IF) {
5660 		for (int i = 0; i < NECP_MAX_INTERFACE_PARAMETERS; i++) {
5661 			if (strlen(parsed_parameters->prohibited_interfaces[i]) == 0) {
5662 				break;
5663 			}
5664 
5665 			if (necp_ifnet_matches_name(ifp, parsed_parameters->prohibited_interfaces[i], TRUE)) {
5666 				return FALSE;
5667 			}
5668 		}
5669 	}
5670 
5671 	if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT) {
5672 		for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
5673 			if (uuid_is_null(parsed_parameters->required_netagents[i])) {
5674 				break;
5675 			}
5676 
5677 			if (!necp_ifnet_matches_agent(ifp, &parsed_parameters->required_netagents[i], FALSE)) {
5678 				return FALSE;
5679 			}
5680 
5681 			if (require_scoped_field) {
5682 				matched_some_scoped_field = TRUE;
5683 			}
5684 		}
5685 	}
5686 
5687 	if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT) {
5688 		for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
5689 			if (uuid_is_null(parsed_parameters->prohibited_netagents[i])) {
5690 				break;
5691 			}
5692 
5693 			if (necp_ifnet_matches_agent(ifp, &parsed_parameters->prohibited_netagents[i], TRUE)) {
5694 				return FALSE;
5695 			}
5696 		}
5697 	}
5698 
5699 	if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE) {
5700 		for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
5701 			if (strlen(parsed_parameters->required_netagent_types[i].netagent_domain) == 0 &&
5702 			    strlen(parsed_parameters->required_netagent_types[i].netagent_type) == 0) {
5703 				break;
5704 			}
5705 
5706 			if (!necp_ifnet_matches_agent_type(ifp, parsed_parameters->required_netagent_types[i].netagent_domain, parsed_parameters->required_netagent_types[i].netagent_type, FALSE)) {
5707 				return FALSE;
5708 			}
5709 
5710 			if (require_scoped_field) {
5711 				matched_some_scoped_field = TRUE;
5712 			}
5713 		}
5714 	}
5715 
5716 	if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT_TYPE) {
5717 		for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
5718 			if (strlen(parsed_parameters->prohibited_netagent_types[i].netagent_domain) == 0 &&
5719 			    strlen(parsed_parameters->prohibited_netagent_types[i].netagent_type) == 0) {
5720 				break;
5721 			}
5722 
5723 			if (necp_ifnet_matches_agent_type(ifp, parsed_parameters->prohibited_netagent_types[i].netagent_domain, parsed_parameters->prohibited_netagent_types[i].netagent_type, TRUE)) {
5724 				return FALSE;
5725 			}
5726 		}
5727 	}
5728 
5729 	// Checked preferred properties
5730 	if (preferred_count) {
5731 		if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT) {
5732 			for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
5733 				if (uuid_is_null(parsed_parameters->preferred_netagents[i])) {
5734 					break;
5735 				}
5736 
5737 				if (necp_ifnet_matches_agent(ifp, &parsed_parameters->preferred_netagents[i], TRUE)) {
5738 					(*preferred_count)++;
5739 					if (require_scoped_field) {
5740 						matched_some_scoped_field = TRUE;
5741 					}
5742 				}
5743 			}
5744 		}
5745 
5746 		if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT_TYPE) {
5747 			for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
5748 				if (strlen(parsed_parameters->preferred_netagent_types[i].netagent_domain) == 0 &&
5749 				    strlen(parsed_parameters->preferred_netagent_types[i].netagent_type) == 0) {
5750 					break;
5751 				}
5752 
5753 				if (necp_ifnet_matches_agent_type(ifp, parsed_parameters->preferred_netagent_types[i].netagent_domain, parsed_parameters->preferred_netagent_types[i].netagent_type, TRUE)) {
5754 					(*preferred_count)++;
5755 					if (require_scoped_field) {
5756 						matched_some_scoped_field = TRUE;
5757 					}
5758 				}
5759 			}
5760 		}
5761 
5762 		if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT) {
5763 			for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
5764 				if (uuid_is_null(parsed_parameters->avoided_netagents[i])) {
5765 					break;
5766 				}
5767 
5768 				if (!necp_ifnet_matches_agent(ifp, &parsed_parameters->avoided_netagents[i], TRUE)) {
5769 					(*preferred_count)++;
5770 				}
5771 			}
5772 		}
5773 
5774 		if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT_TYPE) {
5775 			for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
5776 				if (strlen(parsed_parameters->avoided_netagent_types[i].netagent_domain) == 0 &&
5777 				    strlen(parsed_parameters->avoided_netagent_types[i].netagent_type) == 0) {
5778 					break;
5779 				}
5780 
5781 				if (!necp_ifnet_matches_agent_type(ifp, parsed_parameters->avoided_netagent_types[i].netagent_domain,
5782 				    parsed_parameters->avoided_netagent_types[i].netagent_type, TRUE)) {
5783 					(*preferred_count)++;
5784 				}
5785 			}
5786 		}
5787 	}
5788 
5789 	if (require_scoped_field) {
5790 		return matched_some_scoped_field;
5791 	}
5792 
5793 	return TRUE;
5794 }
5795 
5796 static bool
necp_find_matching_interface_index(struct necp_client_parsed_parameters * parsed_parameters,u_int * return_ifindex,bool * validate_agents)5797 necp_find_matching_interface_index(struct necp_client_parsed_parameters *parsed_parameters,
5798     u_int *return_ifindex, bool *validate_agents)
5799 {
5800 	struct ifnet *ifp = NULL;
5801 	u_int32_t best_preferred_count = 0;
5802 	bool has_preferred_fields = FALSE;
5803 	*return_ifindex = 0;
5804 
5805 	if (parsed_parameters->required_interface_index != 0) {
5806 		*return_ifindex = parsed_parameters->required_interface_index;
5807 		return TRUE;
5808 	}
5809 
5810 	// Check and save off flags
5811 	u_int32_t flags = 0;
5812 	bool has_prohibit_flags = FALSE;
5813 	if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_FLAGS) {
5814 		flags = parsed_parameters->flags;
5815 		has_prohibit_flags = (parsed_parameters->flags &
5816 		    (NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_EXPENSIVE |
5817 		    NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_CONSTRAINED));
5818 	}
5819 
5820 	if (!(parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_INTERESTING_IFNET_FIELDS) &&
5821 	    !has_prohibit_flags) {
5822 		return TRUE;
5823 	}
5824 
5825 	has_preferred_fields = (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_PREFERRED_FIELDS);
5826 
5827 	// We have interesting parameters to parse and find a matching interface
5828 	ifnet_head_lock_shared();
5829 
5830 	if (!(parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_SCOPED_FIELDS) &&
5831 	    !has_preferred_fields) {
5832 		// We do have fields to match, but they are only prohibitory
5833 		// If the first interface in the list matches, or there are no ordered interfaces, we don't need to scope
5834 		ifp = TAILQ_FIRST(&ifnet_ordered_head);
5835 		if (ifp == NULL || necp_ifnet_matches_parameters(ifp, parsed_parameters, 0, NULL, false, false)) {
5836 			// Don't set return_ifindex, so the client doesn't need to scope
5837 			ifnet_head_done();
5838 			return TRUE;
5839 		}
5840 	}
5841 
5842 	// First check the ordered interface list
5843 	TAILQ_FOREACH(ifp, &ifnet_ordered_head, if_ordered_link) {
5844 		u_int32_t preferred_count = 0;
5845 		if (necp_ifnet_matches_parameters(ifp, parsed_parameters, flags, &preferred_count, false, false)) {
5846 			if (preferred_count > best_preferred_count ||
5847 			    *return_ifindex == 0) {
5848 				// Everything matched, and is most preferred. Return this interface.
5849 				*return_ifindex = ifp->if_index;
5850 				best_preferred_count = preferred_count;
5851 
5852 				if (!has_preferred_fields) {
5853 					break;
5854 				}
5855 			}
5856 		}
5857 
5858 		if (has_prohibit_flags &&
5859 		    ifp == TAILQ_FIRST(&ifnet_ordered_head)) {
5860 			// This was the first interface. From here on, if the
5861 			// client prohibited either expensive or constrained,
5862 			// don't allow either as a secondary interface option.
5863 			flags |= (NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_EXPENSIVE |
5864 			    NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_CONSTRAINED);
5865 		}
5866 	}
5867 
5868 	bool is_listener = ((parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_FLAGS) &&
5869 	    (parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER));
5870 
5871 	// Then check the remaining interfaces
5872 	if ((parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_SCOPED_FIELDS) &&
5873 	    ((!(parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE)) ||
5874 	    necp_interface_type_should_match_unranked_interfaces(parsed_parameters->required_interface_type) ||
5875 	    (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR) ||
5876 	    is_listener) &&
5877 	    (*return_ifindex == 0 || has_preferred_fields)) {
5878 		TAILQ_FOREACH(ifp, &ifnet_head, if_link) {
5879 			u_int32_t preferred_count = 0;
5880 			if (NECP_IFP_IS_ON_ORDERED_LIST(ifp)) {
5881 				// This interface was in the ordered list, skip
5882 				continue;
5883 			}
5884 			if (necp_ifnet_matches_parameters(ifp, parsed_parameters, flags, &preferred_count, false, true)) {
5885 				if (preferred_count > best_preferred_count ||
5886 				    *return_ifindex == 0) {
5887 					// Everything matched, and is most preferred. Return this interface.
5888 					*return_ifindex = ifp->if_index;
5889 					best_preferred_count = preferred_count;
5890 
5891 					if (!has_preferred_fields) {
5892 						break;
5893 					}
5894 				}
5895 			}
5896 		}
5897 	}
5898 
5899 	ifnet_head_done();
5900 
5901 	if (has_preferred_fields && best_preferred_count == 0 &&
5902 	    ((parsed_parameters->valid_fields & (NECP_PARSED_PARAMETERS_SCOPED_FIELDS | NECP_PARSED_PARAMETERS_PREFERRED_FIELDS)) ==
5903 	    (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_PREFERRED_FIELDS))) {
5904 		// If only has preferred ifnet fields, and nothing was found, clear the interface index and return TRUE
5905 		*return_ifindex = 0;
5906 		return TRUE;
5907 	}
5908 
5909 	if (*return_ifindex == 0 &&
5910 	    !(parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_SCOPED_IFNET_FIELDS)) {
5911 		// Has required fields, but not including specific interface fields. Pass for now, and check
5912 		// to see if agents are satisfied by policy.
5913 		*validate_agents = TRUE;
5914 		return TRUE;
5915 	}
5916 
5917 	return *return_ifindex != 0;
5918 }
5919 
5920 void
necp_copy_inp_domain_info(struct inpcb * inp,struct socket * so,nstat_domain_info * domain_info)5921 necp_copy_inp_domain_info(struct inpcb *inp, struct socket *so, nstat_domain_info *domain_info)
5922 {
5923 	if (inp == NULL || so == NULL || domain_info == NULL) {
5924 		return;
5925 	}
5926 
5927 	necp_lock_socket_attributes();
5928 
5929 	domain_info->is_tracker = !!(so->so_flags1 & SOF1_KNOWN_TRACKER);
5930 	domain_info->is_non_app_initiated = !!(so->so_flags1 & SOF1_TRACKER_NON_APP_INITIATED);
5931 	if (domain_info->is_tracker &&
5932 	    inp->inp_necp_attributes.inp_tracker_domain != NULL) {
5933 		strlcpy(domain_info->domain_name, inp->inp_necp_attributes.inp_tracker_domain,
5934 		    sizeof(domain_info->domain_name));
5935 	} else if (inp->inp_necp_attributes.inp_domain != NULL) {
5936 		strlcpy(domain_info->domain_name, inp->inp_necp_attributes.inp_domain,
5937 		    sizeof(domain_info->domain_name));
5938 	}
5939 	if (inp->inp_necp_attributes.inp_domain_owner != NULL) {
5940 		strlcpy(domain_info->domain_owner, inp->inp_necp_attributes.inp_domain_owner,
5941 		    sizeof(domain_info->domain_owner));
5942 	}
5943 	if (inp->inp_necp_attributes.inp_domain_context != NULL) {
5944 		strlcpy(domain_info->domain_tracker_ctxt, inp->inp_necp_attributes.inp_domain_context,
5945 		    sizeof(domain_info->domain_tracker_ctxt));
5946 	}
5947 
5948 	necp_unlock_socket_attributes();
5949 }
5950 
5951 void
necp_with_inp_domain_name(struct socket * so,void * ctx,void (* with_func)(char * domain_name,void * ctx))5952 necp_with_inp_domain_name(struct socket *so, void *ctx, void (*with_func)(char *domain_name, void *ctx))
5953 {
5954 	struct inpcb *inp = NULL;
5955 
5956 	if (so == NULL || with_func == NULL) {
5957 		return;
5958 	}
5959 
5960 	inp = (struct inpcb *)so->so_pcb;
5961 	if (inp == NULL) {
5962 		return;
5963 	}
5964 
5965 	necp_lock_socket_attributes();
5966 	with_func(inp->inp_necp_attributes.inp_domain, ctx);
5967 	necp_unlock_socket_attributes();
5968 }
5969 
5970 static size_t
necp_find_domain_info_common(struct necp_client * client,u_int8_t * parameters,size_t parameters_size,struct necp_client_flow_registration * flow_registration,nstat_domain_info * domain_info)5971 necp_find_domain_info_common(struct necp_client *client,
5972     u_int8_t *parameters,
5973     size_t parameters_size,
5974     struct necp_client_flow_registration *flow_registration,    /* For logging purposes only */
5975     nstat_domain_info *domain_info)
5976 {
5977 	if (client == NULL) {
5978 		return 0;
5979 	}
5980 	if (domain_info == NULL) {
5981 		return sizeof(nstat_domain_info);
5982 	}
5983 
5984 	size_t offset = 0;
5985 	u_int32_t flags = 0;
5986 	u_int8_t *tracker_domain = NULL;
5987 	u_int8_t *domain = NULL;
5988 	size_t tracker_domain_length = 0;
5989 	size_t domain_length = 0;
5990 
5991 	NECP_CLIENT_FLOW_LOG(client, flow_registration, "Collecting stats");
5992 
5993 	while ((offset + sizeof(struct necp_tlv_header)) <= parameters_size) {
5994 		u_int8_t type = necp_buffer_get_tlv_type(parameters, offset);
5995 		u_int32_t length = necp_buffer_get_tlv_length(parameters, offset);
5996 
5997 		if (length > (parameters_size - (offset + sizeof(struct necp_tlv_header)))) {
5998 			// If the length is larger than what can fit in the remaining parameters size, bail
5999 			NECPLOG(LOG_ERR, "Invalid TLV length (%u)", length);
6000 			break;
6001 		}
6002 
6003 		if (length > 0) {
6004 			u_int8_t *value = necp_buffer_get_tlv_value(parameters, offset, NULL);
6005 			if (value != NULL) {
6006 				switch (type) {
6007 				case NECP_CLIENT_PARAMETER_FLAGS: {
6008 					if (length >= sizeof(u_int32_t)) {
6009 						memcpy(&flags, value, sizeof(u_int32_t));
6010 					}
6011 
6012 					domain_info->is_tracker =
6013 					    !!(flags & NECP_CLIENT_PARAMETER_FLAG_KNOWN_TRACKER);
6014 					domain_info->is_non_app_initiated =
6015 					    !!(flags & NECP_CLIENT_PARAMETER_FLAG_NON_APP_INITIATED);
6016 					domain_info->is_silent =
6017 					    !!(flags & NECP_CLIENT_PARAMETER_FLAG_SILENT);
6018 					break;
6019 				}
6020 				case NECP_CLIENT_PARAMETER_TRACKER_DOMAIN: {
6021 					tracker_domain_length = length;
6022 					tracker_domain = value;
6023 					break;
6024 				}
6025 				case NECP_CLIENT_PARAMETER_DOMAIN: {
6026 					domain_length = length;
6027 					domain = value;
6028 					break;
6029 				}
6030 				case NECP_CLIENT_PARAMETER_DOMAIN_OWNER: {
6031 					size_t length_to_copy = MIN(length, sizeof(domain_info->domain_owner));
6032 					strlcpy(domain_info->domain_owner, (const char *)value, length_to_copy);
6033 					break;
6034 				}
6035 				case NECP_CLIENT_PARAMETER_DOMAIN_CONTEXT: {
6036 					size_t length_to_copy = MIN(length, sizeof(domain_info->domain_tracker_ctxt));
6037 					strlcpy(domain_info->domain_tracker_ctxt, (const char *)value, length_to_copy);
6038 					break;
6039 				}
6040 				case NECP_CLIENT_PARAMETER_ATTRIBUTED_BUNDLE_IDENTIFIER: {
6041 					size_t length_to_copy = MIN(length, sizeof(domain_info->domain_attributed_bundle_id));
6042 					strlcpy(domain_info->domain_attributed_bundle_id, (const char *)value, length_to_copy);
6043 					break;
6044 				}
6045 				case NECP_CLIENT_PARAMETER_REMOTE_ADDRESS: {
6046 					if (length >= sizeof(struct necp_policy_condition_addr)) {
6047 						struct necp_policy_condition_addr *address_struct = (struct necp_policy_condition_addr *)(void *)value;
6048 						if (necp_client_address_is_valid(&address_struct->address.sa)) {
6049 							memcpy(&domain_info->remote, &address_struct->address, sizeof(address_struct->address));
6050 						}
6051 					}
6052 					break;
6053 				}
6054 				default: {
6055 					break;
6056 				}
6057 				}
6058 			}
6059 		}
6060 		offset += sizeof(struct necp_tlv_header) + length;
6061 	}
6062 
6063 	if (domain_info->is_tracker && tracker_domain != NULL && tracker_domain_length > 0) {
6064 		size_t length_to_copy = MIN(tracker_domain_length, sizeof(domain_info->domain_name));
6065 		strlcpy(domain_info->domain_name, (const char *)tracker_domain, length_to_copy);
6066 	} else if (domain != NULL && domain_length > 0) {
6067 		size_t length_to_copy = MIN(domain_length, sizeof(domain_info->domain_name));
6068 		strlcpy(domain_info->domain_name, (const char *)domain, length_to_copy);
6069 	}
6070 
6071 	NECP_CLIENT_FLOW_LOG(client, flow_registration,
6072 	    "Collected stats - domain <%s> owner <%s> ctxt <%s> bundle id <%s> "
6073 	    "is_tracker %d is_non_app_initiated %d is_silent %d",
6074 	    domain_info->domain_name,
6075 	    domain_info->domain_owner,
6076 	    domain_info->domain_tracker_ctxt,
6077 	    domain_info->domain_attributed_bundle_id,
6078 	    domain_info->is_tracker,
6079 	    domain_info->is_non_app_initiated,
6080 	    domain_info->is_silent);
6081 
6082 	return sizeof(nstat_domain_info);
6083 }
6084 
6085 static size_t
necp_find_conn_extension_info(nstat_provider_context ctx,int requested_extension,void * buf,size_t buf_size)6086 necp_find_conn_extension_info(nstat_provider_context ctx,
6087     int requested_extension,    /* The extension to be returned */
6088     void *buf,                  /* If not NULL, the address for extensions to be returned in */
6089     size_t buf_size)            /* The size of the buffer space, typically matching the return from a previous call with a NULL buf pointer */
6090 {
6091 	// Note, the caller has guaranteed that any buffer has been zeroed, there is no need to clear it again
6092 
6093 	if (ctx == NULL) {
6094 		return 0;
6095 	}
6096 	struct necp_client *client = (struct necp_client *)ctx;
6097 	switch (requested_extension) {
6098 	case NSTAT_EXTENDED_UPDATE_TYPE_DOMAIN:
6099 		// This is for completeness.  The intent is that domain information can be extracted at user level from the TLV parameters
6100 		if (buf == NULL) {
6101 			return sizeof(nstat_domain_info);
6102 		}
6103 		if (buf_size < sizeof(nstat_domain_info)) {
6104 			return 0;
6105 		}
6106 		return necp_find_domain_info_common(client, client->parameters, client->parameters_length, NULL, (nstat_domain_info *)buf);
6107 
6108 	case NSTAT_EXTENDED_UPDATE_TYPE_NECP_TLV: {
6109 		size_t parameters_length = client->parameters_length;
6110 		if (buf == NULL) {
6111 			return parameters_length;
6112 		}
6113 		if (buf_size < parameters_length) {
6114 			return 0;
6115 		}
6116 		memcpy(buf, client->parameters, parameters_length);
6117 		return parameters_length;
6118 	}
6119 	case NSTAT_EXTENDED_UPDATE_TYPE_ORIGINAL_NECP_TLV:
6120 		if (buf == NULL) {
6121 			return (client->original_parameters_source != NULL) ? client->original_parameters_source->parameters_length : 0;
6122 		}
6123 		if ((client->original_parameters_source == NULL) || (buf_size < client->original_parameters_source->parameters_length)) {
6124 			return 0;
6125 		}
6126 		memcpy(buf, client->original_parameters_source->parameters, client->original_parameters_source->parameters_length);
6127 		return client->original_parameters_source->parameters_length;
6128 
6129 	case NSTAT_EXTENDED_UPDATE_TYPE_ORIGINAL_DOMAIN:
6130 		if (buf == NULL) {
6131 			return (client->original_parameters_source != NULL) ? sizeof(nstat_domain_info) : 0;
6132 		}
6133 		if ((buf_size < sizeof(nstat_domain_info)) || (client->original_parameters_source == NULL)) {
6134 			return 0;
6135 		}
6136 		return necp_find_domain_info_common(client, client->original_parameters_source->parameters, client->original_parameters_source->parameters_length,
6137 		           NULL, (nstat_domain_info *)buf);
6138 
6139 	default:
6140 		return 0;
6141 	}
6142 }
6143 
6144 #if SKYWALK
6145 
6146 static size_t
necp_find_extension_info(userland_stats_provider_context * ctx,int requested_extension,void * buf,size_t buf_size)6147 necp_find_extension_info(userland_stats_provider_context *ctx,
6148     int requested_extension,    /* The extension to be returned */
6149     void *buf,                  /* If not NULL, the address for extensions to be returned in */
6150     size_t buf_size)            /* The size of the buffer space, typically matching the return from a previous call with a NULL buf pointer */
6151 {
6152 	if (ctx == NULL) {
6153 		return 0;
6154 	}
6155 	struct necp_client_flow_registration *flow_registration = (struct necp_client_flow_registration *)(uintptr_t)ctx;
6156 	struct necp_client *client = flow_registration->client;
6157 
6158 	switch (requested_extension) {
6159 	case NSTAT_EXTENDED_UPDATE_TYPE_DOMAIN:
6160 		if (buf == NULL) {
6161 			return sizeof(nstat_domain_info);
6162 		}
6163 		if (buf_size < sizeof(nstat_domain_info)) {
6164 			return 0;
6165 		}
6166 		return necp_find_domain_info_common(client, client->parameters, client->parameters_length, flow_registration, (nstat_domain_info *)buf);
6167 
6168 	case NSTAT_EXTENDED_UPDATE_TYPE_NECP_TLV:
6169 		if (buf == NULL) {
6170 			return client->parameters_length;
6171 		}
6172 		if (buf_size < client->parameters_length) {
6173 			return 0;
6174 		}
6175 		memcpy(buf, client->parameters, client->parameters_length);
6176 		return client->parameters_length;
6177 
6178 	case NSTAT_EXTENDED_UPDATE_TYPE_FUUID:
6179 		if (buf == NULL) {
6180 			return sizeof(uuid_t);
6181 		}
6182 		if (buf_size < sizeof(uuid_t)) {
6183 			return 0;
6184 		}
6185 		uuid_copy(buf, flow_registration->registration_id);
6186 		return sizeof(uuid_t);
6187 
6188 	default:
6189 		return 0;
6190 	}
6191 }
6192 
6193 static void
necp_find_netstat_data(struct necp_client * client,union necp_sockaddr_union * remote,pid_t * effective_pid,uid_t * uid,uuid_t euuid,uid_t * persona_id,u_int32_t * traffic_class,u_int8_t * fallback_mode)6194 necp_find_netstat_data(struct necp_client *client,
6195     union necp_sockaddr_union *remote,
6196     pid_t *effective_pid,
6197     uid_t *uid,
6198     uuid_t euuid,
6199     uid_t *persona_id,
6200     u_int32_t *traffic_class,
6201     u_int8_t *fallback_mode)
6202 {
6203 	bool have_set_euuid = false;
6204 	size_t offset = 0;
6205 	u_int8_t *parameters;
6206 	u_int32_t parameters_size;
6207 
6208 	parameters = client->parameters;
6209 	parameters_size = (u_int32_t)client->parameters_length;
6210 
6211 	while ((offset + sizeof(struct necp_tlv_header)) <= parameters_size) {
6212 		u_int8_t type = necp_buffer_get_tlv_type(parameters, offset);
6213 		u_int32_t length = necp_buffer_get_tlv_length(parameters, offset);
6214 
6215 		if (length > (parameters_size - (offset + sizeof(struct necp_tlv_header)))) {
6216 			// If the length is larger than what can fit in the remaining parameters size, bail
6217 			NECPLOG(LOG_ERR, "Invalid TLV length (%u)", length);
6218 			break;
6219 		}
6220 
6221 		if (length > 0) {
6222 			u_int8_t *value = necp_buffer_get_tlv_value(parameters, offset, NULL);
6223 			if (value != NULL) {
6224 				switch (type) {
6225 				case NECP_CLIENT_PARAMETER_APPLICATION: {
6226 					if (length >= sizeof(uuid_t)) {
6227 						uuid_copy(euuid, value);
6228 					}
6229 					break;
6230 				}
6231 				case NECP_CLIENT_PARAMETER_PID: {
6232 					if (length >= sizeof(pid_t)) {
6233 						memcpy(effective_pid, value, sizeof(pid_t));
6234 					}
6235 					break;
6236 				}
6237 				case NECP_CLIENT_PARAMETER_TRAFFIC_CLASS: {
6238 					if (length >= sizeof(u_int32_t)) {
6239 						memcpy(traffic_class, value, sizeof(u_int32_t));
6240 					}
6241 					break;
6242 				}
6243 				case NECP_CLIENT_PARAMETER_FALLBACK_MODE: {
6244 					if (length >= sizeof(u_int8_t)) {
6245 						memcpy(fallback_mode, value, sizeof(u_int8_t));
6246 					}
6247 					break;
6248 				}
6249 				// It is an implementation quirk that the remote address can be found in the necp parameters
6250 				// while the local address must be retrieved from the flowswitch
6251 				case NECP_CLIENT_PARAMETER_REMOTE_ADDRESS: {
6252 					if (length >= sizeof(struct necp_policy_condition_addr)) {
6253 						struct necp_policy_condition_addr *address_struct = (struct necp_policy_condition_addr *)(void *)value;
6254 						if (necp_client_address_is_valid(&address_struct->address.sa)) {
6255 							memcpy(remote, &address_struct->address, sizeof(address_struct->address));
6256 						}
6257 					}
6258 					break;
6259 				}
6260 				case NECP_CLIENT_PARAMETER_APPLICATION_ID: {
6261 					if (length >= sizeof(necp_application_id_t) && uid && persona_id) {
6262 						necp_application_id_t *application_id = (necp_application_id_t *)(void *)value;
6263 						memcpy(uid, &application_id->uid, sizeof(uid_t));
6264 						uuid_copy(euuid, application_id->effective_uuid);
6265 						memcpy(persona_id, &application_id->persona_id, sizeof(uid_t));
6266 						have_set_euuid = true;
6267 					}
6268 					break;
6269 				}
6270 				default: {
6271 					break;
6272 				}
6273 				}
6274 			}
6275 		}
6276 		offset += sizeof(struct necp_tlv_header) + length;
6277 	}
6278 
6279 	if (!have_set_euuid) {
6280 		proc_t proc = proc_find(client->proc_pid);
6281 		if (proc != PROC_NULL) {
6282 			uuid_t responsible_uuid = { 0 };
6283 			proc_getresponsibleuuid(proc, responsible_uuid, sizeof(responsible_uuid));
6284 			proc_rele(proc);
6285 			if (!uuid_is_null(responsible_uuid)) {
6286 				uuid_copy(euuid, responsible_uuid);
6287 			}
6288 		}
6289 	}
6290 }
6291 
6292 static u_int64_t
necp_find_netstat_initial_properties(struct necp_client * client)6293 necp_find_netstat_initial_properties(struct necp_client *client)
6294 {
6295 	size_t offset = 0;
6296 	u_int64_t retval = 0;
6297 	u_int8_t *parameters;
6298 	u_int32_t parameters_size;
6299 
6300 	parameters = client->parameters;
6301 	parameters_size = (u_int32_t)client->parameters_length;
6302 
6303 	while ((offset + sizeof(struct necp_tlv_header)) <= parameters_size) {
6304 		u_int8_t type = necp_buffer_get_tlv_type(parameters, offset);
6305 		u_int32_t length = necp_buffer_get_tlv_length(parameters, offset);
6306 
6307 		if (length > (parameters_size - (offset + sizeof(struct necp_tlv_header)))) {
6308 			// If the length is larger than what can fit in the remaining parameters size, bail
6309 			NECPLOG(LOG_ERR, "Invalid TLV length (%u)", length);
6310 			break;
6311 		}
6312 
6313 		if (type == NECP_CLIENT_PARAMETER_FLAGS) {
6314 			u_int32_t policy_condition_client_flags;
6315 			u_int8_t *value = necp_buffer_get_tlv_value(parameters, offset, NULL);
6316 			if ((value != NULL) && (length >= sizeof(policy_condition_client_flags))) {
6317 				memcpy(&policy_condition_client_flags, value, sizeof(policy_condition_client_flags));
6318 				if (policy_condition_client_flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) {
6319 					retval |= NSTAT_SOURCE_IS_LISTENER;
6320 				}
6321 				if (policy_condition_client_flags & NECP_CLIENT_PARAMETER_FLAG_INBOUND) {
6322 					retval |= NSTAT_SOURCE_IS_INBOUND;
6323 				}
6324 			}
6325 			break;
6326 		}
6327 		offset += sizeof(struct necp_tlv_header) + length;
6328 	}
6329 	if (retval == 0) {
6330 		retval = NSTAT_SOURCE_IS_OUTBOUND;
6331 	}
6332 	return retval;
6333 }
6334 
6335 // Called from NetworkStatistics when it wishes to collect latest information for a TCP flow.
6336 // It is a responsibility of NetworkStatistics to have previously zeroed any supplied memory.
6337 static bool
necp_request_tcp_netstats(userland_stats_provider_context * ctx,u_int32_t * ifflagsp,nstat_progress_digest * digestp,nstat_counts * countsp,void * metadatap)6338 necp_request_tcp_netstats(userland_stats_provider_context *ctx,
6339     u_int32_t *ifflagsp,
6340     nstat_progress_digest *digestp,
6341     nstat_counts *countsp,
6342     void *metadatap)
6343 {
6344 	if (ctx == NULL) {
6345 		return false;
6346 	}
6347 
6348 	struct necp_client_flow_registration *flow_registration = (struct necp_client_flow_registration *)(uintptr_t)ctx;
6349 	struct necp_client *client = flow_registration->client;
6350 	struct necp_all_stats *ustats_kaddr = ((struct necp_all_kstats *)flow_registration->kstats_kaddr)->necp_stats_ustats;
6351 	struct necp_tcp_stats *tcpstats = (struct necp_tcp_stats *)ustats_kaddr;
6352 	ASSERT(tcpstats != NULL);
6353 
6354 	u_int32_t nstat_diagnostic_flags = 0;
6355 
6356 	// Retrieve details from the last time the assigned flows were updated
6357 	u_int32_t route_ifindex = IFSCOPE_NONE;
6358 	u_int32_t route_ifflags = NSTAT_IFNET_IS_UNKNOWN_TYPE;
6359 	u_int64_t combined_interface_details = 0;
6360 
6361 	combined_interface_details = os_atomic_load(&flow_registration->last_interface_details, relaxed);
6362 	split_interface_details(combined_interface_details, &route_ifindex, &route_ifflags);
6363 
6364 	if (route_ifindex == IFSCOPE_NONE) {
6365 		// Mark no interface
6366 		nstat_diagnostic_flags |= NSTAT_IFNET_ROUTE_VALUE_UNOBTAINABLE;
6367 		route_ifflags = NSTAT_IFNET_IS_UNKNOWN_TYPE;
6368 		NECPLOG(LOG_INFO, "req tcp stats, failed to get route details for pid %d curproc %d %s\n",
6369 		    client->proc_pid, proc_pid(current_proc()), proc_best_name(current_proc()));
6370 	}
6371 
6372 	if (ifflagsp) {
6373 		*ifflagsp = route_ifflags | nstat_diagnostic_flags;
6374 		if (tcpstats->necp_tcp_extra.flags1 & SOF1_CELLFALLBACK) {
6375 			*ifflagsp |= NSTAT_IFNET_VIA_CELLFALLBACK;
6376 		}
6377 		if ((digestp == NULL) && (countsp == NULL) && (metadatap == NULL)) {
6378 			return true;
6379 		}
6380 	}
6381 
6382 	if (digestp) {
6383 		// The digest is intended to give information that may help give insight into the state of the link
6384 		// while avoiding the need to do the relatively expensive flowswitch lookup
6385 		digestp->rxbytes = tcpstats->necp_tcp_counts.necp_stat_rxbytes;
6386 		digestp->txbytes = tcpstats->necp_tcp_counts.necp_stat_txbytes;
6387 		digestp->rxduplicatebytes = tcpstats->necp_tcp_counts.necp_stat_rxduplicatebytes;
6388 		digestp->rxoutoforderbytes = tcpstats->necp_tcp_counts.necp_stat_rxoutoforderbytes;
6389 		digestp->txretransmit = tcpstats->necp_tcp_counts.necp_stat_txretransmit;
6390 		digestp->ifindex = route_ifindex;
6391 		digestp->state = tcpstats->necp_tcp_extra.state;
6392 		digestp->txunacked = tcpstats->necp_tcp_extra.txunacked;
6393 		digestp->txwindow = tcpstats->necp_tcp_extra.txwindow;
6394 		digestp->connstatus.probe_activated    = tcpstats->necp_tcp_extra.probestatus.probe_activated;
6395 		digestp->connstatus.write_probe_failed = tcpstats->necp_tcp_extra.probestatus.write_probe_failed;
6396 		digestp->connstatus.read_probe_failed  = tcpstats->necp_tcp_extra.probestatus.read_probe_failed;
6397 		digestp->connstatus.conn_probe_failed  = tcpstats->necp_tcp_extra.probestatus.conn_probe_failed;
6398 
6399 		if ((countsp == NULL) && (metadatap == NULL)) {
6400 			return true;
6401 		}
6402 	}
6403 
6404 	const struct sk_stats_flow *sf = &flow_registration->nexus_stats->fs_stats;
6405 	if (sf == NULL) {
6406 		nstat_diagnostic_flags |= NSTAT_IFNET_FLOWSWITCH_VALUE_UNOBTAINABLE;
6407 		char namebuf[MAXCOMLEN + 1];
6408 		(void) strlcpy(namebuf, "unknown", sizeof(namebuf));
6409 		proc_name(client->proc_pid, namebuf, sizeof(namebuf));
6410 		NECPLOG(LOG_ERR, "req tcp stats, necp_client flow_registration flow_stats missing for pid %d %s curproc %d %s\n",
6411 		    client->proc_pid, namebuf, proc_pid(current_proc()), proc_best_name(current_proc()));
6412 		sf = &ntstat_sk_stats_zero;
6413 	}
6414 
6415 	if (countsp) {
6416 		countsp->nstat_rxbytes = tcpstats->necp_tcp_counts.necp_stat_rxbytes;
6417 		countsp->nstat_txbytes = tcpstats->necp_tcp_counts.necp_stat_txbytes;
6418 
6419 		countsp->nstat_rxduplicatebytes = tcpstats->necp_tcp_counts.necp_stat_rxduplicatebytes;
6420 		countsp->nstat_rxoutoforderbytes = tcpstats->necp_tcp_counts.necp_stat_rxoutoforderbytes;
6421 		countsp->nstat_txretransmit = tcpstats->necp_tcp_counts.necp_stat_txretransmit;
6422 
6423 		countsp->nstat_min_rtt = tcpstats->necp_tcp_counts.necp_stat_min_rtt;
6424 		countsp->nstat_avg_rtt = tcpstats->necp_tcp_counts.necp_stat_avg_rtt;
6425 		countsp->nstat_var_rtt = tcpstats->necp_tcp_counts.necp_stat_var_rtt;
6426 
6427 		countsp->nstat_connectattempts = tcpstats->necp_tcp_extra.state >= TCPS_SYN_SENT ? 1 : 0;
6428 		countsp->nstat_connectsuccesses = tcpstats->necp_tcp_extra.state >= TCPS_ESTABLISHED ? 1 : 0;
6429 
6430 		// Supplement what the user level has told us with what we know from the flowswitch
6431 		countsp->nstat_rxpackets = sf->sf_ipackets;
6432 		countsp->nstat_txpackets = sf->sf_opackets;
6433 		if (route_ifflags & NSTAT_IFNET_IS_CELLULAR) {
6434 			countsp->nstat_cell_rxbytes = sf->sf_ibytes;
6435 			countsp->nstat_cell_txbytes = sf->sf_obytes;
6436 		} else if (route_ifflags & NSTAT_IFNET_IS_WIFI) {
6437 			countsp->nstat_wifi_rxbytes = sf->sf_ibytes;
6438 			countsp->nstat_wifi_txbytes = sf->sf_obytes;
6439 		} else if (route_ifflags & NSTAT_IFNET_IS_WIRED) {
6440 			countsp->nstat_wired_rxbytes = sf->sf_ibytes;
6441 			countsp->nstat_wired_txbytes = sf->sf_obytes;
6442 		}
6443 	}
6444 
6445 	if (metadatap) {
6446 		nstat_tcp_descriptor *desc = (nstat_tcp_descriptor *)metadatap;
6447 		memset(desc, 0, sizeof(*desc));
6448 
6449 		// Metadata from the flow registration
6450 		uuid_copy(desc->fuuid, flow_registration->registration_id);
6451 
6452 		// Metadata that the necp client should have in TLV format.
6453 		pid_t effective_pid = client->proc_pid;
6454 		necp_find_netstat_data(client, (union necp_sockaddr_union *)&desc->remote, &effective_pid, &desc->uid, desc->euuid, &desc->persona_id, &desc->traffic_class, &desc->fallback_mode);
6455 		desc->epid = (u_int32_t)effective_pid;
6456 
6457 		// Metadata from the flow registration
6458 		// This needs to revisited if multiple flows are created from one flow registration
6459 		struct necp_client_flow *flow = NULL;
6460 		LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
6461 			memcpy(&desc->local, &flow->local_addr, sizeof(desc->local));
6462 			break;
6463 		}
6464 
6465 		// Metadata from the route
6466 		desc->ifindex = route_ifindex;
6467 		desc->ifnet_properties = route_ifflags | nstat_diagnostic_flags;
6468 		desc->ifnet_properties |= (sf->sf_flags & SFLOWF_ONLINK) ? NSTAT_IFNET_IS_LOCAL : NSTAT_IFNET_IS_NON_LOCAL;
6469 		if (tcpstats->necp_tcp_extra.flags1 & SOF1_CELLFALLBACK) {
6470 			desc->ifnet_properties |= NSTAT_IFNET_VIA_CELLFALLBACK;
6471 		}
6472 
6473 		// Basic metadata from userland
6474 		desc->rcvbufsize = tcpstats->necp_tcp_basic.rcvbufsize;
6475 		desc->rcvbufused = tcpstats->necp_tcp_basic.rcvbufused;
6476 
6477 		// Additional TCP specific data
6478 		desc->sndbufsize = tcpstats->necp_tcp_extra.sndbufsize;
6479 		desc->sndbufused = tcpstats->necp_tcp_extra.sndbufused;
6480 		desc->txunacked = tcpstats->necp_tcp_extra.txunacked;
6481 		desc->txwindow = tcpstats->necp_tcp_extra.txwindow;
6482 		desc->txcwindow = tcpstats->necp_tcp_extra.txcwindow;
6483 		desc->traffic_mgt_flags = tcpstats->necp_tcp_extra.traffic_mgt_flags;
6484 		desc->state = tcpstats->necp_tcp_extra.state;
6485 
6486 		u_int32_t cc_alg_index = tcpstats->necp_tcp_extra.cc_alg_index;
6487 		if (cc_alg_index < TCP_CC_ALGO_COUNT) {
6488 			strlcpy(desc->cc_algo, tcp_cc_algo_list[cc_alg_index]->name, sizeof(desc->cc_algo));
6489 		} else {
6490 			strlcpy(desc->cc_algo, "unknown", sizeof(desc->cc_algo));
6491 		}
6492 
6493 		desc->connstatus.probe_activated        = tcpstats->necp_tcp_extra.probestatus.probe_activated;
6494 		desc->connstatus.write_probe_failed     = tcpstats->necp_tcp_extra.probestatus.write_probe_failed;
6495 		desc->connstatus.read_probe_failed      = tcpstats->necp_tcp_extra.probestatus.read_probe_failed;
6496 		desc->connstatus.conn_probe_failed      = tcpstats->necp_tcp_extra.probestatus.conn_probe_failed;
6497 
6498 		memcpy(&desc->activity_bitmap, &sf->sf_activity, sizeof(sf->sf_activity));
6499 
6500 		if (NECP_ENABLE_CLIENT_TRACE(NECP_CLIENT_TRACE_LEVEL_FLOW)) {
6501 			uuid_string_t euuid_str = { 0 };
6502 			uuid_unparse(desc->euuid, euuid_str);
6503 			NECPLOG(LOG_NOTICE, "Collected stats - TCP - epid %d uid %d euuid %s persona id %d", desc->epid, desc->uid, euuid_str, desc->persona_id);
6504 		}
6505 	}
6506 
6507 	return true;
6508 }
6509 
6510 // Called from NetworkStatistics when it wishes to collect latest information for a UDP flow.
6511 static bool
necp_request_udp_netstats(userland_stats_provider_context * ctx,u_int32_t * ifflagsp,nstat_progress_digest * digestp,nstat_counts * countsp,void * metadatap)6512 necp_request_udp_netstats(userland_stats_provider_context *ctx,
6513     u_int32_t *ifflagsp,
6514     nstat_progress_digest *digestp,
6515     nstat_counts *countsp,
6516     void *metadatap)
6517 {
6518 #pragma unused(digestp)
6519 
6520 	if (ctx == NULL) {
6521 		return false;
6522 	}
6523 
6524 	struct necp_client_flow_registration *flow_registration = (struct necp_client_flow_registration *)(uintptr_t)ctx;
6525 	struct necp_client *client = flow_registration->client;
6526 	struct necp_all_stats *ustats_kaddr = ((struct necp_all_kstats *)flow_registration->kstats_kaddr)->necp_stats_ustats;
6527 	struct necp_udp_stats *udpstats = (struct necp_udp_stats *)ustats_kaddr;
6528 	ASSERT(udpstats != NULL);
6529 
6530 	u_int32_t nstat_diagnostic_flags = 0;
6531 
6532 	// Retrieve details from the last time the assigned flows were updated
6533 	u_int32_t route_ifindex = IFSCOPE_NONE;
6534 	u_int32_t route_ifflags = NSTAT_IFNET_IS_UNKNOWN_TYPE;
6535 	u_int64_t combined_interface_details = 0;
6536 
6537 	combined_interface_details = os_atomic_load(&flow_registration->last_interface_details, relaxed);
6538 	split_interface_details(combined_interface_details, &route_ifindex, &route_ifflags);
6539 
6540 	if (route_ifindex == IFSCOPE_NONE) {
6541 		// Mark no interface
6542 		nstat_diagnostic_flags |= NSTAT_IFNET_ROUTE_VALUE_UNOBTAINABLE;
6543 		route_ifflags = NSTAT_IFNET_IS_UNKNOWN_TYPE;
6544 		NECPLOG(LOG_INFO, "req udp stats, failed to get route details for pid %d curproc %d %s\n",
6545 		    client->proc_pid, proc_pid(current_proc()), proc_best_name(current_proc()));
6546 	}
6547 
6548 	if (ifflagsp) {
6549 		*ifflagsp = route_ifflags | nstat_diagnostic_flags;
6550 		if ((countsp == NULL) && (metadatap == NULL)) {
6551 			return true;
6552 		}
6553 	}
6554 	const struct sk_stats_flow *sf = &flow_registration->nexus_stats->fs_stats;
6555 	if (sf == NULL) {
6556 		nstat_diagnostic_flags |= NSTAT_IFNET_FLOWSWITCH_VALUE_UNOBTAINABLE;
6557 		char namebuf[MAXCOMLEN + 1];
6558 		(void) strlcpy(namebuf, "unknown", sizeof(namebuf));
6559 		proc_name(client->proc_pid, namebuf, sizeof(namebuf));
6560 		NECPLOG(LOG_ERR, "req udp stats, necp_client flow_registration flow_stats missing for pid %d %s curproc %d %s\n",
6561 		    client->proc_pid, namebuf, proc_pid(current_proc()), proc_best_name(current_proc()));
6562 		sf = &ntstat_sk_stats_zero;
6563 	}
6564 
6565 	if (countsp) {
6566 		countsp->nstat_rxbytes = udpstats->necp_udp_counts.necp_stat_rxbytes;
6567 		countsp->nstat_txbytes = udpstats->necp_udp_counts.necp_stat_txbytes;
6568 
6569 		countsp->nstat_rxduplicatebytes = udpstats->necp_udp_counts.necp_stat_rxduplicatebytes;
6570 		countsp->nstat_rxoutoforderbytes = udpstats->necp_udp_counts.necp_stat_rxoutoforderbytes;
6571 		countsp->nstat_txretransmit = udpstats->necp_udp_counts.necp_stat_txretransmit;
6572 
6573 		countsp->nstat_min_rtt = udpstats->necp_udp_counts.necp_stat_min_rtt;
6574 		countsp->nstat_avg_rtt = udpstats->necp_udp_counts.necp_stat_avg_rtt;
6575 		countsp->nstat_var_rtt = udpstats->necp_udp_counts.necp_stat_var_rtt;
6576 
6577 		// Supplement what the user level has told us with what we know from the flowswitch
6578 		countsp->nstat_rxpackets = sf->sf_ipackets;
6579 		countsp->nstat_txpackets = sf->sf_opackets;
6580 		if (route_ifflags & NSTAT_IFNET_IS_CELLULAR) {
6581 			countsp->nstat_cell_rxbytes = sf->sf_ibytes;
6582 			countsp->nstat_cell_txbytes = sf->sf_obytes;
6583 		} else if (route_ifflags & NSTAT_IFNET_IS_WIFI) {
6584 			countsp->nstat_wifi_rxbytes = sf->sf_ibytes;
6585 			countsp->nstat_wifi_txbytes = sf->sf_obytes;
6586 		} else if (route_ifflags & NSTAT_IFNET_IS_WIRED) {
6587 			countsp->nstat_wired_rxbytes = sf->sf_ibytes;
6588 			countsp->nstat_wired_txbytes = sf->sf_obytes;
6589 		}
6590 	}
6591 
6592 	if (metadatap) {
6593 		nstat_udp_descriptor *desc = (nstat_udp_descriptor *)metadatap;
6594 		memset(desc, 0, sizeof(*desc));
6595 
6596 		// Metadata from the flow registration
6597 		uuid_copy(desc->fuuid, flow_registration->registration_id);
6598 
6599 		// Metadata that the necp client should have in TLV format.
6600 		pid_t effective_pid = client->proc_pid;
6601 		necp_find_netstat_data(client, (union necp_sockaddr_union *)&desc->remote, &effective_pid, &desc->uid, desc->euuid, &desc->persona_id, &desc->traffic_class, &desc->fallback_mode);
6602 		desc->epid = (u_int32_t)effective_pid;
6603 
6604 		// Metadata from the flow registration
6605 		// This needs to revisited if multiple flows are created from one flow registration
6606 		struct necp_client_flow *flow = NULL;
6607 		LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
6608 			memcpy(&desc->local, &flow->local_addr, sizeof(desc->local));
6609 			break;
6610 		}
6611 
6612 		// Metadata from the route
6613 		desc->ifindex = route_ifindex;
6614 		desc->ifnet_properties = route_ifflags | nstat_diagnostic_flags;
6615 		desc->ifnet_properties |= (sf->sf_flags & SFLOWF_ONLINK) ? NSTAT_IFNET_IS_LOCAL : NSTAT_IFNET_IS_NON_LOCAL;
6616 
6617 		// Basic metadata is all that is required for UDP
6618 		desc->rcvbufsize = udpstats->necp_udp_basic.rcvbufsize;
6619 		desc->rcvbufused = udpstats->necp_udp_basic.rcvbufused;
6620 
6621 		memcpy(&desc->activity_bitmap, &sf->sf_activity, sizeof(sf->sf_activity));
6622 
6623 		if (NECP_ENABLE_CLIENT_TRACE(NECP_CLIENT_TRACE_LEVEL_FLOW)) {
6624 			uuid_string_t euuid_str = { 0 };
6625 			uuid_unparse(desc->euuid, euuid_str);
6626 			NECPLOG(LOG_NOTICE, "Collected stats - UDP - epid %d uid %d euuid %s persona id %d", desc->epid, desc->uid, euuid_str, desc->persona_id);
6627 		}
6628 	}
6629 
6630 	return true;
6631 }
6632 
6633 // Called from NetworkStatistics when it wishes to collect latest information for a QUIC flow.
6634 //
6635 // TODO: For now it is an exact implementation as that of TCP.
6636 // Still to keep the logic separate for future divergence, keeping the routines separate.
6637 // It also seems there are lots of common code between existing implementations and
6638 // it would be good to refactor this logic at some point.
6639 static bool
necp_request_quic_netstats(userland_stats_provider_context * ctx,u_int32_t * ifflagsp,nstat_progress_digest * digestp,nstat_counts * countsp,void * metadatap)6640 necp_request_quic_netstats(userland_stats_provider_context *ctx,
6641     u_int32_t *ifflagsp,
6642     nstat_progress_digest *digestp,
6643     nstat_counts *countsp,
6644     void *metadatap)
6645 {
6646 	if (ctx == NULL) {
6647 		return false;
6648 	}
6649 
6650 	struct necp_client_flow_registration *flow_registration = (struct necp_client_flow_registration *)(uintptr_t)ctx;
6651 	struct necp_client *client = flow_registration->client;
6652 	struct necp_all_stats *ustats_kaddr = ((struct necp_all_kstats *)flow_registration->kstats_kaddr)->necp_stats_ustats;
6653 	struct necp_quic_stats *quicstats = (struct necp_quic_stats *)ustats_kaddr;
6654 	ASSERT(quicstats != NULL);
6655 
6656 	u_int32_t nstat_diagnostic_flags = 0;
6657 
6658 	// Retrieve details from the last time the assigned flows were updated
6659 	u_int32_t route_ifindex = IFSCOPE_NONE;
6660 	u_int32_t route_ifflags = NSTAT_IFNET_IS_UNKNOWN_TYPE;
6661 	u_int64_t combined_interface_details = 0;
6662 
6663 	combined_interface_details = os_atomic_load(&flow_registration->last_interface_details, relaxed);
6664 	split_interface_details(combined_interface_details, &route_ifindex, &route_ifflags);
6665 
6666 	if (route_ifindex == IFSCOPE_NONE) {
6667 		// Mark no interface
6668 		nstat_diagnostic_flags |= NSTAT_IFNET_ROUTE_VALUE_UNOBTAINABLE;
6669 		route_ifflags = NSTAT_IFNET_IS_UNKNOWN_TYPE;
6670 		NECPLOG(LOG_INFO, "req quic stats, failed to get route details for pid %d curproc %d %s\n",
6671 		    client->proc_pid, proc_pid(current_proc()), proc_best_name(current_proc()));
6672 	}
6673 
6674 	if (ifflagsp) {
6675 		*ifflagsp = route_ifflags | nstat_diagnostic_flags;
6676 		if ((digestp == NULL) && (countsp == NULL) && (metadatap == NULL)) {
6677 			return true;
6678 		}
6679 	}
6680 
6681 	if (digestp) {
6682 		// The digest is intended to give information that may help give insight into the state of the link
6683 		// while avoiding the need to do the relatively expensive flowswitch lookup
6684 		digestp->rxbytes = quicstats->necp_quic_counts.necp_stat_rxbytes;
6685 		digestp->txbytes = quicstats->necp_quic_counts.necp_stat_txbytes;
6686 		digestp->rxduplicatebytes = quicstats->necp_quic_counts.necp_stat_rxduplicatebytes;
6687 		digestp->rxoutoforderbytes = quicstats->necp_quic_counts.necp_stat_rxoutoforderbytes;
6688 		digestp->txretransmit = quicstats->necp_quic_counts.necp_stat_txretransmit;
6689 		digestp->ifindex = route_ifindex;
6690 		digestp->state = quicstats->necp_quic_extra.state;
6691 		digestp->txunacked = quicstats->necp_quic_extra.txunacked;
6692 		digestp->txwindow = quicstats->necp_quic_extra.txwindow;
6693 		digestp->connstatus.probe_activated    = quicstats->necp_quic_extra.probestatus.probe_activated;
6694 		digestp->connstatus.write_probe_failed = quicstats->necp_quic_extra.probestatus.write_probe_failed;
6695 		digestp->connstatus.read_probe_failed  = quicstats->necp_quic_extra.probestatus.read_probe_failed;
6696 		digestp->connstatus.conn_probe_failed  = quicstats->necp_quic_extra.probestatus.conn_probe_failed;
6697 
6698 		if ((countsp == NULL) && (metadatap == NULL)) {
6699 			return true;
6700 		}
6701 	}
6702 
6703 	const struct sk_stats_flow *sf = &flow_registration->nexus_stats->fs_stats;
6704 	if (sf == NULL) {
6705 		nstat_diagnostic_flags |= NSTAT_IFNET_FLOWSWITCH_VALUE_UNOBTAINABLE;
6706 		char namebuf[MAXCOMLEN + 1];
6707 		(void) strlcpy(namebuf, "unknown", sizeof(namebuf));
6708 		proc_name(client->proc_pid, namebuf, sizeof(namebuf));
6709 		NECPLOG(LOG_ERR, "req quic stats, necp_client flow_registration flow_stats missing for pid %d %s curproc %d %s\n",
6710 		    client->proc_pid, namebuf, proc_pid(current_proc()), proc_best_name(current_proc()));
6711 		sf = &ntstat_sk_stats_zero;
6712 	}
6713 
6714 	if (countsp) {
6715 		countsp->nstat_rxbytes = quicstats->necp_quic_counts.necp_stat_rxbytes;
6716 		countsp->nstat_txbytes = quicstats->necp_quic_counts.necp_stat_txbytes;
6717 
6718 		countsp->nstat_rxduplicatebytes = quicstats->necp_quic_counts.necp_stat_rxduplicatebytes;
6719 		countsp->nstat_rxoutoforderbytes = quicstats->necp_quic_counts.necp_stat_rxoutoforderbytes;
6720 		countsp->nstat_txretransmit = quicstats->necp_quic_counts.necp_stat_txretransmit;
6721 
6722 		countsp->nstat_min_rtt = quicstats->necp_quic_counts.necp_stat_min_rtt;
6723 		countsp->nstat_avg_rtt = quicstats->necp_quic_counts.necp_stat_avg_rtt;
6724 		countsp->nstat_var_rtt = quicstats->necp_quic_counts.necp_stat_var_rtt;
6725 
6726 		// TODO: It would be good to expose QUIC stats for CH/SH retransmission and connection state
6727 		// Supplement what the user level has told us with what we know from the flowswitch
6728 		countsp->nstat_rxpackets = sf->sf_ipackets;
6729 		countsp->nstat_txpackets = sf->sf_opackets;
6730 		if (route_ifflags & NSTAT_IFNET_IS_CELLULAR) {
6731 			countsp->nstat_cell_rxbytes = sf->sf_ibytes;
6732 			countsp->nstat_cell_txbytes = sf->sf_obytes;
6733 		} else if (route_ifflags & NSTAT_IFNET_IS_WIFI) {
6734 			countsp->nstat_wifi_rxbytes = sf->sf_ibytes;
6735 			countsp->nstat_wifi_txbytes = sf->sf_obytes;
6736 		} else if (route_ifflags & NSTAT_IFNET_IS_WIRED) {
6737 			countsp->nstat_wired_rxbytes = sf->sf_ibytes;
6738 			countsp->nstat_wired_txbytes = sf->sf_obytes;
6739 		}
6740 	}
6741 
6742 	if (metadatap) {
6743 		nstat_quic_descriptor *desc = (nstat_quic_descriptor *)metadatap;
6744 		memset(desc, 0, sizeof(*desc));
6745 
6746 		// Metadata from the flow registration
6747 		uuid_copy(desc->fuuid, flow_registration->registration_id);
6748 
6749 		// Metadata, that the necp client should have, in TLV format.
6750 		pid_t effective_pid = client->proc_pid;
6751 		necp_find_netstat_data(client, (union necp_sockaddr_union *)&desc->remote, &effective_pid, &desc->uid, desc->euuid, &desc->persona_id, &desc->traffic_class, &desc->fallback_mode);
6752 		desc->epid = (u_int32_t)effective_pid;
6753 
6754 		// Metadata from the flow registration
6755 		// This needs to revisited if multiple flows are created from one flow registration
6756 		struct necp_client_flow *flow = NULL;
6757 		LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
6758 			memcpy(&desc->local, &flow->local_addr, sizeof(desc->local));
6759 			break;
6760 		}
6761 
6762 		// Metadata from the route
6763 		desc->ifindex = route_ifindex;
6764 		desc->ifnet_properties = route_ifflags | nstat_diagnostic_flags;
6765 		desc->ifnet_properties |= (sf->sf_flags & SFLOWF_ONLINK) ? NSTAT_IFNET_IS_LOCAL : NSTAT_IFNET_IS_NON_LOCAL;
6766 
6767 		// Basic metadata from userland
6768 		desc->rcvbufsize = quicstats->necp_quic_basic.rcvbufsize;
6769 		desc->rcvbufused = quicstats->necp_quic_basic.rcvbufused;
6770 
6771 		// Additional QUIC specific data
6772 		desc->sndbufsize = quicstats->necp_quic_extra.sndbufsize;
6773 		desc->sndbufused = quicstats->necp_quic_extra.sndbufused;
6774 		desc->txunacked = quicstats->necp_quic_extra.txunacked;
6775 		desc->txwindow = quicstats->necp_quic_extra.txwindow;
6776 		desc->txcwindow = quicstats->necp_quic_extra.txcwindow;
6777 		desc->traffic_mgt_flags = quicstats->necp_quic_extra.traffic_mgt_flags;
6778 		desc->state = quicstats->necp_quic_extra.state;
6779 
6780 		// TODO: CC algo defines should be named agnostic of the protocol
6781 		u_int32_t cc_alg_index = quicstats->necp_quic_extra.cc_alg_index;
6782 		if (cc_alg_index < TCP_CC_ALGO_COUNT) {
6783 			strlcpy(desc->cc_algo, tcp_cc_algo_list[cc_alg_index]->name, sizeof(desc->cc_algo));
6784 		} else {
6785 			strlcpy(desc->cc_algo, "unknown", sizeof(desc->cc_algo));
6786 		}
6787 
6788 		memcpy(&desc->activity_bitmap, &sf->sf_activity, sizeof(sf->sf_activity));
6789 
6790 		desc->connstatus.probe_activated        = quicstats->necp_quic_extra.probestatus.probe_activated;
6791 		desc->connstatus.write_probe_failed     = quicstats->necp_quic_extra.probestatus.write_probe_failed;
6792 		desc->connstatus.read_probe_failed      = quicstats->necp_quic_extra.probestatus.read_probe_failed;
6793 		desc->connstatus.conn_probe_failed      = quicstats->necp_quic_extra.probestatus.conn_probe_failed;
6794 
6795 		if (NECP_ENABLE_CLIENT_TRACE(NECP_CLIENT_TRACE_LEVEL_FLOW)) {
6796 			uuid_string_t euuid_str = { 0 };
6797 			uuid_unparse(desc->euuid, euuid_str);
6798 			NECPLOG(LOG_NOTICE, "Collected stats - QUIC - epid %d uid %d euuid %s persona id %d", desc->epid, desc->uid, euuid_str, desc->persona_id);
6799 		}
6800 	}
6801 	return true;
6802 }
6803 
6804 #endif /* SKYWALK */
6805 
6806 // Support functions for NetworkStatistics support for necp_client connections
6807 
6808 static void
necp_client_inherit_from_parent(struct necp_client * client,struct necp_client * parent)6809 necp_client_inherit_from_parent(
6810 	struct necp_client *client,
6811 	struct necp_client *parent)
6812 {
6813 	assert(client->original_parameters_source == NULL);
6814 
6815 	if (parent->original_parameters_source != NULL) {
6816 		client->original_parameters_source = parent->original_parameters_source;
6817 	} else {
6818 		client->original_parameters_source = parent;
6819 	}
6820 	necp_client_retain(client->original_parameters_source);
6821 }
6822 
6823 static void
necp_find_conn_netstat_data(struct necp_client * client,u_int32_t * ntstat_flags,pid_t * effective_pid,uuid_t puuid,uid_t * uid,uuid_t euuid,uid_t * persona_id)6824 necp_find_conn_netstat_data(struct necp_client *client,
6825     u_int32_t *ntstat_flags,
6826     pid_t *effective_pid,
6827     uuid_t puuid,
6828     uid_t *uid,
6829     uuid_t euuid,
6830     uid_t *persona_id)
6831 {
6832 	bool has_remote_address = false;
6833 	bool has_ip_protocol = false;
6834 	bool has_transport_protocol = false;
6835 	size_t offset = 0;
6836 	u_int8_t *parameters;
6837 	u_int32_t parameters_size;
6838 
6839 
6840 	parameters = client->parameters;
6841 	parameters_size = (u_int32_t)client->parameters_length;
6842 
6843 	while ((offset + sizeof(struct necp_tlv_header)) <= parameters_size) {
6844 		u_int8_t type = necp_buffer_get_tlv_type(parameters, offset);
6845 		u_int32_t length = necp_buffer_get_tlv_length(parameters, offset);
6846 
6847 		if (length > (parameters_size - (offset + sizeof(struct necp_tlv_header)))) {
6848 			// If the length is larger than what can fit in the remaining parameters size, bail
6849 			NECPLOG(LOG_ERR, "Invalid TLV length (%u)", length);
6850 			break;
6851 		}
6852 
6853 		if (length > 0) {
6854 			u_int8_t *value = necp_buffer_get_tlv_value(parameters, offset, NULL);
6855 			if (value != NULL) {
6856 				switch (type) {
6857 				case NECP_CLIENT_PARAMETER_APPLICATION: {
6858 					if ((euuid) && (length >= sizeof(uuid_t))) {
6859 						uuid_copy(euuid, value);
6860 					}
6861 					break;
6862 				}
6863 				case NECP_CLIENT_PARAMETER_IP_PROTOCOL: {
6864 					if (length >= 1) {
6865 						has_ip_protocol = true;
6866 					}
6867 					break;
6868 				}
6869 				case NECP_CLIENT_PARAMETER_PID: {
6870 					if ((effective_pid) && length >= sizeof(pid_t)) {
6871 						memcpy(effective_pid, value, sizeof(pid_t));
6872 					}
6873 					break;
6874 				}
6875 				case NECP_CLIENT_PARAMETER_PARENT_ID: {
6876 					if ((puuid) && (length == sizeof(uuid_t))) {
6877 						uuid_copy(puuid, value);
6878 					}
6879 					break;
6880 				}
6881 				// It is an implementation quirk that the remote address can be found in the necp parameters
6882 				case NECP_CLIENT_PARAMETER_REMOTE_ADDRESS: {
6883 					if (length >= sizeof(struct necp_policy_condition_addr)) {
6884 						struct necp_policy_condition_addr *address_struct = (struct necp_policy_condition_addr *)(void *)value;
6885 						if (necp_client_address_is_valid(&address_struct->address.sa)) {
6886 							has_remote_address = true;
6887 						}
6888 					}
6889 					break;
6890 				}
6891 				case NECP_CLIENT_PARAMETER_TRANSPORT_PROTOCOL: {
6892 					if (length >= 1) {
6893 						has_transport_protocol = true;
6894 					}
6895 					break;
6896 				}
6897 				case NECP_CLIENT_PARAMETER_APPLICATION_ID: {
6898 					if (length >= sizeof(necp_application_id_t) && uid && persona_id) {
6899 						necp_application_id_t *application_id = (necp_application_id_t *)(void *)value;
6900 						memcpy(uid, &application_id->uid, sizeof(uid_t));
6901 						uuid_copy(euuid, application_id->effective_uuid);
6902 						memcpy(persona_id, &application_id->persona_id, sizeof(uid_t));
6903 					}
6904 					break;
6905 				}
6906 				default: {
6907 					break;
6908 				}
6909 				}
6910 			}
6911 		}
6912 		offset += sizeof(struct necp_tlv_header) + length;
6913 	}
6914 	if (ntstat_flags) {
6915 		*ntstat_flags = (has_remote_address && has_ip_protocol && has_transport_protocol)? NSTAT_NECP_CONN_HAS_NET_ACCESS: 0;
6916 	}
6917 }
6918 
6919 static bool
necp_request_conn_netstats(nstat_provider_context ctx,u_int32_t * ifflagsp,nstat_counts * countsp,void * metadatap)6920 necp_request_conn_netstats(nstat_provider_context ctx,
6921     u_int32_t *ifflagsp,
6922     nstat_counts *countsp,
6923     void *metadatap)
6924 {
6925 	if (ctx == NULL) {
6926 		return false;
6927 	}
6928 	struct necp_client *client = (struct necp_client *)(uintptr_t)ctx;
6929 	nstat_connection_descriptor *desc = (nstat_connection_descriptor *)metadatap;
6930 
6931 	if (ifflagsp) {
6932 		necp_find_conn_netstat_data(client, ifflagsp, NULL, NULL, NULL, NULL, NULL);
6933 	}
6934 	if (countsp) {
6935 		memset(countsp, 0, sizeof(*countsp));
6936 	}
6937 	if (desc) {
6938 		memset(desc, 0, sizeof(*desc));
6939 		// Metadata, that the necp client should have, in TLV format.
6940 		pid_t effective_pid = client->proc_pid;
6941 		necp_find_conn_netstat_data(client, &desc->ifnet_properties, &effective_pid, desc->puuid, &desc->uid, desc->euuid, &desc->persona_id);
6942 		desc->epid = (u_int32_t)effective_pid;
6943 
6944 		// User level should obtain almost all connection information from an extension
6945 		// leaving little to do here
6946 		uuid_copy(desc->fuuid, client->latest_flow_registration_id);
6947 		uuid_copy(desc->cuuid, client->client_id);
6948 	}
6949 	return true;
6950 }
6951 
6952 static int
necp_skywalk_priv_check_cred(proc_t p,kauth_cred_t cred)6953 necp_skywalk_priv_check_cred(proc_t p, kauth_cred_t cred)
6954 {
6955 #pragma unused(p, cred)
6956 #if SKYWALK
6957 	/* This includes Nexus controller and Skywalk observer privs */
6958 	return skywalk_nxctl_check_privileges(p, cred);
6959 #else /* !SKYWALK */
6960 	return 0;
6961 #endif /* !SKYWALK */
6962 }
6963 
6964 /// System calls
6965 
6966 int
necp_open(struct proc * p,struct necp_open_args * uap,int * retval)6967 necp_open(struct proc *p, struct necp_open_args *uap, int *retval)
6968 {
6969 #pragma unused(retval)
6970 	int error = 0;
6971 	struct necp_fd_data *fd_data = NULL;
6972 	struct fileproc *fp = NULL;
6973 	int fd = -1;
6974 
6975 	if (uap->flags & NECP_OPEN_FLAG_OBSERVER ||
6976 	    uap->flags & NECP_OPEN_FLAG_PUSH_OBSERVER) {
6977 		if (necp_skywalk_priv_check_cred(p, kauth_cred_get()) != 0 &&
6978 		    priv_check_cred(kauth_cred_get(), PRIV_NET_PRIVILEGED_NETWORK_STATISTICS, 0) != 0) {
6979 			NECPLOG0(LOG_ERR, "Client does not hold necessary entitlement to observe other NECP clients");
6980 			error = EACCES;
6981 			goto done;
6982 		}
6983 	}
6984 
6985 #if CONFIG_MACF
6986 	error = mac_necp_check_open(p, uap->flags);
6987 	if (error) {
6988 		goto done;
6989 	}
6990 #endif /* MACF */
6991 
6992 	error = falloc(p, &fp, &fd);
6993 	if (error != 0) {
6994 		goto done;
6995 	}
6996 
6997 	fd_data = kalloc_type(struct necp_fd_data, Z_WAITOK | Z_ZERO | Z_NOFAIL);
6998 
6999 	fd_data->necp_fd_type = necp_fd_type_client;
7000 	fd_data->flags = uap->flags;
7001 	RB_INIT(&fd_data->clients);
7002 	RB_INIT(&fd_data->flows);
7003 	TAILQ_INIT(&fd_data->update_list);
7004 	lck_mtx_init(&fd_data->fd_lock, &necp_fd_mtx_grp, &necp_fd_mtx_attr);
7005 	klist_init(&fd_data->si.si_note);
7006 	fd_data->proc_pid = proc_pid(p);
7007 #if SKYWALK
7008 	LIST_INIT(&fd_data->stats_arena_list);
7009 #endif /* !SKYWALK */
7010 
7011 	fp->fp_flags |= FP_CLOEXEC | FP_CLOFORK;
7012 	fp->fp_glob->fg_flag = FREAD;
7013 	fp->fp_glob->fg_ops = &necp_fd_ops;
7014 	fp_set_data(fp, fd_data);
7015 
7016 	proc_fdlock(p);
7017 
7018 	procfdtbl_releasefd(p, fd, NULL);
7019 	fp_drop(p, fd, fp, 1);
7020 
7021 	*retval = fd;
7022 
7023 	if (fd_data->flags & NECP_OPEN_FLAG_PUSH_OBSERVER) {
7024 		NECP_OBSERVER_LIST_LOCK_EXCLUSIVE();
7025 		LIST_INSERT_HEAD(&necp_fd_observer_list, fd_data, chain);
7026 		OSIncrementAtomic(&necp_observer_fd_count);
7027 		NECP_OBSERVER_LIST_UNLOCK();
7028 
7029 		// Walk all existing clients and add them
7030 		NECP_CLIENT_TREE_LOCK_SHARED();
7031 		struct necp_client *existing_client = NULL;
7032 		RB_FOREACH(existing_client, _necp_client_global_tree, &necp_client_global_tree) {
7033 			NECP_CLIENT_LOCK(existing_client);
7034 			necp_client_update_observer_add_internal(fd_data, existing_client);
7035 			necp_client_update_observer_update_internal(fd_data, existing_client);
7036 			NECP_CLIENT_UNLOCK(existing_client);
7037 		}
7038 		NECP_CLIENT_TREE_UNLOCK();
7039 	} else {
7040 		NECP_FD_LIST_LOCK_EXCLUSIVE();
7041 		LIST_INSERT_HEAD(&necp_fd_list, fd_data, chain);
7042 		OSIncrementAtomic(&necp_client_fd_count);
7043 		NECP_FD_LIST_UNLOCK();
7044 	}
7045 
7046 	proc_fdunlock(p);
7047 
7048 done:
7049 	if (error != 0) {
7050 		if (fp != NULL) {
7051 			fp_free(p, fd, fp);
7052 			fp = NULL;
7053 		}
7054 		if (fd_data != NULL) {
7055 			kfree_type(struct necp_fd_data, fd_data);
7056 		}
7057 	}
7058 
7059 	return error;
7060 }
7061 
7062 // All functions called directly from necp_client_action() to handle one of the
7063 // types should be marked with NECP_CLIENT_ACTION_FUNCTION. This ensures that
7064 // necp_client_action() does not inline all the actions into a single function.
7065 #define NECP_CLIENT_ACTION_FUNCTION __attribute__((noinline))
7066 
7067 static NECP_CLIENT_ACTION_FUNCTION int
necp_client_add(struct proc * p,struct necp_fd_data * fd_data,struct necp_client_action_args * uap,int * retval)7068 necp_client_add(struct proc *p, struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
7069 {
7070 	int error = 0;
7071 	struct necp_client *client = NULL;
7072 	const size_t buffer_size = uap->buffer_size;
7073 
7074 	if (fd_data->flags & NECP_OPEN_FLAG_PUSH_OBSERVER) {
7075 		NECPLOG0(LOG_ERR, "NECP client observers with push enabled may not add their own clients");
7076 		return EINVAL;
7077 	}
7078 
7079 	if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t) ||
7080 	    buffer_size == 0 || buffer_size > NECP_MAX_CLIENT_PARAMETERS_SIZE || uap->buffer == 0) {
7081 		return EINVAL;
7082 	}
7083 
7084 	client = kalloc_type(struct necp_client, Z_WAITOK | Z_ZERO | Z_NOFAIL);
7085 	client->parameters = kalloc_data(buffer_size, Z_WAITOK | Z_NOFAIL);
7086 	client->parameters_length = buffer_size;
7087 	lck_mtx_init(&client->lock, &necp_fd_mtx_grp, &necp_fd_mtx_attr);
7088 	lck_mtx_init(&client->route_lock, &necp_fd_mtx_grp, &necp_fd_mtx_attr);
7089 
7090 	error = copyin(uap->buffer, client->parameters, buffer_size);
7091 	if (error) {
7092 		NECPLOG(LOG_ERR, "necp_client_add parameters copyin error (%d)", error);
7093 		goto done;
7094 	}
7095 
7096 	os_ref_init(&client->reference_count, &necp_client_refgrp); // Hold our reference until close
7097 
7098 	client->proc_pid = fd_data->proc_pid; // Save off proc pid in case the client will persist past fd
7099 	client->agent_handle = (void *)fd_data;
7100 	client->platform_binary = ((csproc_get_platform_binary(p) == 0) ? 0 : 1);
7101 
7102 	necp_generate_client_id(client->client_id, false);
7103 	LIST_INIT(&client->assertion_list);
7104 	RB_INIT(&client->flow_registrations);
7105 
7106 	NECP_CLIENT_LOG(client, "Adding client");
7107 
7108 	error = copyout(client->client_id, uap->client_id, sizeof(uuid_t));
7109 	if (error) {
7110 		NECPLOG(LOG_ERR, "necp_client_add client_id copyout error (%d)", error);
7111 		goto done;
7112 	}
7113 
7114 #if SKYWALK
7115 	struct necp_client_parsed_parameters parsed_parameters = {};
7116 	int parse_error = necp_client_parse_parameters(client, client->parameters, (u_int32_t)client->parameters_length, &parsed_parameters);
7117 
7118 	if (parse_error == 0 &&
7119 	    ((parsed_parameters.valid_fields & NECP_PARSED_PARAMETERS_FIELD_DELEGATED_UPID) ||
7120 	    (parsed_parameters.valid_fields & NECP_PARSED_PARAMETERS_FIELD_ATTRIBUTED_BUNDLE_IDENTIFIER))) {
7121 		bool has_delegation_entitlement = (priv_check_cred(kauth_cred_get(), PRIV_NET_PRIVILEGED_SOCKET_DELEGATE, 0) == 0);
7122 		if (!has_delegation_entitlement) {
7123 			if (parsed_parameters.valid_fields & NECP_PARSED_PARAMETERS_FIELD_DELEGATED_UPID) {
7124 				NECPLOG(LOG_ERR, "%s(%d) does not hold the necessary entitlement to delegate network traffic for other processes by upid",
7125 				    proc_name_address(p), proc_pid(p));
7126 			}
7127 			if (parsed_parameters.valid_fields & NECP_PARSED_PARAMETERS_FIELD_ATTRIBUTED_BUNDLE_IDENTIFIER) {
7128 				NECPLOG(LOG_ERR, "%s(%d) does not hold the necessary entitlement to set attributed bundle identifier",
7129 				    proc_name_address(p), proc_pid(p));
7130 			}
7131 			error = EPERM;
7132 			goto done;
7133 		}
7134 
7135 		if (parsed_parameters.valid_fields & NECP_PARSED_PARAMETERS_FIELD_DELEGATED_UPID) {
7136 			// Save off delegated unique PID
7137 			client->delegated_upid = parsed_parameters.delegated_upid;
7138 		}
7139 	}
7140 
7141 	if (parse_error == 0 && parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_INTERPOSE) {
7142 		bool has_nexus_entitlement = (necp_skywalk_priv_check_cred(p, kauth_cred_get()) == 0);
7143 		if (!has_nexus_entitlement) {
7144 			NECPLOG(LOG_ERR, "%s(%d) does not hold the necessary entitlement to open a custom nexus client",
7145 			    proc_name_address(p), proc_pid(p));
7146 			error = EPERM;
7147 			goto done;
7148 		}
7149 	}
7150 
7151 	if (parse_error == 0 && (parsed_parameters.flags &
7152 	    (NECP_CLIENT_PARAMETER_FLAG_CUSTOM_ETHER | NECP_CLIENT_PARAMETER_FLAG_CUSTOM_IP))) {
7153 		bool has_custom_protocol_entitlement = (priv_check_cred(kauth_cred_get(), PRIV_NET_CUSTOM_PROTOCOL, 0) == 0);
7154 		if (!has_custom_protocol_entitlement) {
7155 			NECPLOG(LOG_ERR, "%s(%d) does not hold the necessary entitlement for custom protocol APIs",
7156 			    proc_name_address(p), proc_pid(p));
7157 			error = EPERM;
7158 			goto done;
7159 		}
7160 	}
7161 
7162 	if (parse_error == 0 && parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER &&
7163 	    (parsed_parameters.ip_protocol == IPPROTO_TCP || parsed_parameters.ip_protocol == IPPROTO_UDP)) {
7164 		uint32_t *netns_addr = NULL;
7165 		uint8_t netns_addr_len = 0;
7166 		struct ns_flow_info flow_info = {};
7167 		uint32_t netns_flags = NETNS_LISTENER;
7168 		uuid_copy(flow_info.nfi_flow_uuid, client->client_id);
7169 		flow_info.nfi_protocol = parsed_parameters.ip_protocol;
7170 		flow_info.nfi_owner_pid = client->proc_pid;
7171 		if (parsed_parameters.valid_fields & NECP_PARSED_PARAMETERS_FIELD_EFFECTIVE_PID) {
7172 			flow_info.nfi_effective_pid = parsed_parameters.effective_pid;
7173 		} else {
7174 			flow_info.nfi_effective_pid = flow_info.nfi_owner_pid;
7175 		}
7176 		proc_name(flow_info.nfi_owner_pid, flow_info.nfi_owner_name, MAXCOMLEN);
7177 		proc_name(flow_info.nfi_effective_pid, flow_info.nfi_effective_name, MAXCOMLEN);
7178 
7179 		if (parsed_parameters.local_addr.sa.sa_family == AF_UNSPEC) {
7180 			// Treat no local address as a wildcard IPv6
7181 			// parsed_parameters is already initialized to all zeros
7182 			parsed_parameters.local_addr.sin6.sin6_family = AF_INET6;
7183 			parsed_parameters.local_addr.sin6.sin6_len = sizeof(struct sockaddr_in6);
7184 		}
7185 
7186 		switch (parsed_parameters.local_addr.sa.sa_family) {
7187 		case AF_INET: {
7188 			memcpy(&flow_info.nfi_laddr, &parsed_parameters.local_addr.sa, parsed_parameters.local_addr.sa.sa_len);
7189 			netns_addr = (uint32_t *)&parsed_parameters.local_addr.sin.sin_addr;
7190 			netns_addr_len = 4;
7191 			break;
7192 		}
7193 		case AF_INET6: {
7194 			memcpy(&flow_info.nfi_laddr, &parsed_parameters.local_addr.sa, parsed_parameters.local_addr.sa.sa_len);
7195 			netns_addr = (uint32_t *)&parsed_parameters.local_addr.sin6.sin6_addr;
7196 			netns_addr_len = 16;
7197 			break;
7198 		}
7199 
7200 		default: {
7201 			NECPLOG(LOG_ERR, "necp_client_add listener invalid address family (%d)", parsed_parameters.local_addr.sa.sa_family);
7202 			error = EINVAL;
7203 			goto done;
7204 		}
7205 		}
7206 		if ((parsed_parameters.valid_fields & NECP_PARSED_PARAMETERS_FIELD_FLAGS) &&
7207 		    (parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_REUSE_LOCAL)) {
7208 			netns_flags |= NETNS_REUSEPORT;
7209 		}
7210 		if (parsed_parameters.local_addr.sin.sin_port == 0) {
7211 			error = netns_reserve_ephemeral(&client->port_reservation, netns_addr, netns_addr_len, parsed_parameters.ip_protocol,
7212 			    &parsed_parameters.local_addr.sin.sin_port, netns_flags, &flow_info);
7213 			if (error) {
7214 				NECPLOG(LOG_ERR, "necp_client_add netns_reserve_ephemeral error (%d)", error);
7215 				goto done;
7216 			}
7217 
7218 			// Update the parameter TLVs with the assigned port
7219 			necp_client_update_local_port_parameters(client->parameters, (u_int32_t)client->parameters_length, parsed_parameters.local_addr.sin.sin_port);
7220 		} else {
7221 			error = netns_reserve(&client->port_reservation, netns_addr, netns_addr_len, parsed_parameters.ip_protocol,
7222 			    parsed_parameters.local_addr.sin.sin_port, netns_flags, &flow_info);
7223 			if (error) {
7224 				NECPLOG(LOG_ERR, "necp_client_add netns_reserve error (%d)", error);
7225 				goto done;
7226 			}
7227 		}
7228 	}
7229 
7230 	struct necp_client *parent = NULL;
7231 	uuid_t parent_client_id;
7232 	uuid_clear(parent_client_id);
7233 	struct necp_client_nexus_parameters parent_parameters = {};
7234 	uint16_t num_flow_regs = 0;
7235 	if (parsed_parameters.valid_fields & NECP_PARSED_PARAMETERS_FIELD_PARENT_UUID) {
7236 		// The parent "should" be found on fd_data without having to search across the whole necp_fd_list
7237 		// It would be nice to do this a little further down where there's another instance of NECP_FD_LOCK
7238 		// but the logic here depends on the parse paramters
7239 		NECP_FD_LOCK(fd_data);
7240 		parent = necp_client_fd_find_client_unlocked(fd_data, parsed_parameters.parent_uuid);
7241 		if (parent != NULL) {
7242 			necp_client_inherit_from_parent(client, parent);
7243 			necp_client_copy_parameters_locked(client, &parent_parameters);
7244 			uuid_copy(parent_client_id, parsed_parameters.parent_uuid);
7245 			struct necp_client_flow_registration *flow_registration = NULL;
7246 			RB_FOREACH(flow_registration, _necp_client_flow_tree, &parent->flow_registrations) {
7247 				num_flow_regs++;
7248 			}
7249 		}
7250 		NECP_FD_UNLOCK(fd_data);
7251 		if (parent == NULL) {
7252 			NECPLOG0(LOG_ERR, "necp_client_add, no necp_client_inherit_from_parent as can't find parent on fd_data");
7253 		}
7254 	}
7255 	if (parse_error == 0 && parent != NULL && parsed_parameters.valid_fields & NECP_PARSED_PARAMETERS_FIELD_FLOW_DEMUX_PATTERN) {
7256 		do {
7257 			if (parsed_parameters.demux_patterns[0].len == 0) {
7258 				NECPLOG0(LOG_INFO, "necp_client_add, child does not have a demux pattern");
7259 				break;
7260 			}
7261 
7262 			if (uuid_is_null(parent_client_id)) {
7263 				NECPLOG0(LOG_INFO, "necp_client_add, parent ID is null");
7264 				break;
7265 			}
7266 
7267 			if (num_flow_regs > 1) {
7268 				NECPLOG0(LOG_INFO, "necp_client_add, multiple parent flows not supported");
7269 				break;
7270 			}
7271 			if (parsed_parameters.ip_protocol != IPPROTO_UDP) {
7272 				NECPLOG(LOG_INFO, "necp_client_add, flow demux pattern not supported for %d protocol",
7273 				    parsed_parameters.ip_protocol);
7274 				break;
7275 			}
7276 			if (parsed_parameters.ip_protocol != parent_parameters.ip_protocol) {
7277 				NECPLOG0(LOG_INFO, "necp_client_add, parent/child ip protocol mismatch");
7278 				break;
7279 			}
7280 			if (parsed_parameters.local_addr.sa.sa_family != AF_INET && parsed_parameters.local_addr.sa.sa_family != AF_INET6) {
7281 				NECPLOG(LOG_INFO, "necp_client_add, flow demux pattern not supported for %d family",
7282 				    parsed_parameters.local_addr.sa.sa_family);
7283 				break;
7284 			}
7285 			if (parsed_parameters.local_addr.sa.sa_family != parsed_parameters.remote_addr.sa.sa_family) {
7286 				NECPLOG0(LOG_INFO, "necp_client_add, local/remote address family mismatch");
7287 				break;
7288 			}
7289 			if (parsed_parameters.local_addr.sa.sa_family != parent_parameters.local_addr.sa.sa_family) {
7290 				NECPLOG0(LOG_INFO, "necp_client_add, parent/child address family mismatch");
7291 				break;
7292 			}
7293 			if (memcmp(&parsed_parameters.local_addr.sa, &parent_parameters.local_addr.sa, parsed_parameters.local_addr.sa.sa_len)) {
7294 				NECPLOG0(LOG_INFO, "necp_client_add, parent/child local address mismatch");
7295 				break;
7296 			}
7297 			if (memcmp(&parsed_parameters.remote_addr.sa, &parent_parameters.remote_addr.sa, parsed_parameters.remote_addr.sa.sa_len)) {
7298 				NECPLOG0(LOG_INFO, "necp_client_add, parent/child remote address mismatch");
7299 				break;
7300 			}
7301 			if (parsed_parameters.local_addr.sin.sin_port != parent_parameters.local_addr.sin.sin_port) {
7302 				NECPLOG0(LOG_INFO, "necp_client_add, parent/child local port mismatch");
7303 				break;
7304 			}
7305 			if (parsed_parameters.remote_addr.sin.sin_port != parent_parameters.remote_addr.sin.sin_port) {
7306 				NECPLOG0(LOG_INFO, "necp_client_add, parent/child remote port mismatch");
7307 				break;
7308 			}
7309 			client->validated_parent = 1;
7310 			uuid_copy(client->parent_client_id, parent_client_id);
7311 		} while (false);
7312 	}
7313 
7314 #endif /* !SKYWALK */
7315 
7316 	necp_client_update_observer_add(client);
7317 
7318 	NECP_FD_LOCK(fd_data);
7319 	RB_INSERT(_necp_client_tree, &fd_data->clients, client);
7320 	OSIncrementAtomic(&necp_client_count);
7321 	NECP_CLIENT_TREE_LOCK_EXCLUSIVE();
7322 	RB_INSERT(_necp_client_global_tree, &necp_client_global_tree, client);
7323 	NECP_CLIENT_TREE_UNLOCK();
7324 
7325 	// Prime the client result
7326 	NECP_CLIENT_LOCK(client);
7327 	(void)necp_update_client_result(current_proc(), fd_data, client, NULL);
7328 	necp_client_retain_locked(client);
7329 	NECP_CLIENT_UNLOCK(client);
7330 	NECP_FD_UNLOCK(fd_data);
7331 	// Now everything is set, it's safe to plumb this in to NetworkStatistics
7332 	uint32_t ntstat_properties = 0;
7333 	necp_find_conn_netstat_data(client, &ntstat_properties, NULL, NULL, NULL, NULL, NULL);
7334 
7335 	client->nstat_context = nstat_provider_stats_open((nstat_provider_context)client,
7336 	    NSTAT_PROVIDER_CONN_USERLAND, (u_int64_t)ntstat_properties, necp_request_conn_netstats, necp_find_conn_extension_info);
7337 	necp_client_release(client);
7338 done:
7339 	if (error != 0 && client != NULL) {
7340 		necp_client_free(client);
7341 		client = NULL;
7342 	}
7343 	*retval = error;
7344 
7345 	return error;
7346 }
7347 
7348 static NECP_CLIENT_ACTION_FUNCTION int
necp_client_claim(struct proc * p,struct necp_fd_data * fd_data,struct necp_client_action_args * uap,int * retval)7349 necp_client_claim(struct proc *p, struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
7350 {
7351 	int error = 0;
7352 	uuid_t client_id = {};
7353 	struct necp_client *client = NULL;
7354 
7355 	if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t)) {
7356 		error = EINVAL;
7357 		goto done;
7358 	}
7359 
7360 	error = copyin(uap->client_id, client_id, sizeof(uuid_t));
7361 	if (error) {
7362 		NECPLOG(LOG_ERR, "necp_client_claim copyin client_id error (%d)", error);
7363 		goto done;
7364 	}
7365 
7366 	if (necp_client_id_is_flow(client_id)) {
7367 		NECPLOG0(LOG_ERR, "necp_client_claim cannot claim from flow UUID");
7368 		error = EINVAL;
7369 		goto done;
7370 	}
7371 
7372 	u_int64_t upid = proc_uniqueid(p);
7373 
7374 	NECP_FD_LIST_LOCK_SHARED();
7375 
7376 	struct necp_fd_data *find_fd = NULL;
7377 	LIST_FOREACH(find_fd, &necp_fd_list, chain) {
7378 		NECP_FD_LOCK(find_fd);
7379 		struct necp_client *find_client = necp_client_fd_find_client_and_lock(find_fd, client_id);
7380 		if (find_client != NULL) {
7381 			if (find_client->delegated_upid == upid &&
7382 			    RB_EMPTY(&find_client->flow_registrations)) {
7383 				// Matched the client to claim; remove from the old fd
7384 				client = find_client;
7385 				RB_REMOVE(_necp_client_tree, &find_fd->clients, client);
7386 				necp_client_retain_locked(client);
7387 			}
7388 			NECP_CLIENT_UNLOCK(find_client);
7389 		}
7390 		NECP_FD_UNLOCK(find_fd);
7391 
7392 		if (client != NULL) {
7393 			break;
7394 		}
7395 	}
7396 
7397 	NECP_FD_LIST_UNLOCK();
7398 
7399 	if (client == NULL) {
7400 		error = ENOENT;
7401 		goto done;
7402 	}
7403 
7404 	client->proc_pid = fd_data->proc_pid; // Transfer client to claiming pid
7405 	client->agent_handle = (void *)fd_data;
7406 	client->platform_binary = ((csproc_get_platform_binary(p) == 0) ? 0 : 1);
7407 
7408 	NECP_CLIENT_LOG(client, "Claiming client");
7409 
7410 	// Add matched client to our fd and re-run result
7411 	NECP_FD_LOCK(fd_data);
7412 	RB_INSERT(_necp_client_tree, &fd_data->clients, client);
7413 	NECP_CLIENT_LOCK(client);
7414 	(void)necp_update_client_result(current_proc(), fd_data, client, NULL);
7415 	NECP_CLIENT_UNLOCK(client);
7416 	NECP_FD_UNLOCK(fd_data);
7417 
7418 	necp_client_release(client);
7419 
7420 done:
7421 	*retval = error;
7422 
7423 	return error;
7424 }
7425 
7426 static NECP_CLIENT_ACTION_FUNCTION int
necp_client_remove(struct necp_fd_data * fd_data,struct necp_client_action_args * uap,int * retval)7427 necp_client_remove(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
7428 {
7429 	int error = 0;
7430 	uuid_t client_id = {};
7431 	struct ifnet_stats_per_flow flow_ifnet_stats = {};
7432 	const size_t buffer_size = uap->buffer_size;
7433 
7434 	if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t)) {
7435 		error = EINVAL;
7436 		goto done;
7437 	}
7438 
7439 	error = copyin(uap->client_id, client_id, sizeof(uuid_t));
7440 	if (error) {
7441 		NECPLOG(LOG_ERR, "necp_client_remove copyin client_id error (%d)", error);
7442 		goto done;
7443 	}
7444 
7445 	if (uap->buffer != 0 && buffer_size == sizeof(flow_ifnet_stats)) {
7446 		error = copyin(uap->buffer, &flow_ifnet_stats, buffer_size);
7447 		if (error) {
7448 			NECPLOG(LOG_ERR, "necp_client_remove flow_ifnet_stats copyin error (%d)", error);
7449 			// Not fatal; make sure to zero-out stats in case of partial copy
7450 			memset(&flow_ifnet_stats, 0, sizeof(flow_ifnet_stats));
7451 			error = 0;
7452 		}
7453 	} else if (uap->buffer != 0) {
7454 		NECPLOG(LOG_ERR, "necp_client_remove unexpected parameters length (%zu)", buffer_size);
7455 	}
7456 
7457 	NECP_FD_LOCK(fd_data);
7458 
7459 	pid_t pid = fd_data->proc_pid;
7460 	struct necp_client *client = necp_client_fd_find_client_unlocked(fd_data, client_id);
7461 
7462 	NECP_CLIENT_LOG(client, "Removing client");
7463 
7464 	if (client != NULL) {
7465 		// Remove any flow registrations that match
7466 		struct necp_client_flow_registration *flow_registration = NULL;
7467 		struct necp_client_flow_registration *temp_flow_registration = NULL;
7468 		RB_FOREACH_SAFE(flow_registration, _necp_fd_flow_tree, &fd_data->flows, temp_flow_registration) {
7469 			if (flow_registration->client == client) {
7470 #if SKYWALK
7471 				necp_destroy_flow_stats(fd_data, flow_registration, NULL, TRUE);
7472 #endif /* SKYWALK */
7473 				NECP_FLOW_TREE_LOCK_EXCLUSIVE();
7474 				RB_REMOVE(_necp_client_flow_global_tree, &necp_client_flow_global_tree, flow_registration);
7475 				NECP_FLOW_TREE_UNLOCK();
7476 				RB_REMOVE(_necp_fd_flow_tree, &fd_data->flows, flow_registration);
7477 			}
7478 		}
7479 #if SKYWALK
7480 		if (client->nstat_context != NULL) {
7481 			// Main path, we expect stats to be in existance at this point
7482 			nstat_provider_stats_close(client->nstat_context);
7483 			client->nstat_context = NULL;
7484 		} else {
7485 			NECPLOG0(LOG_ERR, "necp_client_remove ntstat shutdown finds nstat_context NULL");
7486 		}
7487 #endif /* SKYWALK */
7488 		// Remove client from lists
7489 		NECP_CLIENT_TREE_LOCK_EXCLUSIVE();
7490 		RB_REMOVE(_necp_client_global_tree, &necp_client_global_tree, client);
7491 		NECP_CLIENT_TREE_UNLOCK();
7492 		RB_REMOVE(_necp_client_tree, &fd_data->clients, client);
7493 	}
7494 
7495 #if SKYWALK
7496 	// If the currently-active arena is idle (has no more flows referring to it), or if there are defunct
7497 	// arenas lingering in the list, schedule a threadcall to do the clean up.  The idle check is done
7498 	// by checking if the reference count is 3: one held by this client (will be released below when we
7499 	// destroy it) when it's non-NULL; the rest held by stats_arena_{active,list}.
7500 	if ((fd_data->stats_arena_active != NULL && fd_data->stats_arena_active->nai_use_count == 3) ||
7501 	    (fd_data->stats_arena_active == NULL && !LIST_EMPTY(&fd_data->stats_arena_list))) {
7502 		uint64_t deadline = 0;
7503 		uint64_t leeway = 0;
7504 		clock_interval_to_deadline(necp_close_arenas_timeout_microseconds, NSEC_PER_USEC, &deadline);
7505 		clock_interval_to_absolutetime_interval(necp_close_arenas_timeout_leeway_microseconds, NSEC_PER_USEC, &leeway);
7506 
7507 		thread_call_enter_delayed_with_leeway(necp_close_empty_arenas_tcall, NULL,
7508 		    deadline, leeway, THREAD_CALL_DELAY_LEEWAY);
7509 	}
7510 #endif /* SKYWALK */
7511 
7512 	NECP_FD_UNLOCK(fd_data);
7513 
7514 	if (client != NULL) {
7515 		ASSERT(error == 0);
7516 		necp_destroy_client(client, pid, true);
7517 	} else {
7518 		error = ENOENT;
7519 		NECPLOG(LOG_ERR, "necp_client_remove invalid client_id (%d)", error);
7520 	}
7521 done:
7522 	*retval = error;
7523 
7524 	return error;
7525 }
7526 
7527 static struct necp_client_flow_registration *
necp_client_fd_find_flow(struct necp_fd_data * client_fd,uuid_t flow_id)7528 necp_client_fd_find_flow(struct necp_fd_data *client_fd, uuid_t flow_id)
7529 {
7530 	NECP_FD_ASSERT_LOCKED(client_fd);
7531 	struct necp_client_flow_registration *flow = NULL;
7532 
7533 	if (necp_client_id_is_flow(flow_id)) {
7534 		struct necp_client_flow_registration find;
7535 		uuid_copy(find.registration_id, flow_id);
7536 		flow = RB_FIND(_necp_fd_flow_tree, &client_fd->flows, &find);
7537 	}
7538 
7539 	return flow;
7540 }
7541 
7542 static NECP_CLIENT_ACTION_FUNCTION int
necp_client_remove_flow(struct necp_fd_data * fd_data,struct necp_client_action_args * uap,int * retval)7543 necp_client_remove_flow(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
7544 {
7545 	int error = 0;
7546 	uuid_t flow_id = {};
7547 	struct ifnet_stats_per_flow flow_ifnet_stats = {};
7548 	const size_t buffer_size = uap->buffer_size;
7549 
7550 	if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t)) {
7551 		error = EINVAL;
7552 		NECPLOG(LOG_ERR, "necp_client_remove_flow invalid client_id (length %zu)", (size_t)uap->client_id_len);
7553 		goto done;
7554 	}
7555 
7556 	error = copyin(uap->client_id, flow_id, sizeof(uuid_t));
7557 	if (error) {
7558 		NECPLOG(LOG_ERR, "necp_client_remove_flow copyin client_id error (%d)", error);
7559 		goto done;
7560 	}
7561 
7562 	if (uap->buffer != 0 && buffer_size == sizeof(flow_ifnet_stats)) {
7563 		error = copyin(uap->buffer, &flow_ifnet_stats, buffer_size);
7564 		if (error) {
7565 			NECPLOG(LOG_ERR, "necp_client_remove flow_ifnet_stats copyin error (%d)", error);
7566 			// Not fatal
7567 		}
7568 	} else if (uap->buffer != 0) {
7569 		NECPLOG(LOG_ERR, "necp_client_remove unexpected parameters length (%zu)", buffer_size);
7570 	}
7571 
7572 	NECP_FD_LOCK(fd_data);
7573 	struct necp_client *client = NULL;
7574 	struct necp_client_flow_registration *flow_registration = necp_client_fd_find_flow(fd_data, flow_id);
7575 	if (flow_registration != NULL) {
7576 #if SKYWALK
7577 		// Cleanup stats per flow
7578 		necp_destroy_flow_stats(fd_data, flow_registration, &flow_ifnet_stats, TRUE);
7579 #endif /* SKYWALK */
7580 		NECP_FLOW_TREE_LOCK_EXCLUSIVE();
7581 		RB_REMOVE(_necp_client_flow_global_tree, &necp_client_flow_global_tree, flow_registration);
7582 		NECP_FLOW_TREE_UNLOCK();
7583 		RB_REMOVE(_necp_fd_flow_tree, &fd_data->flows, flow_registration);
7584 
7585 		client = flow_registration->client;
7586 		if (client != NULL) {
7587 			necp_client_retain(client);
7588 		}
7589 	}
7590 	NECP_FD_UNLOCK(fd_data);
7591 
7592 	NECP_CLIENT_FLOW_LOG(client, flow_registration, "removing flow");
7593 
7594 	if (flow_registration != NULL && client != NULL) {
7595 		NECP_CLIENT_LOCK(client);
7596 		if (flow_registration->client == client) {
7597 			necp_destroy_client_flow_registration(client, flow_registration, fd_data->proc_pid, false);
7598 		}
7599 		necp_client_release_locked(client);
7600 		NECP_CLIENT_UNLOCK(client);
7601 	}
7602 
7603 done:
7604 	*retval = error;
7605 	if (error != 0) {
7606 		NECPLOG(LOG_ERR, "Remove flow error (%d)", error);
7607 	}
7608 
7609 	return error;
7610 }
7611 
7612 // Don't inline the function since it includes necp_client_parsed_parameters on the stack
7613 static __attribute__((noinline)) int
necp_client_check_tcp_heuristics(struct necp_client * client,struct necp_client_flow * flow,u_int32_t * flags,u_int8_t * tfo_cookie,u_int8_t * tfo_cookie_len)7614 necp_client_check_tcp_heuristics(struct necp_client *client, struct necp_client_flow *flow, u_int32_t *flags, u_int8_t *tfo_cookie, u_int8_t *tfo_cookie_len)
7615 {
7616 	struct necp_client_parsed_parameters parsed_parameters;
7617 	int error = 0;
7618 
7619 	error = necp_client_parse_parameters(client, client->parameters,
7620 	    (u_int32_t)client->parameters_length,
7621 	    &parsed_parameters);
7622 	if (error) {
7623 		NECPLOG(LOG_ERR, "necp_client_parse_parameters error (%d)", error);
7624 		return error;
7625 	}
7626 
7627 	if ((flow->remote_addr.sa.sa_family != AF_INET &&
7628 	    flow->remote_addr.sa.sa_family != AF_INET6) ||
7629 	    (flow->local_addr.sa.sa_family != AF_INET &&
7630 	    flow->local_addr.sa.sa_family != AF_INET6)) {
7631 		return EINVAL;
7632 	}
7633 
7634 	NECP_CLIENT_ROUTE_LOCK(client);
7635 
7636 	if (client->current_route == NULL) {
7637 		error = ENOENT;
7638 		goto do_unlock;
7639 	}
7640 
7641 	bool check_ecn = false;
7642 	do {
7643 		if ((parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_ECN_ENABLE) ==
7644 		    NECP_CLIENT_PARAMETER_FLAG_ECN_ENABLE) {
7645 			check_ecn = true;
7646 			break;
7647 		}
7648 
7649 		if ((parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_ECN_DISABLE) ==
7650 		    NECP_CLIENT_PARAMETER_FLAG_ECN_DISABLE) {
7651 			break;
7652 		}
7653 
7654 		if (client->current_route != NULL) {
7655 			if (client->current_route->rt_ifp->if_eflags & IFEF_ECN_ENABLE) {
7656 				check_ecn = true;
7657 				break;
7658 			}
7659 			if (client->current_route->rt_ifp->if_eflags & IFEF_ECN_DISABLE) {
7660 				break;
7661 			}
7662 		}
7663 
7664 		bool inbound = ((parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) == 0);
7665 		if ((inbound && tcp_ecn_inbound == 1) ||
7666 		    (!inbound && tcp_ecn_outbound == 1)) {
7667 			check_ecn = true;
7668 		}
7669 	} while (false);
7670 
7671 	if (check_ecn) {
7672 		if (tcp_heuristic_do_ecn_with_address(client->current_route->rt_ifp,
7673 		    (union sockaddr_in_4_6 *)&flow->local_addr)) {
7674 			*flags |= NECP_CLIENT_RESULT_FLAG_ECN_ENABLED;
7675 		}
7676 	}
7677 
7678 	if ((parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_TFO_ENABLE) ==
7679 	    NECP_CLIENT_PARAMETER_FLAG_TFO_ENABLE) {
7680 		if (!tcp_heuristic_do_tfo_with_address(client->current_route->rt_ifp,
7681 		    (union sockaddr_in_4_6 *)&flow->local_addr,
7682 		    (union sockaddr_in_4_6 *)&flow->remote_addr,
7683 		    tfo_cookie, tfo_cookie_len)) {
7684 			*flags |= NECP_CLIENT_RESULT_FLAG_FAST_OPEN_BLOCKED;
7685 			*tfo_cookie_len = 0;
7686 		}
7687 	} else {
7688 		*flags |= NECP_CLIENT_RESULT_FLAG_FAST_OPEN_BLOCKED;
7689 		*tfo_cookie_len = 0;
7690 	}
7691 do_unlock:
7692 	NECP_CLIENT_ROUTE_UNLOCK(client);
7693 
7694 	return error;
7695 }
7696 
7697 static size_t
necp_client_calculate_flow_tlv_size(struct necp_client_flow_registration * flow_registration)7698 necp_client_calculate_flow_tlv_size(struct necp_client_flow_registration *flow_registration)
7699 {
7700 	size_t assigned_results_size = 0;
7701 	struct necp_client_flow *flow = NULL;
7702 	LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
7703 		if (flow->assigned || !necp_client_endpoint_is_unspecified((struct necp_client_endpoint *)&flow->remote_addr)) {
7704 			size_t header_length = 0;
7705 			if (flow->nexus) {
7706 				header_length = sizeof(struct necp_client_nexus_flow_header);
7707 			} else {
7708 				header_length = sizeof(struct necp_client_flow_header);
7709 			}
7710 			assigned_results_size += (header_length + flow->assigned_results_length);
7711 
7712 			if (flow->has_protoctl_event) {
7713 				assigned_results_size += sizeof(struct necp_client_flow_protoctl_event_header);
7714 			}
7715 		}
7716 	}
7717 	return assigned_results_size;
7718 }
7719 
7720 static int
necp_client_fillout_flow_tlvs(struct necp_client * client,bool client_is_observed,struct necp_client_flow_registration * flow_registration,struct necp_client_action_args * uap,size_t * assigned_results_cursor)7721 necp_client_fillout_flow_tlvs(struct necp_client *client,
7722     bool client_is_observed,
7723     struct necp_client_flow_registration *flow_registration,
7724     struct necp_client_action_args *uap,
7725     size_t *assigned_results_cursor)
7726 {
7727 	int error = 0;
7728 	struct necp_client_flow *flow = NULL;
7729 	LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
7730 		if (flow->assigned || !necp_client_endpoint_is_unspecified((struct necp_client_endpoint *)&flow->remote_addr)) {
7731 			// Write TLV headers
7732 			struct necp_client_nexus_flow_header header = {};
7733 			u_int32_t length = 0;
7734 			u_int32_t flags = 0;
7735 			u_int8_t tfo_cookie_len = 0;
7736 			u_int8_t type = 0;
7737 
7738 			type = NECP_CLIENT_RESULT_FLOW_ID;
7739 			length = sizeof(header.flow_header.flow_id);
7740 			memcpy(&header.flow_header.flow_id_tlv_header.type, &type, sizeof(type));
7741 			memcpy(&header.flow_header.flow_id_tlv_header.length, &length, sizeof(length));
7742 			uuid_copy(header.flow_header.flow_id, flow_registration->registration_id);
7743 
7744 			if (flow->nexus) {
7745 				if (flow->check_tcp_heuristics) {
7746 					u_int8_t tfo_cookie[NECP_TFO_COOKIE_LEN_MAX];
7747 					tfo_cookie_len = NECP_TFO_COOKIE_LEN_MAX;
7748 
7749 					if (necp_client_check_tcp_heuristics(client, flow, &flags,
7750 					    tfo_cookie, &tfo_cookie_len) != 0) {
7751 						tfo_cookie_len = 0;
7752 					} else {
7753 						flow->check_tcp_heuristics = FALSE;
7754 
7755 						if (tfo_cookie_len != 0) {
7756 							type = NECP_CLIENT_RESULT_TFO_COOKIE;
7757 							length = tfo_cookie_len;
7758 							memcpy(&header.tfo_cookie_tlv_header.type, &type, sizeof(type));
7759 							memcpy(&header.tfo_cookie_tlv_header.length, &length, sizeof(length));
7760 							memcpy(&header.tfo_cookie_value, tfo_cookie, tfo_cookie_len);
7761 						}
7762 					}
7763 				}
7764 			}
7765 
7766 			size_t header_length = 0;
7767 			if (flow->nexus) {
7768 				if (tfo_cookie_len != 0) {
7769 					header_length = sizeof(struct necp_client_nexus_flow_header) - (NECP_TFO_COOKIE_LEN_MAX - tfo_cookie_len);
7770 				} else {
7771 					header_length = sizeof(struct necp_client_nexus_flow_header) - sizeof(struct necp_tlv_header) - NECP_TFO_COOKIE_LEN_MAX;
7772 				}
7773 			} else {
7774 				header_length = sizeof(struct necp_client_flow_header);
7775 			}
7776 
7777 			type = NECP_CLIENT_RESULT_FLAGS;
7778 			length = sizeof(header.flow_header.flags_value);
7779 			memcpy(&header.flow_header.flags_tlv_header.type, &type, sizeof(type));
7780 			memcpy(&header.flow_header.flags_tlv_header.length, &length, sizeof(length));
7781 			if (flow->assigned) {
7782 				flags |= NECP_CLIENT_RESULT_FLAG_FLOW_ASSIGNED;
7783 			}
7784 			if (flow->viable) {
7785 				flags |= NECP_CLIENT_RESULT_FLAG_FLOW_VIABLE;
7786 			}
7787 			if (flow_registration->defunct) {
7788 				flags |= NECP_CLIENT_RESULT_FLAG_DEFUNCT;
7789 			}
7790 			flags |= flow->necp_flow_flags;
7791 			memcpy(&header.flow_header.flags_value, &flags, sizeof(flags));
7792 
7793 			type = NECP_CLIENT_RESULT_INTERFACE;
7794 			length = sizeof(header.flow_header.interface_value);
7795 			memcpy(&header.flow_header.interface_tlv_header.type, &type, sizeof(type));
7796 			memcpy(&header.flow_header.interface_tlv_header.length, &length, sizeof(length));
7797 
7798 			struct necp_client_result_interface interface_struct;
7799 			interface_struct.generation = 0;
7800 			interface_struct.index = flow->interface_index;
7801 
7802 			memcpy(&header.flow_header.interface_value, &interface_struct, sizeof(interface_struct));
7803 			if (flow->nexus) {
7804 				type = NECP_CLIENT_RESULT_NETAGENT;
7805 				length = sizeof(header.agent_value);
7806 				memcpy(&header.agent_tlv_header.type, &type, sizeof(type));
7807 				memcpy(&header.agent_tlv_header.length, &length, sizeof(length));
7808 
7809 				struct necp_client_result_netagent agent_struct;
7810 				uuid_copy(agent_struct.netagent_uuid, flow->u.nexus_agent);
7811 				agent_struct.generation = netagent_get_generation(agent_struct.netagent_uuid);
7812 
7813 				memcpy(&header.agent_value, &agent_struct, sizeof(agent_struct));
7814 			}
7815 
7816 			// Don't include outer TLV header in length field
7817 			type = NECP_CLIENT_RESULT_FLOW;
7818 			length = (header_length - sizeof(struct necp_tlv_header) + flow->assigned_results_length);
7819 			if (flow->has_protoctl_event) {
7820 				length += sizeof(struct necp_client_flow_protoctl_event_header);
7821 			}
7822 			memcpy(&header.flow_header.outer_header.type, &type, sizeof(type));
7823 			memcpy(&header.flow_header.outer_header.length, &length, sizeof(length));
7824 
7825 			error = copyout(&header, uap->buffer + client->result_length + *assigned_results_cursor, header_length);
7826 			if (error) {
7827 				NECPLOG(LOG_ERR, "necp_client_copy assigned results tlv_header copyout error (%d)", error);
7828 				return error;
7829 			}
7830 			*assigned_results_cursor += header_length;
7831 
7832 			if (flow->assigned_results && flow->assigned_results_length) {
7833 				// Write inner TLVs
7834 				error = copyout(flow->assigned_results, uap->buffer + client->result_length + *assigned_results_cursor,
7835 				    flow->assigned_results_length);
7836 				if (error) {
7837 					NECPLOG(LOG_ERR, "necp_client_copy assigned results copyout error (%d)", error);
7838 					return error;
7839 				}
7840 			}
7841 			*assigned_results_cursor += flow->assigned_results_length;
7842 
7843 			/* Read the protocol event and reset it */
7844 			if (flow->has_protoctl_event) {
7845 				struct necp_client_flow_protoctl_event_header protoctl_event_header = {};
7846 
7847 				type = NECP_CLIENT_RESULT_PROTO_CTL_EVENT;
7848 				length = sizeof(protoctl_event_header.protoctl_event);
7849 
7850 				memcpy(&protoctl_event_header.protoctl_tlv_header.type, &type, sizeof(type));
7851 				memcpy(&protoctl_event_header.protoctl_tlv_header.length, &length, sizeof(length));
7852 				memcpy(&protoctl_event_header.protoctl_event, &flow->protoctl_event,
7853 				    sizeof(flow->protoctl_event));
7854 
7855 				error = copyout(&protoctl_event_header, uap->buffer + client->result_length + *assigned_results_cursor,
7856 				    sizeof(protoctl_event_header));
7857 
7858 				if (error) {
7859 					NECPLOG(LOG_ERR, "necp_client_copy protocol control event results"
7860 					    " tlv_header copyout error (%d)", error);
7861 					return error;
7862 				}
7863 				*assigned_results_cursor += sizeof(protoctl_event_header);
7864 				flow->has_protoctl_event = FALSE;
7865 				flow->protoctl_event.protoctl_event_code = 0;
7866 				flow->protoctl_event.protoctl_event_val = 0;
7867 				flow->protoctl_event.protoctl_event_tcp_seq_num = 0;
7868 			}
7869 		}
7870 	}
7871 	if (!client_is_observed) {
7872 		flow_registration->flow_result_read = TRUE;
7873 	}
7874 	return 0;
7875 }
7876 
7877 static int
necp_client_copy_internal(struct necp_client * client,uuid_t client_id,bool client_is_observed,struct necp_client_action_args * uap,int * retval)7878 necp_client_copy_internal(struct necp_client *client, uuid_t client_id, bool client_is_observed, struct necp_client_action_args *uap, int *retval)
7879 {
7880 	NECP_CLIENT_ASSERT_LOCKED(client);
7881 	int error = 0;
7882 	// Copy results out
7883 	if (uap->action == NECP_CLIENT_ACTION_COPY_PARAMETERS) {
7884 		if (uap->buffer_size < client->parameters_length) {
7885 			return EINVAL;
7886 		}
7887 		error = copyout(client->parameters, uap->buffer, client->parameters_length);
7888 		if (error) {
7889 			NECPLOG(LOG_ERR, "necp_client_copy parameters copyout error (%d)", error);
7890 			return error;
7891 		}
7892 		*retval = client->parameters_length;
7893 	} else if (uap->action == NECP_CLIENT_ACTION_COPY_UPDATED_RESULT &&
7894 	    client->result_read && client->group_members_read && !necp_client_has_unread_flows(client)) {
7895 		// Copy updates only, but nothing to read
7896 		// Just return 0 for bytes read
7897 		*retval = 0;
7898 	} else if (uap->action == NECP_CLIENT_ACTION_COPY_RESULT ||
7899 	    uap->action == NECP_CLIENT_ACTION_COPY_UPDATED_RESULT) {
7900 		size_t assigned_results_size = client->assigned_group_members_length;
7901 
7902 		bool some_flow_is_defunct = false;
7903 		struct necp_client_flow_registration *single_flow_registration = NULL;
7904 		if (necp_client_id_is_flow(client_id)) {
7905 			single_flow_registration = necp_client_find_flow(client, client_id);
7906 			if (single_flow_registration != NULL) {
7907 				assigned_results_size += necp_client_calculate_flow_tlv_size(single_flow_registration);
7908 			}
7909 		} else {
7910 			// This request is for the client, so copy everything
7911 			struct necp_client_flow_registration *flow_registration = NULL;
7912 			RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
7913 				if (flow_registration->defunct) {
7914 					some_flow_is_defunct = true;
7915 				}
7916 				assigned_results_size += necp_client_calculate_flow_tlv_size(flow_registration);
7917 			}
7918 		}
7919 		if (uap->buffer_size < (client->result_length + assigned_results_size)) {
7920 			return EINVAL;
7921 		}
7922 
7923 		u_int32_t original_flags = 0;
7924 		bool flags_updated = false;
7925 		if (some_flow_is_defunct && client->legacy_client_is_flow) {
7926 			// If our client expects the defunct flag in the client, add it now
7927 			u_int32_t client_flags = 0;
7928 			u_int32_t value_size = 0;
7929 			u_int8_t *flags_pointer = necp_buffer_get_tlv_value(client->result, 0, &value_size);
7930 			if (flags_pointer != NULL && value_size == sizeof(client_flags)) {
7931 				memcpy(&client_flags, flags_pointer, value_size);
7932 				original_flags = client_flags;
7933 				client_flags |= NECP_CLIENT_RESULT_FLAG_DEFUNCT;
7934 				(void)necp_buffer_write_tlv_if_different(client->result, NECP_CLIENT_RESULT_FLAGS,
7935 				    sizeof(client_flags), &client_flags, &flags_updated,
7936 				    client->result, sizeof(client->result));
7937 			}
7938 		}
7939 
7940 		error = copyout(client->result, uap->buffer, client->result_length);
7941 
7942 		if (flags_updated) {
7943 			// Revert stored flags
7944 			(void)necp_buffer_write_tlv_if_different(client->result, NECP_CLIENT_RESULT_FLAGS,
7945 			    sizeof(original_flags), &original_flags, &flags_updated,
7946 			    client->result, sizeof(client->result));
7947 		}
7948 
7949 		if (error != 0) {
7950 			NECPLOG(LOG_ERR, "necp_client_copy result copyout error (%d)", error);
7951 			return error;
7952 		}
7953 
7954 		if (client->assigned_group_members != NULL && client->assigned_group_members_length > 0) {
7955 			error = copyout(client->assigned_group_members, uap->buffer + client->result_length, client->assigned_group_members_length);
7956 			if (error != 0) {
7957 				NECPLOG(LOG_ERR, "necp_client_copy group members copyout error (%d)", error);
7958 				return error;
7959 			}
7960 		}
7961 
7962 		size_t assigned_results_cursor = client->assigned_group_members_length; // Start with an offset based on the group members
7963 		if (necp_client_id_is_flow(client_id)) {
7964 			if (single_flow_registration != NULL) {
7965 				error = necp_client_fillout_flow_tlvs(client, client_is_observed, single_flow_registration, uap, &assigned_results_cursor);
7966 				if (error != 0) {
7967 					return error;
7968 				}
7969 			}
7970 		} else {
7971 			// This request is for the client, so copy everything
7972 			struct necp_client_flow_registration *flow_registration = NULL;
7973 			RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
7974 				error = necp_client_fillout_flow_tlvs(client, client_is_observed, flow_registration, uap, &assigned_results_cursor);
7975 				if (error != 0) {
7976 					return error;
7977 				}
7978 			}
7979 		}
7980 
7981 		*retval = client->result_length + assigned_results_cursor;
7982 
7983 		if (!client_is_observed) {
7984 			client->result_read = TRUE;
7985 			client->group_members_read = TRUE;
7986 		}
7987 	}
7988 
7989 	return 0;
7990 }
7991 
7992 static NECP_CLIENT_ACTION_FUNCTION int
necp_client_copy(struct necp_fd_data * fd_data,struct necp_client_action_args * uap,int * retval)7993 necp_client_copy(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
7994 {
7995 	int error = 0;
7996 	struct necp_client *client = NULL;
7997 	uuid_t client_id;
7998 	uuid_clear(client_id);
7999 
8000 	*retval = 0;
8001 
8002 	if (uap->buffer_size == 0 || uap->buffer == 0) {
8003 		return EINVAL;
8004 	}
8005 
8006 	if (uap->action != NECP_CLIENT_ACTION_COPY_PARAMETERS &&
8007 	    uap->action != NECP_CLIENT_ACTION_COPY_RESULT &&
8008 	    uap->action != NECP_CLIENT_ACTION_COPY_UPDATED_RESULT) {
8009 		return EINVAL;
8010 	}
8011 
8012 	if (uap->client_id) {
8013 		if (uap->client_id_len != sizeof(uuid_t)) {
8014 			NECPLOG(LOG_ERR, "Incorrect length (got %zu, expected %zu)", (size_t)uap->client_id_len, sizeof(uuid_t));
8015 			return ERANGE;
8016 		}
8017 
8018 		error = copyin(uap->client_id, client_id, sizeof(uuid_t));
8019 		if (error) {
8020 			NECPLOG(LOG_ERR, "necp_client_copy client_id copyin error (%d)", error);
8021 			return error;
8022 		}
8023 	}
8024 
8025 	const bool is_wildcard = (bool)uuid_is_null(client_id);
8026 
8027 	NECP_FD_LOCK(fd_data);
8028 
8029 	bool send_in_process_flow_divert_message = false;
8030 	if (is_wildcard) {
8031 		if (uap->action == NECP_CLIENT_ACTION_COPY_RESULT || uap->action == NECP_CLIENT_ACTION_COPY_UPDATED_RESULT) {
8032 			struct necp_client *find_client = NULL;
8033 			RB_FOREACH(find_client, _necp_client_tree, &fd_data->clients) {
8034 				NECP_CLIENT_LOCK(find_client);
8035 				if (!find_client->result_read || !find_client->group_members_read || necp_client_has_unread_flows(find_client)) {
8036 					client = find_client;
8037 					// Leave the client locked, and break
8038 					break;
8039 				}
8040 				NECP_CLIENT_UNLOCK(find_client);
8041 			}
8042 
8043 			if (client == NULL && fd_data->request_in_process_flow_divert) {
8044 				// No client found that needs update. Check for an event requesting in-process flow divert.
8045 				send_in_process_flow_divert_message = true;
8046 			}
8047 		}
8048 	} else {
8049 		client = necp_client_fd_find_client_and_lock(fd_data, client_id);
8050 	}
8051 
8052 	if (client != NULL) {
8053 		if (!send_in_process_flow_divert_message) {
8054 			// If client is set, it is locked
8055 			error = necp_client_copy_internal(client, client_id, FALSE, uap, retval);
8056 		}
8057 		NECP_CLIENT_UNLOCK(client);
8058 	}
8059 
8060 	if (send_in_process_flow_divert_message) {
8061 		fd_data->request_in_process_flow_divert = false;
8062 
8063 		struct necp_tlv_header request_tlv = {
8064 			.type = NECP_CLIENT_RESULT_REQUEST_IN_PROCESS_FLOW_DIVERT,
8065 			.length = 0,
8066 		};
8067 		if (uap->buffer_size < sizeof(request_tlv)) {
8068 			error = EINVAL;
8069 		} else {
8070 			error = copyout(&request_tlv, uap->buffer, sizeof(request_tlv));
8071 			if (error) {
8072 				NECPLOG(LOG_ERR, "necp_client_copy request flow divert TLV copyout error (%d)", error);
8073 			} else {
8074 				*retval = sizeof(request_tlv);
8075 			}
8076 		}
8077 	}
8078 
8079 	// Unlock our own fd before moving on or returning
8080 	NECP_FD_UNLOCK(fd_data);
8081 
8082 	if (client == NULL && !send_in_process_flow_divert_message) {
8083 		if (fd_data->flags & NECP_OPEN_FLAG_OBSERVER) {
8084 			// Observers are allowed to lookup clients on other fds
8085 
8086 			// Lock tree
8087 			NECP_CLIENT_TREE_LOCK_SHARED();
8088 
8089 			bool found_client = FALSE;
8090 
8091 			client = necp_find_client_and_lock(client_id);
8092 			if (client != NULL) {
8093 				// Matched, copy out data
8094 				found_client = TRUE;
8095 				error = necp_client_copy_internal(client, client_id, TRUE, uap, retval);
8096 				NECP_CLIENT_UNLOCK(client);
8097 			}
8098 
8099 			// Unlock tree
8100 			NECP_CLIENT_TREE_UNLOCK();
8101 
8102 			// No client found, fail
8103 			if (!found_client) {
8104 				return ENOENT;
8105 			}
8106 		} else {
8107 			// No client found, and not allowed to search other fds, fail
8108 			return ENOENT;
8109 		}
8110 	}
8111 
8112 	return error;
8113 }
8114 
8115 static NECP_CLIENT_ACTION_FUNCTION int
necp_client_copy_client_update(struct necp_fd_data * fd_data,struct necp_client_action_args * uap,int * retval)8116 necp_client_copy_client_update(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
8117 {
8118 	int error = 0;
8119 
8120 	*retval = 0;
8121 
8122 	if (!(fd_data->flags & NECP_OPEN_FLAG_PUSH_OBSERVER)) {
8123 		NECPLOG0(LOG_ERR, "NECP fd is not observer, cannot copy client update");
8124 		return EINVAL;
8125 	}
8126 
8127 	if (uap->client_id_len != sizeof(uuid_t) || uap->client_id == 0) {
8128 		NECPLOG0(LOG_ERR, "Client id invalid, cannot copy client update");
8129 		return EINVAL;
8130 	}
8131 
8132 	if (uap->buffer_size == 0 || uap->buffer == 0) {
8133 		NECPLOG0(LOG_ERR, "Buffer invalid, cannot copy client update");
8134 		return EINVAL;
8135 	}
8136 
8137 	NECP_FD_LOCK(fd_data);
8138 	struct necp_client_update *client_update = TAILQ_FIRST(&fd_data->update_list);
8139 	if (client_update != NULL) {
8140 		TAILQ_REMOVE(&fd_data->update_list, client_update, chain);
8141 		VERIFY(fd_data->update_count > 0);
8142 		fd_data->update_count--;
8143 	}
8144 	NECP_FD_UNLOCK(fd_data);
8145 
8146 	if (client_update != NULL) {
8147 		error = copyout(client_update->client_id, uap->client_id, sizeof(uuid_t));
8148 		if (error) {
8149 			NECPLOG(LOG_ERR, "Copy client update copyout client id error (%d)", error);
8150 		} else {
8151 			if (uap->buffer_size < client_update->update_length) {
8152 				NECPLOG(LOG_ERR, "Buffer size cannot hold update (%zu < %zu)", (size_t)uap->buffer_size, client_update->update_length);
8153 				error = EINVAL;
8154 			} else {
8155 				error = copyout(client_update->update, uap->buffer, client_update->update_length);
8156 				if (error) {
8157 					NECPLOG(LOG_ERR, "Copy client update copyout error (%d)", error);
8158 				} else {
8159 					*retval = client_update->update_length;
8160 				}
8161 			}
8162 		}
8163 
8164 		necp_client_update_free(client_update);
8165 		client_update = NULL;
8166 	} else {
8167 		error = ENOENT;
8168 	}
8169 
8170 	return error;
8171 }
8172 
8173 static int
necp_client_copy_parameters_locked(struct necp_client * client,struct necp_client_nexus_parameters * parameters)8174 necp_client_copy_parameters_locked(struct necp_client *client,
8175     struct necp_client_nexus_parameters *parameters)
8176 {
8177 	VERIFY(parameters != NULL);
8178 
8179 	struct necp_client_parsed_parameters parsed_parameters = {};
8180 	int error = necp_client_parse_parameters(client, client->parameters, (u_int32_t)client->parameters_length, &parsed_parameters);
8181 
8182 	parameters->pid = client->proc_pid;
8183 	if (parsed_parameters.valid_fields & NECP_PARSED_PARAMETERS_FIELD_EFFECTIVE_PID) {
8184 		parameters->epid = parsed_parameters.effective_pid;
8185 	} else {
8186 		parameters->epid = parameters->pid;
8187 	}
8188 #if SKYWALK
8189 	parameters->port_reservation = client->port_reservation;
8190 #endif /* !SKYWALK */
8191 	memcpy(&parameters->local_addr, &parsed_parameters.local_addr, sizeof(parameters->local_addr));
8192 	memcpy(&parameters->remote_addr, &parsed_parameters.remote_addr, sizeof(parameters->remote_addr));
8193 	parameters->ip_protocol = parsed_parameters.ip_protocol;
8194 	if (parsed_parameters.valid_fields & NECP_PARSED_PARAMETERS_FIELD_TRANSPORT_PROTOCOL) {
8195 		parameters->transport_protocol = parsed_parameters.transport_protocol;
8196 	} else {
8197 		parameters->transport_protocol = parsed_parameters.ip_protocol;
8198 	}
8199 	parameters->ethertype = parsed_parameters.ethertype;
8200 	parameters->traffic_class = parsed_parameters.traffic_class;
8201 	if (uuid_is_null(client->override_euuid)) {
8202 		uuid_copy(parameters->euuid, parsed_parameters.effective_uuid);
8203 	} else {
8204 		uuid_copy(parameters->euuid, client->override_euuid);
8205 	}
8206 	parameters->is_listener = (parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) ? 1 : 0;
8207 	parameters->is_interpose = (parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_INTERPOSE) ? 1 : 0;
8208 	parameters->is_custom_ether = (parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_CUSTOM_ETHER) ? 1 : 0;
8209 	parameters->policy_id = client->policy_id;
8210 	parameters->skip_policy_id = client->skip_policy_id;
8211 
8212 	// parse client result flag
8213 	u_int32_t client_result_flags = 0;
8214 	u_int32_t value_size = 0;
8215 	u_int8_t *flags_pointer = NULL;
8216 	flags_pointer = necp_buffer_get_tlv_value(client->result, 0, &value_size);
8217 	if (flags_pointer && value_size == sizeof(client_result_flags)) {
8218 		memcpy(&client_result_flags, flags_pointer, value_size);
8219 	}
8220 	parameters->allow_qos_marking = (client_result_flags & NECP_CLIENT_RESULT_FLAG_ALLOW_QOS_MARKING) ? 1 : 0;
8221 
8222 	if (parsed_parameters.valid_fields & NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR_PREFERENCE) {
8223 		if (parsed_parameters.local_address_preference == NECP_CLIENT_PARAMETER_LOCAL_ADDRESS_PREFERENCE_DEFAULT) {
8224 			parameters->override_address_selection = false;
8225 		} else if (parsed_parameters.local_address_preference == NECP_CLIENT_PARAMETER_LOCAL_ADDRESS_PREFERENCE_TEMPORARY) {
8226 			parameters->override_address_selection = true;
8227 			parameters->use_stable_address = false;
8228 		} else if (parsed_parameters.local_address_preference == NECP_CLIENT_PARAMETER_LOCAL_ADDRESS_PREFERENCE_STABLE) {
8229 			parameters->override_address_selection = true;
8230 			parameters->use_stable_address = true;
8231 		}
8232 	} else {
8233 		parameters->override_address_selection = false;
8234 	}
8235 
8236 	if ((parsed_parameters.valid_fields & NECP_PARSED_PARAMETERS_FIELD_FLAGS) &&
8237 	    (parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_NO_WAKE_FROM_SLEEP)) {
8238 		parameters->no_wake_from_sleep = true;
8239 	}
8240 
8241 	if ((parsed_parameters.valid_fields & NECP_PARSED_PARAMETERS_FIELD_FLAGS) &&
8242 	    (parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_REUSE_LOCAL)) {
8243 		parameters->reuse_port = true;
8244 	}
8245 
8246 #if SKYWALK
8247 	if (!parameters->is_listener) {
8248 		if (parsed_parameters.valid_fields & NECP_PARSED_PARAMETERS_FIELD_FLOW_DEMUX_PATTERN) {
8249 			if (parsed_parameters.demux_patterns[0].len == 0) {
8250 				parameters->is_demuxable_parent = 1;
8251 			} else {
8252 				if (client->validated_parent) {
8253 					ASSERT(!uuid_is_null(client->parent_client_id));
8254 
8255 					NECP_CLIENT_TREE_LOCK_SHARED();
8256 					struct necp_client *parent = necp_find_client_and_lock(client->parent_client_id);
8257 					if (parent != NULL) {
8258 						struct necp_client_flow_registration *parent_flow_registration = NULL;
8259 						RB_FOREACH(parent_flow_registration, _necp_client_flow_tree, &parent->flow_registrations) {
8260 							uuid_copy(parameters->parent_flow_uuid, parent_flow_registration->registration_id);
8261 							break;
8262 						}
8263 
8264 						NECP_CLIENT_UNLOCK(parent);
8265 					}
8266 					NECP_CLIENT_TREE_UNLOCK();
8267 
8268 					if (parsed_parameters.demux_pattern_count > 0) {
8269 						for (int i = 0; i < parsed_parameters.demux_pattern_count; i++) {
8270 							memcpy(&parameters->demux_patterns[i], &parsed_parameters.demux_patterns[i], sizeof(struct necp_demux_pattern));
8271 						}
8272 						parameters->demux_pattern_count = parsed_parameters.demux_pattern_count;
8273 					}
8274 				}
8275 			}
8276 		}
8277 	}
8278 #endif // SKYWALK
8279 
8280 	return error;
8281 }
8282 
8283 static NECP_CLIENT_ACTION_FUNCTION int
necp_client_list(struct necp_fd_data * fd_data,struct necp_client_action_args * uap,int * retval)8284 necp_client_list(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
8285 {
8286 	int error = 0;
8287 	struct necp_client *find_client = NULL;
8288 	uuid_t *list = NULL;
8289 	u_int32_t requested_client_count = 0;
8290 	u_int32_t client_count = 0;
8291 	size_t copy_buffer_size = 0;
8292 
8293 	if (uap->buffer_size < sizeof(requested_client_count) || uap->buffer == 0) {
8294 		error = EINVAL;
8295 		goto done;
8296 	}
8297 
8298 	if (!(fd_data->flags & NECP_OPEN_FLAG_OBSERVER)) {
8299 		NECPLOG0(LOG_ERR, "Client does not hold necessary entitlement to list other NECP clients");
8300 		error = EACCES;
8301 		goto done;
8302 	}
8303 
8304 	error = copyin(uap->buffer, &requested_client_count, sizeof(requested_client_count));
8305 	if (error) {
8306 		goto done;
8307 	}
8308 
8309 	if (os_mul_overflow(sizeof(uuid_t), requested_client_count, &copy_buffer_size)) {
8310 		error = ERANGE;
8311 		goto done;
8312 	}
8313 
8314 	if (uap->buffer_size - sizeof(requested_client_count) != copy_buffer_size) {
8315 		error = EINVAL;
8316 		goto done;
8317 	}
8318 
8319 	if (copy_buffer_size > NECP_MAX_CLIENT_LIST_SIZE) {
8320 		error = EINVAL;
8321 		goto done;
8322 	}
8323 
8324 	if (requested_client_count > 0) {
8325 		if ((list = (uuid_t*)kalloc_data(copy_buffer_size, Z_WAITOK | Z_ZERO)) == NULL) {
8326 			error = ENOMEM;
8327 			goto done;
8328 		}
8329 	}
8330 
8331 	// Lock tree
8332 	NECP_CLIENT_TREE_LOCK_SHARED();
8333 
8334 	find_client = NULL;
8335 	RB_FOREACH(find_client, _necp_client_global_tree, &necp_client_global_tree) {
8336 		NECP_CLIENT_LOCK(find_client);
8337 		if (!uuid_is_null(find_client->client_id)) {
8338 			if (client_count < requested_client_count) {
8339 				uuid_copy(list[client_count], find_client->client_id);
8340 			}
8341 			client_count++;
8342 		}
8343 		NECP_CLIENT_UNLOCK(find_client);
8344 	}
8345 
8346 	// Unlock tree
8347 	NECP_CLIENT_TREE_UNLOCK();
8348 
8349 	error = copyout(&client_count, uap->buffer, sizeof(client_count));
8350 	if (error) {
8351 		NECPLOG(LOG_ERR, "necp_client_list buffer copyout error (%d)", error);
8352 		goto done;
8353 	}
8354 
8355 	if (requested_client_count > 0 &&
8356 	    client_count > 0 &&
8357 	    list != NULL) {
8358 		error = copyout(list, uap->buffer + sizeof(client_count), copy_buffer_size);
8359 		if (error) {
8360 			NECPLOG(LOG_ERR, "necp_client_list client count copyout error (%d)", error);
8361 			goto done;
8362 		}
8363 	}
8364 done:
8365 	if (list != NULL) {
8366 		kfree_data(list, copy_buffer_size);
8367 	}
8368 	*retval = error;
8369 
8370 	return error;
8371 }
8372 
8373 static NECP_CLIENT_ACTION_FUNCTION int
necp_client_add_flow(struct necp_fd_data * fd_data,struct necp_client_action_args * uap,int * retval)8374 necp_client_add_flow(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
8375 {
8376 	int error = 0;
8377 	struct necp_client *client = NULL;
8378 	uuid_t client_id;
8379 	struct necp_client_nexus_parameters parameters = {};
8380 	struct proc *proc = PROC_NULL;
8381 	struct necp_client_add_flow *add_request = NULL;
8382 	struct necp_client_add_flow *allocated_add_request = NULL;
8383 	struct necp_client_add_flow_default default_add_request = {};
8384 	const size_t buffer_size = uap->buffer_size;
8385 
8386 	if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t)) {
8387 		error = EINVAL;
8388 		NECPLOG(LOG_ERR, "necp_client_add_flow invalid client_id (length %zu)", (size_t)uap->client_id_len);
8389 		goto done;
8390 	}
8391 
8392 	if (uap->buffer == 0 || buffer_size < sizeof(struct necp_client_add_flow) ||
8393 	    buffer_size > sizeof(struct necp_client_add_flow_default) * 4) {
8394 		error = EINVAL;
8395 		NECPLOG(LOG_ERR, "necp_client_add_flow invalid buffer (length %zu)", buffer_size);
8396 		goto done;
8397 	}
8398 
8399 	error = copyin(uap->client_id, client_id, sizeof(uuid_t));
8400 	if (error) {
8401 		NECPLOG(LOG_ERR, "necp_client_add_flow copyin client_id error (%d)", error);
8402 		goto done;
8403 	}
8404 
8405 	if (buffer_size <= sizeof(struct necp_client_add_flow_default)) {
8406 		// Fits in default size
8407 		error = copyin(uap->buffer, &default_add_request, buffer_size);
8408 		if (error) {
8409 			NECPLOG(LOG_ERR, "necp_client_add_flow copyin default_add_request error (%d)", error);
8410 			goto done;
8411 		}
8412 
8413 		add_request = (struct necp_client_add_flow *)&default_add_request;
8414 	} else {
8415 		allocated_add_request = (struct necp_client_add_flow *)kalloc_data(buffer_size, Z_WAITOK | Z_ZERO);
8416 		if (allocated_add_request == NULL) {
8417 			error = ENOMEM;
8418 			goto done;
8419 		}
8420 
8421 		error = copyin(uap->buffer, allocated_add_request, buffer_size);
8422 		if (error) {
8423 			NECPLOG(LOG_ERR, "necp_client_add_flow copyin default_add_request error (%d)", error);
8424 			goto done;
8425 		}
8426 
8427 		add_request = allocated_add_request;
8428 	}
8429 
8430 	NECP_FD_LOCK(fd_data);
8431 	pid_t pid = fd_data->proc_pid;
8432 	proc = proc_find(pid);
8433 	if (proc == PROC_NULL) {
8434 		NECP_FD_UNLOCK(fd_data);
8435 		NECPLOG(LOG_ERR, "necp_client_add_flow process not found for pid %d error (%d)", pid, error);
8436 		error = ESRCH;
8437 		goto done;
8438 	}
8439 
8440 	client = necp_client_fd_find_client_and_lock(fd_data, client_id);
8441 	if (client == NULL) {
8442 		error = ENOENT;
8443 		NECP_FD_UNLOCK(fd_data);
8444 		goto done;
8445 	}
8446 
8447 	// Using ADD_FLOW indicates that the client supports multiple flows per client
8448 	client->legacy_client_is_flow = false;
8449 
8450 	necp_client_retain_locked(client);
8451 	necp_client_copy_parameters_locked(client, &parameters);
8452 
8453 	struct necp_client_flow_registration *new_registration = necp_client_create_flow_registration(fd_data, client);
8454 	if (new_registration == NULL) {
8455 		error = ENOMEM;
8456 		NECP_CLIENT_UNLOCK(client);
8457 		NECP_FD_UNLOCK(fd_data);
8458 		NECPLOG0(LOG_ERR, "Failed to allocate flow registration");
8459 		goto done;
8460 	}
8461 
8462 	new_registration->flags = add_request->flags;
8463 
8464 	// Copy new ID out to caller
8465 	uuid_copy(add_request->registration_id, new_registration->registration_id);
8466 
8467 	NECP_CLIENT_FLOW_LOG(client, new_registration, "adding flow");
8468 
8469 	size_t trailer_offset = (sizeof(struct necp_client_add_flow) +
8470 	    add_request->stats_request_count * sizeof(struct necp_client_flow_stats));
8471 
8472 	// Copy override address
8473 	struct sockaddr *override_address = NULL;
8474 	if (add_request->flags & NECP_CLIENT_FLOW_FLAGS_OVERRIDE_ADDRESS) {
8475 		size_t offset_of_address = trailer_offset;
8476 		if (buffer_size >= offset_of_address + sizeof(struct sockaddr_in)) {
8477 			override_address = (struct sockaddr *)(((uint8_t *)add_request) + offset_of_address);
8478 			if (buffer_size >= offset_of_address + override_address->sa_len &&
8479 			    override_address->sa_len <= sizeof(parameters.remote_addr)) {
8480 				memcpy(&parameters.remote_addr, override_address, override_address->sa_len);
8481 				trailer_offset += override_address->sa_len;
8482 			} else {
8483 				override_address = NULL;
8484 			}
8485 		}
8486 	}
8487 
8488 	// Copy override IP protocol
8489 	if (add_request->flags & NECP_CLIENT_FLOW_FLAGS_OVERRIDE_IP_PROTOCOL) {
8490 		size_t offset_of_ip_protocol = trailer_offset;
8491 		if (buffer_size >= offset_of_ip_protocol + sizeof(uint8_t)) {
8492 			uint8_t *ip_protocol_p = (uint8_t *)(((uint8_t *)add_request) + offset_of_ip_protocol);
8493 			memcpy(&parameters.ip_protocol, ip_protocol_p, sizeof(uint8_t));
8494 		}
8495 	}
8496 
8497 #if SKYWALK
8498 	if (add_request->flags & NECP_CLIENT_FLOW_FLAGS_ALLOW_NEXUS) {
8499 		void *assigned_results = NULL;
8500 		size_t assigned_results_length = 0;
8501 		uint32_t interface_index = 0;
8502 
8503 		// Validate that the nexus UUID is assigned
8504 		bool found_nexus = false;
8505 		for (u_int32_t option_i = 0; option_i < client->interface_option_count; option_i++) {
8506 			if (option_i < NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT) {
8507 				struct necp_client_interface_option *option = &client->interface_options[option_i];
8508 				if (uuid_compare(option->nexus_agent, add_request->agent_uuid) == 0) {
8509 					interface_index = option->interface_index;
8510 					found_nexus = true;
8511 					break;
8512 				}
8513 			} else {
8514 				struct necp_client_interface_option *option = &client->extra_interface_options[option_i - NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT];
8515 				if (uuid_compare(option->nexus_agent, add_request->agent_uuid) == 0) {
8516 					interface_index = option->interface_index;
8517 					found_nexus = true;
8518 					break;
8519 				}
8520 			}
8521 		}
8522 
8523 		if (!found_nexus) {
8524 			NECPLOG0(LOG_ERR, "Requested nexus not found");
8525 		} else {
8526 			necp_client_add_nexus_flow_if_needed(new_registration, add_request->agent_uuid, interface_index);
8527 
8528 			error = netagent_client_message_with_params(add_request->agent_uuid,
8529 			    ((new_registration->flags & NECP_CLIENT_FLOW_FLAGS_USE_CLIENT_ID) ?
8530 			    client->client_id :
8531 			    new_registration->registration_id),
8532 			    pid, client->agent_handle,
8533 			    NETAGENT_MESSAGE_TYPE_REQUEST_NEXUS,
8534 			    (struct necp_client_agent_parameters *)&parameters,
8535 			    &assigned_results, &assigned_results_length);
8536 			if (error != 0) {
8537 				VERIFY(assigned_results == NULL);
8538 				VERIFY(assigned_results_length == 0);
8539 				NECPLOG(LOG_ERR, "netagent_client_message error (%d)", error);
8540 			} else if (assigned_results != NULL) {
8541 				if (!necp_assign_client_result_locked(proc, fd_data, client, new_registration, add_request->agent_uuid,
8542 				    assigned_results, assigned_results_length, false, false)) {
8543 					kfree_data(assigned_results, assigned_results_length);
8544 				}
8545 			} else if (override_address != NULL) {
8546 				// Save the overridden address in the flow. Find the correct flow,
8547 				// and assign just the address TLV. Don't set the assigned flag.
8548 				struct necp_client_flow *flow = NULL;
8549 				LIST_FOREACH(flow, &new_registration->flow_list, flow_chain) {
8550 					if (flow->nexus &&
8551 					    uuid_compare(flow->u.nexus_agent, add_request->agent_uuid) == 0) {
8552 						if (flow->assigned_results == NULL) {
8553 							memcpy(&flow->remote_addr, override_address, override_address->sa_len);
8554 							uuid_t empty_uuid;
8555 							uuid_clear(empty_uuid);
8556 							flow->assigned_results = necp_create_nexus_assign_message(empty_uuid, 0, NULL, 0,
8557 							    (struct necp_client_endpoint *)&flow->local_addr,
8558 							    (struct necp_client_endpoint *)&flow->remote_addr,
8559 							    NULL, 0, NULL, &flow->assigned_results_length);
8560 						}
8561 						break;
8562 					}
8563 				}
8564 			}
8565 		}
8566 	}
8567 
8568 	// Don't request stats if nexus creation fails
8569 	if (error == 0 && add_request->stats_request_count > 0 && necp_arena_initialize(fd_data, true) == 0) {
8570 		struct necp_client_flow_stats *stats_request = (struct necp_client_flow_stats *)&add_request->stats_requests[0];
8571 		struct necp_stats_bufreq bufreq = {};
8572 
8573 		NECP_CLIENT_FLOW_LOG(client, new_registration, "Initializing stats");
8574 
8575 		bufreq.necp_stats_bufreq_id = NECP_CLIENT_STATISTICS_BUFREQ_ID;
8576 		bufreq.necp_stats_bufreq_type = stats_request->stats_type;
8577 		bufreq.necp_stats_bufreq_ver = stats_request->stats_version;
8578 		bufreq.necp_stats_bufreq_size = stats_request->stats_size;
8579 		bufreq.necp_stats_bufreq_uaddr = stats_request->stats_addr;
8580 		(void)necp_stats_initialize(fd_data, client, new_registration, &bufreq);
8581 		stats_request->stats_type = bufreq.necp_stats_bufreq_type;
8582 		stats_request->stats_version = bufreq.necp_stats_bufreq_ver;
8583 		stats_request->stats_size = bufreq.necp_stats_bufreq_size;
8584 		stats_request->stats_addr = bufreq.necp_stats_bufreq_uaddr;
8585 	}
8586 #endif /* !SKYWALK */
8587 
8588 	if (error == 0 &&
8589 	    (add_request->flags & NECP_CLIENT_FLOW_FLAGS_BROWSE ||
8590 	    add_request->flags & NECP_CLIENT_FLOW_FLAGS_RESOLVE)) {
8591 		uint32_t interface_index = IFSCOPE_NONE;
8592 		ifnet_head_lock_shared();
8593 		struct ifnet *interface = NULL;
8594 		TAILQ_FOREACH(interface, &ifnet_head, if_link) {
8595 			ifnet_lock_shared(interface);
8596 			if (interface->if_agentids != NULL) {
8597 				for (u_int32_t i = 0; i < interface->if_agentcount; i++) {
8598 					if (uuid_compare(interface->if_agentids[i], add_request->agent_uuid) == 0) {
8599 						interface_index = interface->if_index;
8600 						break;
8601 					}
8602 				}
8603 			}
8604 			ifnet_lock_done(interface);
8605 			if (interface_index != IFSCOPE_NONE) {
8606 				break;
8607 			}
8608 		}
8609 		ifnet_head_done();
8610 
8611 		necp_client_add_nexus_flow_if_needed(new_registration, add_request->agent_uuid, interface_index);
8612 
8613 		error = netagent_client_message_with_params(add_request->agent_uuid,
8614 		    ((new_registration->flags & NECP_CLIENT_FLOW_FLAGS_USE_CLIENT_ID) ?
8615 		    client->client_id :
8616 		    new_registration->registration_id),
8617 		    pid, client->agent_handle,
8618 		    NETAGENT_MESSAGE_TYPE_CLIENT_ASSERT,
8619 		    (struct necp_client_agent_parameters *)&parameters,
8620 		    NULL, NULL);
8621 		if (error != 0) {
8622 			NECPLOG(LOG_ERR, "netagent_client_message error (%d)", error);
8623 		}
8624 	}
8625 
8626 	if (error != 0) {
8627 		// Encountered an error in adding the flow, destroy the flow registration
8628 #if SKYWALK
8629 		necp_destroy_flow_stats(fd_data, new_registration, NULL, false);
8630 #endif /* SKYWALK */
8631 		NECP_FLOW_TREE_LOCK_EXCLUSIVE();
8632 		RB_REMOVE(_necp_client_flow_global_tree, &necp_client_flow_global_tree, new_registration);
8633 		NECP_FLOW_TREE_UNLOCK();
8634 		RB_REMOVE(_necp_fd_flow_tree, &fd_data->flows, new_registration);
8635 		necp_destroy_client_flow_registration(client, new_registration, fd_data->proc_pid, true);
8636 		new_registration = NULL;
8637 	}
8638 
8639 	NECP_CLIENT_UNLOCK(client);
8640 	NECP_FD_UNLOCK(fd_data);
8641 
8642 	necp_client_release(client);
8643 
8644 	if (error != 0) {
8645 		goto done;
8646 	}
8647 
8648 	// Copy the request back out to the caller with assigned fields
8649 	error = copyout(add_request, uap->buffer, buffer_size);
8650 	if (error != 0) {
8651 		NECPLOG(LOG_ERR, "necp_client_add_flow copyout add_request error (%d)", error);
8652 	}
8653 
8654 done:
8655 	*retval = error;
8656 	if (error != 0) {
8657 		NECPLOG(LOG_ERR, "Add flow error (%d)", error);
8658 	}
8659 
8660 	if (allocated_add_request != NULL) {
8661 		kfree_data(allocated_add_request, buffer_size);
8662 	}
8663 
8664 	if (proc != PROC_NULL) {
8665 		proc_rele(proc);
8666 	}
8667 	return error;
8668 }
8669 
8670 #if SKYWALK
8671 
8672 static NECP_CLIENT_ACTION_FUNCTION int
necp_client_request_nexus(struct necp_fd_data * fd_data,struct necp_client_action_args * uap,int * retval)8673 necp_client_request_nexus(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
8674 {
8675 	int error = 0;
8676 	struct necp_client *client = NULL;
8677 	uuid_t client_id;
8678 	struct necp_client_nexus_parameters parameters = {};
8679 	struct proc *proc = PROC_NULL;
8680 	const size_t buffer_size = uap->buffer_size;
8681 
8682 	if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t)) {
8683 		error = EINVAL;
8684 		goto done;
8685 	}
8686 
8687 	error = copyin(uap->client_id, client_id, sizeof(uuid_t));
8688 	if (error) {
8689 		NECPLOG(LOG_ERR, "necp_client_request_nexus copyin client_id error (%d)", error);
8690 		goto done;
8691 	}
8692 
8693 	NECP_FD_LOCK(fd_data);
8694 	pid_t pid = fd_data->proc_pid;
8695 	proc = proc_find(pid);
8696 	if (proc == PROC_NULL) {
8697 		NECP_FD_UNLOCK(fd_data);
8698 		NECPLOG(LOG_ERR, "necp_client_request_nexus process not found for pid %d error (%d)", pid, error);
8699 		error = ESRCH;
8700 		goto done;
8701 	}
8702 
8703 	client = necp_client_fd_find_client_and_lock(fd_data, client_id);
8704 	if (client == NULL) {
8705 		NECP_FD_UNLOCK(fd_data);
8706 		error = ENOENT;
8707 		goto done;
8708 	}
8709 
8710 	// Using REQUEST_NEXUS indicates that the client only supports one flow per client
8711 	client->legacy_client_is_flow = true;
8712 
8713 	necp_client_retain_locked(client);
8714 	necp_client_copy_parameters_locked(client, &parameters);
8715 
8716 	do {
8717 		void *assigned_results = NULL;
8718 		size_t assigned_results_length = 0;
8719 		uuid_t nexus_uuid;
8720 		uint32_t interface_index = 0;
8721 
8722 		// Validate that the nexus UUID is assigned
8723 		bool found_nexus = false;
8724 		for (u_int32_t option_i = 0; option_i < client->interface_option_count; option_i++) {
8725 			if (option_i < NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT) {
8726 				struct necp_client_interface_option *option = &client->interface_options[option_i];
8727 				if (!uuid_is_null(option->nexus_agent)) {
8728 					uuid_copy(nexus_uuid, option->nexus_agent);
8729 					interface_index = option->interface_index;
8730 					found_nexus = true;
8731 					break;
8732 				}
8733 			} else {
8734 				struct necp_client_interface_option *option = &client->extra_interface_options[option_i - NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT];
8735 				if (!uuid_is_null(option->nexus_agent)) {
8736 					uuid_copy(nexus_uuid, option->nexus_agent);
8737 					interface_index = option->interface_index;
8738 					found_nexus = true;
8739 					break;
8740 				}
8741 			}
8742 		}
8743 
8744 		if (!found_nexus) {
8745 			NECP_CLIENT_UNLOCK(client);
8746 			NECP_FD_UNLOCK(fd_data);
8747 			necp_client_release(client);
8748 			// Break the loop
8749 			error = ENETDOWN;
8750 			goto done;
8751 		}
8752 
8753 		struct necp_client_flow_registration *new_registration = necp_client_create_flow_registration(fd_data, client);
8754 		if (new_registration == NULL) {
8755 			error = ENOMEM;
8756 			NECP_CLIENT_UNLOCK(client);
8757 			NECP_FD_UNLOCK(fd_data);
8758 			necp_client_release(client);
8759 			NECPLOG0(LOG_ERR, "Failed to allocate flow registration");
8760 			goto done;
8761 		}
8762 
8763 		new_registration->flags = (NECP_CLIENT_FLOW_FLAGS_ALLOW_NEXUS | NECP_CLIENT_FLOW_FLAGS_USE_CLIENT_ID);
8764 
8765 		necp_client_add_nexus_flow_if_needed(new_registration, nexus_uuid, interface_index);
8766 
8767 		// Note: Any clients using "request_nexus" are not flow-registration aware.
8768 		// Register the Client ID rather than the Registration ID with the nexus, since
8769 		// the client will send traffic based on the client ID.
8770 		error = netagent_client_message_with_params(nexus_uuid,
8771 		    ((new_registration->flags & NECP_CLIENT_FLOW_FLAGS_USE_CLIENT_ID) ?
8772 		    client->client_id :
8773 		    new_registration->registration_id),
8774 		    pid, client->agent_handle,
8775 		    NETAGENT_MESSAGE_TYPE_REQUEST_NEXUS,
8776 		    (struct necp_client_agent_parameters *)&parameters,
8777 		    &assigned_results, &assigned_results_length);
8778 		if (error) {
8779 			NECP_CLIENT_UNLOCK(client);
8780 			NECP_FD_UNLOCK(fd_data);
8781 			necp_client_release(client);
8782 			VERIFY(assigned_results == NULL);
8783 			VERIFY(assigned_results_length == 0);
8784 			NECPLOG(LOG_ERR, "netagent_client_message error (%d)", error);
8785 			goto done;
8786 		}
8787 
8788 		if (assigned_results != NULL) {
8789 			if (!necp_assign_client_result_locked(proc, fd_data, client, new_registration, nexus_uuid,
8790 			    assigned_results, assigned_results_length, false, false)) {
8791 				kfree_data(assigned_results, assigned_results_length);
8792 			}
8793 		}
8794 
8795 		if (uap->buffer != 0 && buffer_size == sizeof(struct necp_stats_bufreq) &&
8796 		    necp_arena_initialize(fd_data, true) == 0) {
8797 			struct necp_stats_bufreq bufreq = {};
8798 			int copy_error = copyin(uap->buffer, &bufreq, buffer_size);
8799 			if (copy_error) {
8800 				NECPLOG(LOG_ERR, "necp_client_request_nexus copyin bufreq error (%d)", copy_error);
8801 			} else {
8802 				(void)necp_stats_initialize(fd_data, client, new_registration, &bufreq);
8803 				copy_error = copyout(&bufreq, uap->buffer, buffer_size);
8804 				if (copy_error != 0) {
8805 					NECPLOG(LOG_ERR, "necp_client_request_nexus copyout bufreq error (%d)", copy_error);
8806 				}
8807 			}
8808 		}
8809 	} while (false);
8810 
8811 	NECP_CLIENT_UNLOCK(client);
8812 	NECP_FD_UNLOCK(fd_data);
8813 
8814 	necp_client_release(client);
8815 
8816 done:
8817 	*retval = error;
8818 	if (error != 0) {
8819 		NECPLOG(LOG_ERR, "Request nexus error (%d)", error);
8820 	}
8821 
8822 	if (proc != PROC_NULL) {
8823 		proc_rele(proc);
8824 	}
8825 	return error;
8826 }
8827 #endif /* !SKYWALK */
8828 
8829 static void
necp_client_add_assertion(struct necp_client * client,uuid_t netagent_uuid)8830 necp_client_add_assertion(struct necp_client *client, uuid_t netagent_uuid)
8831 {
8832 	struct necp_client_assertion *new_assertion = NULL;
8833 
8834 	new_assertion = kalloc_type(struct necp_client_assertion,
8835 	    Z_WAITOK | Z_NOFAIL);
8836 
8837 	uuid_copy(new_assertion->asserted_netagent, netagent_uuid);
8838 
8839 	LIST_INSERT_HEAD(&client->assertion_list, new_assertion, assertion_chain);
8840 }
8841 
8842 static bool
necp_client_remove_assertion(struct necp_client * client,uuid_t netagent_uuid)8843 necp_client_remove_assertion(struct necp_client *client, uuid_t netagent_uuid)
8844 {
8845 	struct necp_client_assertion *found_assertion = NULL;
8846 	struct necp_client_assertion *search_assertion = NULL;
8847 	LIST_FOREACH(search_assertion, &client->assertion_list, assertion_chain) {
8848 		if (uuid_compare(search_assertion->asserted_netagent, netagent_uuid) == 0) {
8849 			found_assertion = search_assertion;
8850 			break;
8851 		}
8852 	}
8853 
8854 	if (found_assertion == NULL) {
8855 		NECPLOG0(LOG_ERR, "Netagent uuid not previously asserted");
8856 		return false;
8857 	}
8858 
8859 	LIST_REMOVE(found_assertion, assertion_chain);
8860 	kfree_type(struct necp_client_assertion, found_assertion);
8861 	return true;
8862 }
8863 
8864 static NECP_CLIENT_ACTION_FUNCTION int
necp_client_agent_action(struct necp_fd_data * fd_data,struct necp_client_action_args * uap,int * retval)8865 necp_client_agent_action(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
8866 {
8867 	int error = 0;
8868 	struct necp_client *client = NULL;
8869 	uuid_t client_id;
8870 	bool acted_on_agent = FALSE;
8871 	u_int8_t *parameters = NULL;
8872 	const size_t buffer_size = uap->buffer_size;
8873 
8874 	if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t) ||
8875 	    buffer_size == 0 || uap->buffer == 0) {
8876 		NECPLOG0(LOG_ERR, "necp_client_agent_action invalid parameters");
8877 		error = EINVAL;
8878 		goto done;
8879 	}
8880 
8881 	error = copyin(uap->client_id, client_id, sizeof(uuid_t));
8882 	if (error) {
8883 		NECPLOG(LOG_ERR, "necp_client_agent_action copyin client_id error (%d)", error);
8884 		goto done;
8885 	}
8886 
8887 	if (buffer_size > NECP_MAX_AGENT_ACTION_SIZE) {
8888 		NECPLOG(LOG_ERR, "necp_client_agent_action invalid buffer size (>%u)", NECP_MAX_AGENT_ACTION_SIZE);
8889 		error = EINVAL;
8890 		goto done;
8891 	}
8892 
8893 	if ((parameters = (u_int8_t *)kalloc_data(buffer_size, Z_WAITOK | Z_ZERO)) == NULL) {
8894 		NECPLOG0(LOG_ERR, "necp_client_agent_action malloc failed");
8895 		error = ENOMEM;
8896 		goto done;
8897 	}
8898 
8899 	error = copyin(uap->buffer, parameters, buffer_size);
8900 	if (error) {
8901 		NECPLOG(LOG_ERR, "necp_client_agent_action parameters copyin error (%d)", error);
8902 		goto done;
8903 	}
8904 
8905 	NECP_FD_LOCK(fd_data);
8906 	client = necp_client_fd_find_client_and_lock(fd_data, client_id);
8907 	if (client != NULL) {
8908 		size_t offset = 0;
8909 		while ((offset + sizeof(struct necp_tlv_header)) <= buffer_size) {
8910 			u_int8_t type = necp_buffer_get_tlv_type(parameters, offset);
8911 			u_int32_t length = necp_buffer_get_tlv_length(parameters, offset);
8912 
8913 			if (length > (buffer_size - (offset + sizeof(struct necp_tlv_header)))) {
8914 				// If the length is larger than what can fit in the remaining parameters size, bail
8915 				NECPLOG(LOG_ERR, "Invalid TLV length (%u)", length);
8916 				break;
8917 			}
8918 
8919 			if (length >= sizeof(uuid_t)) {
8920 				u_int8_t *value = necp_buffer_get_tlv_value(parameters, offset, NULL);
8921 				if (value == NULL) {
8922 					NECPLOG0(LOG_ERR, "Invalid TLV value");
8923 					break;
8924 				}
8925 				if (type == NECP_CLIENT_PARAMETER_TRIGGER_AGENT ||
8926 				    type == NECP_CLIENT_PARAMETER_ASSERT_AGENT ||
8927 				    type == NECP_CLIENT_PARAMETER_UNASSERT_AGENT) {
8928 					uuid_t agent_uuid;
8929 					uuid_copy(agent_uuid, value);
8930 					u_int8_t netagent_message_type = 0;
8931 					if (type == NECP_CLIENT_PARAMETER_TRIGGER_AGENT) {
8932 						netagent_message_type = NETAGENT_MESSAGE_TYPE_CLIENT_TRIGGER;
8933 					} else if (type == NECP_CLIENT_PARAMETER_ASSERT_AGENT) {
8934 						netagent_message_type = NETAGENT_MESSAGE_TYPE_CLIENT_ASSERT;
8935 					} else if (type == NECP_CLIENT_PARAMETER_UNASSERT_AGENT) {
8936 						netagent_message_type = NETAGENT_MESSAGE_TYPE_CLIENT_UNASSERT;
8937 					}
8938 
8939 					// Before unasserting, verify that the assertion was already taken
8940 					if (type == NECP_CLIENT_PARAMETER_UNASSERT_AGENT) {
8941 						if (!necp_client_remove_assertion(client, agent_uuid)) {
8942 							error = ENOENT;
8943 							break;
8944 						}
8945 					}
8946 
8947 					struct necp_client_nexus_parameters parsed_parameters = {};
8948 					necp_client_copy_parameters_locked(client, &parsed_parameters);
8949 
8950 					error = netagent_client_message_with_params(agent_uuid,
8951 					    client_id,
8952 					    fd_data->proc_pid,
8953 					    client->agent_handle,
8954 					    netagent_message_type,
8955 					    (struct necp_client_agent_parameters *)&parsed_parameters,
8956 					    NULL, NULL);
8957 					if (error == 0) {
8958 						acted_on_agent = TRUE;
8959 					} else {
8960 						break;
8961 					}
8962 
8963 					// Only save the assertion if the action succeeded
8964 					if (type == NECP_CLIENT_PARAMETER_ASSERT_AGENT) {
8965 						necp_client_add_assertion(client, agent_uuid);
8966 					}
8967 				} else if (type == NECP_CLIENT_PARAMETER_AGENT_ADD_GROUP_MEMBERS ||
8968 				    type == NECP_CLIENT_PARAMETER_AGENT_REMOVE_GROUP_MEMBERS) {
8969 					uuid_t agent_uuid;
8970 					uuid_copy(agent_uuid, value);
8971 					u_int8_t netagent_message_type = 0;
8972 					if (type == NECP_CLIENT_PARAMETER_AGENT_ADD_GROUP_MEMBERS) {
8973 						netagent_message_type = NETAGENT_MESSAGE_TYPE_ADD_GROUP_MEMBERS;
8974 					} else if (type == NECP_CLIENT_PARAMETER_AGENT_REMOVE_GROUP_MEMBERS) {
8975 						netagent_message_type = NETAGENT_MESSAGE_TYPE_REMOVE_GROUP_MEMBERS;
8976 					}
8977 
8978 					struct necp_client_group_members group_members = {};
8979 					group_members.group_members_length = (length - sizeof(uuid_t));
8980 					group_members.group_members = (value + sizeof(uuid_t));
8981 					error = netagent_client_message_with_params(agent_uuid,
8982 					    client_id,
8983 					    fd_data->proc_pid,
8984 					    client->agent_handle,
8985 					    netagent_message_type,
8986 					    (struct necp_client_agent_parameters *)&group_members,
8987 					    NULL, NULL);
8988 					if (error == 0) {
8989 						acted_on_agent = TRUE;
8990 					} else {
8991 						break;
8992 					}
8993 				} else if (type == NECP_CLIENT_PARAMETER_REPORT_AGENT_ERROR) {
8994 					uuid_t agent_uuid;
8995 					uuid_copy(agent_uuid, value);
8996 					struct necp_client_agent_parameters agent_params = {};
8997 					if ((length - sizeof(uuid_t)) >= sizeof(agent_params.u.error.error)) {
8998 						memcpy(&agent_params.u.error.error,
8999 						    (value + sizeof(uuid_t)),
9000 						    sizeof(agent_params.u.error.error));
9001 					}
9002 					bool agent_reported = false;
9003 					for (int agent_i = 0; agent_i < NECP_FD_REPORTED_AGENT_COUNT; agent_i++) {
9004 						if (uuid_compare(agent_uuid, fd_data->reported_agents.agent_uuid[agent_i]) == 0) {
9005 							// Found a match, already reported
9006 							agent_reported = true;
9007 							break;
9008 						}
9009 					}
9010 					agent_params.u.error.force_report = !agent_reported;
9011 					if (!agent_reported) {
9012 						// Save this agent as having been reported
9013 						bool saved_agent_uuid = false;
9014 						for (int agent_i = 0; agent_i < NECP_FD_REPORTED_AGENT_COUNT; agent_i++) {
9015 							if (uuid_is_null(fd_data->reported_agents.agent_uuid[agent_i])) {
9016 								uuid_copy(fd_data->reported_agents.agent_uuid[agent_i], agent_uuid);
9017 								saved_agent_uuid = true;
9018 								break;
9019 							}
9020 						}
9021 						if (!saved_agent_uuid) {
9022 							// Reported agent UUIDs full, move over and insert at the end
9023 							for (int agent_i = 0; agent_i < NECP_FD_REPORTED_AGENT_COUNT; agent_i++) {
9024 								if (agent_i + 1 < NECP_FD_REPORTED_AGENT_COUNT) {
9025 									uuid_copy(fd_data->reported_agents.agent_uuid[agent_i], fd_data->reported_agents.agent_uuid[agent_i + 1]);
9026 								} else {
9027 									uuid_copy(fd_data->reported_agents.agent_uuid[agent_i], agent_uuid);
9028 								}
9029 							}
9030 						}
9031 					}
9032 					error = netagent_client_message_with_params(agent_uuid,
9033 					    client_id,
9034 					    fd_data->proc_pid,
9035 					    client->agent_handle,
9036 					    NETAGENT_MESSAGE_TYPE_CLIENT_ERROR,
9037 					    &agent_params,
9038 					    NULL, NULL);
9039 					if (error == 0) {
9040 						acted_on_agent = TRUE;
9041 					} else {
9042 						break;
9043 					}
9044 				}
9045 			}
9046 
9047 			offset += sizeof(struct necp_tlv_header) + length;
9048 		}
9049 
9050 		NECP_CLIENT_UNLOCK(client);
9051 	}
9052 	NECP_FD_UNLOCK(fd_data);
9053 
9054 	if (!acted_on_agent &&
9055 	    error == 0) {
9056 		error = ENOENT;
9057 	}
9058 done:
9059 	*retval = error;
9060 	if (parameters != NULL) {
9061 		kfree_data(parameters, buffer_size);
9062 		parameters = NULL;
9063 	}
9064 
9065 	return error;
9066 }
9067 
9068 static NECP_CLIENT_ACTION_FUNCTION int
necp_client_copy_agent(__unused struct necp_fd_data * fd_data,struct necp_client_action_args * uap,int * retval)9069 necp_client_copy_agent(__unused struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
9070 {
9071 	int error = 0;
9072 	uuid_t agent_uuid;
9073 	const size_t buffer_size = uap->buffer_size;
9074 
9075 	if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t) ||
9076 	    buffer_size == 0 || uap->buffer == 0) {
9077 		NECPLOG0(LOG_ERR, "necp_client_copy_agent bad input");
9078 		error = EINVAL;
9079 		goto done;
9080 	}
9081 
9082 	error = copyin(uap->client_id, agent_uuid, sizeof(uuid_t));
9083 	if (error) {
9084 		NECPLOG(LOG_ERR, "necp_client_copy_agent copyin agent_uuid error (%d)", error);
9085 		goto done;
9086 	}
9087 
9088 	error = netagent_copyout(agent_uuid, uap->buffer, buffer_size);
9089 	if (error) {
9090 		// netagent_copyout already logs appropriate errors
9091 		goto done;
9092 	}
9093 done:
9094 	*retval = error;
9095 
9096 	return error;
9097 }
9098 
9099 static NECP_CLIENT_ACTION_FUNCTION int
necp_client_agent_use(struct necp_fd_data * fd_data,struct necp_client_action_args * uap,int * retval)9100 necp_client_agent_use(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
9101 {
9102 	int error = 0;
9103 	struct necp_client *client = NULL;
9104 	uuid_t client_id;
9105 	struct necp_agent_use_parameters parameters = {};
9106 	const size_t buffer_size = uap->buffer_size;
9107 
9108 	if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t) ||
9109 	    buffer_size != sizeof(parameters) || uap->buffer == 0) {
9110 		error = EINVAL;
9111 		goto done;
9112 	}
9113 
9114 	error = copyin(uap->client_id, client_id, sizeof(uuid_t));
9115 	if (error) {
9116 		NECPLOG(LOG_ERR, "Copyin client_id error (%d)", error);
9117 		goto done;
9118 	}
9119 
9120 	error = copyin(uap->buffer, &parameters, buffer_size);
9121 	if (error) {
9122 		NECPLOG(LOG_ERR, "Parameters copyin error (%d)", error);
9123 		goto done;
9124 	}
9125 
9126 	NECP_FD_LOCK(fd_data);
9127 	client = necp_client_fd_find_client_and_lock(fd_data, client_id);
9128 	if (client != NULL) {
9129 		error = netagent_use(parameters.agent_uuid, &parameters.out_use_count);
9130 		NECP_CLIENT_UNLOCK(client);
9131 	} else {
9132 		error = ENOENT;
9133 	}
9134 
9135 	NECP_FD_UNLOCK(fd_data);
9136 
9137 	if (error == 0) {
9138 		error = copyout(&parameters, uap->buffer, buffer_size);
9139 		if (error) {
9140 			NECPLOG(LOG_ERR, "Parameters copyout error (%d)", error);
9141 			goto done;
9142 		}
9143 	}
9144 
9145 done:
9146 	*retval = error;
9147 
9148 	return error;
9149 }
9150 
9151 static NECP_CLIENT_ACTION_FUNCTION int
necp_client_acquire_agent_token(__unused struct necp_fd_data * fd_data,struct necp_client_action_args * uap,int * retval)9152 necp_client_acquire_agent_token(__unused struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
9153 {
9154 	int error = 0;
9155 	uuid_t agent_uuid = {};
9156 	const size_t buffer_size = uap->buffer_size;
9157 
9158 	*retval = 0;
9159 
9160 	if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t) ||
9161 	    buffer_size == 0 || uap->buffer == 0) {
9162 		NECPLOG0(LOG_ERR, "necp_client_copy_agent bad input");
9163 		error = EINVAL;
9164 		goto done;
9165 	}
9166 
9167 	error = copyin(uap->client_id, agent_uuid, sizeof(uuid_t));
9168 	if (error) {
9169 		NECPLOG(LOG_ERR, "necp_client_copy_agent copyin agent_uuid error (%d)", error);
9170 		goto done;
9171 	}
9172 
9173 	error = netagent_acquire_token(agent_uuid, uap->buffer, buffer_size, retval);
9174 done:
9175 	return error;
9176 }
9177 
9178 static NECP_CLIENT_ACTION_FUNCTION int
necp_client_copy_interface(__unused struct necp_fd_data * fd_data,struct necp_client_action_args * uap,int * retval)9179 necp_client_copy_interface(__unused struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
9180 {
9181 	int error = 0;
9182 	u_int32_t interface_index = 0;
9183 	struct necp_interface_details interface_details = {};
9184 
9185 	if (uap->client_id == 0 || uap->client_id_len != sizeof(u_int32_t) ||
9186 	    uap->buffer_size < sizeof(interface_details) ||
9187 	    uap->buffer == 0) {
9188 		NECPLOG0(LOG_ERR, "necp_client_copy_interface bad input");
9189 		error = EINVAL;
9190 		goto done;
9191 	}
9192 
9193 	error = copyin(uap->client_id, &interface_index, sizeof(u_int32_t));
9194 	if (error) {
9195 		NECPLOG(LOG_ERR, "necp_client_copy_interface copyin interface_index error (%d)", error);
9196 		goto done;
9197 	}
9198 
9199 	if (interface_index == 0) {
9200 		error = ENOENT;
9201 		NECPLOG(LOG_ERR, "necp_client_copy_interface bad interface_index (%d)", interface_index);
9202 		goto done;
9203 	}
9204 
9205 	lck_mtx_lock(rnh_lock);
9206 	ifnet_head_lock_shared();
9207 	ifnet_t interface = NULL;
9208 	if (interface_index != IFSCOPE_NONE && interface_index <= (u_int32_t)if_index) {
9209 		interface = ifindex2ifnet[interface_index];
9210 	}
9211 
9212 	if (interface != NULL) {
9213 		if (interface->if_xname != NULL) {
9214 			strlcpy((char *)&interface_details.name, interface->if_xname, sizeof(interface_details.name));
9215 		}
9216 		interface_details.index = interface->if_index;
9217 		interface_details.generation = ifnet_get_generation(interface);
9218 		if (interface->if_delegated.ifp != NULL) {
9219 			interface_details.delegate_index = interface->if_delegated.ifp->if_index;
9220 		}
9221 		interface_details.functional_type = if_functional_type(interface, TRUE);
9222 		if (IFNET_IS_EXPENSIVE(interface)) {
9223 			interface_details.flags |= NECP_INTERFACE_FLAG_EXPENSIVE;
9224 		}
9225 		if (IFNET_IS_CONSTRAINED(interface)) {
9226 			interface_details.flags |= NECP_INTERFACE_FLAG_CONSTRAINED;
9227 		}
9228 		if ((interface->if_eflags & IFEF_TXSTART) == IFEF_TXSTART) {
9229 			interface_details.flags |= NECP_INTERFACE_FLAG_TXSTART;
9230 		}
9231 		if ((interface->if_eflags & IFEF_NOACKPRI) == IFEF_NOACKPRI) {
9232 			interface_details.flags |= NECP_INTERFACE_FLAG_NOACKPRI;
9233 		}
9234 		if ((interface->if_eflags & IFEF_3CA) == IFEF_3CA) {
9235 			interface_details.flags |= NECP_INTERFACE_FLAG_3CARRIERAGG;
9236 		}
9237 		if (IFNET_IS_LOW_POWER(interface)) {
9238 			interface_details.flags |= NECP_INTERFACE_FLAG_IS_LOW_POWER;
9239 		}
9240 		if (interface->if_xflags & IFXF_MPK_LOG) {
9241 			interface_details.flags |= NECP_INTERFACE_FLAG_MPK_LOG;
9242 		}
9243 		if (interface->if_flags & IFF_MULTICAST) {
9244 			interface_details.flags |= NECP_INTERFACE_FLAG_SUPPORTS_MULTICAST;
9245 		}
9246 		if (IS_INTF_CLAT46(interface)) {
9247 			interface_details.flags |= NECP_INTERFACE_FLAG_HAS_NAT64;
9248 		}
9249 		interface_details.mtu = interface->if_mtu;
9250 #if SKYWALK
9251 		fsw_get_tso_capabilities(interface, &interface_details.tso_max_segment_size_v4,
9252 		    &interface_details.tso_max_segment_size_v6);
9253 
9254 		interface_details.hwcsum_flags = interface->if_hwassist & IFNET_CHECKSUMF;
9255 #endif /* SKYWALK */
9256 
9257 		u_int8_t ipv4_signature_len = sizeof(interface_details.ipv4_signature.signature);
9258 		u_int16_t ipv4_signature_flags;
9259 		if (ifnet_get_netsignature(interface, AF_INET, &ipv4_signature_len, &ipv4_signature_flags,
9260 		    (u_int8_t *)&interface_details.ipv4_signature) != 0) {
9261 			ipv4_signature_len = 0;
9262 		}
9263 		interface_details.ipv4_signature.signature_len = ipv4_signature_len;
9264 
9265 		// Check for default scoped routes for IPv4 and IPv6
9266 		union necp_sockaddr_union default_address;
9267 		struct rtentry *v4Route = NULL;
9268 		memset(&default_address, 0, sizeof(default_address));
9269 		default_address.sa.sa_family = AF_INET;
9270 		default_address.sa.sa_len = sizeof(struct sockaddr_in);
9271 		v4Route = rtalloc1_scoped_locked((struct sockaddr *)&default_address, 0, 0,
9272 		    interface->if_index);
9273 		if (v4Route != NULL) {
9274 			if (v4Route->rt_ifp != NULL && !IS_INTF_CLAT46(v4Route->rt_ifp)) {
9275 				interface_details.flags |= NECP_INTERFACE_FLAG_IPV4_ROUTABLE;
9276 			}
9277 			rtfree_locked(v4Route);
9278 			v4Route = NULL;
9279 		}
9280 
9281 		struct rtentry *v6Route = NULL;
9282 		memset(&default_address, 0, sizeof(default_address));
9283 		default_address.sa.sa_family = AF_INET6;
9284 		default_address.sa.sa_len = sizeof(struct sockaddr_in6);
9285 		v6Route = rtalloc1_scoped_locked((struct sockaddr *)&default_address, 0, 0,
9286 		    interface->if_index);
9287 		if (v6Route != NULL) {
9288 			if (v6Route->rt_ifp != NULL) {
9289 				interface_details.flags |= NECP_INTERFACE_FLAG_IPV6_ROUTABLE;
9290 			}
9291 			rtfree_locked(v6Route);
9292 			v6Route = NULL;
9293 		}
9294 
9295 		u_int8_t ipv6_signature_len = sizeof(interface_details.ipv6_signature.signature);
9296 		u_int16_t ipv6_signature_flags;
9297 		if (ifnet_get_netsignature(interface, AF_INET6, &ipv6_signature_len, &ipv6_signature_flags,
9298 		    (u_int8_t *)&interface_details.ipv6_signature) != 0) {
9299 			ipv6_signature_len = 0;
9300 		}
9301 		interface_details.ipv6_signature.signature_len = ipv6_signature_len;
9302 
9303 		ifnet_lock_shared(interface);
9304 		struct ifaddr *ifa = NULL;
9305 		TAILQ_FOREACH(ifa, &interface->if_addrhead, ifa_link) {
9306 			IFA_LOCK(ifa);
9307 			if (ifa->ifa_addr->sa_family == AF_INET) {
9308 				interface_details.flags |= NECP_INTERFACE_FLAG_HAS_NETMASK;
9309 				interface_details.ipv4_netmask = ((struct in_ifaddr *)ifa)->ia_sockmask.sin_addr.s_addr;
9310 				if (interface->if_flags & IFF_BROADCAST) {
9311 					interface_details.flags |= NECP_INTERFACE_FLAG_HAS_BROADCAST;
9312 					interface_details.ipv4_broadcast = ((struct in_ifaddr *)ifa)->ia_broadaddr.sin_addr.s_addr;
9313 				}
9314 			}
9315 			IFA_UNLOCK(ifa);
9316 		}
9317 
9318 		interface_details.radio_type = interface->if_radio_type;
9319 		if (interface_details.radio_type == 0 && interface->if_delegated.ifp) {
9320 			interface_details.radio_type = interface->if_delegated.ifp->if_radio_type;
9321 		}
9322 		ifnet_lock_done(interface);
9323 	}
9324 
9325 	ifnet_head_done();
9326 	lck_mtx_unlock(rnh_lock);
9327 
9328 	// If the client is using an older version of the struct, copy that length
9329 	error = copyout(&interface_details, uap->buffer, sizeof(interface_details));
9330 	if (error) {
9331 		NECPLOG(LOG_ERR, "necp_client_copy_interface copyout error (%d)", error);
9332 		goto done;
9333 	}
9334 done:
9335 	*retval = error;
9336 
9337 	return error;
9338 }
9339 
9340 #if SKYWALK
9341 
9342 static NECP_CLIENT_ACTION_FUNCTION int
necp_client_get_interface_address(__unused struct necp_fd_data * fd_data,struct necp_client_action_args * uap,int * retval)9343 necp_client_get_interface_address(__unused struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
9344 {
9345 	int error = 0;
9346 	u_int32_t interface_index = IFSCOPE_NONE;
9347 	struct sockaddr_storage address = {};
9348 	const size_t buffer_size = uap->buffer_size;
9349 
9350 	if (uap->client_id == 0 || uap->client_id_len != sizeof(u_int32_t) ||
9351 	    buffer_size < sizeof(struct sockaddr_in) ||
9352 	    buffer_size > sizeof(struct sockaddr_storage) ||
9353 	    uap->buffer == 0) {
9354 		NECPLOG0(LOG_ERR, "necp_client_get_interface_address bad input");
9355 		error = EINVAL;
9356 		goto done;
9357 	}
9358 
9359 	error = copyin(uap->client_id, &interface_index, sizeof(u_int32_t));
9360 	if (error) {
9361 		NECPLOG(LOG_ERR, "necp_client_get_interface_address copyin interface_index error (%d)", error);
9362 		goto done;
9363 	}
9364 
9365 	if (interface_index == IFSCOPE_NONE) {
9366 		error = ENOENT;
9367 		NECPLOG(LOG_ERR, "necp_client_get_interface_address bad interface_index (%d)", interface_index);
9368 		goto done;
9369 	}
9370 
9371 	error = copyin(uap->buffer, &address, buffer_size);
9372 	if (error) {
9373 		NECPLOG(LOG_ERR, "necp_client_get_interface_address copyin address error (%d)", error);
9374 		goto done;
9375 	}
9376 
9377 	if (address.ss_family != AF_INET && address.ss_family != AF_INET6) {
9378 		error = EINVAL;
9379 		NECPLOG(LOG_ERR, "necp_client_get_interface_address invalid address family (%u)", address.ss_family);
9380 		goto done;
9381 	}
9382 
9383 	if (address.ss_len != buffer_size) {
9384 		error = EINVAL;
9385 		NECPLOG(LOG_ERR, "necp_client_get_interface_address invalid address length (%u)", address.ss_len);
9386 		goto done;
9387 	}
9388 
9389 	ifnet_head_lock_shared();
9390 	ifnet_t ifp = NULL;
9391 	if (interface_index != IFSCOPE_NONE && interface_index <= (u_int32_t)if_index) {
9392 		ifp = ifindex2ifnet[interface_index];
9393 	}
9394 	ifnet_head_done();
9395 	if (ifp == NULL) {
9396 		error = ENOENT;
9397 		NECPLOG0(LOG_ERR, "necp_client_get_interface_address no matching interface found");
9398 		goto done;
9399 	}
9400 
9401 	struct rtentry *rt = rtalloc1_scoped((struct sockaddr *)&address, 0, 0, interface_index);
9402 	if (rt == NULL) {
9403 		error = EINVAL;
9404 		NECPLOG0(LOG_ERR, "necp_client_get_interface_address route lookup failed");
9405 		goto done;
9406 	}
9407 
9408 	uint32_t gencount = 0;
9409 	struct sockaddr_storage local_address = {};
9410 	error = flow_route_select_laddr((union sockaddr_in_4_6 *)&local_address,
9411 	    (union sockaddr_in_4_6 *)&address, ifp, rt, &gencount, 1);
9412 	rtfree(rt);
9413 	rt = NULL;
9414 
9415 	if (error) {
9416 		NECPLOG(LOG_ERR, "necp_client_get_interface_address local address selection failed (%d)", error);
9417 		goto done;
9418 	}
9419 
9420 	if (local_address.ss_len > buffer_size) {
9421 		error = EMSGSIZE;
9422 		NECPLOG(LOG_ERR, "necp_client_get_interface_address local address too long for buffer (%u)",
9423 		    local_address.ss_len);
9424 		goto done;
9425 	}
9426 
9427 	error = copyout(&local_address, uap->buffer, local_address.ss_len);
9428 	if (error) {
9429 		NECPLOG(LOG_ERR, "necp_client_get_interface_address copyout error (%d)", error);
9430 		goto done;
9431 	}
9432 done:
9433 	*retval = error;
9434 
9435 	return error;
9436 }
9437 
9438 extern char *proc_name_address(void *p);
9439 
9440 int
necp_stats_ctor(struct skmem_obj_info * oi,struct skmem_obj_info * oim,void * arg,uint32_t skmflag)9441 necp_stats_ctor(struct skmem_obj_info *oi, struct skmem_obj_info *oim,
9442     void *arg, uint32_t skmflag)
9443 {
9444 #pragma unused(arg, skmflag)
9445 	struct necp_all_kstats *kstats = SKMEM_OBJ_ADDR(oi);
9446 
9447 	ASSERT(oim != NULL && SKMEM_OBJ_ADDR(oim) != NULL);
9448 	ASSERT(SKMEM_OBJ_SIZE(oi) == SKMEM_OBJ_SIZE(oim));
9449 
9450 	kstats->necp_stats_ustats = SKMEM_OBJ_ADDR(oim);
9451 
9452 	return 0;
9453 }
9454 
9455 int
necp_stats_dtor(void * addr,void * arg)9456 necp_stats_dtor(void *addr, void *arg)
9457 {
9458 #pragma unused(addr, arg)
9459 	struct necp_all_kstats *kstats = addr;
9460 
9461 	kstats->necp_stats_ustats = NULL;
9462 
9463 	return 0;
9464 }
9465 
9466 static void
necp_fd_insert_stats_arena(struct necp_fd_data * fd_data,struct necp_arena_info * nai)9467 necp_fd_insert_stats_arena(struct necp_fd_data *fd_data, struct necp_arena_info *nai)
9468 {
9469 	NECP_FD_ASSERT_LOCKED(fd_data);
9470 	VERIFY(!(nai->nai_flags & NAIF_ATTACHED));
9471 	VERIFY(nai->nai_chain.le_next == NULL && nai->nai_chain.le_prev == NULL);
9472 
9473 	LIST_INSERT_HEAD(&fd_data->stats_arena_list, nai, nai_chain);
9474 	nai->nai_flags |= NAIF_ATTACHED;
9475 	necp_arena_info_retain(nai);    // for the list
9476 }
9477 
9478 static void
necp_fd_remove_stats_arena(struct necp_fd_data * fd_data,struct necp_arena_info * nai)9479 necp_fd_remove_stats_arena(struct necp_fd_data *fd_data, struct necp_arena_info *nai)
9480 {
9481 #pragma unused(fd_data)
9482 	NECP_FD_ASSERT_LOCKED(fd_data);
9483 	VERIFY(nai->nai_flags & NAIF_ATTACHED);
9484 	VERIFY(nai->nai_use_count >= 1);
9485 
9486 	LIST_REMOVE(nai, nai_chain);
9487 	nai->nai_flags &= ~NAIF_ATTACHED;
9488 	nai->nai_chain.le_next = NULL;
9489 	nai->nai_chain.le_prev = NULL;
9490 	necp_arena_info_release(nai);   // for the list
9491 }
9492 
9493 static struct necp_arena_info *
necp_fd_mredirect_stats_arena(struct necp_fd_data * fd_data,struct proc * proc)9494 necp_fd_mredirect_stats_arena(struct necp_fd_data *fd_data, struct proc *proc)
9495 {
9496 	struct necp_arena_info *nai, *nai_ret = NULL;
9497 
9498 	NECP_FD_ASSERT_LOCKED(fd_data);
9499 
9500 	// Redirect currently-active stats arena and remove it from the active state;
9501 	// upon process resumption, new flow request would trigger the creation of
9502 	// another active arena.
9503 	if ((nai = fd_data->stats_arena_active) != NULL) {
9504 		boolean_t need_defunct = FALSE;
9505 
9506 		ASSERT(!(nai->nai_flags & (NAIF_REDIRECT | NAIF_DEFUNCT)));
9507 		VERIFY(nai->nai_use_count >= 2);
9508 		ASSERT(nai->nai_arena != NULL);
9509 		ASSERT(nai->nai_mmap.ami_mapref != NULL);
9510 
9511 		int err = skmem_arena_mredirect(nai->nai_arena, &nai->nai_mmap, proc, &need_defunct);
9512 		VERIFY(err == 0);
9513 		// must be TRUE since we don't mmap the arena more than once
9514 		VERIFY(need_defunct == TRUE);
9515 
9516 		nai->nai_flags |= NAIF_REDIRECT;
9517 		nai_ret = nai;  // return to caller
9518 
9519 		necp_arena_info_release(nai);   // for fd_data
9520 		fd_data->stats_arena_active = nai = NULL;
9521 	}
9522 
9523 #if (DEVELOPMENT || DEBUG)
9524 	// make sure this list now contains nothing but redirected/defunct arenas
9525 	LIST_FOREACH(nai, &fd_data->stats_arena_list, nai_chain) {
9526 		ASSERT(nai->nai_use_count >= 1);
9527 		ASSERT(nai->nai_flags & (NAIF_REDIRECT | NAIF_DEFUNCT));
9528 	}
9529 #endif /* (DEVELOPMENT || DEBUG) */
9530 
9531 	return nai_ret;
9532 }
9533 
9534 static void
necp_arena_info_retain(struct necp_arena_info * nai)9535 necp_arena_info_retain(struct necp_arena_info *nai)
9536 {
9537 	nai->nai_use_count++;
9538 	VERIFY(nai->nai_use_count != 0);
9539 }
9540 
9541 static void
necp_arena_info_release(struct necp_arena_info * nai)9542 necp_arena_info_release(struct necp_arena_info *nai)
9543 {
9544 	VERIFY(nai->nai_use_count > 0);
9545 	if (--nai->nai_use_count == 0) {
9546 		necp_arena_info_free(nai);
9547 	}
9548 }
9549 
9550 static struct necp_arena_info *
necp_arena_info_alloc(void)9551 necp_arena_info_alloc(void)
9552 {
9553 	return zalloc_flags(necp_arena_info_zone, Z_WAITOK | Z_ZERO);
9554 }
9555 
9556 static void
necp_arena_info_free(struct necp_arena_info * nai)9557 necp_arena_info_free(struct necp_arena_info *nai)
9558 {
9559 	VERIFY(nai->nai_chain.le_next == NULL && nai->nai_chain.le_prev == NULL);
9560 	VERIFY(nai->nai_use_count == 0);
9561 
9562 	// NOTE: destroying the arena requires that all outstanding objects
9563 	// that were allocated have been freed, else it will assert.
9564 	if (nai->nai_arena != NULL) {
9565 		skmem_arena_munmap(nai->nai_arena, &nai->nai_mmap);
9566 		skmem_arena_release(nai->nai_arena);
9567 		OSDecrementAtomic(&necp_arena_count);
9568 		nai->nai_arena = NULL;
9569 		nai->nai_roff = 0;
9570 	}
9571 
9572 	ASSERT(nai->nai_arena == NULL);
9573 	ASSERT(nai->nai_mmap.ami_mapref == NULL);
9574 	ASSERT(nai->nai_mmap.ami_arena == NULL);
9575 	ASSERT(nai->nai_mmap.ami_maptask == TASK_NULL);
9576 
9577 	zfree(necp_arena_info_zone, nai);
9578 }
9579 
9580 static int
necp_arena_create(struct necp_fd_data * fd_data,size_t obj_size,size_t obj_cnt,struct proc * p)9581 necp_arena_create(struct necp_fd_data *fd_data, size_t obj_size, size_t obj_cnt, struct proc *p)
9582 {
9583 	struct skmem_region_params srp_ustats = {};
9584 	struct skmem_region_params srp_kstats = {};
9585 	struct necp_arena_info *nai;
9586 	char name[32];
9587 	int error = 0;
9588 
9589 	NECP_FD_ASSERT_LOCKED(fd_data);
9590 	ASSERT(fd_data->stats_arena_active == NULL);
9591 	ASSERT(p != PROC_NULL);
9592 	ASSERT(proc_pid(p) == fd_data->proc_pid);
9593 
9594 	// inherit the default parameters for the stats region
9595 	srp_ustats = *skmem_get_default(SKMEM_REGION_USTATS);
9596 	srp_kstats = *skmem_get_default(SKMEM_REGION_KSTATS);
9597 
9598 	// enable multi-segment mode
9599 	srp_ustats.srp_cflags &= ~SKMEM_REGION_CR_MONOLITHIC;
9600 	srp_kstats.srp_cflags &= ~SKMEM_REGION_CR_MONOLITHIC;
9601 
9602 	// configure and adjust the region parameters
9603 	srp_ustats.srp_r_obj_cnt = srp_kstats.srp_r_obj_cnt = obj_cnt;
9604 	srp_ustats.srp_r_obj_size = srp_kstats.srp_r_obj_size = obj_size;
9605 	skmem_region_params_config(&srp_ustats);
9606 	skmem_region_params_config(&srp_kstats);
9607 
9608 	nai = necp_arena_info_alloc();
9609 
9610 	nai->nai_proc_pid = fd_data->proc_pid;
9611 	(void) snprintf(name, sizeof(name), "stats-%u.%s.%d", fd_data->stats_arena_gencnt, proc_name_address(p), fd_data->proc_pid);
9612 	nai->nai_arena = skmem_arena_create_for_necp(name, &srp_ustats, &srp_kstats, &error);
9613 	ASSERT(nai->nai_arena != NULL || error != 0);
9614 	if (error != 0) {
9615 		NECPLOG(LOG_ERR, "failed to create stats arena for pid %d\n", fd_data->proc_pid);
9616 	} else {
9617 		OSIncrementAtomic(&necp_arena_count);
9618 
9619 		// Get region offsets from base of mmap span; the arena
9620 		// doesn't need to be mmap'd at this point, since we simply
9621 		// compute the relative offset.
9622 		nai->nai_roff = skmem_arena_get_region_offset(nai->nai_arena, SKMEM_REGION_USTATS);
9623 
9624 		// map to the task/process; upon success, the base address of the region
9625 		// will be returned in nai_mmap.ami_mapaddr; this can be communicated to
9626 		// the process.
9627 		error = skmem_arena_mmap(nai->nai_arena, p, &nai->nai_mmap);
9628 		if (error != 0) {
9629 			NECPLOG(LOG_ERR, "failed to map stats arena for pid %d\n", fd_data->proc_pid);
9630 		}
9631 	}
9632 
9633 	if (error == 0) {
9634 		fd_data->stats_arena_active = nai;
9635 		necp_arena_info_retain(nai);    // for fd_data
9636 		necp_fd_insert_stats_arena(fd_data, nai);
9637 		++fd_data->stats_arena_gencnt;
9638 	} else {
9639 		necp_arena_info_free(nai);
9640 	}
9641 
9642 	return error;
9643 }
9644 
9645 static int
necp_arena_stats_obj_alloc(struct necp_fd_data * fd_data,mach_vm_offset_t * off,struct necp_arena_info ** stats_arena,void ** kstats_kaddr,boolean_t cansleep)9646 necp_arena_stats_obj_alloc(struct necp_fd_data *fd_data,
9647     mach_vm_offset_t *off,
9648     struct necp_arena_info **stats_arena,
9649     void **kstats_kaddr,
9650     boolean_t cansleep)
9651 {
9652 	struct skmem_cache *kstats_cp = NULL;
9653 	void *ustats_obj = NULL;
9654 	void *kstats_obj = NULL;
9655 	struct necp_all_kstats *kstats = NULL;
9656 	struct skmem_obj_info kstats_oi = {};
9657 
9658 	ASSERT(off != NULL);
9659 	ASSERT(stats_arena != NULL && *stats_arena == NULL);
9660 	ASSERT(kstats_kaddr != NULL && *kstats_kaddr == NULL);
9661 
9662 	NECP_FD_ASSERT_LOCKED(fd_data);
9663 	ASSERT(fd_data->stats_arena_active != NULL);
9664 	ASSERT(fd_data->stats_arena_active->nai_arena != NULL);
9665 
9666 	kstats_cp = skmem_arena_necp(fd_data->stats_arena_active->nai_arena)->arc_kstats_cache;
9667 	if ((kstats_obj = skmem_cache_alloc(kstats_cp, (cansleep ? SKMEM_SLEEP : SKMEM_NOSLEEP))) == NULL) {
9668 		return ENOMEM;
9669 	}
9670 
9671 	kstats = (struct necp_all_kstats*)kstats_obj;
9672 	ustats_obj = kstats->necp_stats_ustats;
9673 
9674 	skmem_cache_get_obj_info(kstats_cp, kstats_obj, &kstats_oi, NULL);
9675 	ASSERT(SKMEM_OBJ_SIZE(&kstats_oi) >= sizeof(struct necp_all_stats));
9676 	// reset all stats counters
9677 	bzero(ustats_obj, SKMEM_OBJ_SIZE(&kstats_oi));
9678 	bzero(&kstats->necp_stats_comm, sizeof(struct necp_all_stats));
9679 	*stats_arena = fd_data->stats_arena_active;
9680 	*kstats_kaddr = kstats_obj;
9681 	// kstats and ustats are mirrored and have the same offset
9682 	*off = fd_data->stats_arena_active->nai_roff + SKMEM_OBJ_ROFF(&kstats_oi);
9683 
9684 	return 0;
9685 }
9686 
9687 static void
necp_arena_stats_obj_free(struct necp_fd_data * fd_data,struct necp_arena_info * stats_arena,void ** kstats_kaddr,mach_vm_address_t * ustats_uaddr)9688 necp_arena_stats_obj_free(struct necp_fd_data *fd_data, struct necp_arena_info *stats_arena, void **kstats_kaddr, mach_vm_address_t *ustats_uaddr)
9689 {
9690 #pragma unused(fd_data)
9691 	NECP_FD_ASSERT_LOCKED(fd_data);
9692 
9693 	ASSERT(stats_arena != NULL);
9694 	ASSERT(stats_arena->nai_arena != NULL);
9695 	ASSERT(kstats_kaddr != NULL && *kstats_kaddr != NULL);
9696 	ASSERT(ustats_uaddr != NULL);
9697 
9698 	skmem_cache_free(skmem_arena_necp(stats_arena->nai_arena)->arc_kstats_cache, *kstats_kaddr);
9699 	*kstats_kaddr = NULL;
9700 	*ustats_uaddr = 0;
9701 }
9702 
9703 // This routine returns the KVA of the sysctls object, as well as the
9704 // offset of that object relative to the mmap base address for the
9705 // task/process.
9706 static void *
necp_arena_sysctls_obj(struct necp_fd_data * fd_data,mach_vm_offset_t * off,size_t * size)9707 necp_arena_sysctls_obj(struct necp_fd_data *fd_data, mach_vm_offset_t *off, size_t *size)
9708 {
9709 	void *objaddr;
9710 
9711 	NECP_FD_ASSERT_LOCKED(fd_data);
9712 	ASSERT(fd_data->sysctl_arena != NULL);
9713 
9714 	// kernel virtual address of the sysctls object
9715 	objaddr = skmem_arena_system_sysctls_obj_addr(fd_data->sysctl_arena);
9716 	ASSERT(objaddr != NULL);
9717 
9718 	// Return the relative offset of the sysctls object; there is
9719 	// only 1 object in the entire sysctls region, and therefore the
9720 	// object's offset is simply the region's offset in the arena.
9721 	// (sysctl_mmap.ami_mapaddr + offset) is the address of this object
9722 	// in the task/process.
9723 	if (off != NULL) {
9724 		*off = fd_data->system_sysctls_roff;
9725 	}
9726 
9727 	if (size != NULL) {
9728 		*size = skmem_arena_system_sysctls_obj_size(fd_data->sysctl_arena);
9729 		ASSERT(*size != 0);
9730 	}
9731 
9732 	return objaddr;
9733 }
9734 
9735 static void
necp_stats_arenas_destroy(struct necp_fd_data * fd_data,boolean_t closing)9736 necp_stats_arenas_destroy(struct necp_fd_data *fd_data, boolean_t closing)
9737 {
9738 	struct necp_arena_info *nai, *nai_tmp;
9739 
9740 	NECP_FD_ASSERT_LOCKED(fd_data);
9741 
9742 	// If reaping (not closing), release reference only for idle active arena; the reference
9743 	// count must be 2 by now, when it's not being referred to by any clients/flows.
9744 	if ((nai = fd_data->stats_arena_active) != NULL && (closing || nai->nai_use_count == 2)) {
9745 		VERIFY(nai->nai_use_count >= 2);
9746 		necp_arena_info_release(nai);   // for fd_data
9747 		fd_data->stats_arena_active = NULL;
9748 	}
9749 
9750 	// clean up any defunct arenas left in the list
9751 	LIST_FOREACH_SAFE(nai, &fd_data->stats_arena_list, nai_chain, nai_tmp) {
9752 		// If reaping, release reference if the list holds the last one
9753 		if (closing || nai->nai_use_count == 1) {
9754 			VERIFY(nai->nai_use_count >= 1);
9755 			// callee unchains nai (and may free it)
9756 			necp_fd_remove_stats_arena(fd_data, nai);
9757 		}
9758 	}
9759 }
9760 
9761 static void
necp_sysctl_arena_destroy(struct necp_fd_data * fd_data)9762 necp_sysctl_arena_destroy(struct necp_fd_data *fd_data)
9763 {
9764 	NECP_FD_ASSERT_LOCKED(fd_data);
9765 
9766 	// NOTE: destroying the arena requires that all outstanding objects
9767 	// that were allocated have been freed, else it will assert.
9768 	if (fd_data->sysctl_arena != NULL) {
9769 		skmem_arena_munmap(fd_data->sysctl_arena, &fd_data->sysctl_mmap);
9770 		skmem_arena_release(fd_data->sysctl_arena);
9771 		OSDecrementAtomic(&necp_sysctl_arena_count);
9772 		fd_data->sysctl_arena = NULL;
9773 		fd_data->system_sysctls_roff = 0;
9774 	}
9775 }
9776 
9777 static int
necp_arena_initialize(struct necp_fd_data * fd_data,bool locked)9778 necp_arena_initialize(struct necp_fd_data *fd_data, bool locked)
9779 {
9780 	int error = 0;
9781 	size_t stats_obj_size = MAX(sizeof(struct necp_all_stats), sizeof(struct necp_all_kstats));
9782 
9783 	if (!locked) {
9784 		NECP_FD_LOCK(fd_data);
9785 	}
9786 	if (fd_data->stats_arena_active == NULL) {
9787 		error = necp_arena_create(fd_data, stats_obj_size,
9788 		    NECP_MAX_PER_PROCESS_CLIENT_STATISTICS_STRUCTS,
9789 		    current_proc());
9790 	}
9791 	if (!locked) {
9792 		NECP_FD_UNLOCK(fd_data);
9793 	}
9794 
9795 	return error;
9796 }
9797 
9798 static int
necp_sysctl_arena_initialize(struct necp_fd_data * fd_data,bool locked)9799 necp_sysctl_arena_initialize(struct necp_fd_data *fd_data, bool locked)
9800 {
9801 	int error = 0;
9802 
9803 	if (!locked) {
9804 		NECP_FD_LOCK(fd_data);
9805 	}
9806 
9807 	NECP_FD_ASSERT_LOCKED(fd_data);
9808 
9809 	if (fd_data->sysctl_arena == NULL) {
9810 		char name[32];
9811 		struct proc *p = current_proc();
9812 
9813 		ASSERT(p != PROC_NULL);
9814 		ASSERT(proc_pid(p) == fd_data->proc_pid);
9815 
9816 		(void) snprintf(name, sizeof(name), "sysctl.%s.%d", proc_name_address(p), fd_data->proc_pid);
9817 		fd_data->sysctl_arena = skmem_arena_create_for_system(name, &error);
9818 		ASSERT(fd_data->sysctl_arena != NULL || error != 0);
9819 		if (error != 0) {
9820 			NECPLOG(LOG_ERR, "failed to create arena for pid %d\n", fd_data->proc_pid);
9821 		} else {
9822 			OSIncrementAtomic(&necp_sysctl_arena_count);
9823 
9824 			// Get region offsets from base of mmap span; the arena
9825 			// doesn't need to be mmap'd at this point, since we simply
9826 			// compute the relative offset.
9827 			fd_data->system_sysctls_roff = skmem_arena_get_region_offset(fd_data->sysctl_arena, SKMEM_REGION_SYSCTLS);
9828 
9829 			// map to the task/process; upon success, the base address of the region
9830 			// will be returned in nai_mmap.ami_mapaddr; this can be communicated to
9831 			// the process.
9832 			error = skmem_arena_mmap(fd_data->sysctl_arena, p, &fd_data->sysctl_mmap);
9833 			if (error != 0) {
9834 				NECPLOG(LOG_ERR, "failed to map sysctl arena for pid %d\n", fd_data->proc_pid);
9835 				necp_sysctl_arena_destroy(fd_data);
9836 			}
9837 		}
9838 	}
9839 
9840 	if (!locked) {
9841 		NECP_FD_UNLOCK(fd_data);
9842 	}
9843 
9844 	return error;
9845 }
9846 
9847 static int
necp_client_stats_bufreq(struct necp_fd_data * fd_data,struct necp_client * client,struct necp_client_flow_registration * flow_registration,struct necp_stats_bufreq * bufreq,struct necp_stats_hdr * out_header)9848 necp_client_stats_bufreq(struct necp_fd_data *fd_data,
9849     struct necp_client *client,
9850     struct necp_client_flow_registration *flow_registration,
9851     struct necp_stats_bufreq *bufreq,
9852     struct necp_stats_hdr *out_header)
9853 {
9854 	int error = 0;
9855 	NECP_CLIENT_ASSERT_LOCKED(client);
9856 	NECP_FD_ASSERT_LOCKED(fd_data);
9857 
9858 	if ((bufreq->necp_stats_bufreq_id == NECP_CLIENT_STATISTICS_BUFREQ_ID) &&
9859 	    ((bufreq->necp_stats_bufreq_type == NECP_CLIENT_STATISTICS_TYPE_TCP &&
9860 	    bufreq->necp_stats_bufreq_ver == NECP_CLIENT_STATISTICS_TYPE_TCP_CURRENT_VER) ||
9861 	    (bufreq->necp_stats_bufreq_type == NECP_CLIENT_STATISTICS_TYPE_UDP &&
9862 	    bufreq->necp_stats_bufreq_ver == NECP_CLIENT_STATISTICS_TYPE_UDP_CURRENT_VER) ||
9863 	    (bufreq->necp_stats_bufreq_type == NECP_CLIENT_STATISTICS_TYPE_QUIC &&
9864 	    bufreq->necp_stats_bufreq_ver == NECP_CLIENT_STATISTICS_TYPE_QUIC_CURRENT_VER)) &&
9865 	    (bufreq->necp_stats_bufreq_size == sizeof(struct necp_all_stats))) {
9866 		// There should be one and only one stats allocation per client.
9867 		// If asked more than once, we just repeat ourselves.
9868 		if (flow_registration->ustats_uaddr == 0) {
9869 			mach_vm_offset_t off;
9870 			ASSERT(flow_registration->stats_arena == NULL);
9871 			ASSERT(flow_registration->kstats_kaddr == NULL);
9872 			ASSERT(flow_registration->ustats_uaddr == 0);
9873 			error = necp_arena_stats_obj_alloc(fd_data, &off, &flow_registration->stats_arena, &flow_registration->kstats_kaddr, FALSE);
9874 			if (error == 0) {
9875 				// upon success, hold a reference for the client; this is released when the client is removed/closed
9876 				ASSERT(flow_registration->stats_arena != NULL);
9877 				necp_arena_info_retain(flow_registration->stats_arena);
9878 
9879 				// compute user address based on mapping info and object offset
9880 				flow_registration->ustats_uaddr = flow_registration->stats_arena->nai_mmap.ami_mapaddr + off;
9881 
9882 				// add to collect_stats list
9883 				NECP_STATS_LIST_LOCK_EXCLUSIVE();
9884 				necp_client_retain_locked(client); // Add a reference to the client
9885 				LIST_INSERT_HEAD(&necp_collect_stats_flow_list, flow_registration, collect_stats_chain);
9886 				NECP_STATS_LIST_UNLOCK();
9887 				necp_schedule_collect_stats_clients(FALSE);
9888 			} else {
9889 				ASSERT(flow_registration->stats_arena == NULL);
9890 				ASSERT(flow_registration->kstats_kaddr == NULL);
9891 			}
9892 		}
9893 		if (flow_registration->ustats_uaddr != 0) {
9894 			ASSERT(error == 0);
9895 			ASSERT(flow_registration->stats_arena != NULL);
9896 			ASSERT(flow_registration->kstats_kaddr != NULL);
9897 
9898 			struct necp_all_kstats *kstats = (struct necp_all_kstats *)flow_registration->kstats_kaddr;
9899 			kstats->necp_stats_ustats->all_stats_u.tcp_stats.necp_tcp_hdr.necp_stats_type = bufreq->necp_stats_bufreq_type;
9900 			kstats->necp_stats_ustats->all_stats_u.tcp_stats.necp_tcp_hdr.necp_stats_ver = bufreq->necp_stats_bufreq_ver;
9901 
9902 			if (out_header) {
9903 				out_header->necp_stats_type = bufreq->necp_stats_bufreq_type;
9904 				out_header->necp_stats_ver = bufreq->necp_stats_bufreq_ver;
9905 			}
9906 
9907 			bufreq->necp_stats_bufreq_uaddr = flow_registration->ustats_uaddr;
9908 		}
9909 	} else {
9910 		error = EINVAL;
9911 	}
9912 
9913 	return error;
9914 }
9915 
9916 static int
necp_client_stats_initial(struct necp_client_flow_registration * flow_registration,uint32_t stats_type,uint32_t stats_ver)9917 necp_client_stats_initial(struct necp_client_flow_registration *flow_registration, uint32_t stats_type, uint32_t stats_ver)
9918 {
9919 	// An attempted create
9920 	assert(flow_registration->stats_handler_context == NULL);
9921 	assert(flow_registration->stats_arena);
9922 	assert(flow_registration->ustats_uaddr);
9923 	assert(flow_registration->kstats_kaddr);
9924 
9925 	int error = 0;
9926 	uint64_t ntstat_properties = necp_find_netstat_initial_properties(flow_registration->client);
9927 
9928 	switch (stats_type) {
9929 	case NECP_CLIENT_STATISTICS_TYPE_TCP: {
9930 		if (stats_ver == NECP_CLIENT_STATISTICS_TYPE_TCP_VER_1) {
9931 			flow_registration->stats_handler_context = ntstat_userland_stats_open((userland_stats_provider_context *)flow_registration,
9932 			    NSTAT_PROVIDER_TCP_USERLAND, ntstat_properties, necp_request_tcp_netstats, necp_find_extension_info);
9933 			if (flow_registration->stats_handler_context == NULL) {
9934 				error = EIO;
9935 			}
9936 		} else {
9937 			error = ENOTSUP;
9938 		}
9939 		break;
9940 	}
9941 	case NECP_CLIENT_STATISTICS_TYPE_UDP: {
9942 		if (stats_ver == NECP_CLIENT_STATISTICS_TYPE_UDP_VER_1) {
9943 			flow_registration->stats_handler_context = ntstat_userland_stats_open((userland_stats_provider_context *)flow_registration,
9944 			    NSTAT_PROVIDER_UDP_USERLAND, ntstat_properties, necp_request_udp_netstats, necp_find_extension_info);
9945 			if (flow_registration->stats_handler_context == NULL) {
9946 				error = EIO;
9947 			}
9948 		} else {
9949 			error = ENOTSUP;
9950 		}
9951 		break;
9952 	}
9953 	case NECP_CLIENT_STATISTICS_TYPE_QUIC: {
9954 		if (stats_ver == NECP_CLIENT_STATISTICS_TYPE_QUIC_VER_1 && flow_registration->flags & NECP_CLIENT_FLOW_FLAGS_ALLOW_NEXUS) {
9955 			flow_registration->stats_handler_context = ntstat_userland_stats_open((userland_stats_provider_context *)flow_registration,
9956 			    NSTAT_PROVIDER_QUIC_USERLAND, ntstat_properties, necp_request_quic_netstats, necp_find_extension_info);
9957 			if (flow_registration->stats_handler_context == NULL) {
9958 				error = EIO;
9959 			}
9960 		} else {
9961 			error = ENOTSUP;
9962 		}
9963 		break;
9964 	}
9965 	default: {
9966 		error = ENOTSUP;
9967 		break;
9968 	}
9969 	}
9970 	return error;
9971 }
9972 
9973 static int
necp_stats_initialize(struct necp_fd_data * fd_data,struct necp_client * client,struct necp_client_flow_registration * flow_registration,struct necp_stats_bufreq * bufreq)9974 necp_stats_initialize(struct necp_fd_data *fd_data,
9975     struct necp_client *client,
9976     struct necp_client_flow_registration *flow_registration,
9977     struct necp_stats_bufreq *bufreq)
9978 {
9979 	int error = 0;
9980 	struct necp_stats_hdr stats_hdr = {};
9981 
9982 	NECP_CLIENT_ASSERT_LOCKED(client);
9983 	NECP_FD_ASSERT_LOCKED(fd_data);
9984 	VERIFY(fd_data->stats_arena_active != NULL);
9985 	VERIFY(fd_data->stats_arena_active->nai_arena != NULL);
9986 	VERIFY(!(fd_data->stats_arena_active->nai_flags & (NAIF_REDIRECT | NAIF_DEFUNCT)));
9987 
9988 	if (bufreq == NULL) {
9989 		return EINVAL;
9990 	}
9991 
9992 	// Setup stats region
9993 	error = necp_client_stats_bufreq(fd_data, client, flow_registration, bufreq, &stats_hdr);
9994 	if (error) {
9995 		return error;
9996 	}
9997 	// Notify ntstat about new flow
9998 	if (flow_registration->stats_handler_context == NULL) {
9999 		error = necp_client_stats_initial(flow_registration, stats_hdr.necp_stats_type, stats_hdr.necp_stats_ver);
10000 		if (flow_registration->stats_handler_context != NULL) {
10001 			ntstat_userland_stats_event(flow_registration->stats_handler_context, NECP_CLIENT_STATISTICS_EVENT_INIT);
10002 		}
10003 		NECP_CLIENT_FLOW_LOG(client, flow_registration, "Initialized stats <error %d>", error);
10004 	}
10005 
10006 	return error;
10007 }
10008 
10009 static NECP_CLIENT_ACTION_FUNCTION int
necp_client_map_sysctls(__unused struct necp_fd_data * fd_data,struct necp_client_action_args * uap,int * retval)10010 necp_client_map_sysctls(__unused struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
10011 {
10012 	int result = 0;
10013 	if (!retval) {
10014 		retval = &result;
10015 	}
10016 
10017 	do {
10018 		mach_vm_address_t uaddr = 0;
10019 		if (uap->buffer_size != sizeof(uaddr)) {
10020 			*retval = EINVAL;
10021 			break;
10022 		}
10023 
10024 		*retval = necp_sysctl_arena_initialize(fd_data, false);
10025 		if (*retval != 0) {
10026 			break;
10027 		}
10028 
10029 		mach_vm_offset_t off = 0;
10030 		void *location = NULL;
10031 		NECP_FD_LOCK(fd_data);
10032 		location = necp_arena_sysctls_obj(fd_data, &off, NULL);
10033 		NECP_FD_UNLOCK(fd_data);
10034 
10035 		if (location == NULL) {
10036 			*retval = ENOENT;
10037 			break;
10038 		}
10039 
10040 		uaddr = fd_data->sysctl_mmap.ami_mapaddr + off;
10041 		*retval = copyout(&uaddr, uap->buffer, sizeof(uaddr));
10042 	} while (false);
10043 
10044 	return *retval;
10045 }
10046 
10047 #endif /* !SKYWALK */
10048 
10049 static NECP_CLIENT_ACTION_FUNCTION int
necp_client_copy_route_statistics(__unused struct necp_fd_data * fd_data,struct necp_client_action_args * uap,int * retval)10050 necp_client_copy_route_statistics(__unused struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
10051 {
10052 	int error = 0;
10053 	struct necp_client *client = NULL;
10054 	uuid_t client_id;
10055 
10056 	if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t) ||
10057 	    uap->buffer_size < sizeof(struct necp_stat_counts) || uap->buffer == 0) {
10058 		NECPLOG0(LOG_ERR, "necp_client_copy_route_statistics bad input");
10059 		error = EINVAL;
10060 		goto done;
10061 	}
10062 
10063 	error = copyin(uap->client_id, client_id, sizeof(uuid_t));
10064 	if (error) {
10065 		NECPLOG(LOG_ERR, "necp_client_copy_route_statistics copyin client_id error (%d)", error);
10066 		goto done;
10067 	}
10068 
10069 	// Lock
10070 	NECP_FD_LOCK(fd_data);
10071 	client = necp_client_fd_find_client_and_lock(fd_data, client_id);
10072 	if (client != NULL) {
10073 		NECP_CLIENT_ROUTE_LOCK(client);
10074 		struct necp_stat_counts route_stats = {};
10075 		if (client->current_route != NULL && client->current_route->rt_stats != NULL) {
10076 			struct nstat_counts     *rt_stats = client->current_route->rt_stats;
10077 			route_stats.necp_stat_rxpackets = os_atomic_load(&rt_stats->nstat_rxpackets, relaxed);
10078 			route_stats.necp_stat_rxbytes = os_atomic_load(&rt_stats->nstat_rxbytes, relaxed);
10079 			route_stats.necp_stat_txpackets = os_atomic_load(&rt_stats->nstat_txpackets, relaxed);
10080 			route_stats.necp_stat_txbytes = os_atomic_load(&rt_stats->nstat_txbytes, relaxed);
10081 			route_stats.necp_stat_rxduplicatebytes = rt_stats->nstat_rxduplicatebytes;
10082 			route_stats.necp_stat_rxoutoforderbytes = rt_stats->nstat_rxoutoforderbytes;
10083 			route_stats.necp_stat_txretransmit = rt_stats->nstat_txretransmit;
10084 			route_stats.necp_stat_connectattempts = rt_stats->nstat_connectattempts;
10085 			route_stats.necp_stat_connectsuccesses = rt_stats->nstat_connectsuccesses;
10086 			route_stats.necp_stat_min_rtt = rt_stats->nstat_min_rtt;
10087 			route_stats.necp_stat_avg_rtt = rt_stats->nstat_avg_rtt;
10088 			route_stats.necp_stat_var_rtt = rt_stats->nstat_var_rtt;
10089 			route_stats.necp_stat_route_flags = client->current_route->rt_flags;
10090 		}
10091 
10092 		// Unlock before copying out
10093 		NECP_CLIENT_ROUTE_UNLOCK(client);
10094 		NECP_CLIENT_UNLOCK(client);
10095 		NECP_FD_UNLOCK(fd_data);
10096 
10097 		error = copyout(&route_stats, uap->buffer, sizeof(route_stats));
10098 		if (error) {
10099 			NECPLOG(LOG_ERR, "necp_client_copy_route_statistics copyout error (%d)", error);
10100 		}
10101 	} else {
10102 		// Unlock
10103 		NECP_FD_UNLOCK(fd_data);
10104 		error = ENOENT;
10105 	}
10106 
10107 
10108 done:
10109 	*retval = error;
10110 	return error;
10111 }
10112 
10113 static NECP_CLIENT_ACTION_FUNCTION int
necp_client_update_cache(struct necp_fd_data * fd_data,struct necp_client_action_args * uap,int * retval)10114 necp_client_update_cache(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
10115 {
10116 	int error = 0;
10117 	struct necp_client *client = NULL;
10118 	uuid_t client_id;
10119 
10120 	if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t)) {
10121 		error = EINVAL;
10122 		goto done;
10123 	}
10124 
10125 	error = copyin(uap->client_id, client_id, sizeof(uuid_t));
10126 	if (error) {
10127 		NECPLOG(LOG_ERR, "necp_client_update_cache copyin client_id error (%d)", error);
10128 		goto done;
10129 	}
10130 
10131 	NECP_FD_LOCK(fd_data);
10132 	client = necp_client_fd_find_client_and_lock(fd_data, client_id);
10133 	if (client == NULL) {
10134 		NECP_FD_UNLOCK(fd_data);
10135 		error = ENOENT;
10136 		goto done;
10137 	}
10138 
10139 	struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
10140 	if (flow_registration == NULL) {
10141 		NECP_CLIENT_UNLOCK(client);
10142 		NECP_FD_UNLOCK(fd_data);
10143 		error = ENOENT;
10144 		goto done;
10145 	}
10146 
10147 	NECP_CLIENT_ROUTE_LOCK(client);
10148 	// This needs to be changed when TFO/ECN is supported by multiple flows
10149 	struct necp_client_flow *flow = LIST_FIRST(&flow_registration->flow_list);
10150 	if (flow == NULL ||
10151 	    (flow->remote_addr.sa.sa_family != AF_INET &&
10152 	    flow->remote_addr.sa.sa_family != AF_INET6) ||
10153 	    (flow->local_addr.sa.sa_family != AF_INET &&
10154 	    flow->local_addr.sa.sa_family != AF_INET6)) {
10155 		error = EINVAL;
10156 		NECPLOG(LOG_ERR, "necp_client_update_cache no flow error (%d)", error);
10157 		goto done_unlock;
10158 	}
10159 
10160 	necp_cache_buffer cache_buffer;
10161 	memset(&cache_buffer, 0, sizeof(cache_buffer));
10162 
10163 	if (uap->buffer_size != sizeof(necp_cache_buffer) ||
10164 	    uap->buffer == USER_ADDR_NULL) {
10165 		error = EINVAL;
10166 		goto done_unlock;
10167 	}
10168 
10169 	error = copyin(uap->buffer, &cache_buffer, sizeof(cache_buffer));
10170 	if (error) {
10171 		NECPLOG(LOG_ERR, "necp_client_update_cache copyin cache buffer error (%d)", error);
10172 		goto done_unlock;
10173 	}
10174 
10175 	if (cache_buffer.necp_cache_buf_type == NECP_CLIENT_CACHE_TYPE_ECN &&
10176 	    cache_buffer.necp_cache_buf_ver == NECP_CLIENT_CACHE_TYPE_ECN_VER_1) {
10177 		if (cache_buffer.necp_cache_buf_size != sizeof(necp_tcp_ecn_cache) ||
10178 		    cache_buffer.necp_cache_buf_addr == USER_ADDR_NULL) {
10179 			error = EINVAL;
10180 			goto done_unlock;
10181 		}
10182 
10183 		necp_tcp_ecn_cache ecn_cache_buffer;
10184 		memset(&ecn_cache_buffer, 0, sizeof(ecn_cache_buffer));
10185 
10186 		error = copyin(cache_buffer.necp_cache_buf_addr, &ecn_cache_buffer, sizeof(necp_tcp_ecn_cache));
10187 		if (error) {
10188 			NECPLOG(LOG_ERR, "necp_client_update_cache copyin ecn cache buffer error (%d)", error);
10189 			goto done_unlock;
10190 		}
10191 
10192 		if (client->current_route != NULL && client->current_route->rt_ifp != NULL) {
10193 			if (!client->platform_binary) {
10194 				ecn_cache_buffer.necp_tcp_ecn_heuristics_success = 0;
10195 			}
10196 			tcp_heuristics_ecn_update(&ecn_cache_buffer, client->current_route->rt_ifp,
10197 			    (union sockaddr_in_4_6 *)&flow->local_addr);
10198 		}
10199 	} else if (cache_buffer.necp_cache_buf_type == NECP_CLIENT_CACHE_TYPE_TFO &&
10200 	    cache_buffer.necp_cache_buf_ver == NECP_CLIENT_CACHE_TYPE_TFO_VER_1) {
10201 		if (cache_buffer.necp_cache_buf_size != sizeof(necp_tcp_tfo_cache) ||
10202 		    cache_buffer.necp_cache_buf_addr == USER_ADDR_NULL) {
10203 			error = EINVAL;
10204 			goto done_unlock;
10205 		}
10206 
10207 		necp_tcp_tfo_cache tfo_cache_buffer;
10208 		memset(&tfo_cache_buffer, 0, sizeof(tfo_cache_buffer));
10209 
10210 		error = copyin(cache_buffer.necp_cache_buf_addr, &tfo_cache_buffer, sizeof(necp_tcp_tfo_cache));
10211 		if (error) {
10212 			NECPLOG(LOG_ERR, "necp_client_update_cache copyin tfo cache buffer error (%d)", error);
10213 			goto done_unlock;
10214 		}
10215 
10216 		if (client->current_route != NULL && client->current_route->rt_ifp != NULL) {
10217 			if (!client->platform_binary) {
10218 				tfo_cache_buffer.necp_tcp_tfo_heuristics_success = 0;
10219 			}
10220 			tcp_heuristics_tfo_update(&tfo_cache_buffer, client->current_route->rt_ifp,
10221 			    (union sockaddr_in_4_6 *)&flow->local_addr,
10222 			    (union sockaddr_in_4_6 *)&flow->remote_addr);
10223 		}
10224 	} else {
10225 		error = EINVAL;
10226 	}
10227 done_unlock:
10228 	NECP_CLIENT_ROUTE_UNLOCK(client);
10229 	NECP_CLIENT_UNLOCK(client);
10230 	NECP_FD_UNLOCK(fd_data);
10231 done:
10232 	*retval = error;
10233 	return error;
10234 }
10235 
10236 // Most results will fit into this size
10237 struct necp_client_signable_default {
10238 	uuid_t client_id;
10239 	u_int32_t sign_type;
10240 	u_int8_t signable_data[NECP_CLIENT_ACTION_SIGN_DEFAULT_DATA_LENGTH];
10241 } __attribute__((__packed__));
10242 
10243 static NECP_CLIENT_ACTION_FUNCTION int
necp_client_sign(__unused struct necp_fd_data * fd_data,struct necp_client_action_args * uap,int * retval)10244 necp_client_sign(__unused struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
10245 {
10246 	int error = 0;
10247 	u_int8_t tag[NECP_CLIENT_ACTION_SIGN_TAG_LENGTH] = {};
10248 	struct necp_client_signable *signable = NULL;
10249 	struct necp_client_signable *allocated_signable = NULL;
10250 	struct necp_client_signable_default default_signable = {};
10251 	size_t tag_size = sizeof(tag);
10252 
10253 	const size_t signable_length = uap->client_id_len;
10254 	const size_t return_tag_length = uap->buffer_size;
10255 
10256 	*retval = 0;
10257 
10258 	const bool has_resolver_entitlement = (priv_check_cred(kauth_cred_get(), PRIV_NET_VALIDATED_RESOLVER, 0) == 0);
10259 	if (!has_resolver_entitlement) {
10260 		NECPLOG0(LOG_ERR, "Process does not hold the necessary entitlement to sign resolver answers");
10261 		error = EPERM;
10262 		goto done;
10263 	}
10264 
10265 	if (uap->client_id == 0 || signable_length < sizeof(*signable) || signable_length > NECP_CLIENT_ACTION_SIGN_MAX_TOTAL_LENGTH) {
10266 		error = EINVAL;
10267 		goto done;
10268 	}
10269 
10270 	if (uap->buffer == 0 || return_tag_length != NECP_CLIENT_ACTION_SIGN_TAG_LENGTH) {
10271 		error = EINVAL;
10272 		goto done;
10273 	}
10274 
10275 	if (signable_length <= sizeof(default_signable)) {
10276 		signable = (struct necp_client_signable *)&default_signable;
10277 	} else {
10278 		if ((allocated_signable = (struct necp_client_signable *)kalloc_data(signable_length, Z_WAITOK | Z_ZERO)) == NULL) {
10279 			NECPLOG(LOG_ERR, "necp_client_sign allocate signable %zu failed", signable_length);
10280 			error = ENOMEM;
10281 			goto done;
10282 		}
10283 		signable = allocated_signable;
10284 	}
10285 
10286 	error = copyin(uap->client_id, signable, signable_length);
10287 	if (error) {
10288 		NECPLOG(LOG_ERR, "necp_client_sign copyin signable error (%d)", error);
10289 		goto done;
10290 	}
10291 
10292 	size_t data_length = 0;
10293 	switch (signable->sign_type) {
10294 	case NECP_CLIENT_SIGN_TYPE_RESOLVER_ANSWER:
10295 	case NECP_CLIENT_SIGN_TYPE_SYSTEM_RESOLVER_ANSWER: {
10296 		data_length = (sizeof(struct necp_client_host_resolver_answer) - sizeof(struct necp_client_signable));
10297 		if (signable_length < (sizeof(struct necp_client_signable) + data_length)) {
10298 			error = EINVAL;
10299 			goto done;
10300 		}
10301 		struct necp_client_host_resolver_answer *signable_struct = (struct necp_client_host_resolver_answer *)signable;
10302 		if (signable_struct->hostname_length > NECP_CLIENT_ACTION_SIGN_MAX_STRING_LENGTH ||
10303 		    signable_length != (sizeof(struct necp_client_signable) + data_length + signable_struct->hostname_length)) {
10304 			error = EINVAL;
10305 			goto done;
10306 		}
10307 		data_length += signable_struct->hostname_length;
10308 		break;
10309 	}
10310 	case NECP_CLIENT_SIGN_TYPE_BROWSE_RESULT:
10311 	case NECP_CLIENT_SIGN_TYPE_SYSTEM_BROWSE_RESULT: {
10312 		data_length = (sizeof(struct necp_client_browse_result) - sizeof(struct necp_client_signable));
10313 		if (signable_length < (sizeof(struct necp_client_signable) + data_length)) {
10314 			error = EINVAL;
10315 			goto done;
10316 		}
10317 		struct necp_client_browse_result *signable_struct = (struct necp_client_browse_result *)signable;
10318 		if (signable_struct->service_length > NECP_CLIENT_ACTION_SIGN_MAX_STRING_LENGTH ||
10319 		    signable_length != (sizeof(struct necp_client_signable) + data_length + signable_struct->service_length)) {
10320 			error = EINVAL;
10321 			goto done;
10322 		}
10323 		data_length += signable_struct->service_length;
10324 		break;
10325 	}
10326 	case NECP_CLIENT_SIGN_TYPE_SERVICE_RESOLVER_ANSWER:
10327 	case NECP_CLIENT_SIGN_TYPE_SYSTEM_SERVICE_RESOLVER_ANSWER: {
10328 		data_length = (sizeof(struct necp_client_service_resolver_answer) - sizeof(struct necp_client_signable));
10329 		if (signable_length < (sizeof(struct necp_client_signable) + data_length)) {
10330 			error = EINVAL;
10331 			goto done;
10332 		}
10333 		struct necp_client_service_resolver_answer *signable_struct = (struct necp_client_service_resolver_answer *)signable;
10334 		if (signable_struct->service_length > NECP_CLIENT_ACTION_SIGN_MAX_STRING_LENGTH ||
10335 		    signable_struct->hostname_length > NECP_CLIENT_ACTION_SIGN_MAX_STRING_LENGTH ||
10336 		    signable_length != (sizeof(struct necp_client_signable) + data_length + signable_struct->service_length + signable_struct->hostname_length)) {
10337 			error = EINVAL;
10338 			goto done;
10339 		}
10340 		data_length += signable_struct->service_length;
10341 		data_length += signable_struct->hostname_length;
10342 		break;
10343 	}
10344 	default: {
10345 		NECPLOG(LOG_ERR, "necp_client_sign unknown signable type (%u)", signable->sign_type);
10346 		error = EINVAL;
10347 		goto done;
10348 	}
10349 	}
10350 
10351 	error = necp_sign_resolver_answer(signable->client_id, signable->sign_type,
10352 	    signable->signable_data, data_length,
10353 	    tag, &tag_size);
10354 	if (tag_size != sizeof(tag)) {
10355 		NECPLOG(LOG_ERR, "necp_client_sign unexpected tag size %zu", tag_size);
10356 		error = EINVAL;
10357 		goto done;
10358 	}
10359 	error = copyout(tag, uap->buffer, tag_size);
10360 	if (error) {
10361 		NECPLOG(LOG_ERR, "necp_client_sign copyout error (%d)", error);
10362 		goto done;
10363 	}
10364 
10365 done:
10366 	if (allocated_signable != NULL) {
10367 		kfree_data(allocated_signable, signable_length);
10368 		allocated_signable = NULL;
10369 	}
10370 	*retval = error;
10371 	return error;
10372 }
10373 
10374 // Most results will fit into this size
10375 struct necp_client_validatable_default {
10376 	struct necp_client_signature signature;
10377 	struct necp_client_signable_default signable;
10378 } __attribute__((__packed__));
10379 
10380 static NECP_CLIENT_ACTION_FUNCTION int
necp_client_validate(__unused struct necp_fd_data * fd_data,struct necp_client_action_args * uap,int * retval)10381 necp_client_validate(__unused struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
10382 {
10383 	int error = 0;
10384 	struct necp_client_validatable *validatable = NULL;
10385 	struct necp_client_validatable *allocated_validatable = NULL;
10386 	struct necp_client_validatable_default default_validatable = {};
10387 
10388 	const size_t validatable_length = uap->client_id_len;
10389 
10390 	*retval = 0;
10391 
10392 	const bool has_resolver_entitlement = (priv_check_cred(kauth_cred_get(), PRIV_NET_VALIDATED_RESOLVER, 0) == 0);
10393 	if (!has_resolver_entitlement) {
10394 		NECPLOG0(LOG_ERR, "Process does not hold the necessary entitlement to directly validate resolver answers");
10395 		error = EPERM;
10396 		goto done;
10397 	}
10398 
10399 	if (uap->client_id == 0 || validatable_length < sizeof(*validatable) ||
10400 	    validatable_length > (NECP_CLIENT_ACTION_SIGN_MAX_TOTAL_LENGTH + NECP_CLIENT_ACTION_SIGN_TAG_LENGTH)) {
10401 		error = EINVAL;
10402 		goto done;
10403 	}
10404 
10405 	if (validatable_length <= sizeof(default_validatable)) {
10406 		validatable = (struct necp_client_validatable *)&default_validatable;
10407 	} else {
10408 		if ((allocated_validatable = (struct necp_client_validatable *)kalloc_data(validatable_length, Z_WAITOK | Z_ZERO)) == NULL) {
10409 			NECPLOG(LOG_ERR, "necp_client_validate allocate struct %zu failed", validatable_length);
10410 			error = ENOMEM;
10411 			goto done;
10412 		}
10413 		validatable = allocated_validatable;
10414 	}
10415 
10416 	error = copyin(uap->client_id, validatable, validatable_length);
10417 	if (error) {
10418 		NECPLOG(LOG_ERR, "necp_client_validate copyin error (%d)", error);
10419 		goto done;
10420 	}
10421 
10422 	const bool validated = necp_validate_resolver_answer(validatable->signable.client_id, validatable->signable.sign_type,
10423 	    validatable->signable.signable_data, validatable_length - sizeof(struct necp_client_validatable),
10424 	    validatable->signature.signed_tag, sizeof(validatable->signature.signed_tag));
10425 	if (!validated) {
10426 		// Return EAUTH to indicate that the signature failed
10427 		error = EAUTH;
10428 	}
10429 
10430 done:
10431 	if (allocated_validatable != NULL) {
10432 		kfree_data(allocated_validatable, validatable_length);
10433 		allocated_validatable = NULL;
10434 	}
10435 	*retval = error;
10436 	return error;
10437 }
10438 
10439 static NECP_CLIENT_ACTION_FUNCTION int
necp_client_get_signed_client_id(__unused struct necp_fd_data * fd_data,struct necp_client_action_args * uap,int * retval)10440 necp_client_get_signed_client_id(__unused struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
10441 {
10442 	int error = 0;
10443 	*retval = 0;
10444 	u_int32_t request_type = 0;
10445 	struct necp_client_signed_client_id_uuid client_id = { 0 };
10446 	const size_t buffer_size = uap->buffer_size;
10447 	u_int8_t tag[NECP_CLIENT_ACTION_SIGN_TAG_LENGTH] = {};
10448 	size_t tag_size = sizeof(tag);
10449 
10450 	// Only allow entitled processes to get the client ID.
10451 	proc_t proc = current_proc();
10452 	task_t __single task = proc_task(proc);
10453 	bool has_delegation_entitlement = task != NULL && IOTaskHasEntitlement(task, kCSWebBrowserNetworkEntitlement);
10454 	if (!has_delegation_entitlement) {
10455 		has_delegation_entitlement = (priv_check_cred(kauth_cred_get(), PRIV_NET_PRIVILEGED_SOCKET_DELEGATE, 0) == 0);
10456 	}
10457 	if (!has_delegation_entitlement) {
10458 		NECPLOG0(LOG_ERR, "necp_client_get_signed_client_id client lacks the necessary entitlement");
10459 		error = EAUTH;
10460 		goto done;
10461 	}
10462 
10463 	if (uap->client_id == 0 || uap->client_id_len != sizeof(u_int32_t) ||
10464 	    buffer_size < sizeof(struct necp_client_signed_client_id_uuid) ||
10465 	    uap->buffer == 0) {
10466 		NECPLOG0(LOG_ERR, "necp_client_get_signed_client_id bad input");
10467 		error = EINVAL;
10468 		goto done;
10469 	}
10470 
10471 	error = copyin(uap->client_id, &request_type, sizeof(u_int32_t));
10472 	if (error) {
10473 		NECPLOG(LOG_ERR, "necp_client_get_signed_client_id copyin request_type error (%d)", error);
10474 		goto done;
10475 	}
10476 
10477 	if (request_type != NECP_CLIENT_SIGNED_CLIENT_ID_TYPE_UUID) {
10478 		error = ENOENT;
10479 		NECPLOG(LOG_ERR, "necp_client_get_signed_client_id bad request_type (%d)", request_type);
10480 		goto done;
10481 	}
10482 
10483 	uuid_t application_uuid;
10484 	uuid_clear(application_uuid);
10485 	proc_getexecutableuuid(proc, application_uuid, sizeof(application_uuid));
10486 
10487 	error = necp_sign_application_id(application_uuid,
10488 	    NECP_CLIENT_SIGNED_CLIENT_ID_TYPE_UUID,
10489 	    tag, &tag_size);
10490 	if (tag_size != sizeof(tag)) {
10491 		NECPLOG(LOG_ERR, "necp_client_get_signed_client_id unexpected tag size %zu", tag_size);
10492 		error = EINVAL;
10493 		goto done;
10494 	}
10495 	uuid_copy(client_id.client_id, application_uuid);
10496 	client_id.signature_length = tag_size;
10497 	memcpy(client_id.signature_data, tag, tag_size);
10498 
10499 	error = copyout(&client_id, uap->buffer, sizeof(client_id));
10500 	if (error != 0) {
10501 		NECPLOG(LOG_ERR, "necp_client_get_signed_client_id copyout error (%d)", error);
10502 		goto done;
10503 	}
10504 
10505 done:
10506 	*retval = error;
10507 	return error;
10508 }
10509 
10510 static NECP_CLIENT_ACTION_FUNCTION int
necp_client_set_signed_client_id(__unused struct necp_fd_data * fd_data,struct necp_client_action_args * uap,int * retval)10511 necp_client_set_signed_client_id(__unused struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
10512 {
10513 	int error = 0;
10514 	*retval = 0;
10515 	u_int32_t request_type = 0;
10516 	struct necp_client_signed_client_id_uuid client_id = { 0 };
10517 	const size_t buffer_size = uap->buffer_size;
10518 
10519 	// Only allow entitled processes to set the client ID.
10520 	proc_t proc = current_proc();
10521 	task_t __single task = proc_task(proc);
10522 	bool has_delegation_entitlement = task != NULL && IOTaskHasEntitlement(task, kCSWebBrowserNetworkEntitlement);
10523 	if (!has_delegation_entitlement) {
10524 		has_delegation_entitlement = (priv_check_cred(kauth_cred_get(), PRIV_NET_PRIVILEGED_SOCKET_DELEGATE, 0) == 0);
10525 	}
10526 	if (!has_delegation_entitlement) {
10527 		NECPLOG0(LOG_ERR, "necp_client_set_signed_client_id client lacks the necessary entitlement");
10528 		error = EAUTH;
10529 		goto done;
10530 	}
10531 
10532 	if (uap->client_id == 0 || uap->client_id_len != sizeof(u_int32_t) ||
10533 	    buffer_size < sizeof(struct necp_client_signed_client_id_uuid) ||
10534 	    uap->buffer == 0) {
10535 		NECPLOG0(LOG_ERR, "necp_client_set_signed_client_id bad input");
10536 		error = EINVAL;
10537 		goto done;
10538 	}
10539 
10540 	error = copyin(uap->client_id, &request_type, sizeof(u_int32_t));
10541 	if (error) {
10542 		NECPLOG(LOG_ERR, "necp_client_set_signed_client_id copyin request_type error (%d)", error);
10543 		goto done;
10544 	}
10545 
10546 	if (request_type != NECP_CLIENT_SIGNED_CLIENT_ID_TYPE_UUID) {
10547 		error = ENOENT;
10548 		NECPLOG(LOG_ERR, "necp_client_set_signed_client_id bad request_type (%d)", request_type);
10549 		goto done;
10550 	}
10551 
10552 	error = copyin(uap->buffer, &client_id, sizeof(struct necp_client_signed_client_id_uuid));
10553 	if (error) {
10554 		NECPLOG(LOG_ERR, "necp_client_set_signed_client_id copyin request error (%d)", error);
10555 		goto done;
10556 	}
10557 
10558 	const bool validated = necp_validate_application_id(client_id.client_id,
10559 	    NECP_CLIENT_SIGNED_CLIENT_ID_TYPE_UUID,
10560 	    client_id.signature_data, sizeof(client_id.signature_data));
10561 	if (!validated) {
10562 		// Return EAUTH to indicate that the signature failed
10563 		error = EAUTH;
10564 		NECPLOG(LOG_ERR, "necp_client_set_signed_client_id signature validation failed (%d)", error);
10565 		goto done;
10566 	}
10567 
10568 	proc_setresponsibleuuid(proc, client_id.client_id, sizeof(client_id.client_id));
10569 
10570 done:
10571 	*retval = error;
10572 	return error;
10573 }
10574 
10575 int
necp_client_action(struct proc * p,struct necp_client_action_args * uap,int * retval)10576 necp_client_action(struct proc *p, struct necp_client_action_args *uap, int *retval)
10577 {
10578 	struct fileproc *fp;
10579 	int error = 0;
10580 	int return_value = 0;
10581 	struct necp_fd_data *fd_data = NULL;
10582 
10583 	error = necp_find_fd_data(p, uap->necp_fd, &fp, &fd_data);
10584 	if (error != 0) {
10585 		NECPLOG(LOG_ERR, "necp_client_action find fd error (%d)", error);
10586 		return error;
10587 	}
10588 
10589 	u_int32_t action = uap->action;
10590 
10591 #if CONFIG_MACF
10592 	error = mac_necp_check_client_action(p, fp->fp_glob, action);
10593 	if (error) {
10594 		return_value = error;
10595 		goto done;
10596 	}
10597 #endif /* MACF */
10598 
10599 	switch (action) {
10600 	case NECP_CLIENT_ACTION_ADD: {
10601 		return_value = necp_client_add(p, fd_data, uap, retval);
10602 		break;
10603 	}
10604 	case NECP_CLIENT_ACTION_CLAIM: {
10605 		return_value = necp_client_claim(p, fd_data, uap, retval);
10606 		break;
10607 	}
10608 	case NECP_CLIENT_ACTION_REMOVE: {
10609 		return_value = necp_client_remove(fd_data, uap, retval);
10610 		break;
10611 	}
10612 	case NECP_CLIENT_ACTION_COPY_PARAMETERS:
10613 	case NECP_CLIENT_ACTION_COPY_RESULT:
10614 	case NECP_CLIENT_ACTION_COPY_UPDATED_RESULT: {
10615 		return_value = necp_client_copy(fd_data, uap, retval);
10616 		break;
10617 	}
10618 	case NECP_CLIENT_ACTION_COPY_LIST: {
10619 		return_value = necp_client_list(fd_data, uap, retval);
10620 		break;
10621 	}
10622 	case NECP_CLIENT_ACTION_ADD_FLOW: {
10623 		return_value = necp_client_add_flow(fd_data, uap, retval);
10624 		break;
10625 	}
10626 	case NECP_CLIENT_ACTION_REMOVE_FLOW: {
10627 		return_value = necp_client_remove_flow(fd_data, uap, retval);
10628 		break;
10629 	}
10630 #if SKYWALK
10631 	case NECP_CLIENT_ACTION_REQUEST_NEXUS_INSTANCE: {
10632 		return_value = necp_client_request_nexus(fd_data, uap, retval);
10633 		break;
10634 	}
10635 #endif /* !SKYWALK */
10636 	case NECP_CLIENT_ACTION_AGENT: {
10637 		return_value = necp_client_agent_action(fd_data, uap, retval);
10638 		break;
10639 	}
10640 	case NECP_CLIENT_ACTION_COPY_AGENT: {
10641 		return_value = necp_client_copy_agent(fd_data, uap, retval);
10642 		break;
10643 	}
10644 	case NECP_CLIENT_ACTION_AGENT_USE: {
10645 		return_value = necp_client_agent_use(fd_data, uap, retval);
10646 		break;
10647 	}
10648 	case NECP_CLIENT_ACTION_ACQUIRE_AGENT_TOKEN: {
10649 		return_value = necp_client_acquire_agent_token(fd_data, uap, retval);
10650 		break;
10651 	}
10652 	case NECP_CLIENT_ACTION_COPY_INTERFACE: {
10653 		return_value = necp_client_copy_interface(fd_data, uap, retval);
10654 		break;
10655 	}
10656 #if SKYWALK
10657 	case NECP_CLIENT_ACTION_GET_INTERFACE_ADDRESS: {
10658 		return_value = necp_client_get_interface_address(fd_data, uap, retval);
10659 		break;
10660 	}
10661 	case NECP_CLIENT_ACTION_SET_STATISTICS: {
10662 		return_value = ENOTSUP;
10663 		break;
10664 	}
10665 	case NECP_CLIENT_ACTION_MAP_SYSCTLS: {
10666 		return_value = necp_client_map_sysctls(fd_data, uap, retval);
10667 		break;
10668 	}
10669 #endif /* !SKYWALK */
10670 	case NECP_CLIENT_ACTION_COPY_ROUTE_STATISTICS: {
10671 		return_value = necp_client_copy_route_statistics(fd_data, uap, retval);
10672 		break;
10673 	}
10674 	case NECP_CLIENT_ACTION_UPDATE_CACHE: {
10675 		return_value = necp_client_update_cache(fd_data, uap, retval);
10676 		break;
10677 	}
10678 	case NECP_CLIENT_ACTION_COPY_CLIENT_UPDATE: {
10679 		return_value = necp_client_copy_client_update(fd_data, uap, retval);
10680 		break;
10681 	}
10682 	case NECP_CLIENT_ACTION_SIGN: {
10683 		return_value = necp_client_sign(fd_data, uap, retval);
10684 		break;
10685 	}
10686 	case NECP_CLIENT_ACTION_VALIDATE: {
10687 		return_value = necp_client_validate(fd_data, uap, retval);
10688 		break;
10689 	}
10690 	case NECP_CLIENT_ACTION_GET_SIGNED_CLIENT_ID: {
10691 		return_value = necp_client_get_signed_client_id(fd_data, uap, retval);
10692 		break;
10693 	}
10694 	case NECP_CLIENT_ACTION_SET_SIGNED_CLIENT_ID: {
10695 		return_value = necp_client_set_signed_client_id(fd_data, uap, retval);
10696 		break;
10697 	}
10698 	default: {
10699 		NECPLOG(LOG_ERR, "necp_client_action unknown action (%u)", action);
10700 		return_value = EINVAL;
10701 		break;
10702 	}
10703 	}
10704 
10705 done:
10706 	fp_drop(p, uap->necp_fd, fp, 0);
10707 	return return_value;
10708 }
10709 
10710 #define NECP_MAX_MATCH_POLICY_PARAMETER_SIZE 1024
10711 
10712 int
necp_match_policy(struct proc * p,struct necp_match_policy_args * uap,int32_t * retval)10713 necp_match_policy(struct proc *p, struct necp_match_policy_args *uap, int32_t *retval)
10714 {
10715 #pragma unused(retval)
10716 	u_int8_t *parameters = NULL;
10717 	struct necp_aggregate_result returned_result;
10718 	int error = 0;
10719 
10720 	if (uap == NULL) {
10721 		error = EINVAL;
10722 		goto done;
10723 	}
10724 
10725 	if (uap->parameters == 0 || uap->parameters_size == 0 || uap->parameters_size > NECP_MAX_MATCH_POLICY_PARAMETER_SIZE || uap->returned_result == 0) {
10726 		error = EINVAL;
10727 		goto done;
10728 	}
10729 
10730 	parameters = (u_int8_t *)kalloc_data(uap->parameters_size, Z_WAITOK | Z_ZERO);
10731 	if (parameters == NULL) {
10732 		error = ENOMEM;
10733 		goto done;
10734 	}
10735 	// Copy parameters in
10736 	error = copyin(uap->parameters, parameters, uap->parameters_size);
10737 	if (error) {
10738 		goto done;
10739 	}
10740 
10741 	error = necp_application_find_policy_match_internal(p, parameters, uap->parameters_size,
10742 	    &returned_result, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, false, false, NULL);
10743 	if (error) {
10744 		goto done;
10745 	}
10746 
10747 	// Copy return value back
10748 	error = copyout(&returned_result, uap->returned_result, sizeof(struct necp_aggregate_result));
10749 	if (error) {
10750 		goto done;
10751 	}
10752 done:
10753 	if (parameters != NULL) {
10754 		kfree_data(parameters, uap->parameters_size);
10755 	}
10756 	return error;
10757 }
10758 
10759 /// Socket operations
10760 
10761 static errno_t
necp_set_socket_attribute(u_int8_t * buffer,size_t buffer_length,u_int8_t type,char ** buffer_p,bool * single_tlv)10762 necp_set_socket_attribute(u_int8_t *buffer, size_t buffer_length, u_int8_t type, char **buffer_p, bool *single_tlv)
10763 {
10764 	int error = 0;
10765 	int cursor = 0;
10766 	size_t string_size = 0;
10767 	char *local_string = NULL;
10768 	u_int8_t *value = NULL;
10769 	char *buffer_to_free = NULL;
10770 
10771 	cursor = necp_buffer_find_tlv(buffer, buffer_length, 0, type, NULL, 0);
10772 	if (cursor < 0) {
10773 		// This will clear out the parameter
10774 		goto done;
10775 	}
10776 
10777 	string_size = necp_buffer_get_tlv_length(buffer, cursor);
10778 	if (single_tlv != NULL && (buffer_length == sizeof(struct necp_tlv_header) + string_size)) {
10779 		*single_tlv = true;
10780 	}
10781 	if (string_size == 0 || string_size > NECP_MAX_SOCKET_ATTRIBUTE_STRING_LENGTH) {
10782 		// This will clear out the parameter
10783 		goto done;
10784 	}
10785 
10786 	local_string = (char *)kalloc_data(string_size + 1, Z_WAITOK | Z_ZERO);
10787 	if (local_string == NULL) {
10788 		NECPLOG(LOG_ERR, "Failed to allocate a socket attribute buffer (size %zu)", string_size);
10789 		goto fail;
10790 	}
10791 
10792 	value = necp_buffer_get_tlv_value(buffer, cursor, NULL);
10793 	if (value == NULL) {
10794 		NECPLOG0(LOG_ERR, "Failed to get socket attribute");
10795 		goto fail;
10796 	}
10797 
10798 	memcpy(local_string, value, string_size);
10799 	local_string[string_size] = 0;
10800 
10801 done:
10802 	buffer_to_free = *buffer_p;
10803 
10804 	// Protect switching of buffer pointer
10805 	necp_lock_socket_attributes();
10806 	*buffer_p = local_string;
10807 	necp_unlock_socket_attributes();
10808 
10809 	if (buffer_to_free != NULL) {
10810 		kfree_data_addr(buffer_to_free);
10811 	}
10812 	return 0;
10813 fail:
10814 	if (local_string != NULL) {
10815 		kfree_data(local_string, string_size + 1);
10816 	}
10817 	return error;
10818 }
10819 
10820 errno_t
necp_set_socket_attributes(struct inp_necp_attributes * attributes,struct sockopt * sopt)10821 necp_set_socket_attributes(struct inp_necp_attributes *attributes, struct sockopt *sopt)
10822 {
10823 	int error = 0;
10824 	u_int8_t *buffer = NULL;
10825 	bool single_tlv = false;
10826 	size_t valsize = sopt->sopt_valsize;
10827 	if (valsize == 0 ||
10828 	    valsize > ((sizeof(struct necp_tlv_header) + NECP_MAX_SOCKET_ATTRIBUTE_STRING_LENGTH) * 4)) {
10829 		goto done;
10830 	}
10831 
10832 	buffer = (u_int8_t *)kalloc_data(valsize, Z_WAITOK | Z_ZERO);
10833 	if (buffer == NULL) {
10834 		goto done;
10835 	}
10836 
10837 	error = sooptcopyin(sopt, buffer, valsize, 0);
10838 	if (error) {
10839 		goto done;
10840 	}
10841 
10842 	// If NECP_TLV_ATTRIBUTE_DOMAIN_CONTEXT is being set/cleared separately from the other attributes,
10843 	// do not clear other attributes.
10844 	error = necp_set_socket_attribute(buffer, valsize, NECP_TLV_ATTRIBUTE_DOMAIN_CONTEXT, &attributes->inp_domain_context, &single_tlv);
10845 	if (error) {
10846 		NECPLOG0(LOG_ERR, "Could not set domain context TLV for socket attributes");
10847 		goto done;
10848 	}
10849 	if (single_tlv == true) {
10850 		goto done;
10851 	}
10852 
10853 	error = necp_set_socket_attribute(buffer, valsize, NECP_TLV_ATTRIBUTE_DOMAIN, &attributes->inp_domain, NULL);
10854 	if (error) {
10855 		NECPLOG0(LOG_ERR, "Could not set domain TLV for socket attributes");
10856 		goto done;
10857 	}
10858 
10859 	error = necp_set_socket_attribute(buffer, valsize, NECP_TLV_ATTRIBUTE_DOMAIN_OWNER, &attributes->inp_domain_owner, NULL);
10860 	if (error) {
10861 		NECPLOG0(LOG_ERR, "Could not set domain owner TLV for socket attributes");
10862 		goto done;
10863 	}
10864 
10865 	error = necp_set_socket_attribute(buffer, valsize, NECP_TLV_ATTRIBUTE_TRACKER_DOMAIN, &attributes->inp_tracker_domain, NULL);
10866 	if (error) {
10867 		NECPLOG0(LOG_ERR, "Could not set tracker domain TLV for socket attributes");
10868 		goto done;
10869 	}
10870 
10871 	error = necp_set_socket_attribute(buffer, valsize, NECP_TLV_ATTRIBUTE_ACCOUNT, &attributes->inp_account, NULL);
10872 	if (error) {
10873 		NECPLOG0(LOG_ERR, "Could not set account TLV for socket attributes");
10874 		goto done;
10875 	}
10876 
10877 done:
10878 	NECP_SOCKET_ATTRIBUTE_LOG("NECP ATTRIBUTES SOCKET - domain <%s> owner <%s> context <%s> tracker domain <%s> account <%s>",
10879 	    attributes->inp_domain,
10880 	    attributes->inp_domain_owner,
10881 	    attributes->inp_domain_context,
10882 	    attributes->inp_tracker_domain,
10883 	    attributes->inp_account);
10884 
10885 	if (necp_debug) {
10886 		NECPLOG(LOG_DEBUG, "Set on socket: Domain %s, Domain owner %s, Domain context %s, Tracker domain %s, Account %s",
10887 		    attributes->inp_domain,
10888 		    attributes->inp_domain_owner,
10889 		    attributes->inp_domain_context,
10890 		    attributes->inp_tracker_domain,
10891 		    attributes->inp_account);
10892 	}
10893 
10894 	if (buffer != NULL) {
10895 		kfree_data(buffer, valsize);
10896 	}
10897 
10898 	return error;
10899 }
10900 
10901 errno_t
necp_get_socket_attributes(struct inp_necp_attributes * attributes,struct sockopt * sopt)10902 necp_get_socket_attributes(struct inp_necp_attributes *attributes, struct sockopt *sopt)
10903 {
10904 	int error = 0;
10905 	u_int8_t *buffer = NULL;
10906 	u_int8_t *cursor = NULL;
10907 	size_t valsize = 0;
10908 
10909 	if (attributes->inp_domain != NULL) {
10910 		valsize += sizeof(struct necp_tlv_header) + strlen(attributes->inp_domain);
10911 	}
10912 	if (attributes->inp_domain_owner != NULL) {
10913 		valsize += sizeof(struct necp_tlv_header) + strlen(attributes->inp_domain_owner);
10914 	}
10915 	if (attributes->inp_domain_context != NULL) {
10916 		valsize += sizeof(struct necp_tlv_header) + strlen(attributes->inp_domain_context);
10917 	}
10918 	if (attributes->inp_tracker_domain != NULL) {
10919 		valsize += sizeof(struct necp_tlv_header) + strlen(attributes->inp_tracker_domain);
10920 	}
10921 	if (attributes->inp_account != NULL) {
10922 		valsize += sizeof(struct necp_tlv_header) + strlen(attributes->inp_account);
10923 	}
10924 	if (valsize == 0) {
10925 		goto done;
10926 	}
10927 
10928 	buffer = (u_int8_t *)kalloc_data(valsize, Z_WAITOK | Z_ZERO);
10929 	if (buffer == NULL) {
10930 		goto done;
10931 	}
10932 
10933 	cursor = buffer;
10934 	if (attributes->inp_domain != NULL) {
10935 		cursor = necp_buffer_write_tlv(cursor, NECP_TLV_ATTRIBUTE_DOMAIN, strlen(attributes->inp_domain), attributes->inp_domain,
10936 		    buffer, valsize);
10937 	}
10938 
10939 	if (attributes->inp_domain_owner != NULL) {
10940 		cursor = necp_buffer_write_tlv(cursor, NECP_TLV_ATTRIBUTE_DOMAIN_OWNER, strlen(attributes->inp_domain_owner), attributes->inp_domain_owner,
10941 		    buffer, valsize);
10942 	}
10943 
10944 	if (attributes->inp_domain_context != NULL) {
10945 		cursor = necp_buffer_write_tlv(cursor, NECP_TLV_ATTRIBUTE_DOMAIN_CONTEXT, strlen(attributes->inp_domain_context), attributes->inp_domain_context,
10946 		    buffer, valsize);
10947 	}
10948 
10949 	if (attributes->inp_tracker_domain != NULL) {
10950 		cursor = necp_buffer_write_tlv(cursor, NECP_TLV_ATTRIBUTE_TRACKER_DOMAIN, strlen(attributes->inp_tracker_domain), attributes->inp_tracker_domain,
10951 		    buffer, valsize);
10952 	}
10953 
10954 	if (attributes->inp_account != NULL) {
10955 		cursor = necp_buffer_write_tlv(cursor, NECP_TLV_ATTRIBUTE_ACCOUNT, strlen(attributes->inp_account), attributes->inp_account,
10956 		    buffer, valsize);
10957 	}
10958 
10959 	error = sooptcopyout(sopt, buffer, valsize);
10960 	if (error) {
10961 		goto done;
10962 	}
10963 done:
10964 	if (buffer != NULL) {
10965 		kfree_data(buffer, valsize);
10966 	}
10967 
10968 	return error;
10969 }
10970 
10971 int
necp_set_socket_resolver_signature(struct inpcb * inp,struct sockopt * sopt)10972 necp_set_socket_resolver_signature(struct inpcb *inp, struct sockopt *sopt)
10973 {
10974 	const size_t valsize = sopt->sopt_valsize;
10975 	if (valsize > NECP_CLIENT_ACTION_SIGN_MAX_TOTAL_LENGTH + NECP_CLIENT_ACTION_SIGN_TAG_LENGTH) {
10976 		return EINVAL;
10977 	}
10978 
10979 	necp_lock_socket_attributes();
10980 	if (inp->inp_resolver_signature != NULL) {
10981 		kfree_data(inp->inp_resolver_signature, inp->inp_resolver_signature_length);
10982 	}
10983 	inp->inp_resolver_signature_length = 0;
10984 
10985 	int error = 0;
10986 	if (valsize > 0) {
10987 		inp->inp_resolver_signature = kalloc_data(valsize, Z_WAITOK | Z_ZERO);
10988 		if ((error = sooptcopyin(sopt, inp->inp_resolver_signature, valsize,
10989 		    valsize)) != 0) {
10990 			// Free the signature buffer if the copyin failed
10991 			kfree_data(inp->inp_resolver_signature, valsize);
10992 		} else {
10993 			inp->inp_resolver_signature_length = valsize;
10994 		}
10995 	}
10996 	necp_unlock_socket_attributes();
10997 
10998 	return error;
10999 }
11000 
11001 int
necp_get_socket_resolver_signature(struct inpcb * inp,struct sockopt * sopt)11002 necp_get_socket_resolver_signature(struct inpcb *inp, struct sockopt *sopt)
11003 {
11004 	int error = 0;
11005 	necp_lock_socket_attributes();
11006 	if (inp->inp_resolver_signature == NULL ||
11007 	    inp->inp_resolver_signature_length == 0) {
11008 		error = ENOENT;
11009 	} else {
11010 		error = sooptcopyout(sopt, inp->inp_resolver_signature,
11011 		    inp->inp_resolver_signature_length);
11012 	}
11013 	necp_unlock_socket_attributes();
11014 	return error;
11015 }
11016 
11017 bool
necp_socket_has_resolver_signature(struct inpcb * inp)11018 necp_socket_has_resolver_signature(struct inpcb *inp)
11019 {
11020 	necp_lock_socket_attributes();
11021 	bool has_signature = (inp->inp_resolver_signature != NULL && inp->inp_resolver_signature_length != 0);
11022 	necp_unlock_socket_attributes();
11023 	return has_signature;
11024 }
11025 
11026 bool
necp_socket_resolver_signature_matches_address(struct inpcb * inp,union necp_sockaddr_union * address)11027 necp_socket_resolver_signature_matches_address(struct inpcb *inp, union necp_sockaddr_union *address)
11028 {
11029 	bool matches_address = false;
11030 	necp_lock_socket_attributes();
11031 	if (inp->inp_resolver_signature != NULL && inp->inp_resolver_signature_length > 0 && address->sa.sa_len > 0) {
11032 		struct necp_client_validatable *validatable = (struct necp_client_validatable *)inp->inp_resolver_signature;
11033 		if (inp->inp_resolver_signature_length > sizeof(struct necp_client_validatable) &&
11034 		    validatable->signable.sign_type == NECP_CLIENT_SIGN_TYPE_SYSTEM_RESOLVER_ANSWER) {
11035 			size_t data_length = inp->inp_resolver_signature_length - sizeof(struct necp_client_validatable);
11036 			if (data_length >= (sizeof(struct necp_client_host_resolver_answer) - sizeof(struct necp_client_signable))) {
11037 				struct necp_client_host_resolver_answer *answer_struct = (struct necp_client_host_resolver_answer *)&validatable->signable;
11038 				if (data_length == (sizeof(struct necp_client_host_resolver_answer) + answer_struct->hostname_length - sizeof(struct necp_client_signable)) &&
11039 				    answer_struct->address_answer.sa.sa_family == address->sa.sa_family &&
11040 				    answer_struct->address_answer.sa.sa_len == address->sa.sa_len &&
11041 				    (answer_struct->address_answer.sin.sin_port == 0 ||
11042 				    answer_struct->address_answer.sin.sin_port == address->sin.sin_port) &&
11043 				    ((answer_struct->address_answer.sa.sa_family == AF_INET &&
11044 				    answer_struct->address_answer.sin.sin_addr.s_addr == address->sin.sin_addr.s_addr) ||
11045 				    (answer_struct->address_answer.sa.sa_family == AF_INET6 &&
11046 				    memcmp(&answer_struct->address_answer.sin6.sin6_addr, &address->sin6.sin6_addr, sizeof(struct in6_addr)) == 0))) {
11047 					// Address matches
11048 					const bool validated = necp_validate_resolver_answer(validatable->signable.client_id,
11049 					    validatable->signable.sign_type,
11050 					    validatable->signable.signable_data, data_length,
11051 					    validatable->signature.signed_tag, sizeof(validatable->signature.signed_tag));
11052 					if (validated) {
11053 						// Answer is validated
11054 						matches_address = true;
11055 					}
11056 				}
11057 			}
11058 		}
11059 	}
11060 	necp_unlock_socket_attributes();
11061 	return matches_address;
11062 }
11063 
11064 /*
11065  * necp_set_socket_domain_attributes
11066  * Called from soconnectlock/soconnectxlock to directly set the tracker domain and owner for
11067  * a newly marked tracker socket.
11068  */
11069 errno_t
necp_set_socket_domain_attributes(struct socket * so,const char * domain,const char * domain_owner)11070 necp_set_socket_domain_attributes(struct socket *so, const char *domain, const char *domain_owner)
11071 {
11072 	int error = 0;
11073 	struct inpcb *inp = NULL;
11074 	u_int8_t *buffer = NULL;
11075 	size_t valsize = 0;
11076 	char *buffer_to_free = NULL;
11077 
11078 	if (SOCK_DOM(so) != PF_INET && SOCK_DOM(so) != PF_INET6) {
11079 		error = EINVAL;
11080 		goto fail;
11081 	}
11082 
11083 	// Set domain (required)
11084 
11085 	valsize = strlen(domain);
11086 	if (valsize == 0 || valsize > NECP_MAX_SOCKET_ATTRIBUTE_STRING_LENGTH) {
11087 		error = EINVAL;
11088 		goto fail;
11089 	}
11090 
11091 	buffer = (u_int8_t *)kalloc_data(valsize + 1, Z_WAITOK | Z_ZERO);
11092 	if (buffer == NULL) {
11093 		error = ENOMEM;
11094 		goto fail;
11095 	}
11096 	bcopy(domain, buffer, valsize);
11097 	buffer[valsize] = 0;
11098 
11099 	inp = sotoinpcb(so);
11100 	// Do not overwrite a previously set domain if tracker domain is different.
11101 	if (inp->inp_necp_attributes.inp_domain != NULL) {
11102 		if (strlen(inp->inp_necp_attributes.inp_domain) != strlen(domain) ||
11103 		    strncmp(inp->inp_necp_attributes.inp_domain, domain, strlen(domain)) != 0) {
11104 			buffer_to_free = inp->inp_necp_attributes.inp_tracker_domain;
11105 			// Protect switching of buffer pointer
11106 			necp_lock_socket_attributes();
11107 			inp->inp_necp_attributes.inp_tracker_domain = (char *)buffer;
11108 			necp_unlock_socket_attributes();
11109 			if (buffer_to_free != NULL) {
11110 				kfree_data_addr(buffer_to_free);
11111 			}
11112 		} else {
11113 			kfree_data_addr(buffer);
11114 		}
11115 	} else {
11116 		// Protect switching of buffer pointer
11117 		necp_lock_socket_attributes();
11118 		inp->inp_necp_attributes.inp_domain = (char *)buffer;
11119 		necp_unlock_socket_attributes();
11120 	}
11121 	buffer = NULL;
11122 
11123 	// set domain_owner (required only for tracker)
11124 	if (!(so->so_flags1 & SOF1_KNOWN_TRACKER)) {
11125 		goto done;
11126 	}
11127 
11128 	valsize = strlen(domain_owner);
11129 	if (valsize == 0 || valsize > NECP_MAX_SOCKET_ATTRIBUTE_STRING_LENGTH) {
11130 		error = EINVAL;
11131 		goto fail;
11132 	}
11133 
11134 	buffer = (u_int8_t *)kalloc_data(valsize + 1, Z_WAITOK | Z_ZERO);
11135 	if (buffer == NULL) {
11136 		error = ENOMEM;
11137 		goto fail;
11138 	}
11139 	bcopy(domain_owner, buffer, valsize);
11140 	buffer[valsize] = 0;
11141 
11142 	inp = sotoinpcb(so);
11143 
11144 	buffer_to_free = inp->inp_necp_attributes.inp_domain_owner;
11145 	// Protect switching of buffer pointer
11146 	necp_lock_socket_attributes();
11147 	inp->inp_necp_attributes.inp_domain_owner = (char *)buffer;
11148 	necp_unlock_socket_attributes();
11149 	buffer = NULL;
11150 
11151 	if (buffer_to_free != NULL) {
11152 		kfree_data_addr(buffer_to_free);
11153 	}
11154 
11155 done:
11156 	NECP_SOCKET_PARAMS_LOG(so, "NECP ATTRIBUTES SOCKET - domain <%s> owner <%s> context <%s> tracker domain <%s> account <%s> "
11157 	    "<so flags - is_tracker %X non-app-initiated %X app-approved-domain %X",
11158 	    inp->inp_necp_attributes.inp_domain,
11159 	    inp->inp_necp_attributes.inp_domain_owner,
11160 	    inp->inp_necp_attributes.inp_domain_context,
11161 	    inp->inp_necp_attributes.inp_tracker_domain,
11162 	    inp->inp_necp_attributes.inp_account,
11163 	    so->so_flags1 & SOF1_KNOWN_TRACKER,
11164 	    so->so_flags1 & SOF1_TRACKER_NON_APP_INITIATED,
11165 	    so->so_flags1 & SOF1_APPROVED_APP_DOMAIN);
11166 
11167 	if (necp_debug) {
11168 		NECPLOG(LOG_DEBUG, "Set on socket: Domain <%s> Domain owner <%s> Domain context <%s> Tracker domain <%s> Account <%s> ",
11169 		    inp->inp_necp_attributes.inp_domain,
11170 		    inp->inp_necp_attributes.inp_domain_owner,
11171 		    inp->inp_necp_attributes.inp_domain_context,
11172 		    inp->inp_necp_attributes.inp_tracker_domain,
11173 		    inp->inp_necp_attributes.inp_account);
11174 	}
11175 fail:
11176 	if (buffer != NULL) {
11177 		kfree_data(buffer, valsize + 1);
11178 	}
11179 	return error;
11180 }
11181 
11182 void *
necp_create_nexus_assign_message(uuid_t nexus_instance,nexus_port_t nexus_port,void * key,uint32_t key_length,struct necp_client_endpoint * local_endpoint,struct necp_client_endpoint * remote_endpoint,struct ether_addr * local_ether_addr,u_int32_t flow_adv_index,void * flow_stats,size_t * message_length)11183 necp_create_nexus_assign_message(uuid_t nexus_instance, nexus_port_t nexus_port, void *key, uint32_t key_length,
11184     struct necp_client_endpoint *local_endpoint, struct necp_client_endpoint *remote_endpoint, struct ether_addr *local_ether_addr,
11185     u_int32_t flow_adv_index, void *flow_stats, size_t *message_length)
11186 {
11187 	u_int8_t *buffer = NULL;
11188 	u_int8_t *cursor = NULL;
11189 	size_t valsize = 0;
11190 	bool has_nexus_assignment = FALSE;
11191 
11192 	if (!uuid_is_null(nexus_instance)) {
11193 		has_nexus_assignment = TRUE;
11194 		valsize += sizeof(struct necp_tlv_header) + sizeof(uuid_t);
11195 		valsize += sizeof(struct necp_tlv_header) + sizeof(nexus_port_t);
11196 	}
11197 	if (flow_adv_index != NECP_FLOWADV_IDX_INVALID) {
11198 		valsize += sizeof(struct necp_tlv_header) + sizeof(u_int32_t);
11199 	}
11200 	if (key != NULL && key_length > 0) {
11201 		valsize += sizeof(struct necp_tlv_header) + key_length;
11202 	}
11203 	if (local_endpoint != NULL) {
11204 		valsize += sizeof(struct necp_tlv_header) + sizeof(struct necp_client_endpoint);
11205 	}
11206 	if (remote_endpoint != NULL) {
11207 		valsize += sizeof(struct necp_tlv_header) + sizeof(struct necp_client_endpoint);
11208 	}
11209 	if (local_ether_addr != NULL) {
11210 		valsize += sizeof(struct necp_tlv_header) + sizeof(struct ether_addr);
11211 	}
11212 	if (flow_stats != NULL) {
11213 		valsize += sizeof(struct necp_tlv_header) + sizeof(void *);
11214 	}
11215 	if (valsize == 0) {
11216 		return NULL;
11217 	}
11218 
11219 	buffer = kalloc_data(valsize, Z_WAITOK | Z_ZERO);
11220 	if (buffer == NULL) {
11221 		return NULL;
11222 	}
11223 
11224 	cursor = buffer;
11225 	if (has_nexus_assignment) {
11226 		cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_NEXUS_INSTANCE, sizeof(uuid_t), nexus_instance, buffer, valsize);
11227 		cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_NEXUS_PORT, sizeof(nexus_port_t), &nexus_port, buffer, valsize);
11228 	}
11229 	if (flow_adv_index != NECP_FLOWADV_IDX_INVALID) {
11230 		cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_NEXUS_PORT_FLOW_INDEX, sizeof(u_int32_t), &flow_adv_index, buffer, valsize);
11231 	}
11232 	if (key != NULL && key_length > 0) {
11233 		cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_PARAMETER_NEXUS_KEY, key_length, key, buffer, valsize);
11234 	}
11235 	if (local_endpoint != NULL) {
11236 		cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_LOCAL_ENDPOINT, sizeof(struct necp_client_endpoint), local_endpoint, buffer, valsize);
11237 	}
11238 	if (remote_endpoint != NULL) {
11239 		cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_REMOTE_ENDPOINT, sizeof(struct necp_client_endpoint), remote_endpoint, buffer, valsize);
11240 	}
11241 	if (local_ether_addr != NULL) {
11242 		cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_LOCAL_ETHER_ADDR, sizeof(struct ether_addr), local_ether_addr, buffer, valsize);
11243 	}
11244 	if (flow_stats != NULL) {
11245 		cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_NEXUS_FLOW_STATS, sizeof(void *), &flow_stats, buffer, valsize);
11246 	}
11247 
11248 	*message_length = valsize;
11249 
11250 	return buffer;
11251 }
11252 
11253 void
necp_inpcb_remove_cb(struct inpcb * inp)11254 necp_inpcb_remove_cb(struct inpcb *inp)
11255 {
11256 	if (!uuid_is_null(inp->necp_client_uuid)) {
11257 		necp_client_unregister_socket_flow(inp->necp_client_uuid, inp);
11258 		uuid_clear(inp->necp_client_uuid);
11259 	}
11260 }
11261 
11262 void
necp_inpcb_dispose(struct inpcb * inp)11263 necp_inpcb_dispose(struct inpcb *inp)
11264 {
11265 	necp_inpcb_remove_cb(inp); // Clear out socket registrations if not yet done
11266 	if (inp->inp_necp_attributes.inp_domain != NULL) {
11267 		kfree_data_addr(inp->inp_necp_attributes.inp_domain);
11268 		inp->inp_necp_attributes.inp_domain = NULL;
11269 	}
11270 	if (inp->inp_necp_attributes.inp_account != NULL) {
11271 		kfree_data_addr(inp->inp_necp_attributes.inp_account);
11272 		inp->inp_necp_attributes.inp_account = NULL;
11273 	}
11274 	if (inp->inp_necp_attributes.inp_domain_owner != NULL) {
11275 		kfree_data_addr(inp->inp_necp_attributes.inp_domain_owner);
11276 		inp->inp_necp_attributes.inp_domain_owner = NULL;
11277 	}
11278 	if (inp->inp_necp_attributes.inp_domain_context != NULL) {
11279 		kfree_data_addr(inp->inp_necp_attributes.inp_domain_context);
11280 		inp->inp_necp_attributes.inp_domain_context = NULL;
11281 	}
11282 	if (inp->inp_necp_attributes.inp_tracker_domain != NULL) {
11283 		kfree_data_addr(inp->inp_necp_attributes.inp_tracker_domain);
11284 		inp->inp_necp_attributes.inp_tracker_domain = NULL;
11285 	}
11286 	if (inp->inp_resolver_signature != NULL) {
11287 		kfree_data(inp->inp_resolver_signature, inp->inp_resolver_signature_length);
11288 	}
11289 	inp->inp_resolver_signature_length = 0;
11290 }
11291 
11292 void
necp_mppcb_dispose(struct mppcb * mpp)11293 necp_mppcb_dispose(struct mppcb *mpp)
11294 {
11295 	if (!uuid_is_null(mpp->necp_client_uuid)) {
11296 		necp_client_unregister_multipath_cb(mpp->necp_client_uuid, mpp);
11297 		uuid_clear(mpp->necp_client_uuid);
11298 	}
11299 
11300 	if (mpp->inp_necp_attributes.inp_domain != NULL) {
11301 		kfree_data_addr(mpp->inp_necp_attributes.inp_domain);
11302 		mpp->inp_necp_attributes.inp_domain = NULL;
11303 	}
11304 	if (mpp->inp_necp_attributes.inp_account != NULL) {
11305 		kfree_data_addr(mpp->inp_necp_attributes.inp_account);
11306 		mpp->inp_necp_attributes.inp_account = NULL;
11307 	}
11308 	if (mpp->inp_necp_attributes.inp_domain_owner != NULL) {
11309 		kfree_data_addr(mpp->inp_necp_attributes.inp_domain_owner);
11310 		mpp->inp_necp_attributes.inp_domain_owner = NULL;
11311 	}
11312 	if (mpp->inp_necp_attributes.inp_tracker_domain != NULL) {
11313 		kfree_data_addr(mpp->inp_necp_attributes.inp_tracker_domain);
11314 		mpp->inp_necp_attributes.inp_tracker_domain = NULL;
11315 	}
11316 }
11317 
11318 /// Module init
11319 
11320 void
necp_client_init(void)11321 necp_client_init(void)
11322 {
11323 	necp_client_update_tcall = thread_call_allocate_with_options(necp_update_all_clients_callout, NULL,
11324 	    THREAD_CALL_PRIORITY_KERNEL, THREAD_CALL_OPTIONS_ONCE);
11325 	VERIFY(necp_client_update_tcall != NULL);
11326 #if SKYWALK
11327 
11328 	necp_client_collect_stats_tcall = thread_call_allocate_with_options(necp_collect_stats_client_callout, NULL,
11329 	    THREAD_CALL_PRIORITY_KERNEL, THREAD_CALL_OPTIONS_ONCE);
11330 	VERIFY(necp_client_collect_stats_tcall != NULL);
11331 
11332 	necp_close_empty_arenas_tcall = thread_call_allocate_with_options(necp_close_empty_arenas_callout, NULL,
11333 	    THREAD_CALL_PRIORITY_KERNEL, THREAD_CALL_OPTIONS_ONCE);
11334 	VERIFY(necp_close_empty_arenas_tcall != NULL);
11335 #endif /* SKYWALK */
11336 
11337 	LIST_INIT(&necp_fd_list);
11338 	LIST_INIT(&necp_fd_observer_list);
11339 	LIST_INIT(&necp_collect_stats_flow_list);
11340 
11341 	RB_INIT(&necp_client_global_tree);
11342 	RB_INIT(&necp_client_flow_global_tree);
11343 }
11344 
11345 #if SKYWALK
11346 pid_t
necp_client_get_proc_pid_from_arena_info(struct skmem_arena_mmap_info * arena_info)11347 necp_client_get_proc_pid_from_arena_info(struct skmem_arena_mmap_info *arena_info)
11348 {
11349 	ASSERT((arena_info->ami_arena->ar_type == SKMEM_ARENA_TYPE_NECP) || (arena_info->ami_arena->ar_type == SKMEM_ARENA_TYPE_SYSTEM));
11350 
11351 	if (arena_info->ami_arena->ar_type == SKMEM_ARENA_TYPE_NECP) {
11352 		struct necp_arena_info *nai = container_of(arena_info, struct necp_arena_info, nai_mmap);
11353 		return nai->nai_proc_pid;
11354 	} else {
11355 		struct necp_fd_data *fd_data = container_of(arena_info, struct necp_fd_data, sysctl_mmap);
11356 		return fd_data->proc_pid;
11357 	}
11358 }
11359 #endif /* !SKYWALK */
11360