]> git.saurik.com Git - apple/xnu.git/blame_incremental - bsd/net/necp_client.c
xnu-7195.101.1.tar.gz
[apple/xnu.git] / bsd / net / necp_client.c
... / ...
CommitLineData
1/*
2 * Copyright (c) 2015-2020 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
71/*
72 * NECP Client Architecture
73 * ------------------------------------------------
74 * See <net/necp.c> for a discussion on NECP database architecture.
75 *
76 * Each client of NECP provides a set of parameters for a connection or network state
77 * evaluation, on which NECP policy evaluation is run. This produces a policy result
78 * which can be accessed by the originating process, along with events for when policies
79 * results have changed.
80 *
81 * ------------------------------------------------
82 * NECP Client FD
83 * ------------------------------------------------
84 * A process opens an NECP file descriptor using necp_open(). This is a very simple
85 * file descriptor, upon which the process may do the following operations:
86 * - necp_client_action(...), to add/remove/query clients
87 * - kqueue, to watch for readable events
88 * - close(), to close the client session and release all clients
89 *
90 * Client objects are allocated structures that hang off of the file descriptor. Each
91 * client contains:
92 * - Client ID, a UUID that references the client across the system
93 * - Parameters, a buffer of TLVs that describe the client's connection parameters,
94 * such as the remote and local endpoints, interface requirements, etc.
95 * - Result, a buffer of TLVs containing the current policy evaluation for the client.
96 * This result will be updated whenever a network change occurs that impacts the
97 * policy result for that client.
98 *
99 * +--------------+
100 * | NECP fd |
101 * +--------------+
102 * ||
103 * ==================================
104 * || || ||
105 * +--------------+ +--------------+ +--------------+
106 * | Client ID | | Client ID | | Client ID |
107 * | ---- | | ---- | | ---- |
108 * | Parameters | | Parameters | | Parameters |
109 * | ---- | | ---- | | ---- |
110 * | Result | | Result | | Result |
111 * +--------------+ +--------------+ +--------------+
112 *
113 * ------------------------------------------------
114 * Client Actions
115 * ------------------------------------------------
116 * - Add. Input parameters as a buffer of TLVs, and output a client ID. Allocates a
117 * new client structure on the file descriptor.
118 * - Remove. Input a client ID. Removes a client structure from the file descriptor.
119 * - Copy Parameters. Input a client ID, and output parameter TLVs.
120 * - Copy Result. Input a client ID, and output result TLVs. Alternatively, input empty
121 * client ID and get next unread client result.
122 * - Copy List. List all client IDs.
123 *
124 * ------------------------------------------------
125 * Client Policy Evaluation
126 * ------------------------------------------------
127 * Policies are evaluated for clients upon client creation, and upon update events,
128 * which are network/agent/policy changes coalesced by a timer.
129 *
130 * The policy evaluation goes through the following steps:
131 * 1. Parse client parameters.
132 * 2. Select a scoped interface if applicable. This involves using require/prohibit
133 * parameters, along with the local address, to select the most appropriate interface
134 * if not explicitly set by the client parameters.
135 * 3. Run NECP application-level policy evalution
136 * 4. Set policy result into client result buffer.
137 *
138 * ------------------------------------------------
139 * Client Observers
140 * ------------------------------------------------
141 * If necp_open() is called with the NECP_OPEN_FLAG_OBSERVER flag, and the process
142 * passes the necessary privilege check, the fd is allowed to use necp_client_action()
143 * to copy client state attached to the file descriptors of other processes, and to
144 * list all client IDs on the system.
145 */
146
147extern u_int32_t necp_debug;
148
149static int necpop_select(struct fileproc *, int, void *, vfs_context_t);
150static int necpop_close(struct fileglob *, vfs_context_t);
151static int necpop_kqfilter(struct fileproc *, struct knote *, struct kevent_qos_s *);
152
153// Timer functions
154static int necp_timeout_microseconds = 1000 * 100; // 100ms
155static int necp_timeout_leeway_microseconds = 1000 * 500; // 500ms
156
157static int necp_client_fd_count = 0;
158static int necp_observer_fd_count = 0;
159static int necp_client_count = 0;
160static int necp_socket_flow_count = 0;
161static int necp_if_flow_count = 0;
162static int necp_observer_message_limit = 256;
163
164os_refgrp_decl(static, necp_client_refgrp, "NECPClientRefGroup", NULL);
165
166SYSCTL_INT(_net_necp, NECPCTL_CLIENT_FD_COUNT, client_fd_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_client_fd_count, 0, "");
167SYSCTL_INT(_net_necp, NECPCTL_OBSERVER_FD_COUNT, observer_fd_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_observer_fd_count, 0, "");
168SYSCTL_INT(_net_necp, NECPCTL_CLIENT_COUNT, client_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_client_count, 0, "");
169SYSCTL_INT(_net_necp, NECPCTL_SOCKET_FLOW_COUNT, socket_flow_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_socket_flow_count, 0, "");
170SYSCTL_INT(_net_necp, NECPCTL_IF_FLOW_COUNT, if_flow_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_if_flow_count, 0, "");
171SYSCTL_INT(_net_necp, NECPCTL_OBSERVER_MESSAGE_LIMIT, observer_message_limit, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_observer_message_limit, 256, "");
172
173#define NECP_MAX_CLIENT_LIST_SIZE 1024 * 1024 // 1MB
174#define NECP_MAX_AGENT_ACTION_SIZE 256
175
176extern int tvtohz(struct timeval *);
177extern unsigned int get_maxmtu(struct rtentry *);
178
179// Parsed parameters
180#define NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR 0x00001
181#define NECP_PARSED_PARAMETERS_FIELD_REMOTE_ADDR 0x00002
182#define NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IF 0x00004
183#define NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IF 0x00008
184#define NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE 0x00010
185#define NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IFTYPE 0x00020
186#define NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT 0x00040
187#define NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT 0x00080
188#define NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT 0x00100
189#define NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT 0x00200
190#define NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE 0x00400
191#define NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT_TYPE 0x00800
192#define NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT_TYPE 0x01000
193#define NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT_TYPE 0x02000
194#define NECP_PARSED_PARAMETERS_FIELD_FLAGS 0x04000
195#define NECP_PARSED_PARAMETERS_FIELD_IP_PROTOCOL 0x08000
196#define NECP_PARSED_PARAMETERS_FIELD_EFFECTIVE_PID 0x10000
197#define NECP_PARSED_PARAMETERS_FIELD_EFFECTIVE_UUID 0x20000
198#define NECP_PARSED_PARAMETERS_FIELD_TRAFFIC_CLASS 0x40000
199#define NECP_PARSED_PARAMETERS_FIELD_LOCAL_PORT 0x80000
200#define NECP_PARSED_PARAMETERS_FIELD_DELEGATED_UPID 0x100000
201#define NECP_PARSED_PARAMETERS_FIELD_ETHERTYPE 0x200000
202#define NECP_PARSED_PARAMETERS_FIELD_TRANSPORT_PROTOCOL 0x400000
203#define NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR_PREFERENCE 0x800000
204
205
206#define NECP_MAX_INTERFACE_PARAMETERS 16
207#define NECP_MAX_AGENT_PARAMETERS 4
208struct necp_client_parsed_parameters {
209 u_int32_t valid_fields;
210 u_int32_t flags;
211 u_int64_t delegated_upid;
212 union necp_sockaddr_union local_addr;
213 union necp_sockaddr_union remote_addr;
214 u_int32_t required_interface_index;
215 char prohibited_interfaces[NECP_MAX_INTERFACE_PARAMETERS][IFXNAMSIZ];
216 u_int8_t required_interface_type;
217 u_int8_t local_address_preference;
218 u_int8_t prohibited_interface_types[NECP_MAX_INTERFACE_PARAMETERS];
219 struct necp_client_parameter_netagent_type required_netagent_types[NECP_MAX_AGENT_PARAMETERS];
220 struct necp_client_parameter_netagent_type prohibited_netagent_types[NECP_MAX_AGENT_PARAMETERS];
221 struct necp_client_parameter_netagent_type preferred_netagent_types[NECP_MAX_AGENT_PARAMETERS];
222 struct necp_client_parameter_netagent_type avoided_netagent_types[NECP_MAX_AGENT_PARAMETERS];
223 uuid_t required_netagents[NECP_MAX_AGENT_PARAMETERS];
224 uuid_t prohibited_netagents[NECP_MAX_AGENT_PARAMETERS];
225 uuid_t preferred_netagents[NECP_MAX_AGENT_PARAMETERS];
226 uuid_t avoided_netagents[NECP_MAX_AGENT_PARAMETERS];
227 u_int8_t ip_protocol;
228 u_int8_t transport_protocol;
229 u_int16_t ethertype;
230 pid_t effective_pid;
231 uuid_t effective_uuid;
232 u_int32_t traffic_class;
233};
234
235static bool
236necp_find_matching_interface_index(struct necp_client_parsed_parameters *parsed_parameters,
237 u_int *return_ifindex, bool *validate_agents);
238
239static bool
240necp_ifnet_matches_local_address(struct ifnet *ifp, struct sockaddr *sa);
241
242static bool
243necp_ifnet_matches_parameters(struct ifnet *ifp,
244 struct necp_client_parsed_parameters *parsed_parameters,
245 u_int32_t override_flags,
246 u_int32_t *preferred_count,
247 bool secondary_interface,
248 bool require_scoped_field);
249
250static const struct fileops necp_fd_ops = {
251 .fo_type = DTYPE_NETPOLICY,
252 .fo_read = fo_no_read,
253 .fo_write = fo_no_write,
254 .fo_ioctl = fo_no_ioctl,
255 .fo_select = necpop_select,
256 .fo_close = necpop_close,
257 .fo_drain = fo_no_drain,
258 .fo_kqfilter = necpop_kqfilter,
259};
260
261struct necp_client_assertion {
262 LIST_ENTRY(necp_client_assertion) assertion_chain;
263 uuid_t asserted_netagent;
264};
265
266struct necp_client_flow_header {
267 struct necp_tlv_header outer_header;
268 struct necp_tlv_header flow_id_tlv_header;
269 uuid_t flow_id;
270 struct necp_tlv_header flags_tlv_header;
271 u_int32_t flags_value;
272 struct necp_tlv_header interface_tlv_header;
273 struct necp_client_result_interface interface_value;
274} __attribute__((__packed__));
275
276struct necp_client_flow_protoctl_event_header {
277 struct necp_tlv_header protoctl_tlv_header;
278 struct necp_client_flow_protoctl_event protoctl_event;
279} __attribute__((__packed__));
280
281struct necp_client_nexus_flow_header {
282 struct necp_client_flow_header flow_header;
283 struct necp_tlv_header agent_tlv_header;
284 struct necp_client_result_netagent agent_value;
285 struct necp_tlv_header tfo_cookie_tlv_header;
286 u_int8_t tfo_cookie_value[NECP_TFO_COOKIE_LEN_MAX];
287} __attribute__((__packed__));
288
289
290struct necp_client_flow {
291 LIST_ENTRY(necp_client_flow) flow_chain;
292 unsigned invalid : 1;
293 unsigned nexus : 1; // If true, flow is a nexus; if false, flow is attached to socket
294 unsigned socket : 1;
295 unsigned viable : 1;
296 unsigned assigned : 1;
297 unsigned has_protoctl_event : 1;
298 unsigned check_tcp_heuristics : 1;
299 unsigned _reserved : 1;
300 union {
301 uuid_t nexus_agent;
302 struct {
303 void *socket_handle;
304 necp_client_flow_cb cb;
305 };
306 } u;
307 uint32_t interface_index;
308 u_short delegated_interface_index;
309 uint16_t interface_flags;
310 uint32_t necp_flow_flags;
311 struct necp_client_flow_protoctl_event protoctl_event;
312 union necp_sockaddr_union local_addr;
313 union necp_sockaddr_union remote_addr;
314
315 size_t assigned_results_length;
316 u_int8_t *assigned_results;
317};
318
319struct necp_client_flow_registration {
320 RB_ENTRY(necp_client_flow_registration) fd_link;
321 RB_ENTRY(necp_client_flow_registration) global_link;
322 RB_ENTRY(necp_client_flow_registration) client_link;
323 LIST_ENTRY(necp_client_flow_registration) collect_stats_chain;
324 uuid_t registration_id;
325 u_int32_t flags;
326 unsigned flow_result_read : 1;
327 unsigned defunct : 1;
328 void *interface_handle;
329 necp_client_flow_cb interface_cb;
330 struct necp_client *client;
331 LIST_HEAD(_necp_registration_flow_list, necp_client_flow) flow_list;
332 u_int64_t last_interface_details __attribute__((aligned(sizeof(u_int64_t))));
333};
334
335static int necp_client_flow_id_cmp(struct necp_client_flow_registration *flow0, struct necp_client_flow_registration *flow1);
336
337RB_HEAD(_necp_client_flow_tree, necp_client_flow_registration);
338RB_PROTOTYPE_PREV(_necp_client_flow_tree, necp_client_flow_registration, client_link, necp_client_flow_id_cmp);
339RB_GENERATE_PREV(_necp_client_flow_tree, necp_client_flow_registration, client_link, necp_client_flow_id_cmp);
340
341#define NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT 4
342#define NECP_CLIENT_MAX_INTERFACE_OPTIONS 16
343
344#define NECP_CLIENT_INTERFACE_OPTION_EXTRA_COUNT (NECP_CLIENT_MAX_INTERFACE_OPTIONS - NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT)
345
346struct necp_client {
347 RB_ENTRY(necp_client) link;
348 RB_ENTRY(necp_client) global_link;
349
350 decl_lck_mtx_data(, lock);
351 decl_lck_mtx_data(, route_lock);
352 os_refcnt_t reference_count;
353
354 uuid_t client_id;
355 unsigned result_read : 1;
356 unsigned allow_multiple_flows : 1;
357 unsigned legacy_client_is_flow : 1;
358
359 unsigned platform_binary : 1;
360
361 size_t result_length;
362 u_int8_t result[NECP_MAX_CLIENT_RESULT_SIZE];
363
364 necp_policy_id policy_id;
365
366 u_int8_t ip_protocol;
367 int proc_pid;
368
369 u_int64_t delegated_upid;
370
371 struct _necp_client_flow_tree flow_registrations;
372 LIST_HEAD(_necp_client_assertion_list, necp_client_assertion) assertion_list;
373
374 struct rtentry *current_route;
375
376 struct necp_client_interface_option interface_options[NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT];
377 struct necp_client_interface_option *extra_interface_options;
378 u_int8_t interface_option_count; // Number in interface_options + extra_interface_options
379
380 struct necp_client_result_netagent failed_trigger_agent;
381
382 void *agent_handle;
383
384 uuid_t override_euuid;
385
386
387 size_t parameters_length;
388 u_int8_t parameters[0];
389};
390
391#define NECP_CLIENT_LOCK(_c) lck_mtx_lock(&_c->lock)
392#define NECP_CLIENT_UNLOCK(_c) lck_mtx_unlock(&_c->lock)
393#define NECP_CLIENT_ASSERT_LOCKED(_c) LCK_MTX_ASSERT(&_c->lock, LCK_MTX_ASSERT_OWNED)
394#define NECP_CLIENT_ASSERT_UNLOCKED(_c) LCK_MTX_ASSERT(&_c->lock, LCK_MTX_ASSERT_NOTOWNED)
395
396#define NECP_CLIENT_ROUTE_LOCK(_c) lck_mtx_lock(&_c->route_lock)
397#define NECP_CLIENT_ROUTE_UNLOCK(_c) lck_mtx_unlock(&_c->route_lock)
398
399static void necp_client_retain_locked(struct necp_client *client);
400static void necp_client_retain(struct necp_client *client);
401
402static bool necp_client_release_locked(struct necp_client *client);
403static bool necp_client_release(struct necp_client *client);
404
405static void
406necp_client_add_assertion(struct necp_client *client, uuid_t netagent_uuid);
407
408static bool
409necp_client_remove_assertion(struct necp_client *client, uuid_t netagent_uuid);
410
411LIST_HEAD(_necp_flow_registration_list, necp_client_flow_registration);
412static struct _necp_flow_registration_list necp_collect_stats_flow_list;
413
414struct necp_flow_defunct {
415 LIST_ENTRY(necp_flow_defunct) chain;
416
417 uuid_t flow_id;
418 uuid_t nexus_agent;
419 void *agent_handle;
420 int proc_pid;
421 u_int32_t flags;
422 struct necp_client_agent_parameters close_parameters;
423 bool has_close_parameters;
424};
425
426LIST_HEAD(_necp_flow_defunct_list, necp_flow_defunct);
427
428static int necp_client_id_cmp(struct necp_client *client0, struct necp_client *client1);
429
430RB_HEAD(_necp_client_tree, necp_client);
431RB_PROTOTYPE_PREV(_necp_client_tree, necp_client, link, necp_client_id_cmp);
432RB_GENERATE_PREV(_necp_client_tree, necp_client, link, necp_client_id_cmp);
433
434RB_HEAD(_necp_client_global_tree, necp_client);
435RB_PROTOTYPE_PREV(_necp_client_global_tree, necp_client, global_link, necp_client_id_cmp);
436RB_GENERATE_PREV(_necp_client_global_tree, necp_client, global_link, necp_client_id_cmp);
437
438RB_HEAD(_necp_fd_flow_tree, necp_client_flow_registration);
439RB_PROTOTYPE_PREV(_necp_fd_flow_tree, necp_client_flow_registration, fd_link, necp_client_flow_id_cmp);
440RB_GENERATE_PREV(_necp_fd_flow_tree, necp_client_flow_registration, fd_link, necp_client_flow_id_cmp);
441
442RB_HEAD(_necp_client_flow_global_tree, necp_client_flow_registration);
443RB_PROTOTYPE_PREV(_necp_client_flow_global_tree, necp_client_flow_registration, global_link, necp_client_flow_id_cmp);
444RB_GENERATE_PREV(_necp_client_flow_global_tree, necp_client_flow_registration, global_link, necp_client_flow_id_cmp);
445
446static struct _necp_client_global_tree necp_client_global_tree;
447static struct _necp_client_flow_global_tree necp_client_flow_global_tree;
448
449struct necp_client_update {
450 TAILQ_ENTRY(necp_client_update) chain;
451
452 uuid_t client_id;
453
454 size_t update_length;
455 struct necp_client_observer_update update;
456};
457
458
459#define NAIF_ATTACHED 0x1 // arena is attached to list
460#define NAIF_REDIRECT 0x2 // arena mmap has been redirected
461#define NAIF_DEFUNCT 0x4 // arena is now defunct
462
463struct necp_fd_data {
464 u_int8_t necp_fd_type;
465 LIST_ENTRY(necp_fd_data) chain;
466 struct _necp_client_tree clients;
467 struct _necp_fd_flow_tree flows;
468 TAILQ_HEAD(_necp_client_update_list, necp_client_update) update_list;
469 int update_count;
470 int flags;
471
472 unsigned background : 1;
473
474 int proc_pid;
475 decl_lck_mtx_data(, fd_lock);
476 struct selinfo si;
477};
478
479#define NECP_FD_LOCK(_f) lck_mtx_lock(&_f->fd_lock)
480#define NECP_FD_UNLOCK(_f) lck_mtx_unlock(&_f->fd_lock)
481#define NECP_FD_ASSERT_LOCKED(_f) LCK_MTX_ASSERT(&_f->fd_lock, LCK_MTX_ASSERT_OWNED)
482#define NECP_FD_ASSERT_UNLOCKED(_f) LCK_MTX_ASSERT(&_f->fd_lock, LCK_MTX_ASSERT_NOTOWNED)
483
484static LIST_HEAD(_necp_fd_list, necp_fd_data) necp_fd_list;
485static LIST_HEAD(_necp_fd_observer_list, necp_fd_data) necp_fd_observer_list;
486
487static ZONE_DECLARE(necp_client_fd_zone, "necp.clientfd",
488 sizeof(struct necp_fd_data), ZC_NONE);
489
490#define NECP_FLOW_ZONE_NAME "necp.flow"
491#define NECP_FLOW_REGISTRATION_ZONE_NAME "necp.flowregistration"
492
493static unsigned int necp_flow_size; /* size of necp_client_flow */
494static struct mcache *necp_flow_cache; /* cache for necp_client_flow */
495
496static unsigned int necp_flow_registration_size; /* size of necp_client_flow_registration */
497static struct mcache *necp_flow_registration_cache; /* cache for necp_client_flow_registration */
498
499
500static lck_grp_attr_t *necp_fd_grp_attr = NULL;
501static lck_attr_t *necp_fd_mtx_attr = NULL;
502static lck_grp_t *necp_fd_mtx_grp = NULL;
503
504decl_lck_rw_data(static, necp_fd_lock);
505decl_lck_rw_data(static, necp_observer_lock);
506decl_lck_rw_data(static, necp_client_tree_lock);
507decl_lck_rw_data(static, necp_flow_tree_lock);
508decl_lck_rw_data(static, necp_collect_stats_list_lock);
509
510#define NECP_STATS_LIST_LOCK_EXCLUSIVE() lck_rw_lock_exclusive(&necp_collect_stats_list_lock)
511#define NECP_STATS_LIST_LOCK_SHARED() lck_rw_lock_shared(&necp_collect_stats_list_lock)
512#define NECP_STATS_LIST_UNLOCK() lck_rw_done(&necp_collect_stats_list_lock)
513
514#define NECP_CLIENT_TREE_LOCK_EXCLUSIVE() lck_rw_lock_exclusive(&necp_client_tree_lock)
515#define NECP_CLIENT_TREE_LOCK_SHARED() lck_rw_lock_shared(&necp_client_tree_lock)
516#define NECP_CLIENT_TREE_UNLOCK() lck_rw_done(&necp_client_tree_lock)
517#define NECP_CLIENT_TREE_ASSERT_LOCKED() LCK_RW_ASSERT(&necp_client_tree_lock, LCK_RW_ASSERT_HELD)
518
519#define NECP_FLOW_TREE_LOCK_EXCLUSIVE() lck_rw_lock_exclusive(&necp_flow_tree_lock)
520#define NECP_FLOW_TREE_LOCK_SHARED() lck_rw_lock_shared(&necp_flow_tree_lock)
521#define NECP_FLOW_TREE_UNLOCK() lck_rw_done(&necp_flow_tree_lock)
522#define NECP_FLOW_TREE_ASSERT_LOCKED() LCK_RW_ASSERT(&necp_flow_tree_lock, LCK_RW_ASSERT_HELD)
523
524#define NECP_FD_LIST_LOCK_EXCLUSIVE() lck_rw_lock_exclusive(&necp_fd_lock)
525#define NECP_FD_LIST_LOCK_SHARED() lck_rw_lock_shared(&necp_fd_lock)
526#define NECP_FD_LIST_UNLOCK() lck_rw_done(&necp_fd_lock)
527
528#define NECP_OBSERVER_LIST_LOCK_EXCLUSIVE() lck_rw_lock_exclusive(&necp_observer_lock)
529#define NECP_OBSERVER_LIST_LOCK_SHARED() lck_rw_lock_shared(&necp_observer_lock)
530#define NECP_OBSERVER_LIST_UNLOCK() lck_rw_done(&necp_observer_lock)
531
532// Locking Notes
533
534// Take NECP_FD_LIST_LOCK when accessing or modifying the necp_fd_list
535// Take NECP_CLIENT_TREE_LOCK when accessing or modifying the necp_client_global_tree
536// Take NECP_FLOW_TREE_LOCK when accessing or modifying the necp_client_flow_global_tree
537// Take NECP_STATS_LIST_LOCK when accessing or modifying the necp_collect_stats_flow_list
538// Take NECP_FD_LOCK when accessing or modifying an necp_fd_data entry
539// Take NECP_CLIENT_LOCK when accessing or modifying a single necp_client
540// Take NECP_CLIENT_ROUTE_LOCK when accessing or modifying a client's route
541
542// Precedence, where 1 is the first lock that must be taken
543// 1. NECP_FD_LIST_LOCK
544// 2. NECP_FD_LOCK (any)
545// 3. NECP_CLIENT_TREE_LOCK
546// 4. NECP_CLIENT_LOCK (any)
547// 5. NECP_FLOW_TREE_LOCK
548// 6. NECP_STATS_LIST_LOCK
549// 7. NECP_CLIENT_ROUTE_LOCK (any)
550
551static thread_call_t necp_client_update_tcall;
552
553
554/// NECP file descriptor functions
555
556static void
557necp_fd_notify(struct necp_fd_data *fd_data, bool locked)
558{
559 struct selinfo *si = &fd_data->si;
560
561 if (!locked) {
562 NECP_FD_LOCK(fd_data);
563 }
564
565 selwakeup(si);
566
567 // use a non-zero hint to tell the notification from the
568 // call done in kqueue_scan() which uses 0
569 KNOTE(&si->si_note, 1); // notification
570
571 if (!locked) {
572 NECP_FD_UNLOCK(fd_data);
573 }
574}
575
576static inline bool
577necp_client_has_unread_flows(struct necp_client *client)
578{
579 NECP_CLIENT_ASSERT_LOCKED(client);
580 struct necp_client_flow_registration *flow_registration = NULL;
581 RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
582 if (!flow_registration->flow_result_read) {
583 return true;
584 }
585 }
586 return false;
587}
588
589static int
590necp_fd_poll(struct necp_fd_data *fd_data, int events, void *wql, struct proc *p, int is_kevent)
591{
592#pragma unused(wql, p, is_kevent)
593 u_int revents = 0;
594
595 u_int want_rx = events & (POLLIN | POLLRDNORM);
596 if (want_rx) {
597 if (fd_data->flags & NECP_OPEN_FLAG_PUSH_OBSERVER) {
598 // Push-mode observers are readable when they have a new update
599 if (!TAILQ_EMPTY(&fd_data->update_list)) {
600 revents |= want_rx;
601 }
602 } else {
603 // Standard fds are readable when some client is unread
604 struct necp_client *client = NULL;
605 bool has_unread_clients = FALSE;
606 RB_FOREACH(client, _necp_client_tree, &fd_data->clients) {
607 NECP_CLIENT_LOCK(client);
608 if (!client->result_read || necp_client_has_unread_flows(client)) {
609 has_unread_clients = TRUE;
610 }
611 NECP_CLIENT_UNLOCK(client);
612 if (has_unread_clients) {
613 break;
614 }
615 }
616
617 if (has_unread_clients) {
618 revents |= want_rx;
619 }
620 }
621 }
622
623 return revents;
624}
625
626static inline void
627necp_generate_client_id(uuid_t client_id, bool is_flow)
628{
629 uuid_generate_random(client_id);
630
631 if (is_flow) {
632 client_id[9] |= 0x01;
633 } else {
634 client_id[9] &= ~0x01;
635 }
636}
637
638static inline bool
639necp_client_id_is_flow(uuid_t client_id)
640{
641 return client_id[9] & 0x01;
642}
643
644static struct necp_client *
645necp_find_client_and_lock(uuid_t client_id)
646{
647 NECP_CLIENT_TREE_ASSERT_LOCKED();
648
649 struct necp_client *client = NULL;
650
651 if (necp_client_id_is_flow(client_id)) {
652 NECP_FLOW_TREE_LOCK_SHARED();
653 struct necp_client_flow_registration find;
654 uuid_copy(find.registration_id, client_id);
655 struct necp_client_flow_registration *flow = RB_FIND(_necp_client_flow_global_tree, &necp_client_flow_global_tree, &find);
656 if (flow != NULL) {
657 client = flow->client;
658 }
659 NECP_FLOW_TREE_UNLOCK();
660 } else {
661 struct necp_client find;
662 uuid_copy(find.client_id, client_id);
663 client = RB_FIND(_necp_client_global_tree, &necp_client_global_tree, &find);
664 }
665
666 if (client != NULL) {
667 NECP_CLIENT_LOCK(client);
668 }
669
670 return client;
671}
672
673static struct necp_client_flow_registration *
674necp_client_find_flow(struct necp_client *client, uuid_t flow_id)
675{
676 NECP_CLIENT_ASSERT_LOCKED(client);
677 struct necp_client_flow_registration *flow = NULL;
678
679 if (necp_client_id_is_flow(flow_id)) {
680 struct necp_client_flow_registration find;
681 uuid_copy(find.registration_id, flow_id);
682 flow = RB_FIND(_necp_client_flow_tree, &client->flow_registrations, &find);
683 } else {
684 flow = RB_ROOT(&client->flow_registrations);
685 }
686
687 return flow;
688}
689
690static struct necp_client *
691necp_client_fd_find_client_unlocked(struct necp_fd_data *client_fd, uuid_t client_id)
692{
693 NECP_FD_ASSERT_LOCKED(client_fd);
694 struct necp_client *client = NULL;
695
696 if (necp_client_id_is_flow(client_id)) {
697 struct necp_client_flow_registration find;
698 uuid_copy(find.registration_id, client_id);
699 struct necp_client_flow_registration *flow = RB_FIND(_necp_fd_flow_tree, &client_fd->flows, &find);
700 if (flow != NULL) {
701 client = flow->client;
702 }
703 } else {
704 struct necp_client find;
705 uuid_copy(find.client_id, client_id);
706 client = RB_FIND(_necp_client_tree, &client_fd->clients, &find);
707 }
708
709 return client;
710}
711
712static struct necp_client *
713necp_client_fd_find_client_and_lock(struct necp_fd_data *client_fd, uuid_t client_id)
714{
715 struct necp_client *client = necp_client_fd_find_client_unlocked(client_fd, client_id);
716 if (client != NULL) {
717 NECP_CLIENT_LOCK(client);
718 }
719
720 return client;
721}
722
723static inline int
724necp_client_id_cmp(struct necp_client *client0, struct necp_client *client1)
725{
726 return uuid_compare(client0->client_id, client1->client_id);
727}
728
729static inline int
730necp_client_flow_id_cmp(struct necp_client_flow_registration *flow0, struct necp_client_flow_registration *flow1)
731{
732 return uuid_compare(flow0->registration_id, flow1->registration_id);
733}
734
735static int
736necpop_select(struct fileproc *fp, int which, void *wql, vfs_context_t ctx)
737{
738#pragma unused(fp, which, wql, ctx)
739 return 0;
740 struct necp_fd_data *fd_data = NULL;
741 int revents = 0;
742 int events = 0;
743 proc_t procp;
744
745 fd_data = (struct necp_fd_data *)fp->fp_glob->fg_data;
746 if (fd_data == NULL) {
747 return 0;
748 }
749
750 procp = vfs_context_proc(ctx);
751
752 switch (which) {
753 case FREAD: {
754 events = POLLIN;
755 break;
756 }
757
758 default: {
759 return 1;
760 }
761 }
762
763 NECP_FD_LOCK(fd_data);
764 revents = necp_fd_poll(fd_data, events, wql, procp, 0);
765 NECP_FD_UNLOCK(fd_data);
766
767 return (events & revents) ? 1 : 0;
768}
769
770static void
771necp_fd_knrdetach(struct knote *kn)
772{
773 struct necp_fd_data *fd_data = (struct necp_fd_data *)kn->kn_hook;
774 struct selinfo *si = &fd_data->si;
775
776 NECP_FD_LOCK(fd_data);
777 KNOTE_DETACH(&si->si_note, kn);
778 NECP_FD_UNLOCK(fd_data);
779}
780
781static int
782necp_fd_knread(struct knote *kn, long hint)
783{
784#pragma unused(kn, hint)
785 return 1; /* assume we are ready */
786}
787
788static int
789necp_fd_knrprocess(struct knote *kn, struct kevent_qos_s *kev)
790{
791 struct necp_fd_data *fd_data;
792 int revents;
793 int res;
794
795 fd_data = (struct necp_fd_data *)kn->kn_hook;
796
797 NECP_FD_LOCK(fd_data);
798 revents = necp_fd_poll(fd_data, POLLIN, NULL, current_proc(), 1);
799 res = ((revents & POLLIN) != 0);
800 if (res) {
801 knote_fill_kevent(kn, kev, 0);
802 }
803 NECP_FD_UNLOCK(fd_data);
804 return res;
805}
806
807static int
808necp_fd_knrtouch(struct knote *kn, struct kevent_qos_s *kev)
809{
810#pragma unused(kev)
811 struct necp_fd_data *fd_data;
812 int revents;
813
814 fd_data = (struct necp_fd_data *)kn->kn_hook;
815
816 NECP_FD_LOCK(fd_data);
817 revents = necp_fd_poll(fd_data, POLLIN, NULL, current_proc(), 1);
818 NECP_FD_UNLOCK(fd_data);
819
820 return (revents & POLLIN) != 0;
821}
822
823SECURITY_READ_ONLY_EARLY(struct filterops) necp_fd_rfiltops = {
824 .f_isfd = 1,
825 .f_detach = necp_fd_knrdetach,
826 .f_event = necp_fd_knread,
827 .f_touch = necp_fd_knrtouch,
828 .f_process = necp_fd_knrprocess,
829};
830
831static int
832necpop_kqfilter(struct fileproc *fp, struct knote *kn,
833 __unused struct kevent_qos_s *kev)
834{
835 struct necp_fd_data *fd_data = NULL;
836 int revents;
837
838 if (kn->kn_filter != EVFILT_READ) {
839 NECPLOG(LOG_ERR, "bad filter request %d", kn->kn_filter);
840 knote_set_error(kn, EINVAL);
841 return 0;
842 }
843
844 fd_data = (struct necp_fd_data *)fp->fp_glob->fg_data;
845 if (fd_data == NULL) {
846 NECPLOG0(LOG_ERR, "No channel for kqfilter");
847 knote_set_error(kn, ENOENT);
848 return 0;
849 }
850
851 NECP_FD_LOCK(fd_data);
852 kn->kn_filtid = EVFILTID_NECP_FD;
853 kn->kn_hook = fd_data;
854 KNOTE_ATTACH(&fd_data->si.si_note, kn);
855
856 revents = necp_fd_poll(fd_data, POLLIN, NULL, current_proc(), 1);
857
858 NECP_FD_UNLOCK(fd_data);
859
860 return (revents & POLLIN) != 0;
861}
862
863#define INTERFACE_FLAGS_SHIFT 32
864#define INTERFACE_FLAGS_MASK 0xffff
865#define INTERFACE_INDEX_SHIFT 0
866#define INTERFACE_INDEX_MASK 0xffffffff
867
868static uint64_t
869combine_interface_details(uint32_t interface_index, uint16_t interface_flags)
870{
871 return ((uint64_t)interface_flags & INTERFACE_FLAGS_MASK) << INTERFACE_FLAGS_SHIFT |
872 ((uint64_t)interface_index & INTERFACE_INDEX_MASK) << INTERFACE_INDEX_SHIFT;
873}
874
875
876static void
877necp_defunct_flow_registration(struct necp_client *client,
878 struct necp_client_flow_registration *flow_registration,
879 struct _necp_flow_defunct_list *defunct_list)
880{
881 NECP_CLIENT_ASSERT_LOCKED(client);
882
883 if (!flow_registration->defunct) {
884 bool needs_defunct = false;
885 struct necp_client_flow *search_flow = NULL;
886 LIST_FOREACH(search_flow, &flow_registration->flow_list, flow_chain) {
887 if (search_flow->nexus &&
888 !uuid_is_null(search_flow->u.nexus_agent)) {
889 // Save defunct values for the nexus
890 if (defunct_list != NULL) {
891 // Sleeping alloc won't fail; copy only what's necessary
892 struct necp_flow_defunct *flow_defunct = _MALLOC(sizeof(struct necp_flow_defunct),
893 M_NECP, M_WAITOK | M_ZERO);
894 uuid_copy(flow_defunct->nexus_agent, search_flow->u.nexus_agent);
895 uuid_copy(flow_defunct->flow_id, ((flow_registration->flags & NECP_CLIENT_FLOW_FLAGS_USE_CLIENT_ID) ?
896 client->client_id :
897 flow_registration->registration_id));
898 flow_defunct->proc_pid = client->proc_pid;
899 flow_defunct->agent_handle = client->agent_handle;
900 flow_defunct->flags = flow_registration->flags;
901 // Add to the list provided by caller
902 LIST_INSERT_HEAD(defunct_list, flow_defunct, chain);
903 }
904
905 needs_defunct = true;
906 }
907 }
908
909 if (needs_defunct) {
910
911 // Only set defunct if there was some assigned flow
912 flow_registration->defunct = true;
913 }
914 }
915}
916
917static void
918necp_defunct_client_for_policy(struct necp_client *client,
919 struct _necp_flow_defunct_list *defunct_list)
920{
921 NECP_CLIENT_ASSERT_LOCKED(client);
922
923 struct necp_client_flow_registration *flow_registration = NULL;
924 RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
925 necp_defunct_flow_registration(client, flow_registration, defunct_list);
926 }
927}
928
929static void
930necp_client_free(struct necp_client *client)
931{
932 NECP_CLIENT_ASSERT_LOCKED(client);
933
934 NECP_CLIENT_UNLOCK(client);
935
936 FREE(client->extra_interface_options, M_NECP);
937 client->extra_interface_options = NULL;
938
939 lck_mtx_destroy(&client->route_lock, necp_fd_mtx_grp);
940 lck_mtx_destroy(&client->lock, necp_fd_mtx_grp);
941
942 FREE(client, M_NECP);
943}
944
945static void
946necp_client_retain_locked(struct necp_client *client)
947{
948 NECP_CLIENT_ASSERT_LOCKED(client);
949
950 os_ref_retain_locked(&client->reference_count);
951}
952
953static void
954necp_client_retain(struct necp_client *client)
955{
956 NECP_CLIENT_LOCK(client);
957 necp_client_retain_locked(client);
958 NECP_CLIENT_UNLOCK(client);
959}
960
961static bool
962necp_client_release_locked(struct necp_client *client)
963{
964 NECP_CLIENT_ASSERT_LOCKED(client);
965
966 os_ref_count_t count = os_ref_release_locked(&client->reference_count);
967 if (count == 0) {
968 necp_client_free(client);
969 }
970
971 return count == 0;
972}
973
974static bool
975necp_client_release(struct necp_client *client)
976{
977 bool last_ref;
978
979 NECP_CLIENT_LOCK(client);
980 if (!(last_ref = necp_client_release_locked(client))) {
981 NECP_CLIENT_UNLOCK(client);
982 }
983
984 return last_ref;
985}
986
987static void
988necp_client_update_observer_add_internal(struct necp_fd_data *observer_fd, struct necp_client *client)
989{
990 NECP_FD_LOCK(observer_fd);
991
992 if (observer_fd->update_count >= necp_observer_message_limit) {
993 NECP_FD_UNLOCK(observer_fd);
994 return;
995 }
996
997 struct necp_client_update *client_update = _MALLOC(sizeof(struct necp_client_update) + client->parameters_length,
998 M_NECP, M_WAITOK | M_ZERO);
999 if (client_update != NULL) {
1000 client_update->update_length = sizeof(struct necp_client_observer_update) + client->parameters_length;
1001 uuid_copy(client_update->client_id, client->client_id);
1002 client_update->update.update_type = NECP_CLIENT_UPDATE_TYPE_PARAMETERS;
1003 memcpy(client_update->update.tlv_buffer, client->parameters, client->parameters_length);
1004 TAILQ_INSERT_TAIL(&observer_fd->update_list, client_update, chain);
1005 observer_fd->update_count++;
1006
1007 necp_fd_notify(observer_fd, true);
1008 }
1009
1010 NECP_FD_UNLOCK(observer_fd);
1011}
1012
1013static void
1014necp_client_update_observer_update_internal(struct necp_fd_data *observer_fd, struct necp_client *client)
1015{
1016 NECP_FD_LOCK(observer_fd);
1017
1018 if (observer_fd->update_count >= necp_observer_message_limit) {
1019 NECP_FD_UNLOCK(observer_fd);
1020 return;
1021 }
1022
1023 struct necp_client_update *client_update = _MALLOC(sizeof(struct necp_client_update) + client->result_length,
1024 M_NECP, M_WAITOK | M_ZERO);
1025 if (client_update != NULL) {
1026 client_update->update_length = sizeof(struct necp_client_observer_update) + client->result_length;
1027 uuid_copy(client_update->client_id, client->client_id);
1028 client_update->update.update_type = NECP_CLIENT_UPDATE_TYPE_RESULT;
1029 memcpy(client_update->update.tlv_buffer, client->result, client->result_length);
1030 TAILQ_INSERT_TAIL(&observer_fd->update_list, client_update, chain);
1031 observer_fd->update_count++;
1032
1033 necp_fd_notify(observer_fd, true);
1034 }
1035
1036 NECP_FD_UNLOCK(observer_fd);
1037}
1038
1039static void
1040necp_client_update_observer_remove_internal(struct necp_fd_data *observer_fd, struct necp_client *client)
1041{
1042 NECP_FD_LOCK(observer_fd);
1043
1044 if (observer_fd->update_count >= necp_observer_message_limit) {
1045 NECP_FD_UNLOCK(observer_fd);
1046 return;
1047 }
1048
1049 struct necp_client_update *client_update = _MALLOC(sizeof(struct necp_client_update),
1050 M_NECP, M_WAITOK | M_ZERO);
1051 if (client_update != NULL) {
1052 client_update->update_length = sizeof(struct necp_client_observer_update);
1053 uuid_copy(client_update->client_id, client->client_id);
1054 client_update->update.update_type = NECP_CLIENT_UPDATE_TYPE_REMOVE;
1055 TAILQ_INSERT_TAIL(&observer_fd->update_list, client_update, chain);
1056 observer_fd->update_count++;
1057
1058 necp_fd_notify(observer_fd, true);
1059 }
1060
1061 NECP_FD_UNLOCK(observer_fd);
1062}
1063
1064static void
1065necp_client_update_observer_add(struct necp_client *client)
1066{
1067 NECP_OBSERVER_LIST_LOCK_SHARED();
1068
1069 if (LIST_EMPTY(&necp_fd_observer_list)) {
1070 // No observers, bail
1071 NECP_OBSERVER_LIST_UNLOCK();
1072 return;
1073 }
1074
1075 struct necp_fd_data *observer_fd = NULL;
1076 LIST_FOREACH(observer_fd, &necp_fd_observer_list, chain) {
1077 necp_client_update_observer_add_internal(observer_fd, client);
1078 }
1079
1080 NECP_OBSERVER_LIST_UNLOCK();
1081}
1082
1083static void
1084necp_client_update_observer_update(struct necp_client *client)
1085{
1086 NECP_OBSERVER_LIST_LOCK_SHARED();
1087
1088 if (LIST_EMPTY(&necp_fd_observer_list)) {
1089 // No observers, bail
1090 NECP_OBSERVER_LIST_UNLOCK();
1091 return;
1092 }
1093
1094 struct necp_fd_data *observer_fd = NULL;
1095 LIST_FOREACH(observer_fd, &necp_fd_observer_list, chain) {
1096 necp_client_update_observer_update_internal(observer_fd, client);
1097 }
1098
1099 NECP_OBSERVER_LIST_UNLOCK();
1100}
1101
1102static void
1103necp_client_update_observer_remove(struct necp_client *client)
1104{
1105 NECP_OBSERVER_LIST_LOCK_SHARED();
1106
1107 if (LIST_EMPTY(&necp_fd_observer_list)) {
1108 // No observers, bail
1109 NECP_OBSERVER_LIST_UNLOCK();
1110 return;
1111 }
1112
1113 struct necp_fd_data *observer_fd = NULL;
1114 LIST_FOREACH(observer_fd, &necp_fd_observer_list, chain) {
1115 necp_client_update_observer_remove_internal(observer_fd, client);
1116 }
1117
1118 NECP_OBSERVER_LIST_UNLOCK();
1119}
1120
1121static void
1122necp_destroy_client_flow_registration(struct necp_client *client,
1123 struct necp_client_flow_registration *flow_registration,
1124 pid_t pid, bool abort)
1125{
1126 NECP_CLIENT_ASSERT_LOCKED(client);
1127
1128 bool has_close_parameters = false;
1129 struct necp_client_agent_parameters close_parameters = {};
1130 memset(close_parameters.u.close_token, 0, sizeof(close_parameters.u.close_token));
1131
1132 struct necp_client_flow *search_flow = NULL;
1133 struct necp_client_flow *temp_flow = NULL;
1134 LIST_FOREACH_SAFE(search_flow, &flow_registration->flow_list, flow_chain, temp_flow) {
1135 if (search_flow->nexus &&
1136 !uuid_is_null(search_flow->u.nexus_agent)) {
1137 // Don't unregister for defunct flows
1138 if (!flow_registration->defunct) {
1139 u_int8_t message_type = (abort ? NETAGENT_MESSAGE_TYPE_ABORT_NEXUS :
1140 NETAGENT_MESSAGE_TYPE_CLOSE_NEXUS);
1141 if (((flow_registration->flags & NECP_CLIENT_FLOW_FLAGS_BROWSE) ||
1142 (flow_registration->flags & NECP_CLIENT_FLOW_FLAGS_RESOLVE)) &&
1143 !(flow_registration->flags & NECP_CLIENT_FLOW_FLAGS_ALLOW_NEXUS)) {
1144 message_type = NETAGENT_MESSAGE_TYPE_CLIENT_UNASSERT;
1145 }
1146 int netagent_error = netagent_client_message_with_params(search_flow->u.nexus_agent,
1147 ((flow_registration->flags & NECP_CLIENT_FLOW_FLAGS_USE_CLIENT_ID) ?
1148 client->client_id :
1149 flow_registration->registration_id),
1150 pid, client->agent_handle,
1151 message_type,
1152 has_close_parameters ? &close_parameters : NULL,
1153 NULL, 0);
1154 if (netagent_error != 0 && netagent_error != ENOENT) {
1155 NECPLOG(LOG_ERR, "necp_client_remove close nexus error (%d) MESSAGE TYPE %u", netagent_error, message_type);
1156 }
1157 }
1158 uuid_clear(search_flow->u.nexus_agent);
1159 }
1160 if (search_flow->assigned_results != NULL) {
1161 FREE(search_flow->assigned_results, M_NETAGENT);
1162 search_flow->assigned_results = NULL;
1163 }
1164 LIST_REMOVE(search_flow, flow_chain);
1165 if (search_flow->socket) {
1166 OSDecrementAtomic(&necp_socket_flow_count);
1167 } else {
1168 OSDecrementAtomic(&necp_if_flow_count);
1169 }
1170 mcache_free(necp_flow_cache, search_flow);
1171 }
1172
1173 RB_REMOVE(_necp_client_flow_tree, &client->flow_registrations, flow_registration);
1174 flow_registration->client = NULL;
1175
1176 mcache_free(necp_flow_registration_cache, flow_registration);
1177}
1178
1179static void
1180necp_destroy_client(struct necp_client *client, pid_t pid, bool abort)
1181{
1182 NECP_CLIENT_ASSERT_UNLOCKED(client);
1183
1184 necp_client_update_observer_remove(client);
1185
1186 NECP_CLIENT_LOCK(client);
1187
1188 // Free route
1189 NECP_CLIENT_ROUTE_LOCK(client);
1190 if (client->current_route != NULL) {
1191 rtfree(client->current_route);
1192 client->current_route = NULL;
1193 }
1194 NECP_CLIENT_ROUTE_UNLOCK(client);
1195
1196 // Remove flow assignments
1197 struct necp_client_flow_registration *flow_registration = NULL;
1198 struct necp_client_flow_registration *temp_flow_registration = NULL;
1199 RB_FOREACH_SAFE(flow_registration, _necp_client_flow_tree, &client->flow_registrations, temp_flow_registration) {
1200 necp_destroy_client_flow_registration(client, flow_registration, pid, abort);
1201 }
1202
1203
1204 // Remove agent assertions
1205 struct necp_client_assertion *search_assertion = NULL;
1206 struct necp_client_assertion *temp_assertion = NULL;
1207 LIST_FOREACH_SAFE(search_assertion, &client->assertion_list, assertion_chain, temp_assertion) {
1208 int netagent_error = netagent_client_message(search_assertion->asserted_netagent, client->client_id, pid,
1209 client->agent_handle, NETAGENT_MESSAGE_TYPE_CLIENT_UNASSERT);
1210 if (netagent_error != 0) {
1211 NECPLOG((netagent_error == ENOENT ? LOG_DEBUG : LOG_ERR),
1212 "necp_client_remove unassert agent error (%d)", netagent_error);
1213 }
1214 LIST_REMOVE(search_assertion, assertion_chain);
1215 FREE(search_assertion, M_NECP);
1216 }
1217
1218 if (!necp_client_release_locked(client)) {
1219 NECP_CLIENT_UNLOCK(client);
1220 }
1221
1222 OSDecrementAtomic(&necp_client_count);
1223}
1224
1225static bool
1226necp_defunct_client_fd_locked_inner(struct necp_fd_data *client_fd, struct _necp_flow_defunct_list *defunct_list, bool destroy_stats);
1227
1228static void
1229necp_process_defunct_list(struct _necp_flow_defunct_list *defunct_list)
1230{
1231 if (!LIST_EMPTY(defunct_list)) {
1232 struct necp_flow_defunct *flow_defunct = NULL;
1233 struct necp_flow_defunct *temp_flow_defunct = NULL;
1234
1235 // For each newly defunct client, send a message to the nexus to remove the flow
1236 LIST_FOREACH_SAFE(flow_defunct, defunct_list, chain, temp_flow_defunct) {
1237 if (!uuid_is_null(flow_defunct->nexus_agent)) {
1238 u_int8_t message_type = NETAGENT_MESSAGE_TYPE_ABORT_NEXUS;
1239 if (((flow_defunct->flags & NECP_CLIENT_FLOW_FLAGS_BROWSE) ||
1240 (flow_defunct->flags & NECP_CLIENT_FLOW_FLAGS_RESOLVE)) &&
1241 !(flow_defunct->flags & NECP_CLIENT_FLOW_FLAGS_ALLOW_NEXUS)) {
1242 message_type = NETAGENT_MESSAGE_TYPE_CLIENT_UNASSERT;
1243 }
1244 int netagent_error = netagent_client_message_with_params(flow_defunct->nexus_agent,
1245 flow_defunct->flow_id,
1246 flow_defunct->proc_pid,
1247 flow_defunct->agent_handle,
1248 message_type,
1249 flow_defunct->has_close_parameters ? &flow_defunct->close_parameters : NULL,
1250 NULL, 0);
1251 if (netagent_error != 0) {
1252 char namebuf[MAXCOMLEN + 1];
1253 (void) strlcpy(namebuf, "unknown", sizeof(namebuf));
1254 proc_name(flow_defunct->proc_pid, namebuf, sizeof(namebuf));
1255 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);
1256 }
1257 }
1258 LIST_REMOVE(flow_defunct, chain);
1259 FREE(flow_defunct, M_NECP);
1260 }
1261 }
1262 ASSERT(LIST_EMPTY(defunct_list));
1263}
1264
1265static int
1266necpop_close(struct fileglob *fg, vfs_context_t ctx)
1267{
1268#pragma unused(ctx)
1269 struct necp_fd_data *fd_data = NULL;
1270 int error = 0;
1271
1272 fd_data = (struct necp_fd_data *)fg->fg_data;
1273 fg->fg_data = NULL;
1274
1275 if (fd_data != NULL) {
1276 struct _necp_client_tree clients_to_close;
1277 RB_INIT(&clients_to_close);
1278
1279 // Remove from list quickly
1280 if (fd_data->flags & NECP_OPEN_FLAG_PUSH_OBSERVER) {
1281 NECP_OBSERVER_LIST_LOCK_EXCLUSIVE();
1282 LIST_REMOVE(fd_data, chain);
1283 NECP_OBSERVER_LIST_UNLOCK();
1284 } else {
1285 NECP_FD_LIST_LOCK_EXCLUSIVE();
1286 LIST_REMOVE(fd_data, chain);
1287 NECP_FD_LIST_UNLOCK();
1288 }
1289
1290 NECP_FD_LOCK(fd_data);
1291 pid_t pid = fd_data->proc_pid;
1292
1293 struct _necp_flow_defunct_list defunct_list;
1294 LIST_INIT(&defunct_list);
1295
1296 (void)necp_defunct_client_fd_locked_inner(fd_data, &defunct_list, false);
1297
1298 struct necp_client_flow_registration *flow_registration = NULL;
1299 struct necp_client_flow_registration *temp_flow_registration = NULL;
1300 RB_FOREACH_SAFE(flow_registration, _necp_fd_flow_tree, &fd_data->flows, temp_flow_registration) {
1301 NECP_FLOW_TREE_LOCK_EXCLUSIVE();
1302 RB_REMOVE(_necp_client_flow_global_tree, &necp_client_flow_global_tree, flow_registration);
1303 NECP_FLOW_TREE_UNLOCK();
1304 RB_REMOVE(_necp_fd_flow_tree, &fd_data->flows, flow_registration);
1305 }
1306
1307 struct necp_client *client = NULL;
1308 struct necp_client *temp_client = NULL;
1309 RB_FOREACH_SAFE(client, _necp_client_tree, &fd_data->clients, temp_client) {
1310 NECP_CLIENT_TREE_LOCK_EXCLUSIVE();
1311 RB_REMOVE(_necp_client_global_tree, &necp_client_global_tree, client);
1312 NECP_CLIENT_TREE_UNLOCK();
1313 RB_REMOVE(_necp_client_tree, &fd_data->clients, client);
1314 RB_INSERT(_necp_client_tree, &clients_to_close, client);
1315 }
1316
1317 struct necp_client_update *client_update = NULL;
1318 struct necp_client_update *temp_update = NULL;
1319 TAILQ_FOREACH_SAFE(client_update, &fd_data->update_list, chain, temp_update) {
1320 // Flush pending updates
1321 TAILQ_REMOVE(&fd_data->update_list, client_update, chain);
1322 FREE(client_update, M_NECP);
1323 }
1324 fd_data->update_count = 0;
1325
1326
1327 NECP_FD_UNLOCK(fd_data);
1328
1329 selthreadclear(&fd_data->si);
1330
1331 lck_mtx_destroy(&fd_data->fd_lock, necp_fd_mtx_grp);
1332
1333 if (fd_data->flags & NECP_OPEN_FLAG_PUSH_OBSERVER) {
1334 OSDecrementAtomic(&necp_observer_fd_count);
1335 } else {
1336 OSDecrementAtomic(&necp_client_fd_count);
1337 }
1338
1339 zfree(necp_client_fd_zone, fd_data);
1340 fd_data = NULL;
1341
1342 RB_FOREACH_SAFE(client, _necp_client_tree, &clients_to_close, temp_client) {
1343 RB_REMOVE(_necp_client_tree, &clients_to_close, client);
1344 necp_destroy_client(client, pid, true);
1345 }
1346
1347 necp_process_defunct_list(&defunct_list);
1348 }
1349
1350 return error;
1351}
1352
1353/// NECP client utilities
1354
1355static inline bool
1356necp_address_is_wildcard(const union necp_sockaddr_union * const addr)
1357{
1358 return (addr->sa.sa_family == AF_INET && addr->sin.sin_addr.s_addr == INADDR_ANY) ||
1359 (addr->sa.sa_family == AF_INET6 && IN6_IS_ADDR_UNSPECIFIED(&addr->sin6.sin6_addr));
1360}
1361
1362static int
1363necp_find_fd_data(struct proc *p, int fd,
1364 struct fileproc **fpp, struct necp_fd_data **fd_data)
1365{
1366 struct fileproc *fp;
1367 int error = fp_get_ftype(p, fd, DTYPE_NETPOLICY, ENODEV, &fp);
1368
1369 if (error == 0) {
1370 *fd_data = (struct necp_fd_data *)fp->fp_glob->fg_data;
1371 *fpp = fp;
1372
1373 if ((*fd_data)->necp_fd_type != necp_fd_type_client) {
1374 // Not a client fd, ignore
1375 fp_drop(p, fd, fp, 0);
1376 error = EINVAL;
1377 }
1378 }
1379 return error;
1380}
1381
1382static void
1383necp_client_add_nexus_flow(struct necp_client_flow_registration *flow_registration,
1384 uuid_t nexus_agent,
1385 uint32_t interface_index,
1386 uint16_t interface_flags)
1387{
1388 struct necp_client_flow *new_flow = mcache_alloc(necp_flow_cache, MCR_SLEEP);
1389 if (new_flow == NULL) {
1390 NECPLOG0(LOG_ERR, "Failed to allocate nexus flow");
1391 return;
1392 }
1393
1394 memset(new_flow, 0, sizeof(*new_flow));
1395
1396 new_flow->nexus = TRUE;
1397 uuid_copy(new_flow->u.nexus_agent, nexus_agent);
1398 new_flow->interface_index = interface_index;
1399 new_flow->interface_flags = interface_flags;
1400 new_flow->check_tcp_heuristics = TRUE;
1401
1402
1403 LIST_INSERT_HEAD(&flow_registration->flow_list, new_flow, flow_chain);
1404
1405}
1406
1407static void
1408necp_client_add_nexus_flow_if_needed(struct necp_client_flow_registration *flow_registration,
1409 uuid_t nexus_agent,
1410 uint32_t interface_index)
1411{
1412 struct necp_client_flow *flow = NULL;
1413 LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
1414 if (flow->nexus &&
1415 uuid_compare(flow->u.nexus_agent, nexus_agent) == 0) {
1416 return;
1417 }
1418 }
1419
1420 uint16_t interface_flags = 0;
1421 ifnet_t ifp = NULL;
1422 ifnet_head_lock_shared();
1423 if (interface_index != IFSCOPE_NONE && interface_index <= (u_int32_t)if_index) {
1424 ifp = ifindex2ifnet[interface_index];
1425 if (ifp != NULL) {
1426 ifnet_lock_shared(ifp);
1427 interface_flags = nstat_ifnet_to_flags(ifp);
1428 ifnet_lock_done(ifp);
1429 }
1430 }
1431 ifnet_head_done();
1432 necp_client_add_nexus_flow(flow_registration, nexus_agent, interface_index, interface_flags);
1433}
1434
1435static struct necp_client_flow *
1436necp_client_add_interface_flow(struct necp_client_flow_registration *flow_registration,
1437 uint32_t interface_index)
1438{
1439 struct necp_client_flow *new_flow = mcache_alloc(necp_flow_cache, MCR_SLEEP);
1440 if (new_flow == NULL) {
1441 NECPLOG0(LOG_ERR, "Failed to allocate interface flow");
1442 return NULL;
1443 }
1444
1445 memset(new_flow, 0, sizeof(*new_flow));
1446
1447 // Neither nexus nor socket
1448 new_flow->interface_index = interface_index;
1449 new_flow->u.socket_handle = flow_registration->interface_handle;
1450 new_flow->u.cb = flow_registration->interface_cb;
1451
1452 OSIncrementAtomic(&necp_if_flow_count);
1453
1454 LIST_INSERT_HEAD(&flow_registration->flow_list, new_flow, flow_chain);
1455
1456 return new_flow;
1457}
1458
1459static struct necp_client_flow *
1460necp_client_add_interface_flow_if_needed(struct necp_client *client,
1461 struct necp_client_flow_registration *flow_registration,
1462 uint32_t interface_index)
1463{
1464 if (!client->allow_multiple_flows ||
1465 interface_index == IFSCOPE_NONE) {
1466 // Interface not set, or client not allowed to use this mode
1467 return NULL;
1468 }
1469
1470 struct necp_client_flow *flow = NULL;
1471 LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
1472 if (!flow->nexus && !flow->socket && flow->interface_index == interface_index) {
1473 // Already have the flow
1474 flow->invalid = FALSE;
1475 flow->u.socket_handle = flow_registration->interface_handle;
1476 flow->u.cb = flow_registration->interface_cb;
1477 return NULL;
1478 }
1479 }
1480 return necp_client_add_interface_flow(flow_registration, interface_index);
1481}
1482
1483static void
1484necp_client_add_interface_option_if_needed(struct necp_client *client,
1485 uint32_t interface_index,
1486 uint32_t interface_generation,
1487 uuid_t *nexus_agent,
1488 bool network_provider)
1489{
1490 if ((interface_index == IFSCOPE_NONE && !network_provider) ||
1491 (client->interface_option_count != 0 && !client->allow_multiple_flows)) {
1492 // Interface or agent not set, or client not allowed to use this mode
1493 return;
1494 }
1495
1496 if (client->interface_option_count >= NECP_CLIENT_MAX_INTERFACE_OPTIONS) {
1497 // Cannot take any more interface options
1498 return;
1499 }
1500
1501 // Check if already present
1502 for (u_int32_t option_i = 0; option_i < client->interface_option_count; option_i++) {
1503 if (option_i < NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT) {
1504 struct necp_client_interface_option *option = &client->interface_options[option_i];
1505 if (option->interface_index == interface_index) {
1506 if (nexus_agent == NULL) {
1507 return;
1508 }
1509 if (uuid_compare(option->nexus_agent, *nexus_agent) == 0) {
1510 return;
1511 }
1512 if (uuid_is_null(option->nexus_agent)) {
1513 uuid_copy(option->nexus_agent, *nexus_agent);
1514 return;
1515 }
1516 // If we get to this point, this is a new nexus flow
1517 }
1518 } else {
1519 struct necp_client_interface_option *option = &client->extra_interface_options[option_i - NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT];
1520 if (option->interface_index == interface_index) {
1521 if (nexus_agent == NULL) {
1522 return;
1523 }
1524 if (uuid_compare(option->nexus_agent, *nexus_agent) == 0) {
1525 return;
1526 }
1527 if (uuid_is_null(option->nexus_agent)) {
1528 uuid_copy(option->nexus_agent, *nexus_agent);
1529 return;
1530 }
1531 // If we get to this point, this is a new nexus flow
1532 }
1533 }
1534 }
1535
1536 // Add a new entry
1537 if (client->interface_option_count < NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT) {
1538 // Add to static
1539 struct necp_client_interface_option *option = &client->interface_options[client->interface_option_count];
1540 option->interface_index = interface_index;
1541 option->interface_generation = interface_generation;
1542 if (nexus_agent != NULL) {
1543 uuid_copy(option->nexus_agent, *nexus_agent);
1544 } else {
1545 uuid_clear(option->nexus_agent);
1546 }
1547 client->interface_option_count++;
1548 } else {
1549 // Add to extra
1550 if (client->extra_interface_options == NULL) {
1551 client->extra_interface_options = _MALLOC(sizeof(struct necp_client_interface_option) * NECP_CLIENT_INTERFACE_OPTION_EXTRA_COUNT, M_NECP, M_WAITOK | M_ZERO);
1552 }
1553 if (client->extra_interface_options != NULL) {
1554 struct necp_client_interface_option *option = &client->extra_interface_options[client->interface_option_count - NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT];
1555 option->interface_index = interface_index;
1556 option->interface_generation = interface_generation;
1557 if (nexus_agent != NULL) {
1558 uuid_copy(option->nexus_agent, *nexus_agent);
1559 } else {
1560 uuid_clear(option->nexus_agent);
1561 }
1562 client->interface_option_count++;
1563 }
1564 }
1565}
1566
1567static bool
1568necp_client_flow_is_viable(proc_t proc, struct necp_client *client,
1569 struct necp_client_flow *flow)
1570{
1571 struct necp_aggregate_result result;
1572 bool ignore_address = (client->allow_multiple_flows && !flow->nexus && !flow->socket);
1573
1574 flow->necp_flow_flags = 0;
1575 int error = necp_application_find_policy_match_internal(proc, client->parameters,
1576 (u_int32_t)client->parameters_length,
1577 &result, &flow->necp_flow_flags, NULL,
1578 flow->interface_index,
1579 &flow->local_addr, &flow->remote_addr, NULL, NULL,
1580 NULL, ignore_address, true, NULL);
1581
1582 // Check for blocking agents
1583 for (int i = 0; i < NECP_MAX_NETAGENTS; i++) {
1584 if (uuid_is_null(result.netagents[i])) {
1585 // Passed end of valid agents
1586 break;
1587 }
1588
1589 u_int32_t flags = netagent_get_flags(result.netagents[i]);
1590 if ((flags & NETAGENT_FLAG_REGISTERED) &&
1591 !(flags & NETAGENT_FLAG_VOLUNTARY) &&
1592 !(flags & NETAGENT_FLAG_ACTIVE) &&
1593 !(flags & NETAGENT_FLAG_SPECIFIC_USE_ONLY)) {
1594 // A required agent is not active, cause the flow to be marked non-viable
1595 return false;
1596 }
1597 }
1598
1599 if (flow->interface_index != IFSCOPE_NONE) {
1600 ifnet_head_lock_shared();
1601
1602 struct ifnet *ifp = ifindex2ifnet[flow->interface_index];
1603 if (ifp && ifp->if_delegated.ifp != IFSCOPE_NONE) {
1604 flow->delegated_interface_index = ifp->if_delegated.ifp->if_index;
1605 }
1606
1607 ifnet_head_done();
1608 }
1609
1610 return error == 0 &&
1611 result.routed_interface_index != IFSCOPE_NONE &&
1612 result.routing_result != NECP_KERNEL_POLICY_RESULT_DROP;
1613}
1614
1615static void
1616necp_flow_add_interface_flows(proc_t proc,
1617 struct necp_client *client,
1618 struct necp_client_flow_registration *flow_registration,
1619 bool send_initial)
1620{
1621 // Traverse all interfaces and add a tracking flow if needed
1622 for (u_int32_t option_i = 0; option_i < client->interface_option_count; option_i++) {
1623 if (option_i < NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT) {
1624 struct necp_client_interface_option *option = &client->interface_options[option_i];
1625 struct necp_client_flow *flow = necp_client_add_interface_flow_if_needed(client, flow_registration, option->interface_index);
1626 if (flow != NULL && send_initial) {
1627 flow->viable = necp_client_flow_is_viable(proc, client, flow);
1628 if (flow->viable && flow->u.cb) {
1629 bool viable = flow->viable;
1630 flow->u.cb(flow_registration->interface_handle, NECP_CLIENT_CBACTION_INITIAL, flow->interface_index, flow->necp_flow_flags, &viable);
1631 flow->viable = viable;
1632 }
1633 }
1634 } else {
1635 struct necp_client_interface_option *option = &client->extra_interface_options[option_i - NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT];
1636 struct necp_client_flow *flow = necp_client_add_interface_flow_if_needed(client, flow_registration, option->interface_index);
1637 if (flow != NULL && send_initial) {
1638 flow->viable = necp_client_flow_is_viable(proc, client, flow);
1639 if (flow->viable && flow->u.cb) {
1640 bool viable = flow->viable;
1641 flow->u.cb(flow_registration->interface_handle, NECP_CLIENT_CBACTION_INITIAL, flow->interface_index, flow->necp_flow_flags, &viable);
1642 flow->viable = viable;
1643 }
1644 }
1645 }
1646 }
1647}
1648
1649static bool
1650necp_client_update_flows(proc_t proc,
1651 struct necp_client *client,
1652 struct _necp_flow_defunct_list *defunct_list)
1653{
1654 NECP_CLIENT_ASSERT_LOCKED(client);
1655
1656 bool any_client_updated = FALSE;
1657 struct necp_client_flow *flow = NULL;
1658 struct necp_client_flow *temp_flow = NULL;
1659 struct necp_client_flow_registration *flow_registration = NULL;
1660 RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
1661 if (flow_registration->interface_cb != NULL) {
1662 // Add any interface flows that are not already tracked
1663 necp_flow_add_interface_flows(proc, client, flow_registration, false);
1664 }
1665
1666 LIST_FOREACH_SAFE(flow, &flow_registration->flow_list, flow_chain, temp_flow) {
1667 bool client_updated = FALSE;
1668
1669 // Check policy result for flow
1670 u_short old_delegated_ifindex = flow->delegated_interface_index;
1671
1672 int old_flags = flow->necp_flow_flags;
1673 bool viable = necp_client_flow_is_viable(proc, client, flow);
1674
1675 // TODO: Defunct nexus flows that are blocked by policy
1676
1677 if (flow->viable != viable) {
1678 flow->viable = viable;
1679 client_updated = TRUE;
1680 }
1681
1682 if ((old_flags & NECP_CLIENT_RESULT_FLAG_FORCE_UPDATE) !=
1683 (flow->necp_flow_flags & NECP_CLIENT_RESULT_FLAG_FORCE_UPDATE)) {
1684 client_updated = TRUE;
1685 }
1686
1687 if (flow->delegated_interface_index != old_delegated_ifindex) {
1688 client_updated = TRUE;
1689 }
1690
1691 if (flow->viable && client_updated && (flow->socket || (!flow->socket && !flow->nexus)) && flow->u.cb) {
1692 bool flow_viable = flow->viable;
1693 flow->u.cb(flow->u.socket_handle, NECP_CLIENT_CBACTION_VIABLE, flow->interface_index, flow->necp_flow_flags, &flow_viable);
1694 flow->viable = flow_viable;
1695 }
1696
1697 if (!flow->viable || flow->invalid) {
1698 if (client_updated && (flow->socket || (!flow->socket && !flow->nexus)) && flow->u.cb) {
1699 bool flow_viable = flow->viable;
1700 flow->u.cb(flow->u.socket_handle, NECP_CLIENT_CBACTION_NONVIABLE, flow->interface_index, flow->necp_flow_flags, &flow_viable);
1701 flow->viable = flow_viable;
1702 }
1703 // The callback might change the viable-flag of the
1704 // flow depending on its policy. Thus, we need to
1705 // check the flags again after the callback.
1706 }
1707
1708 (void)defunct_list;
1709
1710 // Handle flows that no longer match
1711 if (!flow->viable || flow->invalid) {
1712 // Drop them as long as they aren't assigned data
1713 if (!flow->nexus && !flow->assigned) {
1714 if (flow->assigned_results != NULL) {
1715 FREE(flow->assigned_results, M_NETAGENT);
1716 flow->assigned_results = NULL;
1717 client_updated = TRUE;
1718 }
1719 LIST_REMOVE(flow, flow_chain);
1720 if (flow->socket) {
1721 OSDecrementAtomic(&necp_socket_flow_count);
1722 } else {
1723 OSDecrementAtomic(&necp_if_flow_count);
1724 }
1725 mcache_free(necp_flow_cache, flow);
1726 }
1727 }
1728
1729 any_client_updated |= client_updated;
1730 }
1731 }
1732
1733 return any_client_updated;
1734}
1735
1736static void
1737necp_client_mark_all_nonsocket_flows_as_invalid(struct necp_client *client)
1738{
1739 struct necp_client_flow_registration *flow_registration = NULL;
1740 struct necp_client_flow *flow = NULL;
1741 RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
1742 LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
1743 if (!flow->socket) { // Socket flows are not marked as invalid
1744 flow->invalid = TRUE;
1745 }
1746 }
1747 }
1748
1749 // Reset option count every update
1750 client->interface_option_count = 0;
1751}
1752
1753static inline bool
1754necp_netagent_is_required(const struct necp_client_parsed_parameters *parameters,
1755 uuid_t *netagent_uuid)
1756{
1757 // Specific use agents only apply when required
1758 bool required = false;
1759 if (parameters != NULL) {
1760 // Check required agent UUIDs
1761 for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
1762 if (uuid_is_null(parameters->required_netagents[i])) {
1763 break;
1764 }
1765 if (uuid_compare(parameters->required_netagents[i], *netagent_uuid) == 0) {
1766 required = true;
1767 break;
1768 }
1769 }
1770
1771 if (!required) {
1772 // Check required agent types
1773 bool fetched_type = false;
1774 char netagent_domain[NETAGENT_DOMAINSIZE];
1775 char netagent_type[NETAGENT_TYPESIZE];
1776 memset(&netagent_domain, 0, NETAGENT_DOMAINSIZE);
1777 memset(&netagent_type, 0, NETAGENT_TYPESIZE);
1778
1779 for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
1780 if (strlen(parameters->required_netagent_types[i].netagent_domain) == 0 ||
1781 strlen(parameters->required_netagent_types[i].netagent_type) == 0) {
1782 break;
1783 }
1784
1785 if (!fetched_type) {
1786 if (netagent_get_agent_domain_and_type(*netagent_uuid, netagent_domain, netagent_type)) {
1787 fetched_type = TRUE;
1788 } else {
1789 break;
1790 }
1791 }
1792
1793 if ((strlen(parameters->required_netagent_types[i].netagent_domain) == 0 ||
1794 strncmp(netagent_domain, parameters->required_netagent_types[i].netagent_domain, NETAGENT_DOMAINSIZE) == 0) &&
1795 (strlen(parameters->required_netagent_types[i].netagent_type) == 0 ||
1796 strncmp(netagent_type, parameters->required_netagent_types[i].netagent_type, NETAGENT_TYPESIZE) == 0)) {
1797 required = true;
1798 break;
1799 }
1800 }
1801 }
1802 }
1803
1804 return required;
1805}
1806
1807static bool
1808necp_netagent_applies_to_client(struct necp_client *client,
1809 const struct necp_client_parsed_parameters *parameters,
1810 uuid_t *netagent_uuid, bool allow_nexus,
1811 uint32_t interface_index, uint32_t interface_generation)
1812{
1813#pragma unused(interface_index, interface_generation)
1814 bool applies = FALSE;
1815 u_int32_t flags = netagent_get_flags(*netagent_uuid);
1816 if (!(flags & NETAGENT_FLAG_REGISTERED)) {
1817 // Unregistered agents never apply
1818 return applies;
1819 }
1820
1821 const bool is_nexus_agent = ((flags & NETAGENT_FLAG_NEXUS_PROVIDER) ||
1822 (flags & NETAGENT_FLAG_NEXUS_LISTENER) ||
1823 (flags & NETAGENT_FLAG_CUSTOM_ETHER_NEXUS) ||
1824 (flags & NETAGENT_FLAG_CUSTOM_IP_NEXUS) ||
1825 (flags & NETAGENT_FLAG_INTERPOSE_NEXUS));
1826 if (is_nexus_agent) {
1827 if (!allow_nexus) {
1828 // Hide nexus providers unless allowed
1829 // Direct interfaces and direct policies are allowed to use a nexus
1830 // Delegate interfaces or re-scoped interfaces are not allowed
1831 return applies;
1832 }
1833
1834 if ((parameters->flags & NECP_CLIENT_PARAMETER_FLAG_CUSTOM_ETHER) &&
1835 !(flags & NETAGENT_FLAG_CUSTOM_ETHER_NEXUS)) {
1836 // Client requested a custom ether nexus, but this nexus isn't one
1837 return applies;
1838 }
1839
1840 if ((parameters->flags & NECP_CLIENT_PARAMETER_FLAG_CUSTOM_IP) &&
1841 !(flags & NETAGENT_FLAG_CUSTOM_IP_NEXUS)) {
1842 // Client requested a custom IP nexus, but this nexus isn't one
1843 return applies;
1844 }
1845
1846 if ((parameters->flags & NECP_CLIENT_PARAMETER_FLAG_INTERPOSE) &&
1847 !(flags & NETAGENT_FLAG_INTERPOSE_NEXUS)) {
1848 // Client requested an interpose nexus, but this nexus isn't one
1849 return applies;
1850 }
1851
1852 if (!(parameters->flags & NECP_CLIENT_PARAMETER_FLAG_CUSTOM_ETHER) &&
1853 !(parameters->flags & NECP_CLIENT_PARAMETER_FLAG_CUSTOM_IP) &&
1854 !(parameters->flags & NECP_CLIENT_PARAMETER_FLAG_INTERPOSE) &&
1855 !(flags & NETAGENT_FLAG_NEXUS_PROVIDER)) {
1856 // Client requested default parameters, but this nexus isn't generic
1857 return applies;
1858 }
1859 }
1860
1861 if (uuid_compare(client->failed_trigger_agent.netagent_uuid, *netagent_uuid) == 0) {
1862 if (client->failed_trigger_agent.generation == netagent_get_generation(*netagent_uuid)) {
1863 // If this agent was triggered, and failed, and hasn't changed, keep hiding it
1864 return applies;
1865 } else {
1866 // Mismatch generation, clear out old trigger
1867 uuid_clear(client->failed_trigger_agent.netagent_uuid);
1868 client->failed_trigger_agent.generation = 0;
1869 }
1870 }
1871
1872 if (flags & NETAGENT_FLAG_SPECIFIC_USE_ONLY) {
1873 // Specific use agents only apply when required
1874 applies = necp_netagent_is_required(parameters, netagent_uuid);
1875 } else {
1876 applies = TRUE;
1877 }
1878
1879
1880 return applies;
1881}
1882
1883static void
1884necp_client_add_agent_interface_options(struct necp_client *client,
1885 const struct necp_client_parsed_parameters *parsed_parameters,
1886 ifnet_t ifp)
1887{
1888 if (ifp != NULL && ifp->if_agentids != NULL) {
1889 for (u_int32_t i = 0; i < ifp->if_agentcount; i++) {
1890 if (uuid_is_null(ifp->if_agentids[i])) {
1891 continue;
1892 }
1893 // Relies on the side effect that nexus agents that apply will create flows
1894 (void)necp_netagent_applies_to_client(client, parsed_parameters, &ifp->if_agentids[i], TRUE,
1895 ifp->if_index, ifnet_get_generation(ifp));
1896 }
1897 }
1898}
1899
1900static void
1901necp_client_add_browse_interface_options(struct necp_client *client,
1902 const struct necp_client_parsed_parameters *parsed_parameters,
1903 ifnet_t ifp)
1904{
1905 if (ifp != NULL && ifp->if_agentids != NULL) {
1906 for (u_int32_t i = 0; i < ifp->if_agentcount; i++) {
1907 if (uuid_is_null(ifp->if_agentids[i])) {
1908 continue;
1909 }
1910
1911 u_int32_t flags = netagent_get_flags(ifp->if_agentids[i]);
1912 if ((flags & NETAGENT_FLAG_REGISTERED) &&
1913 (flags & NETAGENT_FLAG_ACTIVE) &&
1914 (flags & NETAGENT_FLAG_SUPPORTS_BROWSE) &&
1915 (!(flags & NETAGENT_FLAG_SPECIFIC_USE_ONLY) ||
1916 necp_netagent_is_required(parsed_parameters, &ifp->if_agentids[i]))) {
1917 necp_client_add_interface_option_if_needed(client, ifp->if_index, ifnet_get_generation(ifp),
1918 &ifp->if_agentids[i], (flags & NETAGENT_FLAG_NETWORK_PROVIDER));
1919
1920 // Finding one is enough
1921 break;
1922 }
1923 }
1924 }
1925}
1926
1927static inline bool
1928necp_client_address_is_valid(struct sockaddr *address)
1929{
1930 if (address->sa_family == AF_INET) {
1931 return address->sa_len == sizeof(struct sockaddr_in);
1932 } else if (address->sa_family == AF_INET6) {
1933 return address->sa_len == sizeof(struct sockaddr_in6);
1934 } else {
1935 return FALSE;
1936 }
1937}
1938
1939static inline bool
1940necp_client_endpoint_is_unspecified(struct necp_client_endpoint *endpoint)
1941{
1942 if (necp_client_address_is_valid(&endpoint->u.sa)) {
1943 if (endpoint->u.sa.sa_family == AF_INET) {
1944 return endpoint->u.sin.sin_addr.s_addr == INADDR_ANY;
1945 } else if (endpoint->u.sa.sa_family == AF_INET6) {
1946 return IN6_IS_ADDR_UNSPECIFIED(&endpoint->u.sin6.sin6_addr);
1947 } else {
1948 return TRUE;
1949 }
1950 } else {
1951 return TRUE;
1952 }
1953}
1954
1955
1956static int
1957necp_client_parse_parameters(u_int8_t *parameters,
1958 u_int32_t parameters_size,
1959 struct necp_client_parsed_parameters *parsed_parameters)
1960{
1961 int error = 0;
1962 size_t offset = 0;
1963
1964 u_int32_t num_prohibited_interfaces = 0;
1965 u_int32_t num_prohibited_interface_types = 0;
1966 u_int32_t num_required_agents = 0;
1967 u_int32_t num_prohibited_agents = 0;
1968 u_int32_t num_preferred_agents = 0;
1969 u_int32_t num_avoided_agents = 0;
1970 u_int32_t num_required_agent_types = 0;
1971 u_int32_t num_prohibited_agent_types = 0;
1972 u_int32_t num_preferred_agent_types = 0;
1973 u_int32_t num_avoided_agent_types = 0;
1974 u_int8_t *resolver_tag = NULL;
1975 u_int32_t resolver_tag_length = 0;
1976 u_int8_t *client_hostname = NULL;
1977 u_int32_t hostname_length = 0;
1978 uuid_t parent_id = {};
1979
1980 if (parsed_parameters == NULL) {
1981 return EINVAL;
1982 }
1983
1984 memset(parsed_parameters, 0, sizeof(struct necp_client_parsed_parameters));
1985
1986 while ((offset + sizeof(struct necp_tlv_header)) <= parameters_size) {
1987 u_int8_t type = necp_buffer_get_tlv_type(parameters, offset);
1988 u_int32_t length = necp_buffer_get_tlv_length(parameters, offset);
1989
1990 if (length > (parameters_size - (offset + sizeof(struct necp_tlv_header)))) {
1991 // If the length is larger than what can fit in the remaining parameters size, bail
1992 NECPLOG(LOG_ERR, "Invalid TLV length (%u)", length);
1993 break;
1994 }
1995
1996 if (length > 0) {
1997 u_int8_t *value = necp_buffer_get_tlv_value(parameters, offset, NULL);
1998 if (value != NULL) {
1999 switch (type) {
2000 case NECP_CLIENT_PARAMETER_BOUND_INTERFACE: {
2001 if (length <= IFXNAMSIZ && length > 0) {
2002 ifnet_t bound_interface = NULL;
2003 char interface_name[IFXNAMSIZ];
2004 memcpy(interface_name, value, length);
2005 interface_name[length - 1] = 0; // Make sure the string is NULL terminated
2006 if (ifnet_find_by_name(interface_name, &bound_interface) == 0) {
2007 parsed_parameters->required_interface_index = bound_interface->if_index;
2008 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IF;
2009 ifnet_release(bound_interface);
2010 }
2011 }
2012 break;
2013 }
2014 case NECP_CLIENT_PARAMETER_LOCAL_ADDRESS: {
2015 if (length >= sizeof(struct necp_policy_condition_addr)) {
2016 struct necp_policy_condition_addr *address_struct = (struct necp_policy_condition_addr *)(void *)value;
2017 if (necp_client_address_is_valid(&address_struct->address.sa)) {
2018 memcpy(&parsed_parameters->local_addr, &address_struct->address, sizeof(address_struct->address));
2019 if (!necp_address_is_wildcard(&parsed_parameters->local_addr)) {
2020 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR;
2021 }
2022 if ((parsed_parameters->local_addr.sa.sa_family == AF_INET && parsed_parameters->local_addr.sin.sin_port) ||
2023 (parsed_parameters->local_addr.sa.sa_family == AF_INET6 && parsed_parameters->local_addr.sin6.sin6_port)) {
2024 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_LOCAL_PORT;
2025 }
2026 }
2027 }
2028 break;
2029 }
2030 case NECP_CLIENT_PARAMETER_LOCAL_ENDPOINT: {
2031 if (length >= sizeof(struct necp_client_endpoint)) {
2032 struct necp_client_endpoint *endpoint = (struct necp_client_endpoint *)(void *)value;
2033 if (necp_client_address_is_valid(&endpoint->u.sa)) {
2034 memcpy(&parsed_parameters->local_addr, &endpoint->u.sa, sizeof(union necp_sockaddr_union));
2035 if (!necp_address_is_wildcard(&parsed_parameters->local_addr)) {
2036 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR;
2037 }
2038 if ((parsed_parameters->local_addr.sa.sa_family == AF_INET && parsed_parameters->local_addr.sin.sin_port) ||
2039 (parsed_parameters->local_addr.sa.sa_family == AF_INET6 && parsed_parameters->local_addr.sin6.sin6_port)) {
2040 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_LOCAL_PORT;
2041 }
2042 }
2043 }
2044 break;
2045 }
2046 case NECP_CLIENT_PARAMETER_REMOTE_ADDRESS: {
2047 if (length >= sizeof(struct necp_policy_condition_addr)) {
2048 struct necp_policy_condition_addr *address_struct = (struct necp_policy_condition_addr *)(void *)value;
2049 if (necp_client_address_is_valid(&address_struct->address.sa)) {
2050 memcpy(&parsed_parameters->remote_addr, &address_struct->address, sizeof(address_struct->address));
2051 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REMOTE_ADDR;
2052 }
2053 }
2054 break;
2055 }
2056 case NECP_CLIENT_PARAMETER_REMOTE_ENDPOINT: {
2057 if (length >= sizeof(struct necp_client_endpoint)) {
2058 struct necp_client_endpoint *endpoint = (struct necp_client_endpoint *)(void *)value;
2059 if (necp_client_address_is_valid(&endpoint->u.sa)) {
2060 memcpy(&parsed_parameters->remote_addr, &endpoint->u.sa, sizeof(union necp_sockaddr_union));
2061 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REMOTE_ADDR;
2062 }
2063 }
2064 break;
2065 }
2066 case NECP_CLIENT_PARAMETER_PROHIBIT_INTERFACE: {
2067 if (num_prohibited_interfaces >= NECP_MAX_INTERFACE_PARAMETERS) {
2068 break;
2069 }
2070 if (length <= IFXNAMSIZ && length > 0) {
2071 memcpy(parsed_parameters->prohibited_interfaces[num_prohibited_interfaces], value, length);
2072 parsed_parameters->prohibited_interfaces[num_prohibited_interfaces][length - 1] = 0; // Make sure the string is NULL terminated
2073 num_prohibited_interfaces++;
2074 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IF;
2075 }
2076 break;
2077 }
2078 case NECP_CLIENT_PARAMETER_REQUIRE_IF_TYPE: {
2079 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE) {
2080 break;
2081 }
2082 if (length >= sizeof(u_int8_t)) {
2083 memcpy(&parsed_parameters->required_interface_type, value, sizeof(u_int8_t));
2084 if (parsed_parameters->required_interface_type) {
2085 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE;
2086 }
2087 }
2088 break;
2089 }
2090 case NECP_CLIENT_PARAMETER_PROHIBIT_IF_TYPE: {
2091 if (num_prohibited_interface_types >= NECP_MAX_INTERFACE_PARAMETERS) {
2092 break;
2093 }
2094 if (length >= sizeof(u_int8_t)) {
2095 memcpy(&parsed_parameters->prohibited_interface_types[num_prohibited_interface_types], value, sizeof(u_int8_t));
2096 num_prohibited_interface_types++;
2097 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IFTYPE;
2098 }
2099 break;
2100 }
2101 case NECP_CLIENT_PARAMETER_REQUIRE_AGENT: {
2102 if (num_required_agents >= NECP_MAX_AGENT_PARAMETERS) {
2103 break;
2104 }
2105 if (length >= sizeof(uuid_t)) {
2106 memcpy(&parsed_parameters->required_netagents[num_required_agents], value, sizeof(uuid_t));
2107 num_required_agents++;
2108 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT;
2109 }
2110 break;
2111 }
2112 case NECP_CLIENT_PARAMETER_PROHIBIT_AGENT: {
2113 if (num_prohibited_agents >= NECP_MAX_AGENT_PARAMETERS) {
2114 break;
2115 }
2116 if (length >= sizeof(uuid_t)) {
2117 memcpy(&parsed_parameters->prohibited_netagents[num_prohibited_agents], value, sizeof(uuid_t));
2118 num_prohibited_agents++;
2119 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT;
2120 }
2121 break;
2122 }
2123 case NECP_CLIENT_PARAMETER_PREFER_AGENT: {
2124 if (num_preferred_agents >= NECP_MAX_AGENT_PARAMETERS) {
2125 break;
2126 }
2127 if (length >= sizeof(uuid_t)) {
2128 memcpy(&parsed_parameters->preferred_netagents[num_preferred_agents], value, sizeof(uuid_t));
2129 num_preferred_agents++;
2130 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT;
2131 }
2132 break;
2133 }
2134 case NECP_CLIENT_PARAMETER_AVOID_AGENT: {
2135 if (num_avoided_agents >= NECP_MAX_AGENT_PARAMETERS) {
2136 break;
2137 }
2138 if (length >= sizeof(uuid_t)) {
2139 memcpy(&parsed_parameters->avoided_netagents[num_avoided_agents], value, sizeof(uuid_t));
2140 num_avoided_agents++;
2141 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT;
2142 }
2143 break;
2144 }
2145 case NECP_CLIENT_PARAMETER_REQUIRE_AGENT_TYPE: {
2146 if (num_required_agent_types >= NECP_MAX_AGENT_PARAMETERS) {
2147 break;
2148 }
2149 if (length >= sizeof(struct necp_client_parameter_netagent_type)) {
2150 memcpy(&parsed_parameters->required_netagent_types[num_required_agent_types], value, sizeof(struct necp_client_parameter_netagent_type));
2151 num_required_agent_types++;
2152 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE;
2153 }
2154 break;
2155 }
2156 case NECP_CLIENT_PARAMETER_PROHIBIT_AGENT_TYPE: {
2157 if (num_prohibited_agent_types >= NECP_MAX_AGENT_PARAMETERS) {
2158 break;
2159 }
2160 if (length >= sizeof(struct necp_client_parameter_netagent_type)) {
2161 memcpy(&parsed_parameters->prohibited_netagent_types[num_prohibited_agent_types], value, sizeof(struct necp_client_parameter_netagent_type));
2162 num_prohibited_agent_types++;
2163 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT_TYPE;
2164 }
2165 break;
2166 }
2167 case NECP_CLIENT_PARAMETER_PREFER_AGENT_TYPE: {
2168 if (num_preferred_agent_types >= NECP_MAX_AGENT_PARAMETERS) {
2169 break;
2170 }
2171 if (length >= sizeof(struct necp_client_parameter_netagent_type)) {
2172 memcpy(&parsed_parameters->preferred_netagent_types[num_preferred_agent_types], value, sizeof(struct necp_client_parameter_netagent_type));
2173 num_preferred_agent_types++;
2174 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT_TYPE;
2175 }
2176 break;
2177 }
2178 case NECP_CLIENT_PARAMETER_AVOID_AGENT_TYPE: {
2179 if (num_avoided_agent_types >= NECP_MAX_AGENT_PARAMETERS) {
2180 break;
2181 }
2182 if (length >= sizeof(struct necp_client_parameter_netagent_type)) {
2183 memcpy(&parsed_parameters->avoided_netagent_types[num_avoided_agent_types], value, sizeof(struct necp_client_parameter_netagent_type));
2184 num_avoided_agent_types++;
2185 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT_TYPE;
2186 }
2187 break;
2188 }
2189 case NECP_CLIENT_PARAMETER_FLAGS: {
2190 if (length >= sizeof(u_int32_t)) {
2191 memcpy(&parsed_parameters->flags, value, sizeof(parsed_parameters->flags));
2192 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_FLAGS;
2193 }
2194 break;
2195 }
2196 case NECP_CLIENT_PARAMETER_IP_PROTOCOL: {
2197 if (length == sizeof(u_int16_t)) {
2198 u_int16_t large_ip_protocol = 0;
2199 memcpy(&large_ip_protocol, value, sizeof(large_ip_protocol));
2200 parsed_parameters->ip_protocol = (u_int8_t)large_ip_protocol;
2201 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_IP_PROTOCOL;
2202 } else if (length >= sizeof(parsed_parameters->ip_protocol)) {
2203 memcpy(&parsed_parameters->ip_protocol, value, sizeof(parsed_parameters->ip_protocol));
2204 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_IP_PROTOCOL;
2205 }
2206 break;
2207 }
2208 case NECP_CLIENT_PARAMETER_TRANSPORT_PROTOCOL: {
2209 if (length >= sizeof(parsed_parameters->transport_protocol)) {
2210 memcpy(&parsed_parameters->transport_protocol, value, sizeof(parsed_parameters->transport_protocol));
2211 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_TRANSPORT_PROTOCOL;
2212 }
2213 break;
2214 }
2215 case NECP_CLIENT_PARAMETER_PID: {
2216 if (length >= sizeof(parsed_parameters->effective_pid)) {
2217 memcpy(&parsed_parameters->effective_pid, value, sizeof(parsed_parameters->effective_pid));
2218 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_EFFECTIVE_PID;
2219 }
2220 break;
2221 }
2222 case NECP_CLIENT_PARAMETER_DELEGATED_UPID: {
2223 if (length >= sizeof(parsed_parameters->delegated_upid)) {
2224 memcpy(&parsed_parameters->delegated_upid, value, sizeof(parsed_parameters->delegated_upid));
2225 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_DELEGATED_UPID;
2226 }
2227 break;
2228 }
2229 case NECP_CLIENT_PARAMETER_ETHERTYPE: {
2230 if (length >= sizeof(parsed_parameters->ethertype)) {
2231 memcpy(&parsed_parameters->ethertype, value, sizeof(parsed_parameters->ethertype));
2232 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_ETHERTYPE;
2233 }
2234 break;
2235 }
2236 case NECP_CLIENT_PARAMETER_APPLICATION: {
2237 if (length >= sizeof(parsed_parameters->effective_uuid)) {
2238 memcpy(&parsed_parameters->effective_uuid, value, sizeof(parsed_parameters->effective_uuid));
2239 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_EFFECTIVE_UUID;
2240 }
2241 break;
2242 }
2243 case NECP_CLIENT_PARAMETER_TRAFFIC_CLASS: {
2244 if (length >= sizeof(parsed_parameters->traffic_class)) {
2245 memcpy(&parsed_parameters->traffic_class, value, sizeof(parsed_parameters->traffic_class));
2246 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_TRAFFIC_CLASS;
2247 }
2248 break;
2249 }
2250 case NECP_CLIENT_PARAMETER_RESOLVER_TAG: {
2251 if (length > 0) {
2252 resolver_tag = (u_int8_t *)value;
2253 resolver_tag_length = length;
2254 }
2255 break;
2256 }
2257 case NECP_CLIENT_PARAMETER_DOMAIN: {
2258 if (length > 0) {
2259 client_hostname = (u_int8_t *)value;
2260 hostname_length = length;
2261 }
2262 break;
2263 }
2264 case NECP_CLIENT_PARAMETER_PARENT_ID: {
2265 if (length == sizeof(parent_id)) {
2266 uuid_copy(parent_id, value);
2267 }
2268 break;
2269 }
2270 case NECP_CLIENT_PARAMETER_LOCAL_ADDRESS_PREFERENCE: {
2271 if (length >= sizeof(parsed_parameters->local_address_preference)) {
2272 memcpy(&parsed_parameters->local_address_preference, value, sizeof(parsed_parameters->local_address_preference));
2273 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR_PREFERENCE;
2274 }
2275 break;
2276 }
2277 default: {
2278 break;
2279 }
2280 }
2281 }
2282 }
2283
2284 offset += sizeof(struct necp_tlv_header) + length;
2285 }
2286
2287 if (resolver_tag != NULL) {
2288 union necp_sockaddr_union remote_addr;
2289 memcpy(&remote_addr, &parsed_parameters->remote_addr, sizeof(remote_addr));
2290 remote_addr.sin.sin_port = 0;
2291 const bool validated = necp_validate_resolver_answer(parent_id,
2292 client_hostname, hostname_length,
2293 (u_int8_t *)&remote_addr, sizeof(remote_addr),
2294 resolver_tag, resolver_tag_length);
2295 if (!validated) {
2296 error = EAUTH;
2297 NECPLOG(LOG_ERR, "Failed to validate answer for hostname %s", client_hostname);
2298 }
2299 }
2300
2301 return error;
2302}
2303
2304static int
2305necp_client_parse_result(u_int8_t *result,
2306 u_int32_t result_size,
2307 union necp_sockaddr_union *local_address,
2308 union necp_sockaddr_union *remote_address,
2309 void **flow_stats)
2310{
2311#pragma unused(flow_stats)
2312 int error = 0;
2313 size_t offset = 0;
2314
2315 while ((offset + sizeof(struct necp_tlv_header)) <= result_size) {
2316 u_int8_t type = necp_buffer_get_tlv_type(result, offset);
2317 u_int32_t length = necp_buffer_get_tlv_length(result, offset);
2318
2319 if (length > 0 && (offset + sizeof(struct necp_tlv_header) + length) <= result_size) {
2320 u_int8_t *value = necp_buffer_get_tlv_value(result, offset, NULL);
2321 if (value != NULL) {
2322 switch (type) {
2323 case NECP_CLIENT_RESULT_LOCAL_ENDPOINT: {
2324 if (length >= sizeof(struct necp_client_endpoint)) {
2325 struct necp_client_endpoint *endpoint = (struct necp_client_endpoint *)(void *)value;
2326 if (local_address != NULL && necp_client_address_is_valid(&endpoint->u.sa)) {
2327 memcpy(local_address, &endpoint->u.sa, endpoint->u.sa.sa_len);
2328 }
2329 }
2330 break;
2331 }
2332 case NECP_CLIENT_RESULT_REMOTE_ENDPOINT: {
2333 if (length >= sizeof(struct necp_client_endpoint)) {
2334 struct necp_client_endpoint *endpoint = (struct necp_client_endpoint *)(void *)value;
2335 if (remote_address != NULL && necp_client_address_is_valid(&endpoint->u.sa)) {
2336 memcpy(remote_address, &endpoint->u.sa, endpoint->u.sa.sa_len);
2337 }
2338 }
2339 break;
2340 }
2341 default: {
2342 break;
2343 }
2344 }
2345 }
2346 }
2347
2348 offset += sizeof(struct necp_tlv_header) + length;
2349 }
2350
2351 return error;
2352}
2353
2354static struct necp_client_flow_registration *
2355necp_client_create_flow_registration(struct necp_fd_data *fd_data, struct necp_client *client)
2356{
2357 NECP_FD_ASSERT_LOCKED(fd_data);
2358 NECP_CLIENT_ASSERT_LOCKED(client);
2359
2360 struct necp_client_flow_registration *new_registration = mcache_alloc(necp_flow_registration_cache, MCR_SLEEP);
2361 if (new_registration == NULL) {
2362 return NULL;
2363 }
2364
2365 memset(new_registration, 0, sizeof(*new_registration));
2366
2367 new_registration->last_interface_details = combine_interface_details(IFSCOPE_NONE, NSTAT_IFNET_IS_UNKNOWN_TYPE);
2368
2369 necp_generate_client_id(new_registration->registration_id, true);
2370 LIST_INIT(&new_registration->flow_list);
2371
2372 // Add registration to client list
2373 RB_INSERT(_necp_client_flow_tree, &client->flow_registrations, new_registration);
2374
2375 // Add registration to fd list
2376 RB_INSERT(_necp_fd_flow_tree, &fd_data->flows, new_registration);
2377
2378 // Add registration to global tree for lookup
2379 NECP_FLOW_TREE_LOCK_EXCLUSIVE();
2380 RB_INSERT(_necp_client_flow_global_tree, &necp_client_flow_global_tree, new_registration);
2381 NECP_FLOW_TREE_UNLOCK();
2382
2383 new_registration->client = client;
2384
2385 // Start out assuming there is nothing to read from the flow
2386 new_registration->flow_result_read = true;
2387
2388 return new_registration;
2389}
2390
2391static void
2392necp_client_add_socket_flow(struct necp_client_flow_registration *flow_registration,
2393 struct inpcb *inp)
2394{
2395 struct necp_client_flow *new_flow = mcache_alloc(necp_flow_cache, MCR_SLEEP);
2396 if (new_flow == NULL) {
2397 NECPLOG0(LOG_ERR, "Failed to allocate socket flow");
2398 return;
2399 }
2400
2401 memset(new_flow, 0, sizeof(*new_flow));
2402
2403 new_flow->socket = TRUE;
2404 new_flow->u.socket_handle = inp;
2405 new_flow->u.cb = inp->necp_cb;
2406
2407 OSIncrementAtomic(&necp_socket_flow_count);
2408
2409 LIST_INSERT_HEAD(&flow_registration->flow_list, new_flow, flow_chain);
2410}
2411
2412static int
2413necp_client_register_socket_inner(pid_t pid, uuid_t client_id, struct inpcb *inp, bool is_listener)
2414{
2415 int error = 0;
2416 struct necp_fd_data *client_fd = NULL;
2417 bool found_client = FALSE;
2418
2419 NECP_FD_LIST_LOCK_SHARED();
2420 LIST_FOREACH(client_fd, &necp_fd_list, chain) {
2421 NECP_FD_LOCK(client_fd);
2422 struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
2423 if (client != NULL) {
2424 if (!pid || client->proc_pid == pid) {
2425 if (is_listener) {
2426 found_client = TRUE;
2427 } else {
2428 // Find client flow and assign from socket
2429 struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
2430 if (flow_registration != NULL) {
2431 // Found the right client and flow registration, add a new flow
2432 found_client = TRUE;
2433 necp_client_add_socket_flow(flow_registration, inp);
2434 } else if (RB_EMPTY(&client->flow_registrations) && !necp_client_id_is_flow(client_id)) {
2435 // No flows yet on this client, add a new registration
2436 flow_registration = necp_client_create_flow_registration(client_fd, client);
2437 if (flow_registration == NULL) {
2438 error = ENOMEM;
2439 } else {
2440 // Add a new flow
2441 found_client = TRUE;
2442 necp_client_add_socket_flow(flow_registration, inp);
2443 }
2444 }
2445 }
2446 }
2447
2448 NECP_CLIENT_UNLOCK(client);
2449 }
2450 NECP_FD_UNLOCK(client_fd);
2451
2452 if (found_client) {
2453 break;
2454 }
2455 }
2456 NECP_FD_LIST_UNLOCK();
2457
2458 if (!found_client) {
2459 error = ENOENT;
2460 } else {
2461 // Count the sockets that have the NECP client UUID set
2462 struct socket *so = inp->inp_socket;
2463 if (!(so->so_flags1 & SOF1_HAS_NECP_CLIENT_UUID)) {
2464 so->so_flags1 |= SOF1_HAS_NECP_CLIENT_UUID;
2465 INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_necp_clientuuid_total);
2466 }
2467 }
2468
2469 return error;
2470}
2471
2472int
2473necp_client_register_socket_flow(pid_t pid, uuid_t client_id, struct inpcb *inp)
2474{
2475 return necp_client_register_socket_inner(pid, client_id, inp, false);
2476}
2477
2478int
2479necp_client_register_socket_listener(pid_t pid, uuid_t client_id, struct inpcb *inp)
2480{
2481 return necp_client_register_socket_inner(pid, client_id, inp, true);
2482}
2483
2484
2485static void
2486necp_client_add_multipath_interface_flows(struct necp_client_flow_registration *flow_registration,
2487 struct necp_client *client,
2488 struct mppcb *mpp)
2489{
2490 flow_registration->interface_handle = mpp;
2491 flow_registration->interface_cb = mpp->necp_cb;
2492
2493 proc_t proc = proc_find(client->proc_pid);
2494 if (proc == PROC_NULL) {
2495 return;
2496 }
2497
2498 // Traverse all interfaces and add a tracking flow if needed
2499 necp_flow_add_interface_flows(proc, client, flow_registration, true);
2500
2501 proc_rele(proc);
2502 proc = PROC_NULL;
2503}
2504
2505int
2506necp_client_register_multipath_cb(pid_t pid, uuid_t client_id, struct mppcb *mpp)
2507{
2508 int error = 0;
2509 struct necp_fd_data *client_fd = NULL;
2510 bool found_client = FALSE;
2511
2512 NECP_FD_LIST_LOCK_SHARED();
2513 LIST_FOREACH(client_fd, &necp_fd_list, chain) {
2514 NECP_FD_LOCK(client_fd);
2515 struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
2516 if (client != NULL) {
2517 if (!pid || client->proc_pid == pid) {
2518 struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
2519 if (flow_registration != NULL) {
2520 // Found the right client and flow registration, add a new flow
2521 found_client = TRUE;
2522 necp_client_add_multipath_interface_flows(flow_registration, client, mpp);
2523 } else if (RB_EMPTY(&client->flow_registrations) && !necp_client_id_is_flow(client_id)) {
2524 // No flows yet on this client, add a new registration
2525 flow_registration = necp_client_create_flow_registration(client_fd, client);
2526 if (flow_registration == NULL) {
2527 error = ENOMEM;
2528 } else {
2529 // Add a new flow
2530 found_client = TRUE;
2531 necp_client_add_multipath_interface_flows(flow_registration, client, mpp);
2532 }
2533 }
2534 }
2535
2536 NECP_CLIENT_UNLOCK(client);
2537 }
2538 NECP_FD_UNLOCK(client_fd);
2539
2540 if (found_client) {
2541 break;
2542 }
2543 }
2544 NECP_FD_LIST_UNLOCK();
2545
2546 if (!found_client && error == 0) {
2547 error = ENOENT;
2548 }
2549
2550 return error;
2551}
2552
2553#define NETAGENT_DOMAIN_RADIO_MANAGER "WirelessRadioManager"
2554#define NETAGENT_TYPE_RADIO_MANAGER "WirelessRadioManager:BB Manager"
2555
2556static int
2557necp_client_lookup_bb_radio_manager(struct necp_client *client,
2558 uuid_t netagent_uuid)
2559{
2560 char netagent_domain[NETAGENT_DOMAINSIZE];
2561 char netagent_type[NETAGENT_TYPESIZE];
2562 struct necp_aggregate_result result;
2563 proc_t proc;
2564 int error;
2565
2566 proc = proc_find(client->proc_pid);
2567 if (proc == PROC_NULL) {
2568 return ESRCH;
2569 }
2570
2571 error = necp_application_find_policy_match_internal(proc, client->parameters, (u_int32_t)client->parameters_length,
2572 &result, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, true, true, NULL);
2573
2574 proc_rele(proc);
2575 proc = PROC_NULL;
2576
2577 if (error) {
2578 return error;
2579 }
2580
2581 for (int i = 0; i < NECP_MAX_NETAGENTS; i++) {
2582 if (uuid_is_null(result.netagents[i])) {
2583 // Passed end of valid agents
2584 break;
2585 }
2586
2587 memset(&netagent_domain, 0, NETAGENT_DOMAINSIZE);
2588 memset(&netagent_type, 0, NETAGENT_TYPESIZE);
2589 if (netagent_get_agent_domain_and_type(result.netagents[i], netagent_domain, netagent_type) == FALSE) {
2590 continue;
2591 }
2592
2593 if (strncmp(netagent_domain, NETAGENT_DOMAIN_RADIO_MANAGER, NETAGENT_DOMAINSIZE) != 0) {
2594 continue;
2595 }
2596
2597 if (strncmp(netagent_type, NETAGENT_TYPE_RADIO_MANAGER, NETAGENT_TYPESIZE) != 0) {
2598 continue;
2599 }
2600
2601 uuid_copy(netagent_uuid, result.netagents[i]);
2602
2603 break;
2604 }
2605
2606 return 0;
2607}
2608
2609static int
2610necp_client_assert_bb_radio_manager_common(struct necp_client *client, bool assert)
2611{
2612 uuid_t netagent_uuid;
2613 uint8_t assert_type;
2614 int error;
2615
2616 error = necp_client_lookup_bb_radio_manager(client, netagent_uuid);
2617 if (error) {
2618 NECPLOG0(LOG_ERR, "BB radio manager agent not found");
2619 return error;
2620 }
2621
2622 // Before unasserting, verify that the assertion was already taken
2623 if (assert == FALSE) {
2624 assert_type = NETAGENT_MESSAGE_TYPE_CLIENT_UNASSERT;
2625
2626 if (!necp_client_remove_assertion(client, netagent_uuid)) {
2627 return EINVAL;
2628 }
2629 } else {
2630 assert_type = NETAGENT_MESSAGE_TYPE_CLIENT_ASSERT;
2631 }
2632
2633 error = netagent_client_message(netagent_uuid, client->client_id, client->proc_pid, client->agent_handle, assert_type);
2634 if (error) {
2635 NECPLOG0(LOG_ERR, "netagent_client_message failed");
2636 return error;
2637 }
2638
2639 // Only save the assertion if the action succeeded
2640 if (assert == TRUE) {
2641 necp_client_add_assertion(client, netagent_uuid);
2642 }
2643
2644 return 0;
2645}
2646
2647int
2648necp_client_assert_bb_radio_manager(uuid_t client_id, bool assert)
2649{
2650 struct necp_client *client;
2651 int error = 0;
2652
2653 NECP_CLIENT_TREE_LOCK_SHARED();
2654
2655 client = necp_find_client_and_lock(client_id);
2656
2657 if (client) {
2658 // Found the right client!
2659 error = necp_client_assert_bb_radio_manager_common(client, assert);
2660
2661 NECP_CLIENT_UNLOCK(client);
2662 } else {
2663 NECPLOG0(LOG_ERR, "Couldn't find client");
2664 error = ENOENT;
2665 }
2666
2667 NECP_CLIENT_TREE_UNLOCK();
2668
2669 return error;
2670}
2671
2672static int
2673necp_client_unregister_socket_flow(uuid_t client_id, void *handle)
2674{
2675 int error = 0;
2676 struct necp_fd_data *client_fd = NULL;
2677 bool found_client = FALSE;
2678 bool client_updated = FALSE;
2679
2680 NECP_FD_LIST_LOCK_SHARED();
2681 LIST_FOREACH(client_fd, &necp_fd_list, chain) {
2682 NECP_FD_LOCK(client_fd);
2683
2684 struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
2685 if (client != NULL) {
2686 struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
2687 if (flow_registration != NULL) {
2688 // Found the right client and flow!
2689 found_client = TRUE;
2690
2691 // Remove flow assignment
2692 struct necp_client_flow *search_flow = NULL;
2693 struct necp_client_flow *temp_flow = NULL;
2694 LIST_FOREACH_SAFE(search_flow, &flow_registration->flow_list, flow_chain, temp_flow) {
2695 if (search_flow->socket && search_flow->u.socket_handle == handle) {
2696 if (search_flow->assigned_results != NULL) {
2697 FREE(search_flow->assigned_results, M_NETAGENT);
2698 search_flow->assigned_results = NULL;
2699 }
2700 client_updated = TRUE;
2701 flow_registration->flow_result_read = FALSE;
2702 LIST_REMOVE(search_flow, flow_chain);
2703 OSDecrementAtomic(&necp_socket_flow_count);
2704 mcache_free(necp_flow_cache, search_flow);
2705 }
2706 }
2707 }
2708
2709 NECP_CLIENT_UNLOCK(client);
2710 }
2711
2712 if (client_updated) {
2713 necp_fd_notify(client_fd, true);
2714 }
2715 NECP_FD_UNLOCK(client_fd);
2716
2717 if (found_client) {
2718 break;
2719 }
2720 }
2721 NECP_FD_LIST_UNLOCK();
2722
2723 if (!found_client) {
2724 error = ENOENT;
2725 }
2726
2727 return error;
2728}
2729
2730static int
2731necp_client_unregister_multipath_cb(uuid_t client_id, void *handle)
2732{
2733 int error = 0;
2734 bool found_client = FALSE;
2735
2736 NECP_CLIENT_TREE_LOCK_SHARED();
2737
2738 struct necp_client *client = necp_find_client_and_lock(client_id);
2739 if (client != NULL) {
2740 struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
2741 if (flow_registration != NULL) {
2742 // Found the right client and flow!
2743 found_client = TRUE;
2744
2745 // Remove flow assignment
2746 struct necp_client_flow *search_flow = NULL;
2747 struct necp_client_flow *temp_flow = NULL;
2748 LIST_FOREACH_SAFE(search_flow, &flow_registration->flow_list, flow_chain, temp_flow) {
2749 if (!search_flow->socket && !search_flow->nexus &&
2750 search_flow->u.socket_handle == handle) {
2751 search_flow->u.socket_handle = NULL;
2752 search_flow->u.cb = NULL;
2753 }
2754 }
2755
2756 flow_registration->interface_handle = NULL;
2757 flow_registration->interface_cb = NULL;
2758 }
2759
2760 NECP_CLIENT_UNLOCK(client);
2761 }
2762
2763 NECP_CLIENT_TREE_UNLOCK();
2764
2765 if (!found_client) {
2766 error = ENOENT;
2767 }
2768
2769 return error;
2770}
2771
2772int
2773necp_client_assign_from_socket(pid_t pid, uuid_t client_id, struct inpcb *inp)
2774{
2775 int error = 0;
2776 struct necp_fd_data *client_fd = NULL;
2777 bool found_client = FALSE;
2778 bool client_updated = FALSE;
2779
2780 NECP_FD_LIST_LOCK_SHARED();
2781 LIST_FOREACH(client_fd, &necp_fd_list, chain) {
2782 if (pid && client_fd->proc_pid != pid) {
2783 continue;
2784 }
2785
2786 proc_t proc = proc_find(client_fd->proc_pid);
2787 if (proc == PROC_NULL) {
2788 continue;
2789 }
2790
2791 NECP_FD_LOCK(client_fd);
2792
2793 struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
2794 if (client != NULL) {
2795 struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
2796 if (flow_registration == NULL && RB_EMPTY(&client->flow_registrations) && !necp_client_id_is_flow(client_id)) {
2797 // No flows yet on this client, add a new registration
2798 flow_registration = necp_client_create_flow_registration(client_fd, client);
2799 if (flow_registration == NULL) {
2800 error = ENOMEM;
2801 }
2802 }
2803 if (flow_registration != NULL) {
2804 // Found the right client and flow!
2805 found_client = TRUE;
2806
2807 struct necp_client_flow *flow = NULL;
2808 LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
2809 if (flow->socket && flow->u.socket_handle == inp) {
2810 // Release prior results and route
2811 if (flow->assigned_results != NULL) {
2812 FREE(flow->assigned_results, M_NETAGENT);
2813 flow->assigned_results = NULL;
2814 }
2815
2816 ifnet_t ifp = NULL;
2817 if ((inp->inp_flags & INP_BOUND_IF) && inp->inp_boundifp) {
2818 ifp = inp->inp_boundifp;
2819 } else {
2820 ifp = inp->inp_last_outifp;
2821 }
2822
2823 if (ifp != NULL) {
2824 flow->interface_index = ifp->if_index;
2825 } else {
2826 flow->interface_index = IFSCOPE_NONE;
2827 }
2828
2829 if (inp->inp_vflag & INP_IPV4) {
2830 flow->local_addr.sin.sin_family = AF_INET;
2831 flow->local_addr.sin.sin_len = sizeof(struct sockaddr_in);
2832 flow->local_addr.sin.sin_port = inp->inp_lport;
2833 memcpy(&flow->local_addr.sin.sin_addr, &inp->inp_laddr, sizeof(struct in_addr));
2834
2835 flow->remote_addr.sin.sin_family = AF_INET;
2836 flow->remote_addr.sin.sin_len = sizeof(struct sockaddr_in);
2837 flow->remote_addr.sin.sin_port = inp->inp_fport;
2838 memcpy(&flow->remote_addr.sin.sin_addr, &inp->inp_faddr, sizeof(struct in_addr));
2839 } else if (inp->inp_vflag & INP_IPV6) {
2840 in6_ip6_to_sockaddr(&inp->in6p_laddr, inp->inp_lport, &flow->local_addr.sin6, sizeof(flow->local_addr));
2841 in6_ip6_to_sockaddr(&inp->in6p_faddr, inp->inp_fport, &flow->remote_addr.sin6, sizeof(flow->remote_addr));
2842 }
2843
2844 flow->viable = necp_client_flow_is_viable(proc, client, flow);
2845
2846 uuid_t empty_uuid;
2847 uuid_clear(empty_uuid);
2848 flow->assigned = TRUE;
2849 flow->assigned_results = necp_create_nexus_assign_message(empty_uuid, 0, NULL, 0,
2850 (struct necp_client_endpoint *)&flow->local_addr,
2851 (struct necp_client_endpoint *)&flow->remote_addr,
2852 NULL, 0, NULL, &flow->assigned_results_length);
2853 flow_registration->flow_result_read = FALSE;
2854 client_updated = TRUE;
2855 break;
2856 }
2857 }
2858 }
2859
2860 NECP_CLIENT_UNLOCK(client);
2861 }
2862 if (client_updated) {
2863 necp_fd_notify(client_fd, true);
2864 }
2865 NECP_FD_UNLOCK(client_fd);
2866
2867 proc_rele(proc);
2868 proc = PROC_NULL;
2869
2870 if (found_client) {
2871 break;
2872 }
2873 }
2874 NECP_FD_LIST_UNLOCK();
2875
2876 if (error == 0) {
2877 if (!found_client) {
2878 error = ENOENT;
2879 } else if (!client_updated) {
2880 error = EINVAL;
2881 }
2882 }
2883
2884 return error;
2885}
2886
2887bool
2888necp_socket_is_allowed_to_recv_on_interface(struct inpcb *inp, ifnet_t interface)
2889{
2890 if (interface == NULL ||
2891 inp == NULL ||
2892 !(inp->inp_flags2 & INP2_EXTERNAL_PORT) ||
2893 uuid_is_null(inp->necp_client_uuid)) {
2894 // If there's no interface or client ID to check,
2895 // or if this is not a listener, pass.
2896 // Outbound connections will have already been
2897 // validated for policy.
2898 return TRUE;
2899 }
2900
2901 // Only filter out listener sockets (no remote address specified)
2902 if ((inp->inp_vflag & INP_IPV4) &&
2903 inp->inp_faddr.s_addr != INADDR_ANY) {
2904 return TRUE;
2905 }
2906 if ((inp->inp_vflag & INP_IPV6) &&
2907 !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
2908 return TRUE;
2909 }
2910
2911 bool allowed = TRUE;
2912
2913 NECP_CLIENT_TREE_LOCK_SHARED();
2914
2915 struct necp_client *client = necp_find_client_and_lock(inp->necp_client_uuid);
2916 if (client != NULL) {
2917 struct necp_client_parsed_parameters *parsed_parameters = NULL;
2918
2919 MALLOC(parsed_parameters, struct necp_client_parsed_parameters *, sizeof(*parsed_parameters), M_NECP, (M_WAITOK | M_ZERO));
2920 if (parsed_parameters != NULL) {
2921 int error = necp_client_parse_parameters(client->parameters, (u_int32_t)client->parameters_length, parsed_parameters);
2922 if (error == 0) {
2923 if (!necp_ifnet_matches_parameters(interface, parsed_parameters, 0, NULL, true, false)) {
2924 allowed = FALSE;
2925 }
2926 }
2927 FREE(parsed_parameters, M_NECP);
2928 }
2929
2930 NECP_CLIENT_UNLOCK(client);
2931 }
2932
2933 NECP_CLIENT_TREE_UNLOCK();
2934
2935 return allowed;
2936}
2937
2938int
2939necp_update_flow_protoctl_event(uuid_t netagent_uuid, uuid_t client_id,
2940 uint32_t protoctl_event_code, uint32_t protoctl_event_val,
2941 uint32_t protoctl_event_tcp_seq_number)
2942{
2943 int error = 0;
2944 struct necp_fd_data *client_fd = NULL;
2945 bool found_client = FALSE;
2946 bool client_updated = FALSE;
2947
2948 NECP_FD_LIST_LOCK_SHARED();
2949 LIST_FOREACH(client_fd, &necp_fd_list, chain) {
2950 proc_t proc = proc_find(client_fd->proc_pid);
2951 if (proc == PROC_NULL) {
2952 continue;
2953 }
2954
2955 NECP_FD_LOCK(client_fd);
2956
2957 struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
2958 if (client != NULL) {
2959 struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
2960 if (flow_registration != NULL) {
2961 // Found the right client and flow!
2962 found_client = TRUE;
2963
2964 struct necp_client_flow *flow = NULL;
2965 LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
2966 // Verify that the client nexus agent matches
2967 if ((flow->nexus && uuid_compare(flow->u.nexus_agent, netagent_uuid) == 0) ||
2968 flow->socket) {
2969 flow->has_protoctl_event = TRUE;
2970 flow->protoctl_event.protoctl_event_code = protoctl_event_code;
2971 flow->protoctl_event.protoctl_event_val = protoctl_event_val;
2972 flow->protoctl_event.protoctl_event_tcp_seq_num = protoctl_event_tcp_seq_number;
2973 flow_registration->flow_result_read = FALSE;
2974 client_updated = TRUE;
2975 break;
2976 }
2977 }
2978 }
2979
2980 NECP_CLIENT_UNLOCK(client);
2981 }
2982
2983 if (client_updated) {
2984 necp_fd_notify(client_fd, true);
2985 }
2986
2987 NECP_FD_UNLOCK(client_fd);
2988 proc_rele(proc);
2989 proc = PROC_NULL;
2990
2991 if (found_client) {
2992 break;
2993 }
2994 }
2995 NECP_FD_LIST_UNLOCK();
2996
2997 if (!found_client) {
2998 error = ENOENT;
2999 } else if (!client_updated) {
3000 error = EINVAL;
3001 }
3002 return error;
3003}
3004
3005static bool
3006necp_assign_client_result_locked(struct proc *proc,
3007 struct necp_fd_data *client_fd,
3008 struct necp_client *client,
3009 struct necp_client_flow_registration *flow_registration,
3010 uuid_t netagent_uuid,
3011 u_int8_t *assigned_results,
3012 size_t assigned_results_length,
3013 bool notify_fd)
3014{
3015 bool client_updated = FALSE;
3016
3017 NECP_FD_ASSERT_LOCKED(client_fd);
3018 NECP_CLIENT_ASSERT_LOCKED(client);
3019
3020 struct necp_client_flow *flow = NULL;
3021 LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
3022 // Verify that the client nexus agent matches
3023 if (flow->nexus &&
3024 uuid_compare(flow->u.nexus_agent, netagent_uuid) == 0) {
3025 // Release prior results and route
3026 if (flow->assigned_results != NULL) {
3027 FREE(flow->assigned_results, M_NETAGENT);
3028 flow->assigned_results = NULL;
3029 }
3030
3031 void *nexus_stats = NULL;
3032 if (assigned_results != NULL && assigned_results_length > 0) {
3033 int error = necp_client_parse_result(assigned_results, (u_int32_t)assigned_results_length,
3034 &flow->local_addr, &flow->remote_addr, &nexus_stats);
3035 VERIFY(error == 0);
3036 }
3037
3038 flow->viable = necp_client_flow_is_viable(proc, client, flow);
3039
3040 flow->assigned = TRUE;
3041 flow->assigned_results = assigned_results;
3042 flow->assigned_results_length = assigned_results_length;
3043 flow_registration->flow_result_read = FALSE;
3044 client_updated = TRUE;
3045 break;
3046 }
3047 }
3048
3049 if (client_updated && notify_fd) {
3050 necp_fd_notify(client_fd, true);
3051 }
3052
3053 // if not updated, client must free assigned_results
3054 return client_updated;
3055}
3056
3057int
3058necp_assign_client_result(uuid_t netagent_uuid, uuid_t client_id,
3059 u_int8_t *assigned_results, size_t assigned_results_length)
3060{
3061 int error = 0;
3062 struct necp_fd_data *client_fd = NULL;
3063 bool found_client = FALSE;
3064 bool client_updated = FALSE;
3065
3066 NECP_FD_LIST_LOCK_SHARED();
3067
3068 LIST_FOREACH(client_fd, &necp_fd_list, chain) {
3069 proc_t proc = proc_find(client_fd->proc_pid);
3070 if (proc == PROC_NULL) {
3071 continue;
3072 }
3073
3074 NECP_FD_LOCK(client_fd);
3075 struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
3076 if (client != NULL) {
3077 struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
3078 if (flow_registration != NULL) {
3079 // Found the right client and flow!
3080 found_client = TRUE;
3081 if (necp_assign_client_result_locked(proc, client_fd, client, flow_registration, netagent_uuid,
3082 assigned_results, assigned_results_length, true)) {
3083 client_updated = TRUE;
3084 }
3085 }
3086
3087 NECP_CLIENT_UNLOCK(client);
3088 }
3089 NECP_FD_UNLOCK(client_fd);
3090
3091 proc_rele(proc);
3092 proc = PROC_NULL;
3093
3094 if (found_client) {
3095 break;
3096 }
3097 }
3098
3099 NECP_FD_LIST_UNLOCK();
3100
3101 // upon error, client must free assigned_results
3102 if (!found_client) {
3103 error = ENOENT;
3104 } else if (!client_updated) {
3105 error = EINVAL;
3106 }
3107
3108 return error;
3109}
3110
3111/// Client updating
3112
3113static bool
3114necp_update_parsed_parameters(struct necp_client_parsed_parameters *parsed_parameters,
3115 struct necp_aggregate_result *result)
3116{
3117 if (parsed_parameters == NULL ||
3118 result == NULL) {
3119 return false;
3120 }
3121
3122 bool updated = false;
3123 for (int i = 0; i < NECP_MAX_NETAGENTS; i++) {
3124 if (uuid_is_null(result->netagents[i])) {
3125 // Passed end of valid agents
3126 break;
3127 }
3128
3129 if (!(result->netagent_use_flags[i] & NECP_AGENT_USE_FLAG_SCOPE)) {
3130 // Not a scoped agent, ignore
3131 continue;
3132 }
3133
3134 // This is a scoped agent. Add it to the required agents.
3135 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT) {
3136 // Already some required agents, add this at the end
3137 for (int j = 0; j < NECP_MAX_AGENT_PARAMETERS; j++) {
3138 if (uuid_compare(parsed_parameters->required_netagents[j], result->netagents[i]) == 0) {
3139 // Already required, break
3140 break;
3141 }
3142 if (uuid_is_null(parsed_parameters->required_netagents[j])) {
3143 // Add here
3144 memcpy(&parsed_parameters->required_netagents[j], result->netagents[i], sizeof(uuid_t));
3145 updated = true;
3146 break;
3147 }
3148 }
3149 } else {
3150 // No required agents yet, add this one
3151 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT;
3152 memcpy(&parsed_parameters->required_netagents[0], result->netagents[i], sizeof(uuid_t));
3153 updated = true;
3154 }
3155
3156 // Remove requirements for agents of the same type
3157 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE) {
3158 char remove_agent_domain[NETAGENT_DOMAINSIZE] = { 0 };
3159 char remove_agent_type[NETAGENT_TYPESIZE] = { 0 };
3160 if (netagent_get_agent_domain_and_type(result->netagents[i], remove_agent_domain, remove_agent_type)) {
3161 for (int j = 0; j < NECP_MAX_AGENT_PARAMETERS; j++) {
3162 if (strlen(parsed_parameters->required_netagent_types[j].netagent_domain) == 0 &&
3163 strlen(parsed_parameters->required_netagent_types[j].netagent_type) == 0) {
3164 break;
3165 }
3166
3167 if (strncmp(parsed_parameters->required_netagent_types[j].netagent_domain, remove_agent_domain, NETAGENT_DOMAINSIZE) == 0 &&
3168 strncmp(parsed_parameters->required_netagent_types[j].netagent_type, remove_agent_type, NETAGENT_TYPESIZE) == 0) {
3169 updated = true;
3170
3171 if (j == NECP_MAX_AGENT_PARAMETERS - 1) {
3172 // Last field, just clear and break
3173 memset(&parsed_parameters->required_netagent_types[NECP_MAX_AGENT_PARAMETERS - 1], 0, sizeof(struct necp_client_parameter_netagent_type));
3174 break;
3175 } else {
3176 // Move the parameters down, clear the last entry
3177 memmove(&parsed_parameters->required_netagent_types[j],
3178 &parsed_parameters->required_netagent_types[j + 1],
3179 sizeof(struct necp_client_parameter_netagent_type) * (NECP_MAX_AGENT_PARAMETERS - (j + 1)));
3180 memset(&parsed_parameters->required_netagent_types[NECP_MAX_AGENT_PARAMETERS - 1], 0, sizeof(struct necp_client_parameter_netagent_type));
3181 // Continue, don't increment but look at the new shifted item instead
3182 continue;
3183 }
3184 }
3185
3186 // Increment j to look at the next agent type parameter
3187 j++;
3188 }
3189 }
3190 }
3191 }
3192
3193 if (updated &&
3194 parsed_parameters->required_interface_index != IFSCOPE_NONE &&
3195 (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IF) == 0) {
3196 // A required interface index was added after the fact. Clear it.
3197 parsed_parameters->required_interface_index = IFSCOPE_NONE;
3198 }
3199
3200
3201 return updated;
3202}
3203
3204static inline bool
3205necp_agent_types_match(const char *agent_domain1, const char *agent_type1,
3206 const char *agent_domain2, const char *agent_type2)
3207{
3208 return (strlen(agent_domain1) == 0 ||
3209 strncmp(agent_domain2, agent_domain1, NETAGENT_DOMAINSIZE) == 0) &&
3210 (strlen(agent_type1) == 0 ||
3211 strncmp(agent_type2, agent_type1, NETAGENT_TYPESIZE) == 0);
3212}
3213
3214static inline bool
3215necp_calculate_client_result(proc_t proc,
3216 struct necp_client *client,
3217 struct necp_client_parsed_parameters *parsed_parameters,
3218 struct necp_aggregate_result *result,
3219 u_int32_t *flags,
3220 u_int32_t *reason,
3221 struct necp_client_endpoint *v4_gateway,
3222 struct necp_client_endpoint *v6_gateway,
3223 uuid_t *override_euuid)
3224{
3225 struct rtentry *route = NULL;
3226
3227 // Check parameters to find best interface
3228 bool validate_agents = false;
3229 u_int matching_if_index = 0;
3230 if (necp_find_matching_interface_index(parsed_parameters, &matching_if_index, &validate_agents)) {
3231 if (matching_if_index != 0) {
3232 parsed_parameters->required_interface_index = matching_if_index;
3233 }
3234 // Interface found or not needed, match policy.
3235 memset(result, 0, sizeof(*result));
3236 int error = necp_application_find_policy_match_internal(proc, client->parameters,
3237 (u_int32_t)client->parameters_length,
3238 result, flags, reason, matching_if_index,
3239 NULL, NULL,
3240 v4_gateway, v6_gateway,
3241 &route, false, true,
3242 override_euuid);
3243 if (error != 0) {
3244 if (route != NULL) {
3245 rtfree(route);
3246 }
3247 return FALSE;
3248 }
3249
3250 if (validate_agents) {
3251 bool requirement_failed = FALSE;
3252 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT) {
3253 for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
3254 if (uuid_is_null(parsed_parameters->required_netagents[i])) {
3255 break;
3256 }
3257
3258 bool requirement_found = FALSE;
3259 for (int j = 0; j < NECP_MAX_NETAGENTS; j++) {
3260 if (uuid_is_null(result->netagents[j])) {
3261 break;
3262 }
3263
3264 if (uuid_compare(parsed_parameters->required_netagents[i], result->netagents[j]) == 0) {
3265 requirement_found = TRUE;
3266 break;
3267 }
3268 }
3269
3270 if (!requirement_found) {
3271 requirement_failed = TRUE;
3272 break;
3273 }
3274 }
3275 }
3276
3277 if (!requirement_failed && parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE) {
3278 for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
3279 if (strlen(parsed_parameters->required_netagent_types[i].netagent_domain) == 0 &&
3280 strlen(parsed_parameters->required_netagent_types[i].netagent_type) == 0) {
3281 break;
3282 }
3283
3284 bool requirement_found = FALSE;
3285 for (int j = 0; j < NECP_MAX_NETAGENTS; j++) {
3286 if (uuid_is_null(result->netagents[j])) {
3287 break;
3288 }
3289
3290 char policy_agent_domain[NETAGENT_DOMAINSIZE] = { 0 };
3291 char policy_agent_type[NETAGENT_TYPESIZE] = { 0 };
3292
3293 if (netagent_get_agent_domain_and_type(result->netagents[j], policy_agent_domain, policy_agent_type)) {
3294 if (necp_agent_types_match(parsed_parameters->required_netagent_types[i].netagent_domain,
3295 parsed_parameters->required_netagent_types[i].netagent_type,
3296 policy_agent_domain, policy_agent_type)) {
3297 requirement_found = TRUE;
3298 break;
3299 }
3300 }
3301 }
3302
3303 if (!requirement_found) {
3304 requirement_failed = TRUE;
3305 break;
3306 }
3307 }
3308 }
3309
3310 if (requirement_failed) {
3311 // Agent requirement failed. Clear out the whole result, make everything fail.
3312 memset(result, 0, sizeof(*result));
3313 if (route != NULL) {
3314 rtfree(route);
3315 }
3316 return TRUE;
3317 }
3318 }
3319
3320 // Reset current route
3321 NECP_CLIENT_ROUTE_LOCK(client);
3322 if (client->current_route != NULL) {
3323 rtfree(client->current_route);
3324 }
3325 client->current_route = route;
3326 NECP_CLIENT_ROUTE_UNLOCK(client);
3327 } else {
3328 // Interface not found. Clear out the whole result, make everything fail.
3329 memset(result, 0, sizeof(*result));
3330 }
3331
3332 return TRUE;
3333}
3334
3335#define NECP_PARSED_PARAMETERS_REQUIRED_FIELDS (NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IF | \
3336 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE | \
3337 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT | \
3338 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE)
3339
3340static bool
3341necp_update_client_result(proc_t proc,
3342 struct necp_fd_data *client_fd,
3343 struct necp_client *client,
3344 struct _necp_flow_defunct_list *defunct_list)
3345{
3346 struct necp_client_result_netagent netagent;
3347 struct necp_aggregate_result result;
3348 struct necp_client_parsed_parameters *parsed_parameters = NULL;
3349 u_int32_t flags = 0;
3350 u_int32_t reason = 0;
3351
3352 NECP_CLIENT_ASSERT_LOCKED(client);
3353
3354 MALLOC(parsed_parameters, struct necp_client_parsed_parameters *, sizeof(*parsed_parameters), M_NECP, (M_WAITOK | M_ZERO));
3355 if (parsed_parameters == NULL) {
3356 NECPLOG0(LOG_ERR, "Failed to allocate parsed parameters");
3357 return FALSE;
3358 }
3359
3360 // Nexus flows will be brought back if they are still valid
3361 necp_client_mark_all_nonsocket_flows_as_invalid(client);
3362
3363 int error = necp_client_parse_parameters(client->parameters, (u_int32_t)client->parameters_length, parsed_parameters);
3364 if (error != 0) {
3365 FREE(parsed_parameters, M_NECP);
3366 return FALSE;
3367 }
3368
3369 // Update saved IP protocol
3370 client->ip_protocol = parsed_parameters->ip_protocol;
3371
3372 // Calculate the policy result
3373 struct necp_client_endpoint v4_gateway = {};
3374 struct necp_client_endpoint v6_gateway = {};
3375 uuid_t override_euuid;
3376 uuid_clear(override_euuid);
3377 if (!necp_calculate_client_result(proc, client, parsed_parameters, &result, &flags, &reason, &v4_gateway, &v6_gateway, &override_euuid)) {
3378 FREE(parsed_parameters, M_NECP);
3379 return FALSE;
3380 }
3381
3382 if (necp_update_parsed_parameters(parsed_parameters, &result)) {
3383 // Changed the parameters based on result, try again (only once)
3384 if (!necp_calculate_client_result(proc, client, parsed_parameters, &result, &flags, &reason, &v4_gateway, &v6_gateway, &override_euuid)) {
3385 FREE(parsed_parameters, M_NECP);
3386 return FALSE;
3387 }
3388 }
3389
3390 if ((parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) &&
3391 parsed_parameters->required_interface_index != IFSCOPE_NONE &&
3392 (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IF) == 0) {
3393 // Listener should not apply required interface index if
3394 parsed_parameters->required_interface_index = IFSCOPE_NONE;
3395 }
3396
3397 // Save the last policy id on the client
3398 client->policy_id = result.policy_id;
3399 uuid_copy(client->override_euuid, override_euuid);
3400
3401 if ((parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_MULTIPATH) ||
3402 (parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_BROWSE) ||
3403 ((parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) &&
3404 result.routing_result != NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED)) {
3405 client->allow_multiple_flows = TRUE;
3406 } else {
3407 client->allow_multiple_flows = FALSE;
3408 }
3409
3410 // If the original request was scoped, and the policy result matches, make sure the result is scoped
3411 if ((result.routing_result == NECP_KERNEL_POLICY_RESULT_NONE ||
3412 result.routing_result == NECP_KERNEL_POLICY_RESULT_PASS) &&
3413 result.routed_interface_index != IFSCOPE_NONE &&
3414 parsed_parameters->required_interface_index == result.routed_interface_index) {
3415 result.routing_result = NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED;
3416 result.routing_result_parameter.scoped_interface_index = result.routed_interface_index;
3417 }
3418
3419 if (defunct_list != NULL &&
3420 result.routing_result == NECP_KERNEL_POLICY_RESULT_DROP) {
3421 // If we are forced to drop the client, defunct it if it has flows
3422 necp_defunct_client_for_policy(client, defunct_list);
3423 }
3424
3425 // Recalculate flags
3426 if (parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) {
3427 // Listeners are valid as long as they aren't dropped
3428 if (result.routing_result != NECP_KERNEL_POLICY_RESULT_DROP) {
3429 flags |= NECP_CLIENT_RESULT_FLAG_SATISFIED;
3430 }
3431 } else if (result.routed_interface_index != 0) {
3432 // Clients without flows determine viability based on having some routable interface
3433 flags |= NECP_CLIENT_RESULT_FLAG_SATISFIED;
3434 }
3435
3436 bool updated = FALSE;
3437 u_int8_t *cursor = client->result;
3438 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_FLAGS, sizeof(flags), &flags, &updated, client->result, sizeof(client->result));
3439 if (reason != 0) {
3440 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_REASON, sizeof(reason), &reason, &updated, client->result, sizeof(client->result));
3441 }
3442 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_CLIENT_ID, sizeof(uuid_t), client->client_id, &updated,
3443 client->result, sizeof(client->result));
3444 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_POLICY_RESULT, sizeof(result.routing_result), &result.routing_result, &updated,
3445 client->result, sizeof(client->result));
3446 if (result.routing_result_parameter.tunnel_interface_index != 0) {
3447 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_POLICY_RESULT_PARAMETER,
3448 sizeof(result.routing_result_parameter), &result.routing_result_parameter, &updated,
3449 client->result, sizeof(client->result));
3450 }
3451 if (result.filter_control_unit != 0) {
3452 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_FILTER_CONTROL_UNIT,
3453 sizeof(result.filter_control_unit), &result.filter_control_unit, &updated,
3454 client->result, sizeof(client->result));
3455 }
3456 if (result.flow_divert_aggregate_unit != 0) {
3457 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_FLOW_DIVERT_AGGREGATE_UNIT,
3458 sizeof(result.flow_divert_aggregate_unit), &result.flow_divert_aggregate_unit, &updated,
3459 client->result, sizeof(client->result));
3460 }
3461 if (result.routed_interface_index != 0) {
3462 u_int routed_interface_index = result.routed_interface_index;
3463 if (result.routing_result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL &&
3464 (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_REQUIRED_FIELDS) &&
3465 parsed_parameters->required_interface_index != IFSCOPE_NONE &&
3466 parsed_parameters->required_interface_index != result.routed_interface_index) {
3467 routed_interface_index = parsed_parameters->required_interface_index;
3468 }
3469
3470 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE_INDEX,
3471 sizeof(routed_interface_index), &routed_interface_index, &updated,
3472 client->result, sizeof(client->result));
3473 }
3474 if (client_fd && client_fd->flags & NECP_OPEN_FLAG_BACKGROUND) {
3475 u_int32_t effective_traffic_class = SO_TC_BK_SYS;
3476 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_EFFECTIVE_TRAFFIC_CLASS,
3477 sizeof(effective_traffic_class), &effective_traffic_class, &updated,
3478 client->result, sizeof(client->result));
3479 }
3480
3481 if (client_fd->background) {
3482 bool has_assigned_flow = FALSE;
3483 struct necp_client_flow_registration *flow_registration = NULL;
3484 struct necp_client_flow *search_flow = NULL;
3485 RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
3486 LIST_FOREACH(search_flow, &flow_registration->flow_list, flow_chain) {
3487 if (search_flow->assigned) {
3488 has_assigned_flow = TRUE;
3489 break;
3490 }
3491 }
3492 }
3493
3494 if (has_assigned_flow) {
3495 u_int32_t background = client_fd->background;
3496 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_TRAFFIC_MGMT_BG,
3497 sizeof(background), &background, &updated,
3498 client->result, sizeof(client->result));
3499 }
3500 }
3501
3502 bool write_v4_gateway = !necp_client_endpoint_is_unspecified(&v4_gateway);
3503 bool write_v6_gateway = !necp_client_endpoint_is_unspecified(&v6_gateway);
3504
3505 NECP_CLIENT_ROUTE_LOCK(client);
3506 if (client->current_route != NULL) {
3507 const u_int32_t route_mtu = get_maxmtu(client->current_route);
3508 if (route_mtu != 0) {
3509 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_EFFECTIVE_MTU,
3510 sizeof(route_mtu), &route_mtu, &updated,
3511 client->result, sizeof(client->result));
3512 }
3513 bool has_remote_addr = parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REMOTE_ADDR;
3514 if (has_remote_addr && client->current_route->rt_gateway != NULL) {
3515 if (client->current_route->rt_gateway->sa_family == AF_INET) {
3516 write_v6_gateway = false;
3517 } else if (client->current_route->rt_gateway->sa_family == AF_INET6) {
3518 write_v4_gateway = false;
3519 }
3520 }
3521 }
3522 NECP_CLIENT_ROUTE_UNLOCK(client);
3523
3524 if (write_v4_gateway) {
3525 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_GATEWAY,
3526 sizeof(struct necp_client_endpoint), &v4_gateway, &updated,
3527 client->result, sizeof(client->result));
3528 }
3529
3530 if (write_v6_gateway) {
3531 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_GATEWAY,
3532 sizeof(struct necp_client_endpoint), &v6_gateway, &updated,
3533 client->result, sizeof(client->result));
3534 }
3535
3536 for (int i = 0; i < NAT64_MAX_NUM_PREFIXES; i++) {
3537 if (result.nat64_prefixes[i].prefix_len != 0) {
3538 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_NAT64,
3539 sizeof(result.nat64_prefixes), result.nat64_prefixes, &updated,
3540 client->result, sizeof(client->result));
3541 break;
3542 }
3543 }
3544
3545 if (result.mss_recommended != 0) {
3546 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_RECOMMENDED_MSS,
3547 sizeof(result.mss_recommended), &result.mss_recommended, &updated,
3548 client->result, sizeof(client->result));
3549 }
3550
3551 for (int i = 0; i < NECP_MAX_NETAGENTS; i++) {
3552 if (uuid_is_null(result.netagents[i])) {
3553 break;
3554 }
3555 uuid_copy(netagent.netagent_uuid, result.netagents[i]);
3556 netagent.generation = netagent_get_generation(netagent.netagent_uuid);
3557 if (necp_netagent_applies_to_client(client, parsed_parameters, &netagent.netagent_uuid, TRUE, 0, 0)) {
3558 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_NETAGENT, sizeof(netagent), &netagent, &updated,
3559 client->result, sizeof(client->result));
3560 }
3561 }
3562
3563 ifnet_head_lock_shared();
3564 ifnet_t direct_interface = NULL;
3565 ifnet_t delegate_interface = NULL;
3566 ifnet_t original_scoped_interface = NULL;
3567
3568 if (result.routed_interface_index != IFSCOPE_NONE && result.routed_interface_index <= (u_int32_t)if_index) {
3569 direct_interface = ifindex2ifnet[result.routed_interface_index];
3570 } else if (parsed_parameters->required_interface_index != IFSCOPE_NONE &&
3571 parsed_parameters->required_interface_index <= (u_int32_t)if_index) {
3572 // If the request was scoped, but the route didn't match, still grab the agents
3573 direct_interface = ifindex2ifnet[parsed_parameters->required_interface_index];
3574 } else if (result.routed_interface_index == IFSCOPE_NONE &&
3575 result.routing_result == NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED &&
3576 result.routing_result_parameter.scoped_interface_index != IFSCOPE_NONE) {
3577 direct_interface = ifindex2ifnet[result.routing_result_parameter.scoped_interface_index];
3578 }
3579 if (direct_interface != NULL) {
3580 delegate_interface = direct_interface->if_delegated.ifp;
3581 }
3582 if (result.routing_result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL &&
3583 (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_REQUIRED_FIELDS) &&
3584 parsed_parameters->required_interface_index != IFSCOPE_NONE &&
3585 parsed_parameters->required_interface_index != result.routing_result_parameter.tunnel_interface_index &&
3586 parsed_parameters->required_interface_index <= (u_int32_t)if_index) {
3587 original_scoped_interface = ifindex2ifnet[parsed_parameters->required_interface_index];
3588 }
3589 // Add interfaces
3590 if (original_scoped_interface != NULL) {
3591 struct necp_client_result_interface interface_struct;
3592 interface_struct.index = original_scoped_interface->if_index;
3593 interface_struct.generation = ifnet_get_generation(original_scoped_interface);
3594 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE, sizeof(interface_struct), &interface_struct, &updated,
3595 client->result, sizeof(client->result));
3596 }
3597 if (direct_interface != NULL) {
3598 struct necp_client_result_interface interface_struct;
3599 interface_struct.index = direct_interface->if_index;
3600 interface_struct.generation = ifnet_get_generation(direct_interface);
3601 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE, sizeof(interface_struct), &interface_struct, &updated,
3602 client->result, sizeof(client->result));
3603
3604 // Set the delta time since interface up/down
3605 struct timeval updown_delta = {};
3606 if (ifnet_updown_delta(direct_interface, &updown_delta) == 0) {
3607 u_int32_t delta = updown_delta.tv_sec;
3608 bool ignore_updated = FALSE;
3609 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE_TIME_DELTA,
3610 sizeof(delta), &delta, &ignore_updated,
3611 client->result, sizeof(client->result));
3612 }
3613 }
3614 if (delegate_interface != NULL) {
3615 struct necp_client_result_interface interface_struct;
3616 interface_struct.index = delegate_interface->if_index;
3617 interface_struct.generation = ifnet_get_generation(delegate_interface);
3618 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE, sizeof(interface_struct), &interface_struct, &updated,
3619 client->result, sizeof(client->result));
3620 }
3621
3622 // Update multipath/listener interface flows
3623 if (parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_MULTIPATH) {
3624 // Get multipath interface options from ordered list
3625 struct ifnet *multi_interface = NULL;
3626 TAILQ_FOREACH(multi_interface, &ifnet_ordered_head, if_ordered_link) {
3627 if (necp_ifnet_matches_parameters(multi_interface, parsed_parameters, 0, NULL, true, false)) {
3628 // Add multipath interface flows for kernel MPTCP
3629 necp_client_add_interface_option_if_needed(client, multi_interface->if_index,
3630 ifnet_get_generation(multi_interface), NULL, false);
3631
3632 // Add nexus agents for multipath
3633 necp_client_add_agent_interface_options(client, parsed_parameters, multi_interface);
3634 }
3635 }
3636 } else if (parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) {
3637 if (result.routing_result == NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED) {
3638 if (direct_interface != NULL) {
3639 // If scoped, only listen on that interface
3640 // Add nexus agents for listeners
3641 necp_client_add_agent_interface_options(client, parsed_parameters, direct_interface);
3642
3643 // Add interface option in case it is not a nexus
3644 necp_client_add_interface_option_if_needed(client, direct_interface->if_index,
3645 ifnet_get_generation(direct_interface), NULL, false);
3646 }
3647 } else {
3648 // Get listener interface options from global list
3649 struct ifnet *listen_interface = NULL;
3650 TAILQ_FOREACH(listen_interface, &ifnet_head, if_link) {
3651 if ((listen_interface->if_flags & (IFF_UP | IFF_RUNNING)) &&
3652 necp_ifnet_matches_parameters(listen_interface, parsed_parameters, 0, NULL, true, false)) {
3653 // Add nexus agents for listeners
3654 necp_client_add_agent_interface_options(client, parsed_parameters, listen_interface);
3655 }
3656 }
3657 }
3658 } else if (parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_BROWSE) {
3659 if (result.routing_result == NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED) {
3660 if (direct_interface != NULL) {
3661 // Add browse option if it has an agent
3662 necp_client_add_browse_interface_options(client, parsed_parameters, direct_interface);
3663 }
3664 } else {
3665 // Get browse interface options from global list
3666 struct ifnet *browse_interface = NULL;
3667 TAILQ_FOREACH(browse_interface, &ifnet_head, if_link) {
3668 if (necp_ifnet_matches_parameters(browse_interface, parsed_parameters, 0, NULL, true, false)) {
3669 necp_client_add_browse_interface_options(client, parsed_parameters, browse_interface);
3670 }
3671 }
3672 }
3673 }
3674
3675 // Add agents
3676 if (original_scoped_interface != NULL) {
3677 ifnet_lock_shared(original_scoped_interface);
3678 if (original_scoped_interface->if_agentids != NULL) {
3679 for (u_int32_t i = 0; i < original_scoped_interface->if_agentcount; i++) {
3680 if (uuid_is_null(original_scoped_interface->if_agentids[i])) {
3681 continue;
3682 }
3683 uuid_copy(netagent.netagent_uuid, original_scoped_interface->if_agentids[i]);
3684 netagent.generation = netagent_get_generation(netagent.netagent_uuid);
3685 if (necp_netagent_applies_to_client(client, parsed_parameters, &netagent.netagent_uuid, FALSE,
3686 original_scoped_interface->if_index, ifnet_get_generation(original_scoped_interface))) {
3687 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_NETAGENT, sizeof(netagent), &netagent, &updated,
3688 client->result, sizeof(client->result));
3689 }
3690 }
3691 }
3692 ifnet_lock_done(original_scoped_interface);
3693 }
3694 if (direct_interface != NULL) {
3695 ifnet_lock_shared(direct_interface);
3696 if (direct_interface->if_agentids != NULL) {
3697 for (u_int32_t i = 0; i < direct_interface->if_agentcount; i++) {
3698 if (uuid_is_null(direct_interface->if_agentids[i])) {
3699 continue;
3700 }
3701 uuid_copy(netagent.netagent_uuid, direct_interface->if_agentids[i]);
3702 netagent.generation = netagent_get_generation(netagent.netagent_uuid);
3703 if (necp_netagent_applies_to_client(client, parsed_parameters, &netagent.netagent_uuid, TRUE,
3704 direct_interface->if_index, ifnet_get_generation(direct_interface))) {
3705 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_NETAGENT, sizeof(netagent), &netagent, &updated,
3706 client->result, sizeof(client->result));
3707 }
3708 }
3709 }
3710 ifnet_lock_done(direct_interface);
3711 }
3712 if (delegate_interface != NULL) {
3713 ifnet_lock_shared(delegate_interface);
3714 if (delegate_interface->if_agentids != NULL) {
3715 for (u_int32_t i = 0; i < delegate_interface->if_agentcount; i++) {
3716 if (uuid_is_null(delegate_interface->if_agentids[i])) {
3717 continue;
3718 }
3719 uuid_copy(netagent.netagent_uuid, delegate_interface->if_agentids[i]);
3720 netagent.generation = netagent_get_generation(netagent.netagent_uuid);
3721 if (necp_netagent_applies_to_client(client, parsed_parameters, &netagent.netagent_uuid, FALSE,
3722 delegate_interface->if_index, ifnet_get_generation(delegate_interface))) {
3723 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_NETAGENT, sizeof(netagent), &netagent, &updated,
3724 client->result, sizeof(client->result));
3725 }
3726 }
3727 }
3728 ifnet_lock_done(delegate_interface);
3729 }
3730 ifnet_head_done();
3731
3732 // Add interface options
3733 for (u_int32_t option_i = 0; option_i < client->interface_option_count; option_i++) {
3734 if (option_i < NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT) {
3735 struct necp_client_interface_option *option = &client->interface_options[option_i];
3736 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE_OPTION, sizeof(*option), option, &updated,
3737 client->result, sizeof(client->result));
3738 } else {
3739 struct necp_client_interface_option *option = &client->extra_interface_options[option_i - NECP_CLIENT_INTERFACE_OPTION_STATIC_COUNT];
3740 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE_OPTION, sizeof(*option), option, &updated,
3741 client->result, sizeof(client->result));
3742 }
3743 }
3744
3745 size_t new_result_length = (cursor - client->result);
3746 if (new_result_length != client->result_length) {
3747 client->result_length = new_result_length;
3748 updated = TRUE;
3749 }
3750
3751 // Update flow viability/flags
3752 if (necp_client_update_flows(proc, client, defunct_list)) {
3753 updated = TRUE;
3754 }
3755
3756 if (updated) {
3757 client->result_read = FALSE;
3758 necp_client_update_observer_update(client);
3759 }
3760
3761 FREE(parsed_parameters, M_NECP);
3762 return updated;
3763}
3764
3765static bool
3766necp_defunct_client_fd_locked_inner(struct necp_fd_data *client_fd, struct _necp_flow_defunct_list *defunct_list, bool destroy_stats)
3767{
3768 bool updated_result = FALSE;
3769 struct necp_client *client = NULL;
3770
3771 NECP_FD_ASSERT_LOCKED(client_fd);
3772
3773 RB_FOREACH(client, _necp_client_tree, &client_fd->clients) {
3774 struct necp_client_flow_registration *flow_registration = NULL;
3775
3776 NECP_CLIENT_LOCK(client);
3777
3778 // Prepare close events to be sent to the nexus to effectively remove the flows
3779 struct necp_client_flow *search_flow = NULL;
3780 RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
3781 LIST_FOREACH(search_flow, &flow_registration->flow_list, flow_chain) {
3782 if (search_flow->nexus &&
3783 !uuid_is_null(search_flow->u.nexus_agent)) {
3784 // Sleeping alloc won't fail; copy only what's necessary
3785 struct necp_flow_defunct *flow_defunct = _MALLOC(sizeof(struct necp_flow_defunct), M_NECP, M_WAITOK | M_ZERO);
3786 uuid_copy(flow_defunct->nexus_agent, search_flow->u.nexus_agent);
3787 uuid_copy(flow_defunct->flow_id, ((flow_registration->flags & NECP_CLIENT_FLOW_FLAGS_USE_CLIENT_ID) ?
3788 client->client_id :
3789 flow_registration->registration_id));
3790 flow_defunct->proc_pid = client->proc_pid;
3791 flow_defunct->agent_handle = client->agent_handle;
3792 flow_defunct->flags = flow_registration->flags;
3793 // Add to the list provided by caller
3794 LIST_INSERT_HEAD(defunct_list, flow_defunct, chain);
3795
3796 flow_registration->defunct = true;
3797 flow_registration->flow_result_read = false;
3798 updated_result = true;
3799 }
3800 }
3801 }
3802 if (destroy_stats) {
3803 }
3804 NECP_CLIENT_UNLOCK(client);
3805 }
3806
3807 return updated_result;
3808}
3809
3810static inline void
3811necp_defunct_client_fd_locked(struct necp_fd_data *client_fd, struct _necp_flow_defunct_list *defunct_list, struct proc *proc)
3812{
3813#pragma unused(proc)
3814 bool updated_result = FALSE;
3815
3816 NECP_FD_ASSERT_LOCKED(client_fd);
3817
3818 updated_result = necp_defunct_client_fd_locked_inner(client_fd, defunct_list, true);
3819
3820
3821 if (updated_result) {
3822 necp_fd_notify(client_fd, true);
3823 }
3824}
3825
3826static inline void
3827necp_update_client_fd_locked(struct necp_fd_data *client_fd,
3828 proc_t proc,
3829 struct _necp_flow_defunct_list *defunct_list)
3830{
3831 struct necp_client *client = NULL;
3832 bool updated_result = FALSE;
3833 NECP_FD_ASSERT_LOCKED(client_fd);
3834 RB_FOREACH(client, _necp_client_tree, &client_fd->clients) {
3835 NECP_CLIENT_LOCK(client);
3836 if (necp_update_client_result(proc, client_fd, client, defunct_list)) {
3837 updated_result = TRUE;
3838 }
3839 NECP_CLIENT_UNLOCK(client);
3840 }
3841 if (updated_result) {
3842 necp_fd_notify(client_fd, true);
3843 }
3844}
3845
3846
3847static void
3848necp_update_all_clients_callout(__unused thread_call_param_t dummy,
3849 __unused thread_call_param_t arg)
3850{
3851 struct necp_fd_data *client_fd = NULL;
3852
3853 struct _necp_flow_defunct_list defunct_list;
3854 LIST_INIT(&defunct_list);
3855
3856 NECP_FD_LIST_LOCK_SHARED();
3857
3858 LIST_FOREACH(client_fd, &necp_fd_list, chain) {
3859 proc_t proc = proc_find(client_fd->proc_pid);
3860 if (proc == PROC_NULL) {
3861 continue;
3862 }
3863
3864 // Update all clients on one fd
3865 NECP_FD_LOCK(client_fd);
3866 necp_update_client_fd_locked(client_fd, proc, &defunct_list);
3867 NECP_FD_UNLOCK(client_fd);
3868
3869 proc_rele(proc);
3870 proc = PROC_NULL;
3871 }
3872
3873 NECP_FD_LIST_UNLOCK();
3874
3875 // Handle the case in which some clients became newly defunct
3876 necp_process_defunct_list(&defunct_list);
3877}
3878
3879void
3880necp_update_all_clients(void)
3881{
3882 necp_update_all_clients_immediately_if_needed(false);
3883}
3884
3885void
3886necp_update_all_clients_immediately_if_needed(bool should_update_immediately)
3887{
3888 if (necp_client_update_tcall == NULL) {
3889 // Don't try to update clients if the module is not initialized
3890 return;
3891 }
3892
3893 uint64_t deadline = 0;
3894 uint64_t leeway = 0;
3895
3896 uint32_t timeout_to_use = necp_timeout_microseconds;
3897 uint32_t leeway_to_use = necp_timeout_leeway_microseconds;
3898 if (should_update_immediately) {
3899 timeout_to_use = 1000 * 10; // 10ms
3900 leeway_to_use = 1000 * 10; // 10ms;
3901 }
3902
3903 clock_interval_to_deadline(timeout_to_use, NSEC_PER_USEC, &deadline);
3904 clock_interval_to_absolutetime_interval(leeway_to_use, NSEC_PER_USEC, &leeway);
3905
3906 thread_call_enter_delayed_with_leeway(necp_client_update_tcall, NULL,
3907 deadline, leeway, THREAD_CALL_DELAY_LEEWAY);
3908}
3909
3910bool
3911necp_set_client_as_background(proc_t proc,
3912 struct fileproc *fp,
3913 bool background)
3914{
3915 if (proc == PROC_NULL) {
3916 NECPLOG0(LOG_ERR, "NULL proc");
3917 return FALSE;
3918 }
3919
3920 if (fp == NULL) {
3921 NECPLOG0(LOG_ERR, "NULL fp");
3922 return FALSE;
3923 }
3924
3925 struct necp_fd_data *client_fd = (struct necp_fd_data *)fp->fp_glob->fg_data;
3926 if (client_fd == NULL) {
3927 NECPLOG0(LOG_ERR, "Could not find client structure for backgrounded client");
3928 return FALSE;
3929 }
3930
3931 if (client_fd->necp_fd_type != necp_fd_type_client) {
3932 // Not a client fd, ignore
3933 NECPLOG0(LOG_ERR, "Not a client fd, ignore");
3934 return FALSE;
3935 }
3936
3937 client_fd->background = background;
3938
3939 return TRUE;
3940}
3941
3942void
3943necp_fd_memstatus(proc_t proc, uint32_t status,
3944 struct necp_fd_data *client_fd)
3945{
3946#pragma unused(proc, status, client_fd)
3947 ASSERT(proc != PROC_NULL);
3948 ASSERT(client_fd != NULL);
3949
3950 // Nothing to reap for the process or client for now,
3951 // but this is where we would trigger that in future.
3952}
3953
3954void
3955necp_fd_defunct(proc_t proc, struct necp_fd_data *client_fd)
3956{
3957 struct _necp_flow_defunct_list defunct_list;
3958
3959 ASSERT(proc != PROC_NULL);
3960 ASSERT(client_fd != NULL);
3961
3962 if (client_fd->necp_fd_type != necp_fd_type_client) {
3963 // Not a client fd, ignore
3964 return;
3965 }
3966
3967 // Our local temporary list
3968 LIST_INIT(&defunct_list);
3969
3970 // Need to hold lock so ntstats defunct the same set of clients
3971 NECP_FD_LOCK(client_fd);
3972 necp_defunct_client_fd_locked(client_fd, &defunct_list, proc);
3973 NECP_FD_UNLOCK(client_fd);
3974
3975 necp_process_defunct_list(&defunct_list);
3976}
3977
3978static void
3979necp_client_remove_agent_from_result(struct necp_client *client, uuid_t netagent_uuid)
3980{
3981 size_t offset = 0;
3982
3983 u_int8_t *result_buffer = client->result;
3984 while ((offset + sizeof(struct necp_tlv_header)) <= client->result_length) {
3985 u_int8_t type = necp_buffer_get_tlv_type(result_buffer, offset);
3986 u_int32_t length = necp_buffer_get_tlv_length(result_buffer, offset);
3987
3988 size_t tlv_total_length = (sizeof(struct necp_tlv_header) + length);
3989 if (type == NECP_CLIENT_RESULT_NETAGENT &&
3990 length == sizeof(struct necp_client_result_netagent) &&
3991 (offset + tlv_total_length) <= client->result_length) {
3992 struct necp_client_result_netagent *value = ((struct necp_client_result_netagent *)(void *)
3993 necp_buffer_get_tlv_value(result_buffer, offset, NULL));
3994 if (uuid_compare(value->netagent_uuid, netagent_uuid) == 0) {
3995 // Found a netagent to remove
3996 // Shift bytes down to remove the tlv, and adjust total length
3997 // Don't adjust the current offset
3998 memmove(result_buffer + offset,
3999 result_buffer + offset + tlv_total_length,
4000 client->result_length - (offset + tlv_total_length));
4001 client->result_length -= tlv_total_length;
4002 memset(result_buffer + client->result_length, 0, sizeof(client->result) - client->result_length);
4003 continue;
4004 }
4005 }
4006
4007 offset += tlv_total_length;
4008 }
4009}
4010
4011void
4012necp_force_update_client(uuid_t client_id, uuid_t remove_netagent_uuid, u_int32_t agent_generation)
4013{
4014 struct necp_fd_data *client_fd = NULL;
4015
4016 NECP_FD_LIST_LOCK_SHARED();
4017
4018 LIST_FOREACH(client_fd, &necp_fd_list, chain) {
4019 bool updated_result = FALSE;
4020 NECP_FD_LOCK(client_fd);
4021 struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
4022 if (client != NULL) {
4023 client->failed_trigger_agent.generation = agent_generation;
4024 uuid_copy(client->failed_trigger_agent.netagent_uuid, remove_netagent_uuid);
4025 if (!uuid_is_null(remove_netagent_uuid)) {
4026 necp_client_remove_agent_from_result(client, remove_netagent_uuid);
4027 }
4028 client->result_read = FALSE;
4029 // Found the client, break
4030 updated_result = TRUE;
4031 NECP_CLIENT_UNLOCK(client);
4032 }
4033 if (updated_result) {
4034 necp_fd_notify(client_fd, true);
4035 }
4036 NECP_FD_UNLOCK(client_fd);
4037 if (updated_result) {
4038 // Found the client, break
4039 break;
4040 }
4041 }
4042
4043 NECP_FD_LIST_UNLOCK();
4044}
4045
4046
4047/// Interface matching
4048
4049#define NECP_PARSED_PARAMETERS_INTERESTING_IFNET_FIELDS (NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR | \
4050 NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IF | \
4051 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE | \
4052 NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IFTYPE | \
4053 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT | \
4054 NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT | \
4055 NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT | \
4056 NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT | \
4057 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE | \
4058 NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT_TYPE | \
4059 NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT_TYPE | \
4060 NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT_TYPE)
4061
4062#define NECP_PARSED_PARAMETERS_SCOPED_FIELDS (NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR | \
4063 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE | \
4064 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT | \
4065 NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT | \
4066 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE | \
4067 NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT_TYPE)
4068
4069#define NECP_PARSED_PARAMETERS_SCOPED_IFNET_FIELDS (NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR | \
4070 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE)
4071
4072#define NECP_PARSED_PARAMETERS_PREFERRED_FIELDS (NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT | \
4073 NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT | \
4074 NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT_TYPE | \
4075 NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT_TYPE)
4076
4077static bool
4078necp_ifnet_matches_type(struct ifnet *ifp, u_int8_t interface_type, bool check_delegates)
4079{
4080 struct ifnet *check_ifp = ifp;
4081 while (check_ifp) {
4082 if (if_functional_type(check_ifp, TRUE) == interface_type) {
4083 return TRUE;
4084 }
4085 if (!check_delegates) {
4086 break;
4087 }
4088 check_ifp = check_ifp->if_delegated.ifp;
4089 }
4090 return FALSE;
4091}
4092
4093static bool
4094necp_ifnet_matches_name(struct ifnet *ifp, const char *interface_name, bool check_delegates)
4095{
4096 struct ifnet *check_ifp = ifp;
4097 while (check_ifp) {
4098 if (strncmp(check_ifp->if_xname, interface_name, IFXNAMSIZ) == 0) {
4099 return TRUE;
4100 }
4101 if (!check_delegates) {
4102 break;
4103 }
4104 check_ifp = check_ifp->if_delegated.ifp;
4105 }
4106 return FALSE;
4107}
4108
4109static bool
4110necp_ifnet_matches_agent(struct ifnet *ifp, uuid_t *agent_uuid, bool check_delegates)
4111{
4112 struct ifnet *check_ifp = ifp;
4113
4114 while (check_ifp != NULL) {
4115 ifnet_lock_shared(check_ifp);
4116 if (check_ifp->if_agentids != NULL) {
4117 for (u_int32_t index = 0; index < check_ifp->if_agentcount; index++) {
4118 if (uuid_compare(check_ifp->if_agentids[index], *agent_uuid) == 0) {
4119 ifnet_lock_done(check_ifp);
4120 return TRUE;
4121 }
4122 }
4123 }
4124 ifnet_lock_done(check_ifp);
4125
4126 if (!check_delegates) {
4127 break;
4128 }
4129 check_ifp = check_ifp->if_delegated.ifp;
4130 }
4131 return FALSE;
4132}
4133
4134static bool
4135necp_ifnet_matches_agent_type(struct ifnet *ifp, const char *agent_domain, const char *agent_type, bool check_delegates)
4136{
4137 struct ifnet *check_ifp = ifp;
4138
4139 while (check_ifp != NULL) {
4140 ifnet_lock_shared(check_ifp);
4141 if (check_ifp->if_agentids != NULL) {
4142 for (u_int32_t index = 0; index < check_ifp->if_agentcount; index++) {
4143 if (uuid_is_null(check_ifp->if_agentids[index])) {
4144 continue;
4145 }
4146
4147 char if_agent_domain[NETAGENT_DOMAINSIZE] = { 0 };
4148 char if_agent_type[NETAGENT_TYPESIZE] = { 0 };
4149
4150 if (netagent_get_agent_domain_and_type(check_ifp->if_agentids[index], if_agent_domain, if_agent_type)) {
4151 if (necp_agent_types_match(agent_domain, agent_type, if_agent_domain, if_agent_type)) {
4152 ifnet_lock_done(check_ifp);
4153 return TRUE;
4154 }
4155 }
4156 }
4157 }
4158 ifnet_lock_done(check_ifp);
4159
4160 if (!check_delegates) {
4161 break;
4162 }
4163 check_ifp = check_ifp->if_delegated.ifp;
4164 }
4165 return FALSE;
4166}
4167
4168static bool
4169necp_ifnet_matches_local_address(struct ifnet *ifp, struct sockaddr *sa)
4170{
4171 struct ifaddr *ifa = NULL;
4172 bool matched_local_address = FALSE;
4173
4174 // Transform sa into the ifaddr form
4175 // IPv6 Scope IDs are always embedded in the ifaddr list
4176 struct sockaddr_storage address;
4177 u_int ifscope = IFSCOPE_NONE;
4178 (void)sa_copy(sa, &address, &ifscope);
4179 SIN(&address)->sin_port = 0;
4180 if (address.ss_family == AF_INET6) {
4181 SIN6(&address)->sin6_scope_id = 0;
4182 }
4183
4184 ifa = ifa_ifwithaddr_scoped_locked((struct sockaddr *)&address, ifp->if_index);
4185 matched_local_address = (ifa != NULL);
4186
4187 if (ifa) {
4188 ifaddr_release(ifa);
4189 }
4190
4191 return matched_local_address;
4192}
4193
4194static bool
4195necp_interface_type_is_primary_eligible(u_int8_t interface_type)
4196{
4197 switch (interface_type) {
4198 // These types can never be primary, so a client requesting these types is allowed
4199 // to match an interface that isn't currently eligible to be primary (has default
4200 // route, dns, etc)
4201 case IFRTYPE_FUNCTIONAL_WIFI_AWDL:
4202 case IFRTYPE_FUNCTIONAL_INTCOPROC:
4203 return false;
4204 default:
4205 break;
4206 }
4207 return true;
4208}
4209
4210#define NECP_IFP_IS_ON_ORDERED_LIST(_ifp) ((_ifp)->if_ordered_link.tqe_next != NULL || (_ifp)->if_ordered_link.tqe_prev != NULL)
4211
4212// Secondary interface flag indicates that the interface is being
4213// used for multipath or a listener as an extra path
4214static bool
4215necp_ifnet_matches_parameters(struct ifnet *ifp,
4216 struct necp_client_parsed_parameters *parsed_parameters,
4217 u_int32_t override_flags,
4218 u_int32_t *preferred_count,
4219 bool secondary_interface,
4220 bool require_scoped_field)
4221{
4222 bool matched_some_scoped_field = FALSE;
4223
4224 if (preferred_count) {
4225 *preferred_count = 0;
4226 }
4227
4228 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IF) {
4229 if (parsed_parameters->required_interface_index != ifp->if_index) {
4230 return FALSE;
4231 }
4232 }
4233
4234 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR) {
4235 if (!necp_ifnet_matches_local_address(ifp, &parsed_parameters->local_addr.sa)) {
4236 return FALSE;
4237 }
4238 if (require_scoped_field) {
4239 matched_some_scoped_field = TRUE;
4240 }
4241 }
4242
4243 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_FLAGS) {
4244 if (override_flags != 0) {
4245 if ((override_flags & NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_EXPENSIVE) &&
4246 IFNET_IS_EXPENSIVE(ifp)) {
4247 return FALSE;
4248 }
4249 if ((override_flags & NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_CONSTRAINED) &&
4250 IFNET_IS_CONSTRAINED(ifp)) {
4251 return FALSE;
4252 }
4253 } else {
4254 if ((parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_EXPENSIVE) &&
4255 IFNET_IS_EXPENSIVE(ifp)) {
4256 return FALSE;
4257 }
4258 if ((parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_CONSTRAINED) &&
4259 IFNET_IS_CONSTRAINED(ifp)) {
4260 return FALSE;
4261 }
4262 }
4263 }
4264
4265 if ((!secondary_interface || // Enforce interface type if this is the primary interface
4266 !(parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_FLAGS) || // or if there are no flags
4267 !(parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_ONLY_PRIMARY_REQUIRES_TYPE)) && // or if the flags don't give an exception
4268 (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE) &&
4269 !necp_ifnet_matches_type(ifp, parsed_parameters->required_interface_type, FALSE)) {
4270 return FALSE;
4271 }
4272
4273 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE) {
4274 if (require_scoped_field) {
4275 matched_some_scoped_field = TRUE;
4276 }
4277 }
4278
4279 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IFTYPE) {
4280 for (int i = 0; i < NECP_MAX_INTERFACE_PARAMETERS; i++) {
4281 if (parsed_parameters->prohibited_interface_types[i] == 0) {
4282 break;
4283 }
4284
4285 if (necp_ifnet_matches_type(ifp, parsed_parameters->prohibited_interface_types[i], TRUE)) {
4286 return FALSE;
4287 }
4288 }
4289 }
4290
4291 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IF) {
4292 for (int i = 0; i < NECP_MAX_INTERFACE_PARAMETERS; i++) {
4293 if (strlen(parsed_parameters->prohibited_interfaces[i]) == 0) {
4294 break;
4295 }
4296
4297 if (necp_ifnet_matches_name(ifp, parsed_parameters->prohibited_interfaces[i], TRUE)) {
4298 return FALSE;
4299 }
4300 }
4301 }
4302
4303 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT) {
4304 for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
4305 if (uuid_is_null(parsed_parameters->required_netagents[i])) {
4306 break;
4307 }
4308
4309 if (!necp_ifnet_matches_agent(ifp, &parsed_parameters->required_netagents[i], FALSE)) {
4310 return FALSE;
4311 }
4312
4313 if (require_scoped_field) {
4314 matched_some_scoped_field = TRUE;
4315 }
4316 }
4317 }
4318
4319 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT) {
4320 for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
4321 if (uuid_is_null(parsed_parameters->prohibited_netagents[i])) {
4322 break;
4323 }
4324
4325 if (necp_ifnet_matches_agent(ifp, &parsed_parameters->prohibited_netagents[i], TRUE)) {
4326 return FALSE;
4327 }
4328 }
4329 }
4330
4331 if (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 if (!necp_ifnet_matches_agent_type(ifp, parsed_parameters->required_netagent_types[i].netagent_domain, parsed_parameters->required_netagent_types[i].netagent_type, FALSE)) {
4339 return FALSE;
4340 }
4341
4342 if (require_scoped_field) {
4343 matched_some_scoped_field = TRUE;
4344 }
4345 }
4346 }
4347
4348 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT_TYPE) {
4349 for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
4350 if (strlen(parsed_parameters->prohibited_netagent_types[i].netagent_domain) == 0 &&
4351 strlen(parsed_parameters->prohibited_netagent_types[i].netagent_type) == 0) {
4352 break;
4353 }
4354
4355 if (necp_ifnet_matches_agent_type(ifp, parsed_parameters->prohibited_netagent_types[i].netagent_domain, parsed_parameters->prohibited_netagent_types[i].netagent_type, TRUE)) {
4356 return FALSE;
4357 }
4358 }
4359 }
4360
4361 // Checked preferred properties
4362 if (preferred_count) {
4363 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT) {
4364 for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
4365 if (uuid_is_null(parsed_parameters->preferred_netagents[i])) {
4366 break;
4367 }
4368
4369 if (necp_ifnet_matches_agent(ifp, &parsed_parameters->preferred_netagents[i], TRUE)) {
4370 (*preferred_count)++;
4371 if (require_scoped_field) {
4372 matched_some_scoped_field = TRUE;
4373 }
4374 }
4375 }
4376 }
4377
4378 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT_TYPE) {
4379 for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
4380 if (strlen(parsed_parameters->preferred_netagent_types[i].netagent_domain) == 0 &&
4381 strlen(parsed_parameters->preferred_netagent_types[i].netagent_type) == 0) {
4382 break;
4383 }
4384
4385 if (necp_ifnet_matches_agent_type(ifp, parsed_parameters->preferred_netagent_types[i].netagent_domain, parsed_parameters->preferred_netagent_types[i].netagent_type, TRUE)) {
4386 (*preferred_count)++;
4387 if (require_scoped_field) {
4388 matched_some_scoped_field = TRUE;
4389 }
4390 }
4391 }
4392 }
4393
4394 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT) {
4395 for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
4396 if (uuid_is_null(parsed_parameters->avoided_netagents[i])) {
4397 break;
4398 }
4399
4400 if (!necp_ifnet_matches_agent(ifp, &parsed_parameters->avoided_netagents[i], TRUE)) {
4401 (*preferred_count)++;
4402 }
4403 }
4404 }
4405
4406 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_AVOIDED_AGENT_TYPE) {
4407 for (int i = 0; i < NECP_MAX_AGENT_PARAMETERS; i++) {
4408 if (strlen(parsed_parameters->avoided_netagent_types[i].netagent_domain) == 0 &&
4409 strlen(parsed_parameters->avoided_netagent_types[i].netagent_type) == 0) {
4410 break;
4411 }
4412
4413 if (!necp_ifnet_matches_agent_type(ifp, parsed_parameters->avoided_netagent_types[i].netagent_domain,
4414 parsed_parameters->avoided_netagent_types[i].netagent_type, TRUE)) {
4415 (*preferred_count)++;
4416 }
4417 }
4418 }
4419 }
4420
4421 if (require_scoped_field) {
4422 return matched_some_scoped_field;
4423 }
4424
4425 return TRUE;
4426}
4427
4428static bool
4429necp_find_matching_interface_index(struct necp_client_parsed_parameters *parsed_parameters,
4430 u_int *return_ifindex, bool *validate_agents)
4431{
4432 struct ifnet *ifp = NULL;
4433 u_int32_t best_preferred_count = 0;
4434 bool has_preferred_fields = FALSE;
4435 *return_ifindex = 0;
4436
4437 if (parsed_parameters->required_interface_index != 0) {
4438 *return_ifindex = parsed_parameters->required_interface_index;
4439 return TRUE;
4440 }
4441
4442 // Check and save off flags
4443 u_int32_t flags = 0;
4444 bool has_prohibit_flags = FALSE;
4445 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_FLAGS) {
4446 flags = parsed_parameters->flags;
4447 has_prohibit_flags = (parsed_parameters->flags &
4448 (NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_EXPENSIVE |
4449 NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_CONSTRAINED));
4450 }
4451
4452 if (!(parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_INTERESTING_IFNET_FIELDS) &&
4453 !has_prohibit_flags) {
4454 return TRUE;
4455 }
4456
4457 has_preferred_fields = (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_PREFERRED_FIELDS);
4458
4459 // We have interesting parameters to parse and find a matching interface
4460 ifnet_head_lock_shared();
4461
4462 if (!(parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_SCOPED_FIELDS) &&
4463 !has_preferred_fields) {
4464 // We do have fields to match, but they are only prohibitory
4465 // If the first interface in the list matches, or there are no ordered interfaces, we don't need to scope
4466 ifp = TAILQ_FIRST(&ifnet_ordered_head);
4467 if (ifp == NULL || necp_ifnet_matches_parameters(ifp, parsed_parameters, 0, NULL, false, false)) {
4468 // Don't set return_ifindex, so the client doesn't need to scope
4469 ifnet_head_done();
4470 return TRUE;
4471 }
4472 }
4473
4474 // First check the ordered interface list
4475 TAILQ_FOREACH(ifp, &ifnet_ordered_head, if_ordered_link) {
4476 u_int32_t preferred_count = 0;
4477 if (necp_ifnet_matches_parameters(ifp, parsed_parameters, flags, &preferred_count, false, false)) {
4478 if (preferred_count > best_preferred_count ||
4479 *return_ifindex == 0) {
4480 // Everything matched, and is most preferred. Return this interface.
4481 *return_ifindex = ifp->if_index;
4482 best_preferred_count = preferred_count;
4483
4484 if (!has_preferred_fields) {
4485 break;
4486 }
4487 }
4488 }
4489
4490 if (has_prohibit_flags &&
4491 ifp == TAILQ_FIRST(&ifnet_ordered_head)) {
4492 // This was the first interface. From here on, if the
4493 // client prohibited either expensive or constrained,
4494 // don't allow either as a secondary interface option.
4495 flags |= (NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_EXPENSIVE |
4496 NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_CONSTRAINED);
4497 }
4498 }
4499
4500 bool is_listener = ((parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_FLAGS) &&
4501 (parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER));
4502
4503 // Then check the remaining interfaces
4504 if ((parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_SCOPED_FIELDS) &&
4505 ((!(parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE)) ||
4506 !necp_interface_type_is_primary_eligible(parsed_parameters->required_interface_type) ||
4507 (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR) ||
4508 is_listener) &&
4509 (*return_ifindex == 0 || has_preferred_fields)) {
4510 TAILQ_FOREACH(ifp, &ifnet_head, if_link) {
4511 u_int32_t preferred_count = 0;
4512 if (NECP_IFP_IS_ON_ORDERED_LIST(ifp)) {
4513 // This interface was in the ordered list, skip
4514 continue;
4515 }
4516 if (necp_ifnet_matches_parameters(ifp, parsed_parameters, flags, &preferred_count, false, true)) {
4517 if (preferred_count > best_preferred_count ||
4518 *return_ifindex == 0) {
4519 // Everything matched, and is most preferred. Return this interface.
4520 *return_ifindex = ifp->if_index;
4521 best_preferred_count = preferred_count;
4522
4523 if (!has_preferred_fields) {
4524 break;
4525 }
4526 }
4527 }
4528 }
4529 }
4530
4531 ifnet_head_done();
4532
4533 if (has_preferred_fields && best_preferred_count == 0 &&
4534 ((parsed_parameters->valid_fields & (NECP_PARSED_PARAMETERS_SCOPED_FIELDS | NECP_PARSED_PARAMETERS_PREFERRED_FIELDS)) ==
4535 (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_PREFERRED_FIELDS))) {
4536 // If only has preferred ifnet fields, and nothing was found, clear the interface index and return TRUE
4537 *return_ifindex = 0;
4538 return TRUE;
4539 }
4540
4541 if (*return_ifindex == 0 &&
4542 !(parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_SCOPED_IFNET_FIELDS)) {
4543 // Has required fields, but not including specific interface fields. Pass for now, and check
4544 // to see if agents are satisfied by policy.
4545 *validate_agents = TRUE;
4546 return TRUE;
4547 }
4548
4549 return *return_ifindex != 0;
4550}
4551
4552
4553static int
4554necp_skywalk_priv_check_cred(proc_t p, kauth_cred_t cred)
4555{
4556#pragma unused(p, cred)
4557 return 0;
4558}
4559
4560/// System calls
4561
4562int
4563necp_open(struct proc *p, struct necp_open_args *uap, int *retval)
4564{
4565#pragma unused(retval)
4566 int error = 0;
4567 struct necp_fd_data *fd_data = NULL;
4568 struct fileproc *fp = NULL;
4569 int fd = -1;
4570
4571 if (uap->flags & NECP_OPEN_FLAG_OBSERVER ||
4572 uap->flags & NECP_OPEN_FLAG_PUSH_OBSERVER) {
4573 if (necp_skywalk_priv_check_cred(p, kauth_cred_get()) != 0 &&
4574 priv_check_cred(kauth_cred_get(), PRIV_NET_PRIVILEGED_NETWORK_STATISTICS, 0) != 0) {
4575 NECPLOG0(LOG_ERR, "Client does not hold necessary entitlement to observe other NECP clients");
4576 error = EACCES;
4577 goto done;
4578 }
4579 }
4580
4581 error = falloc(p, &fp, &fd, vfs_context_current());
4582 if (error != 0) {
4583 goto done;
4584 }
4585
4586 if ((fd_data = zalloc(necp_client_fd_zone)) == NULL) {
4587 error = ENOMEM;
4588 goto done;
4589 }
4590
4591 memset(fd_data, 0, sizeof(*fd_data));
4592
4593 fd_data->necp_fd_type = necp_fd_type_client;
4594 fd_data->flags = uap->flags;
4595 RB_INIT(&fd_data->clients);
4596 RB_INIT(&fd_data->flows);
4597 TAILQ_INIT(&fd_data->update_list);
4598 lck_mtx_init(&fd_data->fd_lock, necp_fd_mtx_grp, necp_fd_mtx_attr);
4599 klist_init(&fd_data->si.si_note);
4600 fd_data->proc_pid = proc_pid(p);
4601
4602 fp->fp_glob->fg_flag = FREAD;
4603 fp->fp_glob->fg_ops = &necp_fd_ops;
4604 fp->fp_glob->fg_data = fd_data;
4605
4606 proc_fdlock(p);
4607
4608 *fdflags(p, fd) |= (UF_EXCLOSE | UF_FORKCLOSE);
4609 procfdtbl_releasefd(p, fd, NULL);
4610 fp_drop(p, fd, fp, 1);
4611
4612 *retval = fd;
4613
4614 if (fd_data->flags & NECP_OPEN_FLAG_PUSH_OBSERVER) {
4615 NECP_OBSERVER_LIST_LOCK_EXCLUSIVE();
4616 LIST_INSERT_HEAD(&necp_fd_observer_list, fd_data, chain);
4617 OSIncrementAtomic(&necp_observer_fd_count);
4618 NECP_OBSERVER_LIST_UNLOCK();
4619
4620 // Walk all existing clients and add them
4621 NECP_CLIENT_TREE_LOCK_SHARED();
4622 struct necp_client *existing_client = NULL;
4623 RB_FOREACH(existing_client, _necp_client_global_tree, &necp_client_global_tree) {
4624 NECP_CLIENT_LOCK(existing_client);
4625 necp_client_update_observer_add_internal(fd_data, existing_client);
4626 necp_client_update_observer_update_internal(fd_data, existing_client);
4627 NECP_CLIENT_UNLOCK(existing_client);
4628 }
4629 NECP_CLIENT_TREE_UNLOCK();
4630 } else {
4631 NECP_FD_LIST_LOCK_EXCLUSIVE();
4632 LIST_INSERT_HEAD(&necp_fd_list, fd_data, chain);
4633 OSIncrementAtomic(&necp_client_fd_count);
4634 NECP_FD_LIST_UNLOCK();
4635 }
4636
4637 proc_fdunlock(p);
4638
4639done:
4640 if (error != 0) {
4641 if (fp != NULL) {
4642 fp_free(p, fd, fp);
4643 fp = NULL;
4644 }
4645 if (fd_data != NULL) {
4646 zfree(necp_client_fd_zone, fd_data);
4647 fd_data = NULL;
4648 }
4649 }
4650
4651 return error;
4652}
4653
4654// All functions called directly from necp_client_action() to handle one of the
4655// types should be marked with NECP_CLIENT_ACTION_FUNCTION. This ensures that
4656// necp_client_action() does not inline all the actions into a single function.
4657#define NECP_CLIENT_ACTION_FUNCTION __attribute__((noinline))
4658
4659static NECP_CLIENT_ACTION_FUNCTION int
4660necp_client_add(struct proc *p, struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
4661{
4662 int error = 0;
4663 struct necp_client *client = NULL;
4664 const size_t buffer_size = uap->buffer_size;
4665
4666 if (fd_data->flags & NECP_OPEN_FLAG_PUSH_OBSERVER) {
4667 NECPLOG0(LOG_ERR, "NECP client observers with push enabled may not add their own clients");
4668 return EINVAL;
4669 }
4670
4671 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t) ||
4672 buffer_size == 0 || buffer_size > NECP_MAX_CLIENT_PARAMETERS_SIZE || uap->buffer == 0) {
4673 return EINVAL;
4674 }
4675
4676 if ((client = _MALLOC(sizeof(struct necp_client) + buffer_size, M_NECP,
4677 M_WAITOK | M_ZERO)) == NULL) {
4678 error = ENOMEM;
4679 goto done;
4680 }
4681
4682 error = copyin(uap->buffer, client->parameters, buffer_size);
4683 if (error) {
4684 NECPLOG(LOG_ERR, "necp_client_add parameters copyin error (%d)", error);
4685 goto done;
4686 }
4687
4688 lck_mtx_init(&client->lock, necp_fd_mtx_grp, necp_fd_mtx_attr);
4689 lck_mtx_init(&client->route_lock, necp_fd_mtx_grp, necp_fd_mtx_attr);
4690
4691 os_ref_init(&client->reference_count, &necp_client_refgrp); // Hold our reference until close
4692
4693 client->parameters_length = buffer_size;
4694 client->proc_pid = fd_data->proc_pid; // Save off proc pid in case the client will persist past fd
4695 client->agent_handle = (void *)fd_data;
4696 client->platform_binary = ((csproc_get_platform_binary(p) == 0) ? 0 : 1);
4697
4698 necp_generate_client_id(client->client_id, false);
4699 LIST_INIT(&client->assertion_list);
4700 RB_INIT(&client->flow_registrations);
4701
4702 error = copyout(client->client_id, uap->client_id, sizeof(uuid_t));
4703 if (error) {
4704 NECPLOG(LOG_ERR, "necp_client_add client_id copyout error (%d)", error);
4705 goto done;
4706 }
4707
4708
4709 necp_client_update_observer_add(client);
4710
4711 NECP_FD_LOCK(fd_data);
4712 RB_INSERT(_necp_client_tree, &fd_data->clients, client);
4713 OSIncrementAtomic(&necp_client_count);
4714 NECP_CLIENT_TREE_LOCK_EXCLUSIVE();
4715 RB_INSERT(_necp_client_global_tree, &necp_client_global_tree, client);
4716 NECP_CLIENT_TREE_UNLOCK();
4717
4718 // Prime the client result
4719 NECP_CLIENT_LOCK(client);
4720 (void)necp_update_client_result(current_proc(), fd_data, client, NULL);
4721 NECP_CLIENT_UNLOCK(client);
4722 NECP_FD_UNLOCK(fd_data);
4723done:
4724 if (error != 0) {
4725 if (client != NULL) {
4726 FREE(client, M_NECP);
4727 client = NULL;
4728 }
4729 }
4730 *retval = error;
4731
4732 return error;
4733}
4734
4735static NECP_CLIENT_ACTION_FUNCTION int
4736necp_client_claim(struct proc *p, struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
4737{
4738 int error = 0;
4739 uuid_t client_id = {};
4740 struct necp_client *client = NULL;
4741
4742 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t)) {
4743 error = EINVAL;
4744 goto done;
4745 }
4746
4747 error = copyin(uap->client_id, client_id, sizeof(uuid_t));
4748 if (error) {
4749 NECPLOG(LOG_ERR, "necp_client_claim copyin client_id error (%d)", error);
4750 goto done;
4751 }
4752
4753 u_int64_t upid = proc_uniqueid(p);
4754
4755 NECP_FD_LIST_LOCK_SHARED();
4756
4757 struct necp_fd_data *find_fd = NULL;
4758 LIST_FOREACH(find_fd, &necp_fd_list, chain) {
4759 NECP_FD_LOCK(find_fd);
4760 struct necp_client *find_client = necp_client_fd_find_client_and_lock(find_fd, client_id);
4761 if (find_client != NULL) {
4762 if (find_client->delegated_upid == upid) {
4763 // Matched the client to claim; remove from the old fd
4764 client = find_client;
4765 RB_REMOVE(_necp_client_tree, &find_fd->clients, client);
4766 necp_client_retain_locked(client);
4767 }
4768 NECP_CLIENT_UNLOCK(find_client);
4769 }
4770 NECP_FD_UNLOCK(find_fd);
4771
4772 if (client != NULL) {
4773 break;
4774 }
4775 }
4776
4777 NECP_FD_LIST_UNLOCK();
4778
4779 if (client == NULL) {
4780 error = ENOENT;
4781 goto done;
4782 }
4783
4784 client->proc_pid = fd_data->proc_pid; // Transfer client to claiming pid
4785 client->agent_handle = (void *)fd_data;
4786 client->platform_binary = ((csproc_get_platform_binary(p) == 0) ? 0 : 1);
4787
4788 // Add matched client to our fd and re-run result
4789 NECP_FD_LOCK(fd_data);
4790 RB_INSERT(_necp_client_tree, &fd_data->clients, client);
4791 NECP_CLIENT_LOCK(client);
4792 (void)necp_update_client_result(current_proc(), fd_data, client, NULL);
4793 NECP_CLIENT_UNLOCK(client);
4794 NECP_FD_UNLOCK(fd_data);
4795
4796 necp_client_release(client);
4797
4798done:
4799 *retval = error;
4800
4801 return error;
4802}
4803
4804static NECP_CLIENT_ACTION_FUNCTION int
4805necp_client_remove(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
4806{
4807 int error = 0;
4808 uuid_t client_id = {};
4809 struct ifnet_stats_per_flow flow_ifnet_stats = {};
4810 const size_t buffer_size = uap->buffer_size;
4811
4812 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t)) {
4813 error = EINVAL;
4814 goto done;
4815 }
4816
4817 error = copyin(uap->client_id, client_id, sizeof(uuid_t));
4818 if (error) {
4819 NECPLOG(LOG_ERR, "necp_client_remove copyin client_id error (%d)", error);
4820 goto done;
4821 }
4822
4823 if (uap->buffer != 0 && buffer_size == sizeof(flow_ifnet_stats)) {
4824 error = copyin(uap->buffer, &flow_ifnet_stats, buffer_size);
4825 if (error) {
4826 NECPLOG(LOG_ERR, "necp_client_remove flow_ifnet_stats copyin error (%d)", error);
4827 // Not fatal; make sure to zero-out stats in case of partial copy
4828 memset(&flow_ifnet_stats, 0, sizeof(flow_ifnet_stats));
4829 error = 0;
4830 }
4831 } else if (uap->buffer != 0) {
4832 NECPLOG(LOG_ERR, "necp_client_remove unexpected parameters length (%zu)", buffer_size);
4833 }
4834
4835 NECP_FD_LOCK(fd_data);
4836
4837 pid_t pid = fd_data->proc_pid;
4838 struct necp_client *client = necp_client_fd_find_client_unlocked(fd_data, client_id);
4839 if (client != NULL) {
4840 // Remove any flow registrations that match
4841 struct necp_client_flow_registration *flow_registration = NULL;
4842 struct necp_client_flow_registration *temp_flow_registration = NULL;
4843 RB_FOREACH_SAFE(flow_registration, _necp_fd_flow_tree, &fd_data->flows, temp_flow_registration) {
4844 if (flow_registration->client == client) {
4845 NECP_FLOW_TREE_LOCK_EXCLUSIVE();
4846 RB_REMOVE(_necp_client_flow_global_tree, &necp_client_flow_global_tree, flow_registration);
4847 NECP_FLOW_TREE_UNLOCK();
4848 RB_REMOVE(_necp_fd_flow_tree, &fd_data->flows, flow_registration);
4849 }
4850 }
4851 // Remove client from lists
4852 NECP_CLIENT_TREE_LOCK_EXCLUSIVE();
4853 RB_REMOVE(_necp_client_global_tree, &necp_client_global_tree, client);
4854 NECP_CLIENT_TREE_UNLOCK();
4855 RB_REMOVE(_necp_client_tree, &fd_data->clients, client);
4856 }
4857
4858
4859 NECP_FD_UNLOCK(fd_data);
4860
4861 if (client != NULL) {
4862 ASSERT(error == 0);
4863 necp_destroy_client(client, pid, true);
4864 } else {
4865 error = ENOENT;
4866 NECPLOG(LOG_ERR, "necp_client_remove invalid client_id (%d)", error);
4867 }
4868done:
4869 *retval = error;
4870
4871 return error;
4872}
4873
4874static struct necp_client_flow_registration *
4875necp_client_fd_find_flow(struct necp_fd_data *client_fd, uuid_t flow_id)
4876{
4877 NECP_FD_ASSERT_LOCKED(client_fd);
4878 struct necp_client_flow_registration *flow = NULL;
4879
4880 if (necp_client_id_is_flow(flow_id)) {
4881 struct necp_client_flow_registration find;
4882 uuid_copy(find.registration_id, flow_id);
4883 flow = RB_FIND(_necp_fd_flow_tree, &client_fd->flows, &find);
4884 }
4885
4886 return flow;
4887}
4888
4889static NECP_CLIENT_ACTION_FUNCTION int
4890necp_client_remove_flow(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
4891{
4892 int error = 0;
4893 uuid_t flow_id = {};
4894 struct ifnet_stats_per_flow flow_ifnet_stats = {};
4895 const size_t buffer_size = uap->buffer_size;
4896
4897 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t)) {
4898 error = EINVAL;
4899 NECPLOG(LOG_ERR, "necp_client_remove_flow invalid client_id (length %zu)", (size_t)uap->client_id_len);
4900 goto done;
4901 }
4902
4903 error = copyin(uap->client_id, flow_id, sizeof(uuid_t));
4904 if (error) {
4905 NECPLOG(LOG_ERR, "necp_client_remove_flow copyin client_id error (%d)", error);
4906 goto done;
4907 }
4908
4909 if (uap->buffer != 0 && buffer_size == sizeof(flow_ifnet_stats)) {
4910 error = copyin(uap->buffer, &flow_ifnet_stats, buffer_size);
4911 if (error) {
4912 NECPLOG(LOG_ERR, "necp_client_remove flow_ifnet_stats copyin error (%d)", error);
4913 // Not fatal
4914 }
4915 } else if (uap->buffer != 0) {
4916 NECPLOG(LOG_ERR, "necp_client_remove unexpected parameters length (%zu)", buffer_size);
4917 }
4918
4919 NECP_FD_LOCK(fd_data);
4920 struct necp_client *client = NULL;
4921 struct necp_client_flow_registration *flow_registration = necp_client_fd_find_flow(fd_data, flow_id);
4922 if (flow_registration != NULL) {
4923 NECP_FLOW_TREE_LOCK_EXCLUSIVE();
4924 RB_REMOVE(_necp_client_flow_global_tree, &necp_client_flow_global_tree, flow_registration);
4925 NECP_FLOW_TREE_UNLOCK();
4926 RB_REMOVE(_necp_fd_flow_tree, &fd_data->flows, flow_registration);
4927
4928 client = flow_registration->client;
4929 if (client != NULL) {
4930 necp_client_retain(client);
4931 }
4932 }
4933 NECP_FD_UNLOCK(fd_data);
4934
4935 if (flow_registration != NULL && client != NULL) {
4936 NECP_CLIENT_LOCK(client);
4937 if (flow_registration->client == client) {
4938 necp_destroy_client_flow_registration(client, flow_registration, fd_data->proc_pid, false);
4939 }
4940 necp_client_release_locked(client);
4941 NECP_CLIENT_UNLOCK(client);
4942 }
4943
4944done:
4945 *retval = error;
4946 if (error != 0) {
4947 NECPLOG(LOG_ERR, "Remove flow error (%d)", error);
4948 }
4949
4950 return error;
4951}
4952
4953// Don't inline the function since it includes necp_client_parsed_parameters on the stack
4954static __attribute__((noinline)) int
4955necp_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)
4956{
4957 struct necp_client_parsed_parameters parsed_parameters;
4958 int error = 0;
4959
4960 error = necp_client_parse_parameters(client->parameters,
4961 (u_int32_t)client->parameters_length,
4962 &parsed_parameters);
4963 if (error) {
4964 NECPLOG(LOG_ERR, "necp_client_parse_parameters error (%d)", error);
4965 return error;
4966 }
4967
4968 if ((flow->remote_addr.sa.sa_family != AF_INET &&
4969 flow->remote_addr.sa.sa_family != AF_INET6) ||
4970 (flow->local_addr.sa.sa_family != AF_INET &&
4971 flow->local_addr.sa.sa_family != AF_INET6)) {
4972 return EINVAL;
4973 }
4974
4975 NECP_CLIENT_ROUTE_LOCK(client);
4976
4977 if (client->current_route == NULL) {
4978 error = ENOENT;
4979 goto do_unlock;
4980 }
4981
4982 bool check_ecn = false;
4983 do {
4984 if ((parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_ECN_ENABLE) ==
4985 NECP_CLIENT_PARAMETER_FLAG_ECN_ENABLE) {
4986 check_ecn = true;
4987 break;
4988 }
4989
4990 if ((parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_ECN_DISABLE) ==
4991 NECP_CLIENT_PARAMETER_FLAG_ECN_DISABLE) {
4992 break;
4993 }
4994
4995 if (client->current_route != NULL) {
4996 if (client->current_route->rt_ifp->if_eflags & IFEF_ECN_ENABLE) {
4997 check_ecn = true;
4998 break;
4999 }
5000 if (client->current_route->rt_ifp->if_eflags & IFEF_ECN_DISABLE) {
5001 break;
5002 }
5003 }
5004
5005 bool inbound = ((parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) == 0);
5006 if ((inbound && tcp_ecn_inbound == 1) ||
5007 (!inbound && tcp_ecn_outbound == 1)) {
5008 check_ecn = true;
5009 }
5010 } while (false);
5011
5012 if (check_ecn) {
5013 if (tcp_heuristic_do_ecn_with_address(client->current_route->rt_ifp,
5014 (union sockaddr_in_4_6 *)&flow->local_addr)) {
5015 *flags |= NECP_CLIENT_RESULT_FLAG_ECN_ENABLED;
5016 }
5017 }
5018
5019 if ((parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_TFO_ENABLE) ==
5020 NECP_CLIENT_PARAMETER_FLAG_TFO_ENABLE) {
5021 if (!tcp_heuristic_do_tfo_with_address(client->current_route->rt_ifp,
5022 (union sockaddr_in_4_6 *)&flow->local_addr,
5023 (union sockaddr_in_4_6 *)&flow->remote_addr,
5024 tfo_cookie, tfo_cookie_len)) {
5025 *flags |= NECP_CLIENT_RESULT_FLAG_FAST_OPEN_BLOCKED;
5026 *tfo_cookie_len = 0;
5027 }
5028 } else {
5029 *flags |= NECP_CLIENT_RESULT_FLAG_FAST_OPEN_BLOCKED;
5030 *tfo_cookie_len = 0;
5031 }
5032do_unlock:
5033 NECP_CLIENT_ROUTE_UNLOCK(client);
5034
5035 return error;
5036}
5037
5038static size_t
5039necp_client_calculate_flow_tlv_size(struct necp_client_flow_registration *flow_registration)
5040{
5041 size_t assigned_results_size = 0;
5042 struct necp_client_flow *flow = NULL;
5043 LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
5044 if (flow->assigned) {
5045 size_t header_length = 0;
5046 if (flow->nexus) {
5047 header_length = sizeof(struct necp_client_nexus_flow_header);
5048 } else {
5049 header_length = sizeof(struct necp_client_flow_header);
5050 }
5051 assigned_results_size += (header_length + flow->assigned_results_length);
5052
5053 if (flow->has_protoctl_event) {
5054 assigned_results_size += sizeof(struct necp_client_flow_protoctl_event_header);
5055 }
5056 }
5057 }
5058 return assigned_results_size;
5059}
5060
5061static int
5062necp_client_fillout_flow_tlvs(struct necp_client *client,
5063 bool client_is_observed,
5064 struct necp_client_flow_registration *flow_registration,
5065 struct necp_client_action_args *uap,
5066 size_t *assigned_results_cursor)
5067{
5068 int error = 0;
5069 struct necp_client_flow *flow = NULL;
5070 LIST_FOREACH(flow, &flow_registration->flow_list, flow_chain) {
5071 if (flow->assigned) {
5072 // Write TLV headers
5073 struct necp_client_nexus_flow_header header = {};
5074 u_int32_t length = 0;
5075 u_int32_t flags = 0;
5076 u_int8_t tfo_cookie_len = 0;
5077 u_int8_t type = 0;
5078
5079 type = NECP_CLIENT_RESULT_FLOW_ID;
5080 length = sizeof(header.flow_header.flow_id);
5081 memcpy(&header.flow_header.flow_id_tlv_header.type, &type, sizeof(type));
5082 memcpy(&header.flow_header.flow_id_tlv_header.length, &length, sizeof(length));
5083 uuid_copy(header.flow_header.flow_id, flow_registration->registration_id);
5084
5085 if (flow->nexus) {
5086 if (flow->check_tcp_heuristics) {
5087 u_int8_t tfo_cookie[NECP_TFO_COOKIE_LEN_MAX];
5088 tfo_cookie_len = NECP_TFO_COOKIE_LEN_MAX;
5089
5090 if (necp_client_check_tcp_heuristics(client, flow, &flags,
5091 tfo_cookie, &tfo_cookie_len) != 0) {
5092 tfo_cookie_len = 0;
5093 } else {
5094 flow->check_tcp_heuristics = FALSE;
5095
5096 if (tfo_cookie_len != 0) {
5097 type = NECP_CLIENT_RESULT_TFO_COOKIE;
5098 length = tfo_cookie_len;
5099 memcpy(&header.tfo_cookie_tlv_header.type, &type, sizeof(type));
5100 memcpy(&header.tfo_cookie_tlv_header.length, &length, sizeof(length));
5101 memcpy(&header.tfo_cookie_value, tfo_cookie, tfo_cookie_len);
5102 }
5103 }
5104 }
5105 }
5106
5107 size_t header_length = 0;
5108 if (flow->nexus) {
5109 if (tfo_cookie_len != 0) {
5110 header_length = sizeof(struct necp_client_nexus_flow_header) - (NECP_TFO_COOKIE_LEN_MAX - tfo_cookie_len);
5111 } else {
5112 header_length = sizeof(struct necp_client_nexus_flow_header) - sizeof(struct necp_tlv_header) - NECP_TFO_COOKIE_LEN_MAX;
5113 }
5114 } else {
5115 header_length = sizeof(struct necp_client_flow_header);
5116 }
5117
5118 type = NECP_CLIENT_RESULT_FLAGS;
5119 length = sizeof(header.flow_header.flags_value);
5120 memcpy(&header.flow_header.flags_tlv_header.type, &type, sizeof(type));
5121 memcpy(&header.flow_header.flags_tlv_header.length, &length, sizeof(length));
5122 if (flow->assigned) {
5123 flags |= NECP_CLIENT_RESULT_FLAG_FLOW_ASSIGNED;
5124 }
5125 if (flow->viable) {
5126 flags |= NECP_CLIENT_RESULT_FLAG_FLOW_VIABLE;
5127 }
5128 if (flow_registration->defunct) {
5129 flags |= NECP_CLIENT_RESULT_FLAG_DEFUNCT;
5130 }
5131 flags |= flow->necp_flow_flags;
5132 memcpy(&header.flow_header.flags_value, &flags, sizeof(flags));
5133
5134 type = NECP_CLIENT_RESULT_INTERFACE;
5135 length = sizeof(header.flow_header.interface_value);
5136 memcpy(&header.flow_header.interface_tlv_header.type, &type, sizeof(type));
5137 memcpy(&header.flow_header.interface_tlv_header.length, &length, sizeof(length));
5138
5139 struct necp_client_result_interface interface_struct;
5140 interface_struct.generation = 0;
5141 interface_struct.index = flow->interface_index;
5142
5143 memcpy(&header.flow_header.interface_value, &interface_struct, sizeof(interface_struct));
5144 if (flow->nexus) {
5145 type = NECP_CLIENT_RESULT_NETAGENT;
5146 length = sizeof(header.agent_value);
5147 memcpy(&header.agent_tlv_header.type, &type, sizeof(type));
5148 memcpy(&header.agent_tlv_header.length, &length, sizeof(length));
5149
5150 struct necp_client_result_netagent agent_struct;
5151 agent_struct.generation = 0;
5152 uuid_copy(agent_struct.netagent_uuid, flow->u.nexus_agent);
5153
5154 memcpy(&header.agent_value, &agent_struct, sizeof(agent_struct));
5155 }
5156
5157 // Don't include outer TLV header in length field
5158 type = NECP_CLIENT_RESULT_FLOW;
5159 length = (header_length - sizeof(struct necp_tlv_header) + flow->assigned_results_length);
5160 if (flow->has_protoctl_event) {
5161 length += sizeof(struct necp_client_flow_protoctl_event_header);
5162 }
5163 memcpy(&header.flow_header.outer_header.type, &type, sizeof(type));
5164 memcpy(&header.flow_header.outer_header.length, &length, sizeof(length));
5165
5166 error = copyout(&header, uap->buffer + client->result_length + *assigned_results_cursor, header_length);
5167 if (error) {
5168 NECPLOG(LOG_ERR, "necp_client_copy assigned results tlv_header copyout error (%d)", error);
5169 return error;
5170 }
5171 *assigned_results_cursor += header_length;
5172
5173 if (flow->assigned_results && flow->assigned_results_length) {
5174 // Write inner TLVs
5175 error = copyout(flow->assigned_results, uap->buffer + client->result_length + *assigned_results_cursor,
5176 flow->assigned_results_length);
5177 if (error) {
5178 NECPLOG(LOG_ERR, "necp_client_copy assigned results copyout error (%d)", error);
5179 return error;
5180 }
5181 }
5182 *assigned_results_cursor += flow->assigned_results_length;
5183
5184 /* Read the protocol event and reset it */
5185 if (flow->has_protoctl_event) {
5186 struct necp_client_flow_protoctl_event_header protoctl_event_header = {};
5187
5188 type = NECP_CLIENT_RESULT_PROTO_CTL_EVENT;
5189 length = sizeof(protoctl_event_header.protoctl_event);
5190
5191 memcpy(&protoctl_event_header.protoctl_tlv_header.type, &type, sizeof(type));
5192 memcpy(&protoctl_event_header.protoctl_tlv_header.length, &length, sizeof(length));
5193 memcpy(&protoctl_event_header.protoctl_event, &flow->protoctl_event,
5194 sizeof(flow->protoctl_event));
5195
5196 error = copyout(&protoctl_event_header, uap->buffer + client->result_length + *assigned_results_cursor,
5197 sizeof(protoctl_event_header));
5198
5199 if (error) {
5200 NECPLOG(LOG_ERR, "necp_client_copy protocol control event results"
5201 " tlv_header copyout error (%d)", error);
5202 return error;
5203 }
5204 *assigned_results_cursor += sizeof(protoctl_event_header);
5205 flow->has_protoctl_event = FALSE;
5206 flow->protoctl_event.protoctl_event_code = 0;
5207 flow->protoctl_event.protoctl_event_val = 0;
5208 flow->protoctl_event.protoctl_event_tcp_seq_num = 0;
5209 }
5210 }
5211 }
5212 if (!client_is_observed) {
5213 flow_registration->flow_result_read = TRUE;
5214 }
5215 return 0;
5216}
5217
5218static int
5219necp_client_copy_internal(struct necp_client *client, uuid_t client_id, bool client_is_observed, struct necp_client_action_args *uap, int *retval)
5220{
5221 NECP_CLIENT_ASSERT_LOCKED(client);
5222 int error = 0;
5223 // Copy results out
5224 if (uap->action == NECP_CLIENT_ACTION_COPY_PARAMETERS) {
5225 if (uap->buffer_size < client->parameters_length) {
5226 return EINVAL;
5227 }
5228 error = copyout(client->parameters, uap->buffer, client->parameters_length);
5229 if (error) {
5230 NECPLOG(LOG_ERR, "necp_client_copy parameters copyout error (%d)", error);
5231 return error;
5232 }
5233 *retval = client->parameters_length;
5234 } else if (uap->action == NECP_CLIENT_ACTION_COPY_UPDATED_RESULT &&
5235 client->result_read && !necp_client_has_unread_flows(client)) {
5236 // Copy updates only, but nothing to read
5237 // Just return 0 for bytes read
5238 *retval = 0;
5239 } else if (uap->action == NECP_CLIENT_ACTION_COPY_RESULT ||
5240 uap->action == NECP_CLIENT_ACTION_COPY_UPDATED_RESULT) {
5241 size_t assigned_results_size = 0;
5242
5243 bool some_flow_is_defunct = false;
5244 struct necp_client_flow_registration *single_flow_registration = NULL;
5245 if (necp_client_id_is_flow(client_id)) {
5246 single_flow_registration = necp_client_find_flow(client, client_id);
5247 if (single_flow_registration != NULL) {
5248 assigned_results_size += necp_client_calculate_flow_tlv_size(single_flow_registration);
5249 }
5250 } else {
5251 // This request is for the client, so copy everything
5252 struct necp_client_flow_registration *flow_registration = NULL;
5253 RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
5254 if (flow_registration->defunct) {
5255 some_flow_is_defunct = true;
5256 }
5257 assigned_results_size += necp_client_calculate_flow_tlv_size(flow_registration);
5258 }
5259 }
5260 if (uap->buffer_size < (client->result_length + assigned_results_size)) {
5261 return EINVAL;
5262 }
5263
5264 u_int32_t original_flags = 0;
5265 bool flags_updated = false;
5266 if (some_flow_is_defunct && client->legacy_client_is_flow) {
5267 // If our client expects the defunct flag in the client, add it now
5268 u_int32_t client_flags = 0;
5269 u_int32_t value_size = 0;
5270 u_int8_t *flags_pointer = necp_buffer_get_tlv_value(client->result, 0, &value_size);
5271 if (flags_pointer != NULL && value_size == sizeof(client_flags)) {
5272 memcpy(&client_flags, flags_pointer, value_size);
5273 original_flags = client_flags;
5274 client_flags |= NECP_CLIENT_RESULT_FLAG_DEFUNCT;
5275 (void)necp_buffer_write_tlv_if_different(client->result, NECP_CLIENT_RESULT_FLAGS,
5276 sizeof(client_flags), &client_flags, &flags_updated,
5277 client->result, sizeof(client->result));
5278 }
5279 }
5280
5281 error = copyout(client->result, uap->buffer, client->result_length);
5282
5283 if (flags_updated) {
5284 // Revert stored flags
5285 (void)necp_buffer_write_tlv_if_different(client->result, NECP_CLIENT_RESULT_FLAGS,
5286 sizeof(original_flags), &original_flags, &flags_updated,
5287 client->result, sizeof(client->result));
5288 }
5289
5290 if (error) {
5291 NECPLOG(LOG_ERR, "necp_client_copy result copyout error (%d)", error);
5292 return error;
5293 }
5294
5295 size_t assigned_results_cursor = 0;
5296 if (necp_client_id_is_flow(client_id)) {
5297 if (single_flow_registration != NULL) {
5298 error = necp_client_fillout_flow_tlvs(client, client_is_observed, single_flow_registration, uap, &assigned_results_cursor);
5299 if (error != 0) {
5300 return error;
5301 }
5302 }
5303 } else {
5304 // This request is for the client, so copy everything
5305 struct necp_client_flow_registration *flow_registration = NULL;
5306 RB_FOREACH(flow_registration, _necp_client_flow_tree, &client->flow_registrations) {
5307 error = necp_client_fillout_flow_tlvs(client, client_is_observed, flow_registration, uap, &assigned_results_cursor);
5308 if (error != 0) {
5309 return error;
5310 }
5311 }
5312 }
5313
5314 *retval = client->result_length + assigned_results_cursor;
5315
5316 if (!client_is_observed) {
5317 client->result_read = TRUE;
5318 }
5319 }
5320
5321 return 0;
5322}
5323
5324static NECP_CLIENT_ACTION_FUNCTION int
5325necp_client_copy(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
5326{
5327 int error = 0;
5328 struct necp_client *client = NULL;
5329 uuid_t client_id;
5330 uuid_clear(client_id);
5331
5332 *retval = 0;
5333
5334 if (uap->buffer_size == 0 || uap->buffer == 0) {
5335 return EINVAL;
5336 }
5337
5338 if (uap->action != NECP_CLIENT_ACTION_COPY_PARAMETERS &&
5339 uap->action != NECP_CLIENT_ACTION_COPY_RESULT &&
5340 uap->action != NECP_CLIENT_ACTION_COPY_UPDATED_RESULT) {
5341 return EINVAL;
5342 }
5343
5344 if (uap->client_id) {
5345 if (uap->client_id_len != sizeof(uuid_t)) {
5346 NECPLOG(LOG_ERR, "Incorrect length (got %zu, expected %zu)", (size_t)uap->client_id_len, sizeof(uuid_t));
5347 return ERANGE;
5348 }
5349
5350 error = copyin(uap->client_id, client_id, sizeof(uuid_t));
5351 if (error) {
5352 NECPLOG(LOG_ERR, "necp_client_copy client_id copyin error (%d)", error);
5353 return error;
5354 }
5355 }
5356
5357 const bool is_wildcard = (bool)uuid_is_null(client_id);
5358
5359 NECP_FD_LOCK(fd_data);
5360
5361 if (is_wildcard) {
5362 if (uap->action == NECP_CLIENT_ACTION_COPY_RESULT || uap->action == NECP_CLIENT_ACTION_COPY_UPDATED_RESULT) {
5363 struct necp_client *find_client = NULL;
5364 RB_FOREACH(find_client, _necp_client_tree, &fd_data->clients) {
5365 NECP_CLIENT_LOCK(find_client);
5366 if (!find_client->result_read || necp_client_has_unread_flows(find_client)) {
5367 client = find_client;
5368 // Leave the client locked, and break
5369 break;
5370 }
5371 NECP_CLIENT_UNLOCK(find_client);
5372 }
5373 }
5374 } else {
5375 client = necp_client_fd_find_client_and_lock(fd_data, client_id);
5376 }
5377
5378 if (client != NULL) {
5379 // If client is set, it is locked
5380 error = necp_client_copy_internal(client, client_id, FALSE, uap, retval);
5381 NECP_CLIENT_UNLOCK(client);
5382 }
5383
5384 // Unlock our own fd before moving on or returning
5385 NECP_FD_UNLOCK(fd_data);
5386
5387 if (client == NULL) {
5388 if (fd_data->flags & NECP_OPEN_FLAG_OBSERVER) {
5389 // Observers are allowed to lookup clients on other fds
5390
5391 // Lock tree
5392 NECP_CLIENT_TREE_LOCK_SHARED();
5393
5394 bool found_client = FALSE;
5395
5396 client = necp_find_client_and_lock(client_id);
5397 if (client != NULL) {
5398 // Matched, copy out data
5399 found_client = TRUE;
5400 error = necp_client_copy_internal(client, client_id, TRUE, uap, retval);
5401 NECP_CLIENT_UNLOCK(client);
5402 }
5403
5404 // Unlock tree
5405 NECP_CLIENT_TREE_UNLOCK();
5406
5407 // No client found, fail
5408 if (!found_client) {
5409 return ENOENT;
5410 }
5411 } else {
5412 // No client found, and not allowed to search other fds, fail
5413 return ENOENT;
5414 }
5415 }
5416
5417 return error;
5418}
5419
5420static NECP_CLIENT_ACTION_FUNCTION int
5421necp_client_copy_client_update(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
5422{
5423 int error = 0;
5424
5425 *retval = 0;
5426
5427 if (!(fd_data->flags & NECP_OPEN_FLAG_PUSH_OBSERVER)) {
5428 NECPLOG0(LOG_ERR, "NECP fd is not observer, cannot copy client update");
5429 return EINVAL;
5430 }
5431
5432 if (uap->client_id_len != sizeof(uuid_t) || uap->client_id == 0) {
5433 NECPLOG0(LOG_ERR, "Client id invalid, cannot copy client update");
5434 return EINVAL;
5435 }
5436
5437 if (uap->buffer_size == 0 || uap->buffer == 0) {
5438 NECPLOG0(LOG_ERR, "Buffer invalid, cannot copy client update");
5439 return EINVAL;
5440 }
5441
5442 NECP_FD_LOCK(fd_data);
5443 struct necp_client_update *client_update = TAILQ_FIRST(&fd_data->update_list);
5444 if (client_update != NULL) {
5445 TAILQ_REMOVE(&fd_data->update_list, client_update, chain);
5446 VERIFY(fd_data->update_count > 0);
5447 fd_data->update_count--;
5448 }
5449 NECP_FD_UNLOCK(fd_data);
5450
5451 if (client_update != NULL) {
5452 error = copyout(client_update->client_id, uap->client_id, sizeof(uuid_t));
5453 if (error) {
5454 NECPLOG(LOG_ERR, "Copy client update copyout client id error (%d)", error);
5455 } else {
5456 if (uap->buffer_size < client_update->update_length) {
5457 NECPLOG(LOG_ERR, "Buffer size cannot hold update (%zu < %zu)", (size_t)uap->buffer_size, client_update->update_length);
5458 error = EINVAL;
5459 } else {
5460 error = copyout(&client_update->update, uap->buffer, client_update->update_length);
5461 if (error) {
5462 NECPLOG(LOG_ERR, "Copy client update copyout error (%d)", error);
5463 } else {
5464 *retval = client_update->update_length;
5465 }
5466 }
5467 }
5468
5469 FREE(client_update, M_NECP);
5470 client_update = NULL;
5471 } else {
5472 error = ENOENT;
5473 }
5474
5475 return error;
5476}
5477
5478static int
5479necp_client_copy_parameters_locked(struct necp_client *client,
5480 struct necp_client_nexus_parameters *parameters)
5481{
5482 VERIFY(parameters != NULL);
5483
5484 struct necp_client_parsed_parameters parsed_parameters = {};
5485 int error = necp_client_parse_parameters(client->parameters, (u_int32_t)client->parameters_length, &parsed_parameters);
5486
5487 parameters->pid = client->proc_pid;
5488 if (parsed_parameters.valid_fields & NECP_PARSED_PARAMETERS_FIELD_EFFECTIVE_PID) {
5489 parameters->epid = parsed_parameters.effective_pid;
5490 } else {
5491 parameters->epid = parameters->pid;
5492 }
5493 memcpy(&parameters->local_addr, &parsed_parameters.local_addr, sizeof(parameters->local_addr));
5494 memcpy(&parameters->remote_addr, &parsed_parameters.remote_addr, sizeof(parameters->remote_addr));
5495 parameters->ip_protocol = parsed_parameters.ip_protocol;
5496 if (parsed_parameters.valid_fields & NECP_PARSED_PARAMETERS_FIELD_TRANSPORT_PROTOCOL) {
5497 parameters->transport_protocol = parsed_parameters.transport_protocol;
5498 } else {
5499 parameters->transport_protocol = parsed_parameters.ip_protocol;
5500 }
5501 parameters->ethertype = parsed_parameters.ethertype;
5502 parameters->traffic_class = parsed_parameters.traffic_class;
5503 if (uuid_is_null(client->override_euuid)) {
5504 uuid_copy(parameters->euuid, parsed_parameters.effective_uuid);
5505 } else {
5506 uuid_copy(parameters->euuid, client->override_euuid);
5507 }
5508 parameters->is_listener = (parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) ? 1 : 0;
5509 parameters->is_interpose = (parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_INTERPOSE) ? 1 : 0;
5510 parameters->is_custom_ether = (parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_CUSTOM_ETHER) ? 1 : 0;
5511 parameters->policy_id = client->policy_id;
5512
5513 // parse client result flag
5514 u_int32_t client_result_flags = 0;
5515 u_int32_t value_size = 0;
5516 u_int8_t *flags_pointer = NULL;
5517 flags_pointer = necp_buffer_get_tlv_value(client->result, 0, &value_size);
5518 if (flags_pointer && value_size == sizeof(client_result_flags)) {
5519 memcpy(&client_result_flags, flags_pointer, value_size);
5520 }
5521 parameters->allow_qos_marking = (client_result_flags & NECP_CLIENT_RESULT_FLAG_ALLOW_QOS_MARKING) ? 1 : 0;
5522
5523 if (parsed_parameters.valid_fields & NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR_PREFERENCE) {
5524 if (parsed_parameters.local_address_preference == NECP_CLIENT_PARAMETER_LOCAL_ADDRESS_PREFERENCE_DEFAULT) {
5525 parameters->override_address_selection = false;
5526 } else if (parsed_parameters.local_address_preference == NECP_CLIENT_PARAMETER_LOCAL_ADDRESS_PREFERENCE_TEMPORARY) {
5527 parameters->override_address_selection = true;
5528 parameters->use_stable_address = false;
5529 } else if (parsed_parameters.local_address_preference == NECP_CLIENT_PARAMETER_LOCAL_ADDRESS_PREFERENCE_STABLE) {
5530 parameters->override_address_selection = true;
5531 parameters->use_stable_address = true;
5532 }
5533 } else {
5534 parameters->override_address_selection = false;
5535 }
5536
5537 return error;
5538}
5539
5540static NECP_CLIENT_ACTION_FUNCTION int
5541necp_client_list(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
5542{
5543 int error = 0;
5544 struct necp_client *find_client = NULL;
5545 uuid_t *list = NULL;
5546 u_int32_t requested_client_count = 0;
5547 u_int32_t client_count = 0;
5548 size_t copy_buffer_size = 0;
5549
5550 if (uap->buffer_size < sizeof(requested_client_count) || uap->buffer == 0) {
5551 error = EINVAL;
5552 goto done;
5553 }
5554
5555 if (!(fd_data->flags & NECP_OPEN_FLAG_OBSERVER)) {
5556 NECPLOG0(LOG_ERR, "Client does not hold necessary entitlement to list other NECP clients");
5557 error = EACCES;
5558 goto done;
5559 }
5560
5561 error = copyin(uap->buffer, &requested_client_count, sizeof(requested_client_count));
5562 if (error) {
5563 goto done;
5564 }
5565
5566 if (os_mul_overflow(sizeof(uuid_t), requested_client_count, &copy_buffer_size)) {
5567 error = ERANGE;
5568 goto done;
5569 }
5570
5571 if (uap->buffer_size - sizeof(requested_client_count) != copy_buffer_size) {
5572 error = EINVAL;
5573 goto done;
5574 }
5575
5576 if (copy_buffer_size > NECP_MAX_CLIENT_LIST_SIZE) {
5577 error = EINVAL;
5578 goto done;
5579 }
5580
5581 if (requested_client_count > 0) {
5582 if ((list = _MALLOC(copy_buffer_size, M_NECP, M_WAITOK | M_ZERO)) == NULL) {
5583 error = ENOMEM;
5584 goto done;
5585 }
5586 }
5587
5588 // Lock tree
5589 NECP_CLIENT_TREE_LOCK_SHARED();
5590
5591 find_client = NULL;
5592 RB_FOREACH(find_client, _necp_client_global_tree, &necp_client_global_tree) {
5593 NECP_CLIENT_LOCK(find_client);
5594 if (!uuid_is_null(find_client->client_id)) {
5595 if (client_count < requested_client_count) {
5596 uuid_copy(list[client_count], find_client->client_id);
5597 }
5598 client_count++;
5599 }
5600 NECP_CLIENT_UNLOCK(find_client);
5601 }
5602
5603 // Unlock tree
5604 NECP_CLIENT_TREE_UNLOCK();
5605
5606 error = copyout(&client_count, uap->buffer, sizeof(client_count));
5607 if (error) {
5608 NECPLOG(LOG_ERR, "necp_client_list buffer copyout error (%d)", error);
5609 goto done;
5610 }
5611
5612 if (requested_client_count > 0 &&
5613 client_count > 0 &&
5614 list != NULL) {
5615 error = copyout(list, uap->buffer + sizeof(client_count), copy_buffer_size);
5616 if (error) {
5617 NECPLOG(LOG_ERR, "necp_client_list client count copyout error (%d)", error);
5618 goto done;
5619 }
5620 }
5621done:
5622 if (list != NULL) {
5623 FREE(list, M_NECP);
5624 }
5625 *retval = error;
5626
5627 return error;
5628}
5629
5630static NECP_CLIENT_ACTION_FUNCTION int
5631necp_client_add_flow(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
5632{
5633 int error = 0;
5634 struct necp_client *client = NULL;
5635 uuid_t client_id;
5636 struct necp_client_nexus_parameters parameters = {};
5637 struct proc *proc = PROC_NULL;
5638 struct necp_client_add_flow *add_request = NULL;
5639 struct necp_client_add_flow *allocated_add_request = NULL;
5640 struct necp_client_add_flow_default default_add_request = {};
5641 const size_t buffer_size = uap->buffer_size;
5642
5643 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t)) {
5644 error = EINVAL;
5645 NECPLOG(LOG_ERR, "necp_client_add_flow invalid client_id (length %zu)", (size_t)uap->client_id_len);
5646 goto done;
5647 }
5648
5649 if (uap->buffer == 0 || buffer_size < sizeof(struct necp_client_add_flow) ||
5650 buffer_size > sizeof(struct necp_client_add_flow_default) * 4) {
5651 error = EINVAL;
5652 NECPLOG(LOG_ERR, "necp_client_add_flow invalid buffer (length %zu)", buffer_size);
5653 goto done;
5654 }
5655
5656 error = copyin(uap->client_id, client_id, sizeof(uuid_t));
5657 if (error) {
5658 NECPLOG(LOG_ERR, "necp_client_add_flow copyin client_id error (%d)", error);
5659 goto done;
5660 }
5661
5662 if (buffer_size <= sizeof(struct necp_client_add_flow_default)) {
5663 // Fits in default size
5664 error = copyin(uap->buffer, &default_add_request, buffer_size);
5665 if (error) {
5666 NECPLOG(LOG_ERR, "necp_client_add_flow copyin default_add_request error (%d)", error);
5667 goto done;
5668 }
5669
5670 add_request = (struct necp_client_add_flow *)&default_add_request;
5671 } else {
5672 allocated_add_request = _MALLOC(buffer_size, M_NECP, M_WAITOK | M_ZERO);
5673 if (allocated_add_request == NULL) {
5674 error = ENOMEM;
5675 goto done;
5676 }
5677
5678 error = copyin(uap->buffer, allocated_add_request, buffer_size);
5679 if (error) {
5680 NECPLOG(LOG_ERR, "necp_client_add_flow copyin default_add_request error (%d)", error);
5681 goto done;
5682 }
5683
5684 add_request = (struct necp_client_add_flow *)allocated_add_request;
5685 }
5686
5687 NECP_FD_LOCK(fd_data);
5688 pid_t pid = fd_data->proc_pid;
5689 proc = proc_find(pid);
5690 if (proc == PROC_NULL) {
5691 NECP_FD_UNLOCK(fd_data);
5692 NECPLOG(LOG_ERR, "necp_client_add_flow process not found for pid %d error (%d)", pid, error);
5693 error = ESRCH;
5694 goto done;
5695 }
5696
5697 client = necp_client_fd_find_client_and_lock(fd_data, client_id);
5698 if (client == NULL) {
5699 error = ENOENT;
5700 NECP_FD_UNLOCK(fd_data);
5701 goto done;
5702 }
5703
5704 // Using ADD_FLOW indicates that the client supports multiple flows per client
5705 client->legacy_client_is_flow = false;
5706
5707 necp_client_retain_locked(client);
5708 necp_client_copy_parameters_locked(client, &parameters);
5709
5710 struct necp_client_flow_registration *new_registration = necp_client_create_flow_registration(fd_data, client);
5711 if (new_registration == NULL) {
5712 error = ENOMEM;
5713 NECP_CLIENT_UNLOCK(client);
5714 NECP_FD_UNLOCK(fd_data);
5715 NECPLOG0(LOG_ERR, "Failed to allocate flow registration");
5716 goto done;
5717 }
5718
5719 new_registration->flags = add_request->flags;
5720
5721 // Copy new ID out to caller
5722 uuid_copy(add_request->registration_id, new_registration->registration_id);
5723
5724 // Copy override address
5725 if (add_request->flags & NECP_CLIENT_FLOW_FLAGS_OVERRIDE_ADDRESS) {
5726 size_t offset_of_address = (sizeof(struct necp_client_add_flow) +
5727 add_request->stats_request_count * sizeof(struct necp_client_flow_stats));
5728 if (buffer_size >= offset_of_address + sizeof(struct sockaddr_in)) {
5729 struct sockaddr *override_address = (struct sockaddr *)(((uint8_t *)add_request) + offset_of_address);
5730 if (buffer_size >= offset_of_address + override_address->sa_len &&
5731 override_address->sa_len <= sizeof(parameters.remote_addr)) {
5732 memcpy(&parameters.remote_addr, override_address, override_address->sa_len);
5733 }
5734 }
5735 }
5736
5737
5738 if (error == 0 &&
5739 (add_request->flags & NECP_CLIENT_FLOW_FLAGS_BROWSE ||
5740 add_request->flags & NECP_CLIENT_FLOW_FLAGS_RESOLVE)) {
5741 uint32_t interface_index = IFSCOPE_NONE;
5742 ifnet_head_lock_shared();
5743 struct ifnet *interface = NULL;
5744 TAILQ_FOREACH(interface, &ifnet_head, if_link) {
5745 ifnet_lock_shared(interface);
5746 if (interface->if_agentids != NULL) {
5747 for (u_int32_t i = 0; i < interface->if_agentcount; i++) {
5748 if (uuid_compare(interface->if_agentids[i], add_request->agent_uuid) == 0) {
5749 interface_index = interface->if_index;
5750 break;
5751 }
5752 }
5753 }
5754 ifnet_lock_done(interface);
5755 if (interface_index != IFSCOPE_NONE) {
5756 break;
5757 }
5758 }
5759 ifnet_head_done();
5760
5761 necp_client_add_nexus_flow_if_needed(new_registration, add_request->agent_uuid, interface_index);
5762
5763 error = netagent_client_message_with_params(add_request->agent_uuid,
5764 ((new_registration->flags & NECP_CLIENT_FLOW_FLAGS_USE_CLIENT_ID) ?
5765 client->client_id :
5766 new_registration->registration_id),
5767 pid, client->agent_handle,
5768 NETAGENT_MESSAGE_TYPE_CLIENT_ASSERT,
5769 (struct necp_client_agent_parameters *)&parameters,
5770 NULL, NULL);
5771 if (error != 0) {
5772 NECPLOG(LOG_ERR, "netagent_client_message error (%d)", error);
5773 }
5774 }
5775
5776 if (error != 0) {
5777 // Encountered an error in adding the flow, destroy the flow registration
5778 NECP_FLOW_TREE_LOCK_EXCLUSIVE();
5779 RB_REMOVE(_necp_client_flow_global_tree, &necp_client_flow_global_tree, new_registration);
5780 NECP_FLOW_TREE_UNLOCK();
5781 RB_REMOVE(_necp_fd_flow_tree, &fd_data->flows, new_registration);
5782 necp_destroy_client_flow_registration(client, new_registration, fd_data->proc_pid, true);
5783 new_registration = NULL;
5784 }
5785
5786 NECP_CLIENT_UNLOCK(client);
5787 NECP_FD_UNLOCK(fd_data);
5788
5789 necp_client_release(client);
5790
5791 if (error != 0) {
5792 goto done;
5793 }
5794
5795 // Copy the request back out to the caller with assigned fields
5796 error = copyout(add_request, uap->buffer, buffer_size);
5797 if (error != 0) {
5798 NECPLOG(LOG_ERR, "necp_client_add_flow copyout add_request error (%d)", error);
5799 }
5800
5801done:
5802 *retval = error;
5803 if (error != 0) {
5804 NECPLOG(LOG_ERR, "Add flow error (%d)", error);
5805 }
5806
5807 if (allocated_add_request != NULL) {
5808 FREE(allocated_add_request, M_NECP);
5809 }
5810
5811 if (proc != PROC_NULL) {
5812 proc_rele(proc);
5813 }
5814 return error;
5815}
5816
5817
5818static void
5819necp_client_add_assertion(struct necp_client *client, uuid_t netagent_uuid)
5820{
5821 struct necp_client_assertion *new_assertion = NULL;
5822
5823 MALLOC(new_assertion, struct necp_client_assertion *, sizeof(*new_assertion), M_NECP, M_WAITOK);
5824 if (new_assertion == NULL) {
5825 NECPLOG0(LOG_ERR, "Failed to allocate assertion");
5826 return;
5827 }
5828
5829 uuid_copy(new_assertion->asserted_netagent, netagent_uuid);
5830
5831 LIST_INSERT_HEAD(&client->assertion_list, new_assertion, assertion_chain);
5832}
5833
5834static bool
5835necp_client_remove_assertion(struct necp_client *client, uuid_t netagent_uuid)
5836{
5837 struct necp_client_assertion *found_assertion = NULL;
5838 struct necp_client_assertion *search_assertion = NULL;
5839 LIST_FOREACH(search_assertion, &client->assertion_list, assertion_chain) {
5840 if (uuid_compare(search_assertion->asserted_netagent, netagent_uuid) == 0) {
5841 found_assertion = search_assertion;
5842 break;
5843 }
5844 }
5845
5846 if (found_assertion == NULL) {
5847 NECPLOG0(LOG_ERR, "Netagent uuid not previously asserted");
5848 return false;
5849 }
5850
5851 LIST_REMOVE(found_assertion, assertion_chain);
5852 FREE(found_assertion, M_NECP);
5853 return true;
5854}
5855
5856static NECP_CLIENT_ACTION_FUNCTION int
5857necp_client_agent_action(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
5858{
5859 int error = 0;
5860 struct necp_client *client = NULL;
5861 uuid_t client_id;
5862 bool acted_on_agent = FALSE;
5863 u_int8_t *parameters = NULL;
5864 const size_t buffer_size = uap->buffer_size;
5865
5866 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t) ||
5867 buffer_size == 0 || uap->buffer == 0) {
5868 NECPLOG0(LOG_ERR, "necp_client_agent_action invalid parameters");
5869 error = EINVAL;
5870 goto done;
5871 }
5872
5873 error = copyin(uap->client_id, client_id, sizeof(uuid_t));
5874 if (error) {
5875 NECPLOG(LOG_ERR, "necp_client_agent_action copyin client_id error (%d)", error);
5876 goto done;
5877 }
5878
5879 if (buffer_size > NECP_MAX_AGENT_ACTION_SIZE) {
5880 NECPLOG(LOG_ERR, "necp_client_agent_action invalid buffer size (>%u)", NECP_MAX_AGENT_ACTION_SIZE);
5881 error = EINVAL;
5882 goto done;
5883 }
5884
5885 if ((parameters = _MALLOC(buffer_size, M_NECP, M_WAITOK | M_ZERO)) == NULL) {
5886 NECPLOG0(LOG_ERR, "necp_client_agent_action malloc failed");
5887 error = ENOMEM;
5888 goto done;
5889 }
5890
5891 error = copyin(uap->buffer, parameters, buffer_size);
5892 if (error) {
5893 NECPLOG(LOG_ERR, "necp_client_agent_action parameters copyin error (%d)", error);
5894 goto done;
5895 }
5896
5897 NECP_FD_LOCK(fd_data);
5898 client = necp_client_fd_find_client_and_lock(fd_data, client_id);
5899 if (client != NULL) {
5900 size_t offset = 0;
5901 while ((offset + sizeof(struct necp_tlv_header)) <= buffer_size) {
5902 u_int8_t type = necp_buffer_get_tlv_type(parameters, offset);
5903 u_int32_t length = necp_buffer_get_tlv_length(parameters, offset);
5904
5905 if (length > (buffer_size - (offset + sizeof(struct necp_tlv_header)))) {
5906 // If the length is larger than what can fit in the remaining parameters size, bail
5907 NECPLOG(LOG_ERR, "Invalid TLV length (%u)", length);
5908 break;
5909 }
5910
5911 if (length > 0) {
5912 u_int8_t *value = necp_buffer_get_tlv_value(parameters, offset, NULL);
5913 if (length >= sizeof(uuid_t) &&
5914 value != NULL &&
5915 (type == NECP_CLIENT_PARAMETER_TRIGGER_AGENT ||
5916 type == NECP_CLIENT_PARAMETER_ASSERT_AGENT ||
5917 type == NECP_CLIENT_PARAMETER_UNASSERT_AGENT)) {
5918 uuid_t agent_uuid;
5919 uuid_copy(agent_uuid, value);
5920 u_int8_t netagent_message_type = 0;
5921 if (type == NECP_CLIENT_PARAMETER_TRIGGER_AGENT) {
5922 netagent_message_type = NETAGENT_MESSAGE_TYPE_CLIENT_TRIGGER;
5923 } else if (type == NECP_CLIENT_PARAMETER_ASSERT_AGENT) {
5924 netagent_message_type = NETAGENT_MESSAGE_TYPE_CLIENT_ASSERT;
5925 } else if (type == NECP_CLIENT_PARAMETER_UNASSERT_AGENT) {
5926 netagent_message_type = NETAGENT_MESSAGE_TYPE_CLIENT_UNASSERT;
5927 }
5928
5929 // Before unasserting, verify that the assertion was already taken
5930 if (type == NECP_CLIENT_PARAMETER_UNASSERT_AGENT) {
5931 if (!necp_client_remove_assertion(client, agent_uuid)) {
5932 error = ENOENT;
5933 break;
5934 }
5935 }
5936
5937 struct necp_client_nexus_parameters parsed_parameters = {};
5938 necp_client_copy_parameters_locked(client, &parsed_parameters);
5939
5940 error = netagent_client_message_with_params(agent_uuid,
5941 client_id,
5942 fd_data->proc_pid,
5943 client->agent_handle,
5944 netagent_message_type,
5945 (struct necp_client_agent_parameters *)&parsed_parameters,
5946 NULL, NULL);
5947 if (error == 0) {
5948 acted_on_agent = TRUE;
5949 } else {
5950 break;
5951 }
5952
5953 // Only save the assertion if the action succeeded
5954 if (type == NECP_CLIENT_PARAMETER_ASSERT_AGENT) {
5955 necp_client_add_assertion(client, agent_uuid);
5956 }
5957 }
5958 }
5959
5960 offset += sizeof(struct necp_tlv_header) + length;
5961 }
5962
5963 NECP_CLIENT_UNLOCK(client);
5964 }
5965 NECP_FD_UNLOCK(fd_data);
5966
5967 if (!acted_on_agent &&
5968 error == 0) {
5969 error = ENOENT;
5970 }
5971done:
5972 *retval = error;
5973 if (parameters != NULL) {
5974 FREE(parameters, M_NECP);
5975 parameters = NULL;
5976 }
5977
5978 return error;
5979}
5980
5981static NECP_CLIENT_ACTION_FUNCTION int
5982necp_client_copy_agent(__unused struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
5983{
5984 int error = 0;
5985 uuid_t agent_uuid;
5986 const size_t buffer_size = uap->buffer_size;
5987
5988 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t) ||
5989 buffer_size == 0 || uap->buffer == 0) {
5990 NECPLOG0(LOG_ERR, "necp_client_copy_agent bad input");
5991 error = EINVAL;
5992 goto done;
5993 }
5994
5995 error = copyin(uap->client_id, agent_uuid, sizeof(uuid_t));
5996 if (error) {
5997 NECPLOG(LOG_ERR, "necp_client_copy_agent copyin agent_uuid error (%d)", error);
5998 goto done;
5999 }
6000
6001 error = netagent_copyout(agent_uuid, uap->buffer, buffer_size);
6002 if (error) {
6003 // netagent_copyout already logs appropriate errors
6004 goto done;
6005 }
6006done:
6007 *retval = error;
6008
6009 return error;
6010}
6011
6012static NECP_CLIENT_ACTION_FUNCTION int
6013necp_client_agent_use(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
6014{
6015 int error = 0;
6016 struct necp_client *client = NULL;
6017 uuid_t client_id;
6018 struct necp_agent_use_parameters parameters = {};
6019 const size_t buffer_size = uap->buffer_size;
6020
6021 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t) ||
6022 buffer_size != sizeof(parameters) || uap->buffer == 0) {
6023 error = EINVAL;
6024 goto done;
6025 }
6026
6027 error = copyin(uap->client_id, client_id, sizeof(uuid_t));
6028 if (error) {
6029 NECPLOG(LOG_ERR, "Copyin client_id error (%d)", error);
6030 goto done;
6031 }
6032
6033 error = copyin(uap->buffer, &parameters, buffer_size);
6034 if (error) {
6035 NECPLOG(LOG_ERR, "Parameters copyin error (%d)", error);
6036 goto done;
6037 }
6038
6039 NECP_FD_LOCK(fd_data);
6040 client = necp_client_fd_find_client_and_lock(fd_data, client_id);
6041 if (client != NULL) {
6042 error = netagent_use(parameters.agent_uuid, &parameters.out_use_count);
6043 NECP_CLIENT_UNLOCK(client);
6044 } else {
6045 error = ENOENT;
6046 }
6047
6048 NECP_FD_UNLOCK(fd_data);
6049
6050 if (error == 0) {
6051 error = copyout(&parameters, uap->buffer, buffer_size);
6052 if (error) {
6053 NECPLOG(LOG_ERR, "Parameters copyout error (%d)", error);
6054 goto done;
6055 }
6056 }
6057
6058done:
6059 *retval = error;
6060
6061 return error;
6062}
6063
6064static NECP_CLIENT_ACTION_FUNCTION int
6065necp_client_copy_interface(__unused struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
6066{
6067 int error = 0;
6068 u_int32_t interface_index = 0;
6069 struct necp_interface_details interface_details = {};
6070
6071 if (uap->client_id == 0 || uap->client_id_len != sizeof(u_int32_t) ||
6072 uap->buffer_size < sizeof(interface_details) ||
6073 uap->buffer == 0) {
6074 NECPLOG0(LOG_ERR, "necp_client_copy_interface bad input");
6075 error = EINVAL;
6076 goto done;
6077 }
6078
6079 error = copyin(uap->client_id, &interface_index, sizeof(u_int32_t));
6080 if (error) {
6081 NECPLOG(LOG_ERR, "necp_client_copy_interface copyin interface_index error (%d)", error);
6082 goto done;
6083 }
6084
6085 if (interface_index == 0) {
6086 error = ENOENT;
6087 NECPLOG(LOG_ERR, "necp_client_copy_interface bad interface_index (%d)", interface_index);
6088 goto done;
6089 }
6090
6091 lck_mtx_lock(rnh_lock);
6092 ifnet_head_lock_shared();
6093 ifnet_t interface = NULL;
6094 if (interface_index != IFSCOPE_NONE && interface_index <= (u_int32_t)if_index) {
6095 interface = ifindex2ifnet[interface_index];
6096 }
6097
6098 if (interface != NULL) {
6099 if (interface->if_xname != NULL) {
6100 strlcpy((char *)&interface_details.name, interface->if_xname, sizeof(interface_details.name));
6101 }
6102 interface_details.index = interface->if_index;
6103 interface_details.generation = ifnet_get_generation(interface);
6104 if (interface->if_delegated.ifp != NULL) {
6105 interface_details.delegate_index = interface->if_delegated.ifp->if_index;
6106 }
6107 interface_details.functional_type = if_functional_type(interface, TRUE);
6108 if (IFNET_IS_EXPENSIVE(interface)) {
6109 interface_details.flags |= NECP_INTERFACE_FLAG_EXPENSIVE;
6110 }
6111 if (IFNET_IS_CONSTRAINED(interface)) {
6112 interface_details.flags |= NECP_INTERFACE_FLAG_CONSTRAINED;
6113 }
6114 if ((interface->if_eflags & IFEF_TXSTART) == IFEF_TXSTART) {
6115 interface_details.flags |= NECP_INTERFACE_FLAG_TXSTART;
6116 }
6117 if ((interface->if_eflags & IFEF_NOACKPRI) == IFEF_NOACKPRI) {
6118 interface_details.flags |= NECP_INTERFACE_FLAG_NOACKPRI;
6119 }
6120 if ((interface->if_eflags & IFEF_3CA) == IFEF_3CA) {
6121 interface_details.flags |= NECP_INTERFACE_FLAG_3CARRIERAGG;
6122 }
6123 if (IFNET_IS_LOW_POWER(interface)) {
6124 interface_details.flags |= NECP_INTERFACE_FLAG_IS_LOW_POWER;
6125 }
6126 if (interface->if_xflags & IFXF_MPK_LOG) {
6127 interface_details.flags |= NECP_INTERFACE_FLAG_MPK_LOG;
6128 }
6129 if (interface->if_flags & IFF_MULTICAST) {
6130 interface_details.flags |= NECP_INTERFACE_FLAG_SUPPORTS_MULTICAST;
6131 }
6132 if (IS_INTF_CLAT46(interface)) {
6133 interface_details.flags |= NECP_INTERFACE_FLAG_HAS_NAT64;
6134 }
6135 interface_details.mtu = interface->if_mtu;
6136
6137 u_int8_t ipv4_signature_len = sizeof(interface_details.ipv4_signature.signature);
6138 u_int16_t ipv4_signature_flags;
6139 if (ifnet_get_netsignature(interface, AF_INET, &ipv4_signature_len, &ipv4_signature_flags,
6140 (u_int8_t *)&interface_details.ipv4_signature) != 0) {
6141 ipv4_signature_len = 0;
6142 }
6143 interface_details.ipv4_signature.signature_len = ipv4_signature_len;
6144
6145 // Check for default scoped routes for IPv4 and IPv6
6146 union necp_sockaddr_union default_address;
6147 struct rtentry *v4Route = NULL;
6148 memset(&default_address, 0, sizeof(default_address));
6149 default_address.sa.sa_family = AF_INET;
6150 default_address.sa.sa_len = sizeof(struct sockaddr_in);
6151 v4Route = rtalloc1_scoped_locked((struct sockaddr *)&default_address, 0, 0,
6152 interface->if_index);
6153 if (v4Route != NULL) {
6154 if (v4Route->rt_ifp != NULL && !IS_INTF_CLAT46(v4Route->rt_ifp)) {
6155 interface_details.flags |= NECP_INTERFACE_FLAG_IPV4_ROUTABLE;
6156 }
6157 rtfree_locked(v4Route);
6158 v4Route = NULL;
6159 }
6160
6161 struct rtentry *v6Route = NULL;
6162 memset(&default_address, 0, sizeof(default_address));
6163 default_address.sa.sa_family = AF_INET6;
6164 default_address.sa.sa_len = sizeof(struct sockaddr_in6);
6165 v6Route = rtalloc1_scoped_locked((struct sockaddr *)&default_address, 0, 0,
6166 interface->if_index);
6167 if (v6Route != NULL) {
6168 if (v6Route->rt_ifp != NULL) {
6169 interface_details.flags |= NECP_INTERFACE_FLAG_IPV6_ROUTABLE;
6170 }
6171 rtfree_locked(v6Route);
6172 v6Route = NULL;
6173 }
6174
6175 u_int8_t ipv6_signature_len = sizeof(interface_details.ipv6_signature.signature);
6176 u_int16_t ipv6_signature_flags;
6177 if (ifnet_get_netsignature(interface, AF_INET6, &ipv6_signature_len, &ipv6_signature_flags,
6178 (u_int8_t *)&interface_details.ipv6_signature) != 0) {
6179 ipv6_signature_len = 0;
6180 }
6181 interface_details.ipv6_signature.signature_len = ipv6_signature_len;
6182
6183 ifnet_lock_shared(interface);
6184 struct ifaddr *ifa = NULL;
6185 TAILQ_FOREACH(ifa, &interface->if_addrhead, ifa_link) {
6186 IFA_LOCK(ifa);
6187 if (ifa->ifa_addr->sa_family == AF_INET) {
6188 interface_details.flags |= NECP_INTERFACE_FLAG_HAS_NETMASK;
6189 interface_details.ipv4_netmask = ((struct in_ifaddr *)ifa)->ia_sockmask.sin_addr.s_addr;
6190 if (interface->if_flags & IFF_BROADCAST) {
6191 interface_details.flags |= NECP_INTERFACE_FLAG_HAS_BROADCAST;
6192 interface_details.ipv4_broadcast = ((struct in_ifaddr *)ifa)->ia_broadaddr.sin_addr.s_addr;
6193 }
6194 }
6195 IFA_UNLOCK(ifa);
6196 }
6197 ifnet_lock_done(interface);
6198 }
6199
6200 ifnet_head_done();
6201 lck_mtx_unlock(rnh_lock);
6202
6203 // If the client is using an older version of the struct, copy that length
6204 error = copyout(&interface_details, uap->buffer, sizeof(interface_details));
6205 if (error) {
6206 NECPLOG(LOG_ERR, "necp_client_copy_interface copyout error (%d)", error);
6207 goto done;
6208 }
6209done:
6210 *retval = error;
6211
6212 return error;
6213}
6214
6215
6216static NECP_CLIENT_ACTION_FUNCTION int
6217necp_client_copy_route_statistics(__unused struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
6218{
6219 int error = 0;
6220 struct necp_client *client = NULL;
6221 uuid_t client_id;
6222
6223 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t) ||
6224 uap->buffer_size < sizeof(struct necp_stat_counts) || uap->buffer == 0) {
6225 NECPLOG0(LOG_ERR, "necp_client_copy_route_statistics bad input");
6226 error = EINVAL;
6227 goto done;
6228 }
6229
6230 error = copyin(uap->client_id, client_id, sizeof(uuid_t));
6231 if (error) {
6232 NECPLOG(LOG_ERR, "necp_client_copy_route_statistics copyin client_id error (%d)", error);
6233 goto done;
6234 }
6235
6236 // Lock
6237 NECP_FD_LOCK(fd_data);
6238 client = necp_client_fd_find_client_and_lock(fd_data, client_id);
6239 if (client != NULL) {
6240 NECP_CLIENT_ROUTE_LOCK(client);
6241 struct necp_stat_counts route_stats = {};
6242 if (client->current_route != NULL && client->current_route->rt_stats != NULL) {
6243 struct nstat_counts *rt_stats = client->current_route->rt_stats;
6244 atomic_get_64(route_stats.necp_stat_rxpackets, &rt_stats->nstat_rxpackets);
6245 atomic_get_64(route_stats.necp_stat_rxbytes, &rt_stats->nstat_rxbytes);
6246 atomic_get_64(route_stats.necp_stat_txpackets, &rt_stats->nstat_txpackets);
6247 atomic_get_64(route_stats.necp_stat_txbytes, &rt_stats->nstat_txbytes);
6248 route_stats.necp_stat_rxduplicatebytes = rt_stats->nstat_rxduplicatebytes;
6249 route_stats.necp_stat_rxoutoforderbytes = rt_stats->nstat_rxoutoforderbytes;
6250 route_stats.necp_stat_txretransmit = rt_stats->nstat_txretransmit;
6251 route_stats.necp_stat_connectattempts = rt_stats->nstat_connectattempts;
6252 route_stats.necp_stat_connectsuccesses = rt_stats->nstat_connectsuccesses;
6253 route_stats.necp_stat_min_rtt = rt_stats->nstat_min_rtt;
6254 route_stats.necp_stat_avg_rtt = rt_stats->nstat_avg_rtt;
6255 route_stats.necp_stat_var_rtt = rt_stats->nstat_var_rtt;
6256 route_stats.necp_stat_route_flags = client->current_route->rt_flags;
6257 }
6258
6259 // Unlock before copying out
6260 NECP_CLIENT_ROUTE_UNLOCK(client);
6261 NECP_CLIENT_UNLOCK(client);
6262 NECP_FD_UNLOCK(fd_data);
6263
6264 error = copyout(&route_stats, uap->buffer, sizeof(route_stats));
6265 if (error) {
6266 NECPLOG(LOG_ERR, "necp_client_copy_route_statistics copyout error (%d)", error);
6267 }
6268 } else {
6269 // Unlock
6270 NECP_FD_UNLOCK(fd_data);
6271 error = ENOENT;
6272 }
6273
6274
6275done:
6276 *retval = error;
6277 return error;
6278}
6279
6280static NECP_CLIENT_ACTION_FUNCTION int
6281necp_client_update_cache(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
6282{
6283 int error = 0;
6284 struct necp_client *client = NULL;
6285 uuid_t client_id;
6286
6287 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t)) {
6288 error = EINVAL;
6289 goto done;
6290 }
6291
6292 error = copyin(uap->client_id, client_id, sizeof(uuid_t));
6293 if (error) {
6294 NECPLOG(LOG_ERR, "necp_client_update_cache copyin client_id error (%d)", error);
6295 goto done;
6296 }
6297
6298 NECP_FD_LOCK(fd_data);
6299 client = necp_client_fd_find_client_and_lock(fd_data, client_id);
6300 if (client == NULL) {
6301 NECP_FD_UNLOCK(fd_data);
6302 error = ENOENT;
6303 goto done;
6304 }
6305
6306 struct necp_client_flow_registration *flow_registration = necp_client_find_flow(client, client_id);
6307 if (flow_registration == NULL) {
6308 NECP_CLIENT_UNLOCK(client);
6309 NECP_FD_UNLOCK(fd_data);
6310 error = ENOENT;
6311 goto done;
6312 }
6313
6314 NECP_CLIENT_ROUTE_LOCK(client);
6315 // This needs to be changed when TFO/ECN is supported by multiple flows
6316 struct necp_client_flow *flow = LIST_FIRST(&flow_registration->flow_list);
6317 if (flow == NULL ||
6318 (flow->remote_addr.sa.sa_family != AF_INET &&
6319 flow->remote_addr.sa.sa_family != AF_INET6) ||
6320 (flow->local_addr.sa.sa_family != AF_INET &&
6321 flow->local_addr.sa.sa_family != AF_INET6)) {
6322 error = EINVAL;
6323 NECPLOG(LOG_ERR, "necp_client_update_cache no flow error (%d)", error);
6324 goto done_unlock;
6325 }
6326
6327 necp_cache_buffer cache_buffer;
6328 memset(&cache_buffer, 0, sizeof(cache_buffer));
6329
6330 if (uap->buffer_size != sizeof(necp_cache_buffer) ||
6331 uap->buffer == USER_ADDR_NULL) {
6332 error = EINVAL;
6333 goto done_unlock;
6334 }
6335
6336 error = copyin(uap->buffer, &cache_buffer, sizeof(cache_buffer));
6337 if (error) {
6338 NECPLOG(LOG_ERR, "necp_client_update_cache copyin cache buffer error (%d)", error);
6339 goto done_unlock;
6340 }
6341
6342 if (cache_buffer.necp_cache_buf_type == NECP_CLIENT_CACHE_TYPE_ECN &&
6343 cache_buffer.necp_cache_buf_ver == NECP_CLIENT_CACHE_TYPE_ECN_VER_1) {
6344 if (cache_buffer.necp_cache_buf_size != sizeof(necp_tcp_ecn_cache) ||
6345 cache_buffer.necp_cache_buf_addr == USER_ADDR_NULL) {
6346 error = EINVAL;
6347 goto done_unlock;
6348 }
6349
6350 necp_tcp_ecn_cache ecn_cache_buffer;
6351 memset(&ecn_cache_buffer, 0, sizeof(ecn_cache_buffer));
6352
6353 error = copyin(cache_buffer.necp_cache_buf_addr, &ecn_cache_buffer, sizeof(necp_tcp_ecn_cache));
6354 if (error) {
6355 NECPLOG(LOG_ERR, "necp_client_update_cache copyin ecn cache buffer error (%d)", error);
6356 goto done_unlock;
6357 }
6358
6359 if (client->current_route != NULL && client->current_route->rt_ifp != NULL) {
6360 if (!client->platform_binary) {
6361 ecn_cache_buffer.necp_tcp_ecn_heuristics_success = 0;
6362 }
6363 tcp_heuristics_ecn_update(&ecn_cache_buffer, client->current_route->rt_ifp,
6364 (union sockaddr_in_4_6 *)&flow->local_addr);
6365 }
6366 } else if (cache_buffer.necp_cache_buf_type == NECP_CLIENT_CACHE_TYPE_TFO &&
6367 cache_buffer.necp_cache_buf_ver == NECP_CLIENT_CACHE_TYPE_TFO_VER_1) {
6368 if (cache_buffer.necp_cache_buf_size != sizeof(necp_tcp_tfo_cache) ||
6369 cache_buffer.necp_cache_buf_addr == USER_ADDR_NULL) {
6370 error = EINVAL;
6371 goto done_unlock;
6372 }
6373
6374 necp_tcp_tfo_cache tfo_cache_buffer;
6375 memset(&tfo_cache_buffer, 0, sizeof(tfo_cache_buffer));
6376
6377 error = copyin(cache_buffer.necp_cache_buf_addr, &tfo_cache_buffer, sizeof(necp_tcp_tfo_cache));
6378 if (error) {
6379 NECPLOG(LOG_ERR, "necp_client_update_cache copyin tfo cache buffer error (%d)", error);
6380 goto done_unlock;
6381 }
6382
6383 if (client->current_route != NULL && client->current_route->rt_ifp != NULL) {
6384 if (!client->platform_binary) {
6385 tfo_cache_buffer.necp_tcp_tfo_heuristics_success = 0;
6386 }
6387 tcp_heuristics_tfo_update(&tfo_cache_buffer, client->current_route->rt_ifp,
6388 (union sockaddr_in_4_6 *)&flow->local_addr,
6389 (union sockaddr_in_4_6 *)&flow->remote_addr);
6390 }
6391 } else {
6392 error = EINVAL;
6393 }
6394done_unlock:
6395 NECP_CLIENT_ROUTE_UNLOCK(client);
6396 NECP_CLIENT_UNLOCK(client);
6397 NECP_FD_UNLOCK(fd_data);
6398done:
6399 *retval = error;
6400 return error;
6401}
6402
6403#define NECP_CLIENT_ACTION_SIGN_DEFAULT_HOSTNAME_LENGTH 64
6404#define NECP_CLIENT_ACTION_SIGN_MAX_HOSTNAME_LENGTH 1024
6405
6406#define NECP_CLIENT_ACTION_SIGN_TAG_LENGTH 32
6407
6408static NECP_CLIENT_ACTION_FUNCTION int
6409necp_client_sign(__unused struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
6410{
6411 int error = 0;
6412 u_int32_t hostname_length = 0;
6413 u_int8_t tag[NECP_CLIENT_ACTION_SIGN_TAG_LENGTH] = {};
6414 struct necp_client_signable signable = {};
6415 union necp_sockaddr_union address_answer = {};
6416 u_int8_t *client_hostname = NULL;
6417 u_int8_t *allocated_hostname = NULL;
6418 u_int8_t default_hostname[NECP_CLIENT_ACTION_SIGN_DEFAULT_HOSTNAME_LENGTH] = "";
6419 uint32_t tag_size = sizeof(tag);
6420
6421 *retval = 0;
6422
6423 const bool has_resolver_entitlement = (priv_check_cred(kauth_cred_get(), PRIV_NET_VALIDATED_RESOLVER, 0) == 0);
6424 if (!has_resolver_entitlement) {
6425 NECPLOG0(LOG_ERR, "Process does not hold the necessary entitlement to sign resolver answers");
6426 error = EPERM;
6427 goto done;
6428 }
6429
6430 if (uap->client_id == 0 || uap->client_id_len < sizeof(struct necp_client_signable)) {
6431 error = EINVAL;
6432 goto done;
6433 }
6434
6435 if (uap->buffer == 0 || uap->buffer_size != NECP_CLIENT_ACTION_SIGN_TAG_LENGTH) {
6436 error = EINVAL;
6437 goto done;
6438 }
6439
6440 error = copyin(uap->client_id, &signable, sizeof(signable));
6441 if (error) {
6442 NECPLOG(LOG_ERR, "necp_client_sign copyin signable error (%d)", error);
6443 goto done;
6444 }
6445
6446 if (signable.sign_type != NECP_CLIENT_SIGN_TYPE_RESOLVER_ANSWER) {
6447 NECPLOG(LOG_ERR, "necp_client_sign unknown signable type (%u)", signable.sign_type);
6448 error = EINVAL;
6449 goto done;
6450 }
6451
6452 if (uap->client_id_len < sizeof(struct necp_client_resolver_answer)) {
6453 error = EINVAL;
6454 goto done;
6455 }
6456
6457 error = copyin(uap->client_id + sizeof(signable), &address_answer, sizeof(address_answer));
6458 if (error) {
6459 NECPLOG(LOG_ERR, "necp_client_sign copyin address_answer error (%d)", error);
6460 goto done;
6461 }
6462
6463 error = copyin(uap->client_id + sizeof(signable) + sizeof(address_answer), &hostname_length, sizeof(hostname_length));
6464 if (error) {
6465 NECPLOG(LOG_ERR, "necp_client_sign copyin hostname_length error (%d)", error);
6466 goto done;
6467 }
6468
6469 if (hostname_length > NECP_CLIENT_ACTION_SIGN_MAX_HOSTNAME_LENGTH) {
6470 error = EINVAL;
6471 goto done;
6472 }
6473
6474 if (hostname_length > NECP_CLIENT_ACTION_SIGN_DEFAULT_HOSTNAME_LENGTH) {
6475 if ((allocated_hostname = _MALLOC(hostname_length, M_NECP, M_WAITOK | M_ZERO)) == NULL) {
6476 NECPLOG(LOG_ERR, "necp_client_sign malloc hostname %u failed", hostname_length);
6477 error = ENOMEM;
6478 goto done;
6479 }
6480
6481 client_hostname = allocated_hostname;
6482 } else {
6483 client_hostname = default_hostname;
6484 }
6485
6486 error = copyin(uap->client_id + sizeof(signable) + sizeof(address_answer) + sizeof(hostname_length), client_hostname, hostname_length);
6487 if (error) {
6488 NECPLOG(LOG_ERR, "necp_client_sign copyin hostname error (%d)", error);
6489 goto done;
6490 }
6491
6492 address_answer.sin.sin_port = 0;
6493 error = necp_sign_resolver_answer(signable.client_id, client_hostname, hostname_length,
6494 (u_int8_t *)&address_answer, sizeof(address_answer),
6495 tag, &tag_size);
6496 if (tag_size != sizeof(tag)) {
6497 NECPLOG(LOG_ERR, "necp_client_sign unexpected tag size %u", tag_size);
6498 error = EINVAL;
6499 goto done;
6500 }
6501 error = copyout(tag, uap->buffer, tag_size);
6502 if (error) {
6503 NECPLOG(LOG_ERR, "necp_client_sign copyout error (%d)", error);
6504 goto done;
6505 }
6506
6507done:
6508 if (allocated_hostname != NULL) {
6509 FREE(allocated_hostname, M_NECP);
6510 allocated_hostname = NULL;
6511 }
6512 *retval = error;
6513 return error;
6514}
6515
6516int
6517necp_client_action(struct proc *p, struct necp_client_action_args *uap, int *retval)
6518{
6519 struct fileproc *fp;
6520 int error = 0;
6521 int return_value = 0;
6522 struct necp_fd_data *fd_data = NULL;
6523
6524 error = necp_find_fd_data(p, uap->necp_fd, &fp, &fd_data);
6525 if (error != 0) {
6526 NECPLOG(LOG_ERR, "necp_client_action find fd error (%d)", error);
6527 return error;
6528 }
6529
6530 u_int32_t action = uap->action;
6531 switch (action) {
6532 case NECP_CLIENT_ACTION_ADD: {
6533 return_value = necp_client_add(p, fd_data, uap, retval);
6534 break;
6535 }
6536 case NECP_CLIENT_ACTION_CLAIM: {
6537 return_value = necp_client_claim(p, fd_data, uap, retval);
6538 break;
6539 }
6540 case NECP_CLIENT_ACTION_REMOVE: {
6541 return_value = necp_client_remove(fd_data, uap, retval);
6542 break;
6543 }
6544 case NECP_CLIENT_ACTION_COPY_PARAMETERS:
6545 case NECP_CLIENT_ACTION_COPY_RESULT:
6546 case NECP_CLIENT_ACTION_COPY_UPDATED_RESULT: {
6547 return_value = necp_client_copy(fd_data, uap, retval);
6548 break;
6549 }
6550 case NECP_CLIENT_ACTION_COPY_LIST: {
6551 return_value = necp_client_list(fd_data, uap, retval);
6552 break;
6553 }
6554 case NECP_CLIENT_ACTION_ADD_FLOW: {
6555 return_value = necp_client_add_flow(fd_data, uap, retval);
6556 break;
6557 }
6558 case NECP_CLIENT_ACTION_REMOVE_FLOW: {
6559 return_value = necp_client_remove_flow(fd_data, uap, retval);
6560 break;
6561 }
6562 case NECP_CLIENT_ACTION_AGENT: {
6563 return_value = necp_client_agent_action(fd_data, uap, retval);
6564 break;
6565 }
6566 case NECP_CLIENT_ACTION_COPY_AGENT: {
6567 return_value = necp_client_copy_agent(fd_data, uap, retval);
6568 break;
6569 }
6570 case NECP_CLIENT_ACTION_AGENT_USE: {
6571 return_value = necp_client_agent_use(fd_data, uap, retval);
6572 break;
6573 }
6574 case NECP_CLIENT_ACTION_COPY_INTERFACE: {
6575 return_value = necp_client_copy_interface(fd_data, uap, retval);
6576 break;
6577 }
6578 case NECP_CLIENT_ACTION_COPY_ROUTE_STATISTICS: {
6579 return_value = necp_client_copy_route_statistics(fd_data, uap, retval);
6580 break;
6581 }
6582 case NECP_CLIENT_ACTION_UPDATE_CACHE: {
6583 return_value = necp_client_update_cache(fd_data, uap, retval);
6584 break;
6585 }
6586 case NECP_CLIENT_ACTION_COPY_CLIENT_UPDATE: {
6587 return_value = necp_client_copy_client_update(fd_data, uap, retval);
6588 break;
6589 }
6590 case NECP_CLIENT_ACTION_SIGN: {
6591 return_value = necp_client_sign(fd_data, uap, retval);
6592 break;
6593 }
6594 default: {
6595 NECPLOG(LOG_ERR, "necp_client_action unknown action (%u)", action);
6596 return_value = EINVAL;
6597 break;
6598 }
6599 }
6600
6601 fp_drop(p, uap->necp_fd, fp, 0);
6602 return return_value;
6603}
6604
6605#define NECP_MAX_MATCH_POLICY_PARAMETER_SIZE 1024
6606
6607int
6608necp_match_policy(struct proc *p, struct necp_match_policy_args *uap, int32_t *retval)
6609{
6610#pragma unused(retval)
6611 u_int8_t *parameters = NULL;
6612 struct necp_aggregate_result returned_result;
6613 int error = 0;
6614
6615 if (uap == NULL) {
6616 error = EINVAL;
6617 goto done;
6618 }
6619
6620 if (uap->parameters == 0 || uap->parameters_size == 0 || uap->parameters_size > NECP_MAX_MATCH_POLICY_PARAMETER_SIZE || uap->returned_result == 0) {
6621 error = EINVAL;
6622 goto done;
6623 }
6624
6625 MALLOC(parameters, u_int8_t *, uap->parameters_size, M_NECP, M_WAITOK | M_ZERO);
6626 if (parameters == NULL) {
6627 error = ENOMEM;
6628 goto done;
6629 }
6630 // Copy parameters in
6631 error = copyin(uap->parameters, parameters, uap->parameters_size);
6632 if (error) {
6633 goto done;
6634 }
6635
6636 error = necp_application_find_policy_match_internal(p, parameters, uap->parameters_size,
6637 &returned_result, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, false, false, NULL);
6638 if (error) {
6639 goto done;
6640 }
6641
6642 // Copy return value back
6643 error = copyout(&returned_result, uap->returned_result, sizeof(struct necp_aggregate_result));
6644 if (error) {
6645 goto done;
6646 }
6647done:
6648 if (parameters != NULL) {
6649 FREE(parameters, M_NECP);
6650 }
6651 return error;
6652}
6653
6654/// Socket operations
6655#define NECP_MAX_SOCKET_ATTRIBUTE_STRING_LENGTH 253
6656
6657static bool
6658necp_set_socket_attribute(u_int8_t *buffer, size_t buffer_length, u_int8_t type, char **buffer_p)
6659{
6660 int error = 0;
6661 int cursor = 0;
6662 size_t string_size = 0;
6663 char *local_string = NULL;
6664 u_int8_t *value = NULL;
6665
6666 cursor = necp_buffer_find_tlv(buffer, buffer_length, 0, type, NULL, 0);
6667 if (cursor < 0) {
6668 // This will clear out the parameter
6669 goto done;
6670 }
6671
6672 string_size = necp_buffer_get_tlv_length(buffer, cursor);
6673 if (string_size == 0 || string_size > NECP_MAX_SOCKET_ATTRIBUTE_STRING_LENGTH) {
6674 // This will clear out the parameter
6675 goto done;
6676 }
6677
6678 MALLOC(local_string, char *, string_size + 1, M_NECP, M_WAITOK | M_ZERO);
6679 if (local_string == NULL) {
6680 NECPLOG(LOG_ERR, "Failed to allocate a socket attribute buffer (size %zu)", string_size);
6681 goto fail;
6682 }
6683
6684 value = necp_buffer_get_tlv_value(buffer, cursor, NULL);
6685 if (value == NULL) {
6686 NECPLOG0(LOG_ERR, "Failed to get socket attribute");
6687 goto fail;
6688 }
6689
6690 memcpy(local_string, value, string_size);
6691 local_string[string_size] = 0;
6692
6693done:
6694 if (*buffer_p != NULL) {
6695 FREE(*buffer_p, M_NECP);
6696 *buffer_p = NULL;
6697 }
6698
6699 *buffer_p = local_string;
6700 return 0;
6701fail:
6702 if (local_string != NULL) {
6703 FREE(local_string, M_NECP);
6704 }
6705 return error;
6706}
6707
6708errno_t
6709necp_set_socket_attributes(struct socket *so, struct sockopt *sopt)
6710{
6711 int error = 0;
6712 u_int8_t *buffer = NULL;
6713 struct inpcb *inp = NULL;
6714
6715 if (SOCK_DOM(so) != PF_INET && SOCK_DOM(so) != PF_INET6) {
6716 error = EINVAL;
6717 goto done;
6718 }
6719
6720 inp = sotoinpcb(so);
6721
6722 size_t valsize = sopt->sopt_valsize;
6723 if (valsize == 0 ||
6724 valsize > ((sizeof(struct necp_tlv_header) + NECP_MAX_SOCKET_ATTRIBUTE_STRING_LENGTH) * 2)) {
6725 goto done;
6726 }
6727
6728 MALLOC(buffer, u_int8_t *, valsize, M_NECP, M_WAITOK | M_ZERO);
6729 if (buffer == NULL) {
6730 goto done;
6731 }
6732
6733 error = sooptcopyin(sopt, buffer, valsize, 0);
6734 if (error) {
6735 goto done;
6736 }
6737
6738 error = necp_set_socket_attribute(buffer, valsize, NECP_TLV_ATTRIBUTE_DOMAIN, &inp->inp_necp_attributes.inp_domain);
6739 if (error) {
6740 NECPLOG0(LOG_ERR, "Could not set domain TLV for socket attributes");
6741 goto done;
6742 }
6743
6744 error = necp_set_socket_attribute(buffer, valsize, NECP_TLV_ATTRIBUTE_ACCOUNT, &inp->inp_necp_attributes.inp_account);
6745 if (error) {
6746 NECPLOG0(LOG_ERR, "Could not set account TLV for socket attributes");
6747 goto done;
6748 }
6749
6750 if (necp_debug) {
6751 NECPLOG(LOG_DEBUG, "Set on socket: Domain %s, Account %s", inp->inp_necp_attributes.inp_domain, inp->inp_necp_attributes.inp_account);
6752 }
6753done:
6754 if (buffer != NULL) {
6755 FREE(buffer, M_NECP);
6756 }
6757
6758 return error;
6759}
6760
6761errno_t
6762necp_get_socket_attributes(struct socket *so, struct sockopt *sopt)
6763{
6764 int error = 0;
6765 u_int8_t *buffer = NULL;
6766 u_int8_t *cursor = NULL;
6767 size_t valsize = 0;
6768 struct inpcb *inp = NULL;
6769
6770 if (SOCK_DOM(so) != PF_INET && SOCK_DOM(so) != PF_INET6) {
6771 error = EINVAL;
6772 goto done;
6773 }
6774
6775 inp = sotoinpcb(so);
6776 if (inp->inp_necp_attributes.inp_domain != NULL) {
6777 valsize += sizeof(struct necp_tlv_header) + strlen(inp->inp_necp_attributes.inp_domain);
6778 }
6779 if (inp->inp_necp_attributes.inp_account != NULL) {
6780 valsize += sizeof(struct necp_tlv_header) + strlen(inp->inp_necp_attributes.inp_account);
6781 }
6782 if (valsize == 0) {
6783 goto done;
6784 }
6785
6786 MALLOC(buffer, u_int8_t *, valsize, M_NECP, M_WAITOK | M_ZERO);
6787 if (buffer == NULL) {
6788 goto done;
6789 }
6790
6791 cursor = buffer;
6792 if (inp->inp_necp_attributes.inp_domain != NULL) {
6793 cursor = necp_buffer_write_tlv(cursor, NECP_TLV_ATTRIBUTE_DOMAIN, strlen(inp->inp_necp_attributes.inp_domain), inp->inp_necp_attributes.inp_domain,
6794 buffer, valsize);
6795 }
6796
6797 if (inp->inp_necp_attributes.inp_account != NULL) {
6798 cursor = necp_buffer_write_tlv(cursor, NECP_TLV_ATTRIBUTE_ACCOUNT, strlen(inp->inp_necp_attributes.inp_account), inp->inp_necp_attributes.inp_account,
6799 buffer, valsize);
6800 }
6801
6802 error = sooptcopyout(sopt, buffer, valsize);
6803 if (error) {
6804 goto done;
6805 }
6806done:
6807 if (buffer != NULL) {
6808 FREE(buffer, M_NECP);
6809 }
6810
6811 return error;
6812}
6813
6814void *
6815necp_create_nexus_assign_message(uuid_t nexus_instance, u_int32_t nexus_port, void *key, uint32_t key_length,
6816 struct necp_client_endpoint *local_endpoint, struct necp_client_endpoint *remote_endpoint, struct ether_addr *local_ether_addr,
6817 u_int32_t flow_adv_index, void *flow_stats, size_t *message_length)
6818{
6819 u_int8_t *buffer = NULL;
6820 u_int8_t *cursor = NULL;
6821 size_t valsize = 0;
6822 bool has_nexus_assignment = FALSE;
6823
6824 if (!uuid_is_null(nexus_instance)) {
6825 has_nexus_assignment = TRUE;
6826 valsize += sizeof(struct necp_tlv_header) + sizeof(uuid_t);
6827 valsize += sizeof(struct necp_tlv_header) + sizeof(u_int32_t);
6828 }
6829 if (flow_adv_index != NECP_FLOWADV_IDX_INVALID) {
6830 valsize += sizeof(struct necp_tlv_header) + sizeof(u_int32_t);
6831 }
6832 if (key != NULL && key_length > 0) {
6833 valsize += sizeof(struct necp_tlv_header) + key_length;
6834 }
6835 if (local_endpoint != NULL) {
6836 valsize += sizeof(struct necp_tlv_header) + sizeof(struct necp_client_endpoint);
6837 }
6838 if (remote_endpoint != NULL) {
6839 valsize += sizeof(struct necp_tlv_header) + sizeof(struct necp_client_endpoint);
6840 }
6841 if (local_ether_addr != NULL) {
6842 valsize += sizeof(struct necp_tlv_header) + sizeof(struct ether_addr);
6843 }
6844 if (flow_stats != NULL) {
6845 valsize += sizeof(struct necp_tlv_header) + sizeof(void *);
6846 }
6847 if (valsize == 0) {
6848 return NULL;
6849 }
6850
6851 MALLOC(buffer, u_int8_t *, valsize, M_NETAGENT, M_WAITOK | M_ZERO); // Use M_NETAGENT area, since it is expected upon free
6852 if (buffer == NULL) {
6853 return NULL;
6854 }
6855
6856 cursor = buffer;
6857 if (has_nexus_assignment) {
6858 cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_NEXUS_INSTANCE, sizeof(uuid_t), nexus_instance, buffer, valsize);
6859 cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_NEXUS_PORT, sizeof(u_int32_t), &nexus_port, buffer, valsize);
6860 }
6861 if (flow_adv_index != NECP_FLOWADV_IDX_INVALID) {
6862 cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_NEXUS_PORT_FLOW_INDEX, sizeof(u_int32_t), &flow_adv_index, buffer, valsize);
6863 }
6864 if (key != NULL && key_length > 0) {
6865 cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_PARAMETER_NEXUS_KEY, key_length, key, buffer, valsize);
6866 }
6867 if (local_endpoint != NULL) {
6868 cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_LOCAL_ENDPOINT, sizeof(struct necp_client_endpoint), local_endpoint, buffer, valsize);
6869 }
6870 if (remote_endpoint != NULL) {
6871 cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_REMOTE_ENDPOINT, sizeof(struct necp_client_endpoint), remote_endpoint, buffer, valsize);
6872 }
6873 if (local_ether_addr != NULL) {
6874 cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_LOCAL_ETHER_ADDR, sizeof(struct ether_addr), local_ether_addr, buffer, valsize);
6875 }
6876 if (flow_stats != NULL) {
6877 cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_NEXUS_FLOW_STATS, sizeof(void *), &flow_stats, buffer, valsize);
6878 }
6879
6880 *message_length = valsize;
6881
6882 return buffer;
6883}
6884
6885void
6886necp_inpcb_remove_cb(struct inpcb *inp)
6887{
6888 if (!uuid_is_null(inp->necp_client_uuid)) {
6889 necp_client_unregister_socket_flow(inp->necp_client_uuid, inp);
6890 uuid_clear(inp->necp_client_uuid);
6891 }
6892}
6893
6894void
6895necp_inpcb_dispose(struct inpcb *inp)
6896{
6897 necp_inpcb_remove_cb(inp); // Clear out socket registrations if not yet done
6898 if (inp->inp_necp_attributes.inp_domain != NULL) {
6899 FREE(inp->inp_necp_attributes.inp_domain, M_NECP);
6900 inp->inp_necp_attributes.inp_domain = NULL;
6901 }
6902 if (inp->inp_necp_attributes.inp_account != NULL) {
6903 FREE(inp->inp_necp_attributes.inp_account, M_NECP);
6904 inp->inp_necp_attributes.inp_account = NULL;
6905 }
6906}
6907
6908void
6909necp_mppcb_dispose(struct mppcb *mpp)
6910{
6911 if (!uuid_is_null(mpp->necp_client_uuid)) {
6912 necp_client_unregister_multipath_cb(mpp->necp_client_uuid, mpp);
6913 uuid_clear(mpp->necp_client_uuid);
6914 }
6915}
6916
6917/// Module init
6918
6919errno_t
6920necp_client_init(void)
6921{
6922 necp_fd_grp_attr = lck_grp_attr_alloc_init();
6923 if (necp_fd_grp_attr == NULL) {
6924 panic("lck_grp_attr_alloc_init failed\n");
6925 /* NOTREACHED */
6926 }
6927
6928 necp_fd_mtx_grp = lck_grp_alloc_init("necp_fd", necp_fd_grp_attr);
6929 if (necp_fd_mtx_grp == NULL) {
6930 panic("lck_grp_alloc_init failed\n");
6931 /* NOTREACHED */
6932 }
6933
6934 necp_fd_mtx_attr = lck_attr_alloc_init();
6935 if (necp_fd_mtx_attr == NULL) {
6936 panic("lck_attr_alloc_init failed\n");
6937 /* NOTREACHED */
6938 }
6939
6940 necp_flow_size = sizeof(struct necp_client_flow);
6941 necp_flow_cache = mcache_create(NECP_FLOW_ZONE_NAME, necp_flow_size, sizeof(uint64_t), 0, MCR_SLEEP);
6942 if (necp_flow_cache == NULL) {
6943 panic("mcache_create(necp_flow_cache) failed\n");
6944 /* NOTREACHED */
6945 }
6946
6947 necp_flow_registration_size = sizeof(struct necp_client_flow_registration);
6948 necp_flow_registration_cache = mcache_create(NECP_FLOW_REGISTRATION_ZONE_NAME, necp_flow_registration_size, sizeof(uint64_t), 0, MCR_SLEEP);
6949 if (necp_flow_registration_cache == NULL) {
6950 panic("mcache_create(necp_client_flow_registration) failed\n");
6951 /* NOTREACHED */
6952 }
6953
6954 necp_client_update_tcall = thread_call_allocate_with_options(necp_update_all_clients_callout, NULL,
6955 THREAD_CALL_PRIORITY_KERNEL, THREAD_CALL_OPTIONS_ONCE);
6956 VERIFY(necp_client_update_tcall != NULL);
6957
6958 lck_rw_init(&necp_fd_lock, necp_fd_mtx_grp, necp_fd_mtx_attr);
6959 lck_rw_init(&necp_observer_lock, necp_fd_mtx_grp, necp_fd_mtx_attr);
6960 lck_rw_init(&necp_client_tree_lock, necp_fd_mtx_grp, necp_fd_mtx_attr);
6961 lck_rw_init(&necp_flow_tree_lock, necp_fd_mtx_grp, necp_fd_mtx_attr);
6962 lck_rw_init(&necp_collect_stats_list_lock, necp_fd_mtx_grp, necp_fd_mtx_attr);
6963
6964 LIST_INIT(&necp_fd_list);
6965 LIST_INIT(&necp_fd_observer_list);
6966 LIST_INIT(&necp_collect_stats_flow_list);
6967
6968 RB_INIT(&necp_client_global_tree);
6969 RB_INIT(&necp_client_flow_global_tree);
6970
6971 return 0;
6972}
6973
6974void
6975necp_client_reap_caches(boolean_t purge)
6976{
6977 mcache_reap_now(necp_flow_cache, purge);
6978 mcache_reap_now(necp_flow_registration_cache, purge);
6979}
6980