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