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