]> git.saurik.com Git - apple/xnu.git/blob - bsd/net/necp_client.c
xnu-4570.31.3.tar.gz
[apple/xnu.git] / bsd / net / necp_client.c
1 /*
2 * Copyright (c) 2015-2017 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 <libkern/OSMalloc.h>
35
36 #include <net/if.h>
37 #include <net/if_var.h>
38 #include <net/net_api_stats.h>
39 #include <net/necp.h>
40 #include <net/network_agent.h>
41 #include <net/ntstat.h>
42
43 #include <netinet/in_pcb.h>
44 #include <netinet/ip.h>
45 #include <netinet/ip6.h>
46 #include <netinet/mp_pcb.h>
47 #include <netinet/tcp_cc.h>
48 #include <netinet/tcp_fsm.h>
49 #include <netinet/tcp_cache.h>
50 #include <netinet6/in6_var.h>
51
52 #include <sys/domain.h>
53 #include <sys/file_internal.h>
54 #include <sys/kauth.h>
55 #include <sys/kernel.h>
56 #include <sys/malloc.h>
57 #include <sys/poll.h>
58 #include <sys/priv.h>
59 #include <sys/protosw.h>
60 #include <sys/queue.h>
61 #include <sys/socket.h>
62 #include <sys/socketvar.h>
63 #include <sys/sysproto.h>
64 #include <sys/systm.h>
65 #include <sys/types.h>
66 #include <sys/codesign.h>
67 #include <libkern/section_keywords.h>
68
69
70 /*
71 * NECP Client Architecture
72 * ------------------------------------------------
73 * See <net/necp.c> for a discussion on NECP database architecture.
74 *
75 * Each client of NECP provides a set of parameters for a connection or network state
76 * evaluation, on which NECP policy evaluation is run. This produces a policy result
77 * which can be accessed by the originating process, along with events for when policies
78 * results have changed.
79 *
80 * ------------------------------------------------
81 * NECP Client FD
82 * ------------------------------------------------
83 * A process opens an NECP file descriptor using necp_open(). This is a very simple
84 * file descriptor, upon which the process may do the following operations:
85 * - necp_client_action(...), to add/remove/query clients
86 * - kqueue, to watch for readable events
87 * - close(), to close the client session and release all clients
88 *
89 * Client objects are allocated structures that hang off of the file descriptor. Each
90 * client contains:
91 * - Client ID, a UUID that references the client across the system
92 * - Parameters, a buffer of TLVs that describe the client's connection parameters,
93 * such as the remote and local endpoints, interface requirements, etc.
94 * - Result, a buffer of TLVs containing the current policy evaluation for the client.
95 * This result will be updated whenever a network change occurs that impacts the
96 * policy result for that client.
97 *
98 * +--------------+
99 * | NECP fd |
100 * +--------------+
101 * ||
102 * ==================================
103 * || || ||
104 * +--------------+ +--------------+ +--------------+
105 * | Client ID | | Client ID | | Client ID |
106 * | ---- | | ---- | | ---- |
107 * | Parameters | | Parameters | | Parameters |
108 * | ---- | | ---- | | ---- |
109 * | Result | | Result | | Result |
110 * +--------------+ +--------------+ +--------------+
111 *
112 * ------------------------------------------------
113 * Client Actions
114 * ------------------------------------------------
115 * - Add. Input parameters as a buffer of TLVs, and output a client ID. Allocates a
116 * new client structure on the file descriptor.
117 * - Remove. Input a client ID. Removes a client structure from the file descriptor.
118 * - Copy Parameters. Input a client ID, and output parameter TLVs.
119 * - Copy Result. Input a client ID, and output result TLVs. Alternatively, input empty
120 * client ID and get next unread client result.
121 * - Copy List. List all client IDs.
122 *
123 * ------------------------------------------------
124 * Client Policy Evaluation
125 * ------------------------------------------------
126 * Policies are evaluated for clients upon client creation, and upon update events,
127 * which are network/agent/policy changes coalesced by a timer.
128 *
129 * The policy evaluation goes through the following steps:
130 * 1. Parse client parameters.
131 * 2. Select a scoped interface if applicable. This involves using require/prohibit
132 * parameters, along with the local address, to select the most appropriate interface
133 * if not explicitly set by the client parameters.
134 * 3. Run NECP application-level policy evalution
135 * 4. Set policy result into client result buffer.
136 *
137 * ------------------------------------------------
138 * Client Observers
139 * ------------------------------------------------
140 * If necp_open() is called with the NECP_OPEN_FLAG_OBSERVER flag, and the process
141 * passes the necessary privilege check, the fd is allowed to use necp_client_action()
142 * to copy client state attached to the file descriptors of other processes, and to
143 * list all client IDs on the system.
144 */
145
146 extern u_int32_t necp_debug;
147
148 // proc_best_name() is declared here in advance of it landing in a header file.
149 // See comment in kern_proc.c
150 extern char *proc_best_name(proc_t p);
151
152 static int noop_read(struct fileproc *, struct uio *, int, vfs_context_t);
153 static int noop_write(struct fileproc *, struct uio *, int, vfs_context_t);
154 static int noop_ioctl(struct fileproc *, unsigned long, caddr_t,
155 vfs_context_t);
156 static int necpop_select(struct fileproc *, int, void *, vfs_context_t);
157 static int necpop_close(struct fileglob *, vfs_context_t);
158 static int necpop_kqfilter(struct fileproc *, struct knote *,
159 struct kevent_internal_s *kev, vfs_context_t);
160
161 // Timer functions
162 static int necp_timeout_microseconds = 1000 * 100; // 100ms
163 static int necp_timeout_leeway_microseconds = 1000 * 500; // 500ms
164
165 static int necp_client_fd_count = 0;
166 static int necp_observer_fd_count = 0;
167 static int necp_client_count = 0;
168 static int necp_socket_flow_count = 0;
169 static int necp_if_flow_count = 0;
170 static int necp_observer_message_limit = 256;
171
172 SYSCTL_INT(_net_necp, NECPCTL_CLIENT_FD_COUNT, client_fd_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_client_fd_count, 0, "");
173 SYSCTL_INT(_net_necp, NECPCTL_OBSERVER_FD_COUNT, observer_fd_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_observer_fd_count, 0, "");
174 SYSCTL_INT(_net_necp, NECPCTL_CLIENT_COUNT, client_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_client_count, 0, "");
175 SYSCTL_INT(_net_necp, NECPCTL_SOCKET_FLOW_COUNT, socket_flow_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_socket_flow_count, 0, "");
176 SYSCTL_INT(_net_necp, NECPCTL_IF_FLOW_COUNT, if_flow_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_if_flow_count, 0, "");
177 SYSCTL_INT(_net_necp, NECPCTL_OBSERVER_MESSAGE_LIMIT, observer_message_limit, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_observer_message_limit, 256, "");
178
179 #define NECP_MAX_CLIENT_LIST_SIZE 1024 * 1024 // 1MB
180
181 extern int tvtohz(struct timeval *);
182 extern unsigned int get_maxmtu(struct rtentry *);
183
184 // Parsed parameters
185 #define NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR 0x00001
186 #define NECP_PARSED_PARAMETERS_FIELD_REMOTE_ADDR 0x00002
187 #define NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IF 0x00004
188 #define NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IF 0x00008
189 #define NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE 0x00010
190 #define NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IFTYPE 0x00020
191 #define NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT 0x00040
192 #define NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT 0x00080
193 #define NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT 0x00100
194 #define NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE 0x00200
195 #define NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT_TYPE 0x00400
196 #define NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT_TYPE 0x00800
197 #define NECP_PARSED_PARAMETERS_FIELD_FLAGS 0x01000
198 #define NECP_PARSED_PARAMETERS_FIELD_IP_PROTOCOL 0x02000
199 #define NECP_PARSED_PARAMETERS_FIELD_EFFECTIVE_PID 0x04000
200 #define NECP_PARSED_PARAMETERS_FIELD_EFFECTIVE_UUID 0x08000
201 #define NECP_PARSED_PARAMETERS_FIELD_TRAFFIC_CLASS 0x10000
202 #define NECP_PARSED_PARAMETERS_FIELD_LOCAL_PORT 0x20000
203
204 #define NECP_MAX_PARSED_PARAMETERS 16
205 struct necp_client_parsed_parameters {
206 u_int32_t valid_fields;
207 u_int32_t flags;
208 union necp_sockaddr_union local_addr;
209 union necp_sockaddr_union remote_addr;
210 u_int32_t required_interface_index;
211 char prohibited_interfaces[IFXNAMSIZ][NECP_MAX_PARSED_PARAMETERS];
212 u_int8_t required_interface_type;
213 u_int8_t prohibited_interface_types[NECP_MAX_PARSED_PARAMETERS];
214 struct necp_client_parameter_netagent_type required_netagent_types[NECP_MAX_PARSED_PARAMETERS];
215 struct necp_client_parameter_netagent_type prohibited_netagent_types[NECP_MAX_PARSED_PARAMETERS];
216 struct necp_client_parameter_netagent_type preferred_netagent_types[NECP_MAX_PARSED_PARAMETERS];
217 uuid_t required_netagents[NECP_MAX_PARSED_PARAMETERS];
218 uuid_t prohibited_netagents[NECP_MAX_PARSED_PARAMETERS];
219 uuid_t preferred_netagents[NECP_MAX_PARSED_PARAMETERS];
220 u_int16_t ip_protocol;
221 pid_t effective_pid;
222 uuid_t effective_uuid;
223 u_int32_t traffic_class;
224 };
225
226 static bool
227 necp_find_matching_interface_index(struct necp_client_parsed_parameters *parsed_parameters,
228 u_int *return_ifindex);
229
230 static bool
231 necp_ifnet_matches_local_address(struct ifnet *ifp, struct sockaddr *sa);
232
233 static bool
234 necp_ifnet_matches_parameters(struct ifnet *ifp,
235 struct necp_client_parsed_parameters *parsed_parameters,
236 u_int32_t *preferred_count, bool ignore_require_if);
237
238 static const struct fileops necp_fd_ops = {
239 .fo_type = DTYPE_NETPOLICY,
240 .fo_read = noop_read,
241 .fo_write = noop_write,
242 .fo_ioctl = noop_ioctl,
243 .fo_select = necpop_select,
244 .fo_close = necpop_close,
245 .fo_kqfilter = necpop_kqfilter,
246 .fo_drain = NULL,
247 };
248
249 struct necp_client_assertion {
250 LIST_ENTRY(necp_client_assertion) assertion_chain;
251 uuid_t asserted_netagent;
252 };
253
254 struct necp_client_flow_header {
255 struct necp_tlv_header outer_header;
256 struct necp_tlv_header flags_tlv_header;
257 u_int32_t flags_value;
258 struct necp_tlv_header interface_tlv_header;
259 struct necp_client_result_interface interface_value;
260 } __attribute__((__packed__));
261
262 struct necp_client_flow_protoctl_event_header {
263 struct necp_tlv_header protoctl_tlv_header;
264 struct necp_client_flow_protoctl_event protoctl_event;
265 } __attribute__((__packed__));
266
267 struct necp_client_nexus_flow_header {
268 struct necp_client_flow_header flow_header;
269 struct necp_tlv_header agent_tlv_header;
270 struct necp_client_result_netagent agent_value;
271 struct necp_tlv_header tfo_cookie_tlv_header;
272 u_int8_t tfo_cookie_value[NECP_TFO_COOKIE_LEN_MAX];
273 } __attribute__((__packed__));
274
275 struct necp_client {
276 RB_ENTRY(necp_client) link;
277 RB_ENTRY(necp_client) global_link;
278 LIST_ENTRY(necp_client) collect_stats_chain;
279
280 decl_lck_mtx_data(, lock);
281 decl_lck_mtx_data(, route_lock);
282 uint32_t reference_count;
283
284 uuid_t client_id;
285 unsigned result_read : 1;
286 unsigned flow_result_read : 1;
287 unsigned allow_multiple_flows : 1;
288
289 unsigned defunct : 1;
290 unsigned background : 1;
291 unsigned background_update : 1;
292 unsigned platform_binary : 1;
293
294 size_t result_length;
295 u_int8_t result[NECP_MAX_CLIENT_RESULT_SIZE];
296
297 necp_policy_id policy_id;
298
299 u_int16_t ip_protocol;
300 int proc_pid;
301
302 LIST_HEAD(_necp_client_flow_list, necp_client_flow) flow_list;
303 LIST_HEAD(_necp_client_assertion_list, necp_client_assertion) assertion_list;
304
305 struct rtentry *current_route;
306
307 void *interface_handle;
308 void (*interface_cb)(void *handle, int action, struct necp_client_flow *flow);
309
310 size_t parameters_length;
311 u_int8_t parameters[0];
312 };
313
314 #define NECP_CLIENT_LOCK(_c) lck_mtx_lock(&_c->lock)
315 #define NECP_CLIENT_UNLOCK(_c) lck_mtx_unlock(&_c->lock)
316 #define NECP_CLIENT_ASSERT_LOCKED(_c) LCK_MTX_ASSERT(&_c->lock, LCK_MTX_ASSERT_OWNED)
317 #define NECP_CLIENT_ASSERT_UNLOCKED(_c) LCK_MTX_ASSERT(&_c->lock, LCK_MTX_ASSERT_NOTOWNED)
318
319 #define NECP_CLIENT_ROUTE_LOCK(_c) lck_mtx_lock(&_c->route_lock)
320 #define NECP_CLIENT_ROUTE_UNLOCK(_c) lck_mtx_unlock(&_c->route_lock)
321
322 static void necp_client_retain_locked(struct necp_client *client);
323 static void necp_client_retain(struct necp_client *client);
324 static bool necp_client_release_locked(struct necp_client *client);
325
326 static void
327 necp_client_add_assertion(struct necp_client *client, uuid_t netagent_uuid);
328
329 static bool
330 necp_client_remove_assertion(struct necp_client *client, uuid_t netagent_uuid);
331
332 LIST_HEAD(_necp_client_list, necp_client);
333 static struct _necp_client_list necp_collect_stats_client_list;
334
335 struct necp_client_defunct {
336 LIST_ENTRY(necp_client_defunct) chain;
337
338 uuid_t client_id;
339 uuid_t nexus_agent;
340 int proc_pid;
341 };
342
343 LIST_HEAD(_necp_client_defunct_list, necp_client_defunct);
344
345 static int necp_client_id_cmp(struct necp_client *client0, struct necp_client *client1);
346
347 RB_HEAD(_necp_client_tree, necp_client);
348 RB_PROTOTYPE_PREV(_necp_client_tree, necp_client, link, necp_client_id_cmp);
349 RB_GENERATE_PREV(_necp_client_tree, necp_client, link, necp_client_id_cmp);
350
351 RB_HEAD(_necp_client_global_tree, necp_client);
352 RB_PROTOTYPE_PREV(_necp_client_global_tree, necp_client, global_link, necp_client_id_cmp);
353 RB_GENERATE_PREV(_necp_client_global_tree, necp_client, global_link, necp_client_id_cmp);
354
355 static struct _necp_client_global_tree necp_client_global_tree;
356
357 struct necp_client_update {
358 TAILQ_ENTRY(necp_client_update) chain;
359
360 uuid_t client_id;
361
362 size_t update_length;
363 struct necp_client_observer_update update;
364 };
365
366 struct necp_fd_data {
367 u_int8_t necp_fd_type;
368 LIST_ENTRY(necp_fd_data) chain;
369 struct _necp_client_tree clients;
370 TAILQ_HEAD(_necp_client_update_list, necp_client_update) update_list;
371 int update_count;
372 int flags;
373 int proc_pid;
374 decl_lck_mtx_data(, fd_lock);
375 struct selinfo si;
376 };
377
378 #define NECP_FD_LOCK(_f) lck_mtx_lock(&_f->fd_lock)
379 #define NECP_FD_UNLOCK(_f) lck_mtx_unlock(&_f->fd_lock)
380 #define NECP_FD_ASSERT_LOCKED(_f) LCK_MTX_ASSERT(&_f->fd_lock, LCK_MTX_ASSERT_OWNED)
381 #define NECP_FD_ASSERT_UNLOCKED(_f) LCK_MTX_ASSERT(&_f->fd_lock, LCK_MTX_ASSERT_NOTOWNED)
382
383 static LIST_HEAD(_necp_fd_list, necp_fd_data) necp_fd_list;
384 static LIST_HEAD(_necp_fd_observer_list, necp_fd_data) necp_fd_observer_list;
385
386 #define NECP_CLIENT_FD_ZONE_MAX 128
387 #define NECP_CLIENT_FD_ZONE_NAME "necp.clientfd"
388
389 static unsigned int necp_client_fd_size; /* size of zone element */
390 static struct zone *necp_client_fd_zone; /* zone for necp_fd_data */
391
392 #define NECP_FLOW_ZONE_MAX 512
393 #define NECP_FLOW_ZONE_NAME "necp.flow"
394
395 static unsigned int necp_flow_size; /* size of zone element */
396 static struct zone *necp_flow_zone; /* zone for necp_client_flow */
397
398 static lck_grp_attr_t *necp_fd_grp_attr = NULL;
399 static lck_attr_t *necp_fd_mtx_attr = NULL;
400 static lck_grp_t *necp_fd_mtx_grp = NULL;
401
402 decl_lck_rw_data(static, necp_fd_lock);
403 decl_lck_rw_data(static, necp_observer_lock);
404 decl_lck_rw_data(static, necp_client_tree_lock);
405 decl_lck_rw_data(static, necp_collect_stats_list_lock);
406
407 #define NECP_STATS_LIST_LOCK_EXCLUSIVE() lck_rw_lock_exclusive(&necp_collect_stats_list_lock)
408 #define NECP_STATS_LIST_LOCK_SHARED() lck_rw_lock_shared(&necp_collect_stats_list_lock)
409 #define NECP_STATS_LIST_UNLOCK() lck_rw_done(&necp_collect_stats_list_lock)
410
411 #define NECP_CLIENT_TREE_LOCK_EXCLUSIVE() lck_rw_lock_exclusive(&necp_client_tree_lock)
412 #define NECP_CLIENT_TREE_LOCK_SHARED() lck_rw_lock_shared(&necp_client_tree_lock)
413 #define NECP_CLIENT_TREE_UNLOCK() lck_rw_done(&necp_client_tree_lock)
414
415 #define NECP_FD_LIST_LOCK_EXCLUSIVE() lck_rw_lock_exclusive(&necp_fd_lock)
416 #define NECP_FD_LIST_LOCK_SHARED() lck_rw_lock_shared(&necp_fd_lock)
417 #define NECP_FD_LIST_UNLOCK() lck_rw_done(&necp_fd_lock)
418
419 #define NECP_OBSERVER_LIST_LOCK_EXCLUSIVE() lck_rw_lock_exclusive(&necp_observer_lock)
420 #define NECP_OBSERVER_LIST_LOCK_SHARED() lck_rw_lock_shared(&necp_observer_lock)
421 #define NECP_OBSERVER_LIST_UNLOCK() lck_rw_done(&necp_observer_lock)
422
423 // Locking Notes
424
425 // Take NECP_FD_LIST_LOCK when accessing or modifying the necp_fd_list
426 // Take NECP_CLIENT_TREE_LOCK when accessing or modifying the necp_client_global_tree
427 // Take NECP_STATS_LIST_LOCK when accessing or modifying the necp_collect_stats_client_list
428 // Take NECP_FD_LOCK when accessing or modifying an necp_fd_data entry
429 // Take NECP_CLIENT_LOCK when accessing or modifying a single necp_client
430 // Take NECP_CLIENT_ROUTE_LOCK when accessing or modifying a client's route
431
432 // Precedence, where 1 is the first lock that must be taken
433 // 1. NECP_FD_LIST_LOCK
434 // 2. NECP_FD_LOCK (any)
435 // 3. NECP_CLIENT_TREE_LOCK
436 // 4. NECP_CLIENT_LOCK (any)
437 // 5. NECP_STATS_LIST_LOCK
438 // 6. NECP_CLIENT_ROUTE_LOCK (any)
439
440 static thread_call_t necp_client_update_tcall;
441
442
443 /// NECP file descriptor functions
444
445 static int
446 noop_read(struct fileproc *fp, struct uio *uio, int flags, vfs_context_t ctx)
447 {
448 #pragma unused(fp, uio, flags, ctx)
449 return (ENXIO);
450 }
451
452 static int
453 noop_write(struct fileproc *fp, struct uio *uio, int flags,
454 vfs_context_t ctx)
455 {
456 #pragma unused(fp, uio, flags, ctx)
457 return (ENXIO);
458 }
459
460 static int
461 noop_ioctl(struct fileproc *fp, unsigned long com, caddr_t data,
462 vfs_context_t ctx)
463 {
464 #pragma unused(fp, com, data, ctx)
465 return (ENOTTY);
466 }
467
468 static void
469 necp_fd_notify(struct necp_fd_data *fd_data, bool locked)
470 {
471 struct selinfo *si = &fd_data->si;
472
473 if (!locked) {
474 NECP_FD_LOCK(fd_data);
475 }
476
477 selwakeup(si);
478
479 // use a non-zero hint to tell the notification from the
480 // call done in kqueue_scan() which uses 0
481 KNOTE(&si->si_note, 1); // notification
482
483 if (!locked) {
484 NECP_FD_UNLOCK(fd_data);
485 }
486 }
487
488 static int
489 necp_fd_poll(struct necp_fd_data *fd_data, int events, void *wql, struct proc *p, int is_kevent)
490 {
491 #pragma unused(wql, p, is_kevent)
492 u_int revents = 0;
493
494 u_int want_rx = events & (POLLIN | POLLRDNORM);
495 if (want_rx) {
496 if (fd_data->flags & NECP_OPEN_FLAG_PUSH_OBSERVER) {
497 // Push-mode observers are readable when they have a new update
498 if (!TAILQ_EMPTY(&fd_data->update_list)) {
499 revents |= want_rx;
500 }
501 } else {
502 // Standard fds are readable when some client is unread
503 struct necp_client *client = NULL;
504 bool has_unread_clients = FALSE;
505 RB_FOREACH(client, _necp_client_tree, &fd_data->clients) {
506 NECP_CLIENT_LOCK(client);
507 if (!client->result_read || !client->flow_result_read) {
508 has_unread_clients = TRUE;
509 }
510 NECP_CLIENT_UNLOCK(client);
511 if (has_unread_clients) {
512 break;
513 }
514 }
515
516 if (has_unread_clients) {
517 revents |= want_rx;
518 }
519 }
520 }
521
522 return (revents);
523 }
524
525 static struct necp_client *
526 necp_client_fd_find_client_and_lock(struct necp_fd_data *client_fd, uuid_t client_id)
527 {
528 struct necp_client find;
529 NECP_FD_ASSERT_LOCKED(client_fd);
530 uuid_copy(find.client_id, client_id);
531 struct necp_client *client = RB_FIND(_necp_client_tree, &client_fd->clients, &find);
532
533 if (client != NULL) {
534 NECP_CLIENT_LOCK(client);
535 }
536
537 return (client);
538 }
539
540 static inline int
541 necp_client_id_cmp(struct necp_client *client0, struct necp_client *client1)
542 {
543 return (uuid_compare(client0->client_id, client1->client_id));
544 }
545
546 static int
547 necpop_select(struct fileproc *fp, int which, void *wql, vfs_context_t ctx)
548 {
549 #pragma unused(fp, which, wql, ctx)
550 return (0);
551 struct necp_fd_data *fd_data = NULL;
552 int revents = 0;
553 int events = 0;
554 proc_t procp;
555
556 fd_data = (struct necp_fd_data *)fp->f_fglob->fg_data;
557 if (fd_data == NULL) {
558 return (0);
559 }
560
561 procp = vfs_context_proc(ctx);
562
563 switch (which) {
564 case FREAD: {
565 events = POLLIN;
566 break;
567 }
568
569 default: {
570 return (1);
571 }
572 }
573
574 NECP_FD_LOCK(fd_data);
575 revents = necp_fd_poll(fd_data, events, wql, procp, 0);
576 NECP_FD_UNLOCK(fd_data);
577
578 return ((events & revents) ? 1 : 0);
579 }
580
581 static void
582 necp_fd_knrdetach(struct knote *kn)
583 {
584 struct necp_fd_data *fd_data = (struct necp_fd_data *)kn->kn_hook;
585 struct selinfo *si = &fd_data->si;
586
587 NECP_FD_LOCK(fd_data);
588 KNOTE_DETACH(&si->si_note, kn);
589 NECP_FD_UNLOCK(fd_data);
590 }
591
592 static int
593 necp_fd_knread(struct knote *kn, long hint)
594 {
595 #pragma unused(kn, hint)
596 return 1; /* assume we are ready */
597 }
598
599 static int
600 necp_fd_knrprocess(struct knote *kn, struct filt_process_s *data, struct kevent_internal_s *kev)
601 {
602 #pragma unused(data)
603 struct necp_fd_data *fd_data;
604 int revents;
605 int res;
606
607 fd_data = (struct necp_fd_data *)kn->kn_hook;
608
609 NECP_FD_LOCK(fd_data);
610 revents = necp_fd_poll(fd_data, POLLIN, NULL, current_proc(), 1);
611 res = ((revents & POLLIN) != 0);
612 if (res) {
613 *kev = kn->kn_kevent;
614 }
615 NECP_FD_UNLOCK(fd_data);
616 return (res);
617 }
618
619 static int
620 necp_fd_knrtouch(struct knote *kn, struct kevent_internal_s *kev)
621 {
622 #pragma unused(kev)
623 struct necp_fd_data *fd_data;
624 int revents;
625
626 fd_data = (struct necp_fd_data *)kn->kn_hook;
627
628 NECP_FD_LOCK(fd_data);
629 if ((kn->kn_status & KN_UDATA_SPECIFIC) == 0)
630 kn->kn_udata = kev->udata;
631 revents = necp_fd_poll(fd_data, POLLIN, NULL, current_proc(), 1);
632 NECP_FD_UNLOCK(fd_data);
633
634 return ((revents & POLLIN) != 0);
635 }
636
637 SECURITY_READ_ONLY_EARLY(struct filterops) necp_fd_rfiltops = {
638 .f_isfd = 1,
639 .f_detach = necp_fd_knrdetach,
640 .f_event = necp_fd_knread,
641 .f_touch = necp_fd_knrtouch,
642 .f_process = necp_fd_knrprocess,
643 };
644
645 static int
646 necpop_kqfilter(struct fileproc *fp, struct knote *kn,
647 __unused struct kevent_internal_s *kev, vfs_context_t ctx)
648 {
649 #pragma unused(fp, ctx)
650 struct necp_fd_data *fd_data = NULL;
651 int revents;
652
653 if (kn->kn_filter != EVFILT_READ) {
654 NECPLOG(LOG_ERR, "bad filter request %d", kn->kn_filter);
655 kn->kn_flags = EV_ERROR;
656 kn->kn_data = EINVAL;
657 return (0);
658 }
659
660 fd_data = (struct necp_fd_data *)kn->kn_fp->f_fglob->fg_data;
661 if (fd_data == NULL) {
662 NECPLOG0(LOG_ERR, "No channel for kqfilter");
663 kn->kn_flags = EV_ERROR;
664 kn->kn_data = ENOENT;
665 return (0);
666 }
667
668 NECP_FD_LOCK(fd_data);
669 kn->kn_filtid = EVFILTID_NECP_FD;
670 kn->kn_hook = fd_data;
671 KNOTE_ATTACH(&fd_data->si.si_note, kn);
672
673 revents = necp_fd_poll(fd_data, POLLIN, NULL, current_proc(), 1);
674
675 NECP_FD_UNLOCK(fd_data);
676
677 return ((revents & POLLIN) != 0);
678 }
679
680
681 static bool
682 necp_set_client_defunct(struct necp_client *client)
683 {
684 bool updated = FALSE;
685 u_int32_t flags = 0;
686 u_int32_t value_size = 0;
687
688 client->defunct = TRUE;
689
690 u_int8_t *flags_pointer = necp_buffer_get_tlv_value(client->result, 0, &value_size);
691 if (flags_pointer && value_size == sizeof(flags)) {
692 memcpy(&flags, flags_pointer, value_size);
693
694 flags |= NECP_CLIENT_RESULT_FLAG_DEFUNCT;
695
696 (void)necp_buffer_write_tlv_if_different(client->result, NECP_CLIENT_RESULT_FLAGS,
697 sizeof(flags), &flags, &updated, client->result, sizeof(client->result));
698 }
699
700 return (updated);
701 }
702
703 static void
704 necp_defunct_client_for_policy(struct necp_client *client,
705 struct _necp_client_defunct_list *defunct_list)
706 {
707 if (!client->defunct) {
708 bool needs_defunct = false;
709 struct necp_client_flow *search_flow = NULL;
710 LIST_FOREACH(search_flow, &client->flow_list, flow_chain) {
711 if (search_flow->nexus &&
712 !uuid_is_null(search_flow->u.nexus_agent) &&
713 search_flow->requested_nexus) {
714
715 // Save defunct values for the nexus
716 if (defunct_list != NULL) {
717 // Sleeping alloc won't fail; copy only what's necessary
718 struct necp_client_defunct *client_defunct = _MALLOC(sizeof (struct necp_client_defunct),
719 M_NECP, M_WAITOK | M_ZERO);
720 uuid_copy(client_defunct->nexus_agent, search_flow->u.nexus_agent);
721 uuid_copy(client_defunct->client_id, client->client_id);
722 client_defunct->proc_pid = client->proc_pid;
723
724 // Add to the list provided by caller
725 LIST_INSERT_HEAD(defunct_list, client_defunct, chain);
726 }
727
728 needs_defunct = true;
729 }
730 }
731
732 if (needs_defunct) {
733 // Only set defunct if there was some assigned flow
734 client->defunct = true;
735 }
736 }
737 }
738
739 static void
740 necp_client_free(struct necp_client *client)
741 {
742 NECP_CLIENT_ASSERT_LOCKED(client);
743
744 NECP_CLIENT_UNLOCK(client);
745
746 lck_mtx_destroy(&client->route_lock, necp_fd_mtx_grp);
747 lck_mtx_destroy(&client->lock, necp_fd_mtx_grp);
748
749 FREE(client, M_NECP);
750 }
751
752 static void
753 necp_client_retain_locked(struct necp_client *client)
754 {
755 NECP_CLIENT_ASSERT_LOCKED(client);
756
757 client->reference_count++;
758 ASSERT(client->reference_count != 0);
759 }
760
761 static void
762 necp_client_retain(struct necp_client *client)
763 {
764 NECP_CLIENT_LOCK(client);
765 necp_client_retain_locked(client);
766 NECP_CLIENT_UNLOCK(client);
767 }
768
769 static bool
770 necp_client_release_locked(struct necp_client *client)
771 {
772 NECP_CLIENT_ASSERT_LOCKED(client);
773
774 uint32_t old_ref = client->reference_count;
775
776 ASSERT(client->reference_count != 0);
777 if (--client->reference_count == 0) {
778 necp_client_free(client);
779 }
780
781 return (old_ref == 1);
782 }
783
784
785 static void
786 necp_client_update_observer_add_internal(struct necp_fd_data *observer_fd, struct necp_client *client)
787 {
788 NECP_FD_LOCK(observer_fd);
789
790 if (observer_fd->update_count >= necp_observer_message_limit) {
791 NECP_FD_UNLOCK(observer_fd);
792 return;
793 }
794
795 struct necp_client_update *client_update = _MALLOC(sizeof(struct necp_client_update) + client->parameters_length,
796 M_NECP, M_WAITOK | M_ZERO);
797 if (client_update != NULL) {
798 client_update->update_length = sizeof(struct necp_client_observer_update) + client->parameters_length;
799 uuid_copy(client_update->client_id, client->client_id);
800 client_update->update.update_type = NECP_CLIENT_UPDATE_TYPE_PARAMETERS;
801 memcpy(client_update->update.tlv_buffer, client->parameters, client->parameters_length);
802 TAILQ_INSERT_TAIL(&observer_fd->update_list, client_update, chain);
803 observer_fd->update_count++;
804
805 necp_fd_notify(observer_fd, true);
806 }
807
808 NECP_FD_UNLOCK(observer_fd);
809 }
810
811 static void
812 necp_client_update_observer_update_internal(struct necp_fd_data *observer_fd, struct necp_client *client)
813 {
814 NECP_FD_LOCK(observer_fd);
815
816 if (observer_fd->update_count >= necp_observer_message_limit) {
817 NECP_FD_UNLOCK(observer_fd);
818 return;
819 }
820
821 struct necp_client_update *client_update = _MALLOC(sizeof(struct necp_client_update) + client->result_length,
822 M_NECP, M_WAITOK | M_ZERO);
823 if (client_update != NULL) {
824 client_update->update_length = sizeof(struct necp_client_observer_update) + client->result_length;
825 uuid_copy(client_update->client_id, client->client_id);
826 client_update->update.update_type = NECP_CLIENT_UPDATE_TYPE_RESULT;
827 memcpy(client_update->update.tlv_buffer, client->result, client->result_length);
828 TAILQ_INSERT_TAIL(&observer_fd->update_list, client_update, chain);
829 observer_fd->update_count++;
830
831 necp_fd_notify(observer_fd, true);
832 }
833
834 NECP_FD_UNLOCK(observer_fd);
835 }
836
837 static void
838 necp_client_update_observer_remove_internal(struct necp_fd_data *observer_fd, struct necp_client *client)
839 {
840 NECP_FD_LOCK(observer_fd);
841
842 if (observer_fd->update_count >= necp_observer_message_limit) {
843 NECP_FD_UNLOCK(observer_fd);
844 return;
845 }
846
847 struct necp_client_update *client_update = _MALLOC(sizeof(struct necp_client_update),
848 M_NECP, M_WAITOK | M_ZERO);
849 if (client_update != NULL) {
850 client_update->update_length = sizeof(struct necp_client_observer_update);
851 uuid_copy(client_update->client_id, client->client_id);
852 client_update->update.update_type = NECP_CLIENT_UPDATE_TYPE_REMOVE;
853 TAILQ_INSERT_TAIL(&observer_fd->update_list, client_update, chain);
854 observer_fd->update_count++;
855
856 necp_fd_notify(observer_fd, true);
857 }
858
859 NECP_FD_UNLOCK(observer_fd);
860 }
861
862 static void
863 necp_client_update_observer_add(struct necp_client *client)
864 {
865 NECP_OBSERVER_LIST_LOCK_SHARED();
866
867 if (LIST_EMPTY(&necp_fd_observer_list)) {
868 // No observers, bail
869 NECP_OBSERVER_LIST_UNLOCK();
870 return;
871 }
872
873 struct necp_fd_data *observer_fd = NULL;
874 LIST_FOREACH(observer_fd, &necp_fd_observer_list, chain) {
875 necp_client_update_observer_add_internal(observer_fd, client);
876 }
877
878 NECP_OBSERVER_LIST_UNLOCK();
879 }
880
881 static void
882 necp_client_update_observer_update(struct necp_client *client)
883 {
884 NECP_OBSERVER_LIST_LOCK_SHARED();
885
886 if (LIST_EMPTY(&necp_fd_observer_list)) {
887 // No observers, bail
888 NECP_OBSERVER_LIST_UNLOCK();
889 return;
890 }
891
892 struct necp_fd_data *observer_fd = NULL;
893 LIST_FOREACH(observer_fd, &necp_fd_observer_list, chain) {
894 necp_client_update_observer_update_internal(observer_fd, client);
895 }
896
897 NECP_OBSERVER_LIST_UNLOCK();
898 }
899
900 static void
901 necp_client_update_observer_remove(struct necp_client *client)
902 {
903 NECP_OBSERVER_LIST_LOCK_SHARED();
904
905 if (LIST_EMPTY(&necp_fd_observer_list)) {
906 // No observers, bail
907 NECP_OBSERVER_LIST_UNLOCK();
908 return;
909 }
910
911 struct necp_fd_data *observer_fd = NULL;
912 LIST_FOREACH(observer_fd, &necp_fd_observer_list, chain) {
913 necp_client_update_observer_remove_internal(observer_fd, client);
914 }
915
916 NECP_OBSERVER_LIST_UNLOCK();
917 }
918
919 static void
920 necp_destroy_client(struct necp_client *client, pid_t pid, bool abort)
921 {
922 NECP_CLIENT_ASSERT_UNLOCKED(client);
923
924 necp_client_update_observer_remove(client);
925
926 NECP_CLIENT_LOCK(client);
927
928 // Free route
929 NECP_CLIENT_ROUTE_LOCK(client);
930 if (client->current_route != NULL) {
931 rtfree(client->current_route);
932 client->current_route = NULL;
933 }
934 NECP_CLIENT_ROUTE_UNLOCK(client);
935
936 // Remove flow assignments
937 struct necp_client_flow *search_flow = NULL;
938 struct necp_client_flow *temp_flow = NULL;
939 LIST_FOREACH_SAFE(search_flow, &client->flow_list, flow_chain, temp_flow) {
940 if (search_flow->nexus &&
941 !uuid_is_null(search_flow->u.nexus_agent) &&
942 search_flow->requested_nexus) {
943 // Note that if we had defuncted the client earlier, this would result in a harmless ENOENT
944 int netagent_error = netagent_client_message(search_flow->u.nexus_agent, client->client_id, pid,
945 abort ? NETAGENT_MESSAGE_TYPE_ABORT_NEXUS : NETAGENT_MESSAGE_TYPE_CLOSE_NEXUS);
946 if (netagent_error != 0 && netagent_error != ENOENT) {
947 NECPLOG(LOG_ERR, "necp_client_remove close nexus error (%d)", netagent_error);
948 }
949 uuid_clear(search_flow->u.nexus_agent);
950 }
951 if (search_flow->assigned_results != NULL) {
952 FREE(search_flow->assigned_results, M_NETAGENT);
953 search_flow->assigned_results = NULL;
954 }
955 LIST_REMOVE(search_flow, flow_chain);
956 if (search_flow->socket) {
957 OSDecrementAtomic(&necp_socket_flow_count);
958 } else {
959 OSDecrementAtomic(&necp_if_flow_count);
960 }
961 zfree(necp_flow_zone, search_flow);
962 }
963
964 // Remove agent assertions
965 struct necp_client_assertion *search_assertion = NULL;
966 struct necp_client_assertion *temp_assertion = NULL;
967 LIST_FOREACH_SAFE(search_assertion, &client->assertion_list, assertion_chain, temp_assertion) {
968 int netagent_error = netagent_client_message(search_assertion->asserted_netagent, client->client_id, pid, NETAGENT_MESSAGE_TYPE_CLIENT_UNASSERT);
969 if (netagent_error != 0) {
970 NECPLOG((netagent_error == ENOENT ? LOG_DEBUG : LOG_ERR),
971 "necp_client_remove unassert agent error (%d)", netagent_error);
972 }
973 LIST_REMOVE(search_assertion, assertion_chain);
974 FREE(search_assertion, M_NECP);
975 }
976
977 if (!necp_client_release_locked(client)) {
978 NECP_CLIENT_UNLOCK(client);
979 }
980
981 OSDecrementAtomic(&necp_client_count);
982 }
983
984 static int
985 necpop_close(struct fileglob *fg, vfs_context_t ctx)
986 {
987 #pragma unused(ctx)
988 struct necp_fd_data *fd_data = NULL;
989 int error = 0;
990
991 fd_data = (struct necp_fd_data *)fg->fg_data;
992 fg->fg_data = NULL;
993
994 if (fd_data != NULL) {
995 struct _necp_client_tree clients_to_close;
996 RB_INIT(&clients_to_close);
997
998 // Remove from list quickly
999 if (fd_data->flags & NECP_OPEN_FLAG_PUSH_OBSERVER) {
1000 NECP_OBSERVER_LIST_LOCK_EXCLUSIVE();
1001 LIST_REMOVE(fd_data, chain);
1002 NECP_OBSERVER_LIST_UNLOCK();
1003 } else {
1004 NECP_FD_LIST_LOCK_EXCLUSIVE();
1005 LIST_REMOVE(fd_data, chain);
1006 NECP_FD_LIST_UNLOCK();
1007 }
1008
1009 NECP_FD_LOCK(fd_data);
1010 pid_t pid = fd_data->proc_pid;
1011 struct necp_client *client = NULL;
1012 struct necp_client *temp_client = NULL;
1013 RB_FOREACH_SAFE(client, _necp_client_tree, &fd_data->clients, temp_client) {
1014 NECP_CLIENT_TREE_LOCK_EXCLUSIVE();
1015 RB_REMOVE(_necp_client_global_tree, &necp_client_global_tree, client);
1016 NECP_CLIENT_TREE_UNLOCK();
1017 RB_REMOVE(_necp_client_tree, &fd_data->clients, client);
1018 RB_INSERT(_necp_client_tree, &clients_to_close, client);
1019 }
1020
1021 struct necp_client_update *client_update = NULL;
1022 struct necp_client_update *temp_update = NULL;
1023 TAILQ_FOREACH_SAFE(client_update, &fd_data->update_list, chain, temp_update) {
1024 // Flush pending updates
1025 TAILQ_REMOVE(&fd_data->update_list, client_update, chain);
1026 FREE(client_update, M_NECP);
1027 }
1028 fd_data->update_count = 0;
1029
1030
1031 NECP_FD_UNLOCK(fd_data);
1032
1033 selthreadclear(&fd_data->si);
1034
1035 lck_mtx_destroy(&fd_data->fd_lock, necp_fd_mtx_grp);
1036
1037 if (fd_data->flags & NECP_OPEN_FLAG_PUSH_OBSERVER) {
1038 OSDecrementAtomic(&necp_observer_fd_count);
1039 } else {
1040 OSDecrementAtomic(&necp_client_fd_count);
1041 }
1042
1043 zfree(necp_client_fd_zone, fd_data);
1044 fd_data = NULL;
1045
1046 RB_FOREACH_SAFE(client, _necp_client_tree, &clients_to_close, temp_client) {
1047 RB_REMOVE(_necp_client_tree, &clients_to_close, client);
1048 necp_destroy_client(client, pid, true);
1049 }
1050 }
1051
1052 return (error);
1053 }
1054
1055 /// NECP client utilities
1056
1057 static inline bool
1058 necp_address_is_wildcard(const union necp_sockaddr_union * const addr)
1059 {
1060 return ((addr->sa.sa_family == AF_INET && addr->sin.sin_addr.s_addr == INADDR_ANY) ||
1061 (addr->sa.sa_family == AF_INET6 && IN6_IS_ADDR_UNSPECIFIED(&addr->sin6.sin6_addr)));
1062 }
1063
1064 static int
1065 necp_find_fd_data(int fd, struct necp_fd_data **fd_data)
1066 {
1067 proc_t p = current_proc();
1068 struct fileproc *fp = NULL;
1069 int error = 0;
1070
1071 proc_fdlock_spin(p);
1072 if ((error = fp_lookup(p, fd, &fp, 1)) != 0) {
1073 goto done;
1074 }
1075 if (fp->f_fglob->fg_ops->fo_type != DTYPE_NETPOLICY) {
1076 fp_drop(p, fd, fp, 1);
1077 error = ENODEV;
1078 goto done;
1079 }
1080 *fd_data = (struct necp_fd_data *)fp->f_fglob->fg_data;
1081
1082 done:
1083 proc_fdunlock(p);
1084 return (error);
1085 }
1086
1087
1088 static void
1089 necp_client_add_socket_flow(struct necp_client *client, struct inpcb *inp)
1090 {
1091 struct necp_client_flow *new_flow = zalloc(necp_flow_zone);
1092 if (new_flow == NULL) {
1093 NECPLOG0(LOG_ERR, "Failed to allocate socket flow");
1094 return;
1095 }
1096
1097 memset(new_flow, 0, sizeof(*new_flow));
1098
1099 new_flow->socket = TRUE;
1100 new_flow->u.socket_handle = inp;
1101 new_flow->u.cb = inp->necp_cb;
1102
1103 OSIncrementAtomic(&necp_socket_flow_count);
1104
1105 LIST_INSERT_HEAD(&client->flow_list, new_flow, flow_chain);
1106 }
1107
1108 static void
1109 necp_client_add_interface_flow(struct necp_client *client, uint32_t interface_index)
1110 {
1111 struct necp_client_flow *new_flow = zalloc(necp_flow_zone);
1112 if (new_flow == NULL) {
1113 NECPLOG0(LOG_ERR, "Failed to allocate interface flow");
1114 return;
1115 }
1116
1117 memset(new_flow, 0, sizeof(*new_flow));
1118
1119 // Neither nexus nor socket
1120 new_flow->interface_index = interface_index;
1121 new_flow->u.socket_handle = client->interface_handle;
1122 new_flow->u.cb = client->interface_cb;
1123
1124 OSIncrementAtomic(&necp_if_flow_count);
1125
1126 LIST_INSERT_HEAD(&client->flow_list, new_flow, flow_chain);
1127 }
1128
1129 static void
1130 necp_client_add_interface_flow_if_needed(struct necp_client *client, uint32_t interface_index)
1131 {
1132 if (!client->allow_multiple_flows ||
1133 interface_index == IFSCOPE_NONE) {
1134 // Interface not set, or client not allowed to use this mode
1135 return;
1136 }
1137
1138 struct necp_client_flow *flow = NULL;
1139 LIST_FOREACH(flow, &client->flow_list, flow_chain) {
1140 if (!flow->nexus && !flow->socket && flow->interface_index == interface_index) {
1141 // Already have the flow
1142 flow->invalid = FALSE;
1143
1144 flow->u.socket_handle = client->interface_handle;
1145 flow->u.cb = client->interface_cb;
1146 return;
1147 }
1148 }
1149
1150 necp_client_add_interface_flow(client, interface_index);
1151 }
1152
1153 static bool
1154 necp_client_flow_is_viable(proc_t proc, struct necp_client *client,
1155 struct necp_client_flow *flow)
1156 {
1157 struct necp_aggregate_result result;
1158 bool ignore_address = (client->allow_multiple_flows && !flow->nexus && !flow->socket);
1159
1160 flow->necp_flow_flags = 0;
1161 int error = necp_application_find_policy_match_internal(proc, client->parameters,
1162 (u_int32_t)client->parameters_length,
1163 &result, &flow->necp_flow_flags,
1164 flow->interface_index,
1165 &flow->local_addr, &flow->remote_addr, NULL, ignore_address);
1166
1167 return (error == 0 &&
1168 result.routed_interface_index != IFSCOPE_NONE &&
1169 result.routing_result != NECP_KERNEL_POLICY_RESULT_DROP);
1170 }
1171
1172 static bool
1173 necp_client_update_flows(proc_t proc, struct necp_client *client)
1174 {
1175 bool client_updated = FALSE;
1176 struct necp_client_flow *flow = NULL;
1177 struct necp_client_flow *temp_flow = NULL;
1178 LIST_FOREACH_SAFE(flow, &client->flow_list, flow_chain, temp_flow) {
1179 // Check policy result for flow
1180 int old_flags = flow->necp_flow_flags;
1181 bool viable = necp_client_flow_is_viable(proc, client, flow);
1182
1183 // TODO: Defunct nexus flows that are blocked by policy
1184
1185 if (flow->viable != viable) {
1186 flow->viable = viable;
1187 client_updated = TRUE;
1188 }
1189
1190 if ((old_flags & (NECP_CLIENT_RESULT_FLAG_HAS_IPV4 | NECP_CLIENT_RESULT_FLAG_HAS_IPV6)) !=
1191 (flow->necp_flow_flags & (NECP_CLIENT_RESULT_FLAG_HAS_IPV4 | NECP_CLIENT_RESULT_FLAG_HAS_IPV6))) {
1192 client_updated = TRUE;
1193 }
1194
1195 if (flow->viable && client_updated && (flow->socket || (!flow->socket && !flow->nexus)) && flow->u.cb) {
1196 flow->u.cb(flow->u.socket_handle, NECP_CLIENT_CBACTION_VIABLE, flow);
1197 }
1198
1199 if (!flow->viable || flow->invalid) {
1200 if (client_updated && (flow->socket || (!flow->socket && !flow->nexus)) && flow->u.cb) {
1201 flow->u.cb(flow->u.socket_handle, NECP_CLIENT_CBACTION_NONVIABLE, flow);
1202 }
1203 // The callback might change the viable-flag of the
1204 // flow depending on its policy. Thus, we need to
1205 // check again the flags after the callback.
1206 }
1207
1208
1209 // Handle flows that no longer match
1210 if (!flow->viable || flow->invalid) {
1211 // Drop them as long as they aren't assigned data
1212 if (!flow->requested_nexus && !flow->assigned) {
1213 if (flow->assigned_results != NULL) {
1214 FREE(flow->assigned_results, M_NETAGENT);
1215 flow->assigned_results = NULL;
1216 client_updated = TRUE;
1217 }
1218 LIST_REMOVE(flow, flow_chain);
1219 if (flow->socket) {
1220 OSDecrementAtomic(&necp_socket_flow_count);
1221 } else {
1222 OSDecrementAtomic(&necp_if_flow_count);
1223 }
1224 zfree(necp_flow_zone, flow);
1225 }
1226 }
1227 }
1228
1229 return (client_updated);
1230 }
1231
1232 static void
1233 necp_client_mark_all_nonsocket_flows_as_invalid(struct necp_client *client)
1234 {
1235 struct necp_client_flow *flow = NULL;
1236 LIST_FOREACH(flow, &client->flow_list, flow_chain) {
1237 if (!flow->socket) { // Socket flows are not marked as invalid
1238 flow->invalid = TRUE;
1239 }
1240 }
1241 }
1242
1243 static bool
1244 necp_netagent_applies_to_client(__unused struct necp_client *client,
1245 const struct necp_client_parsed_parameters *parameters,
1246 uuid_t netagent_uuid, bool allow_nexus,
1247 uint32_t interface_index, u_int16_t interface_flags)
1248 {
1249 #pragma unused(interface_index, interface_flags)
1250 bool applies = FALSE;
1251 u_int32_t flags = netagent_get_flags(netagent_uuid);
1252 if (!(flags & NETAGENT_FLAG_REGISTERED)) {
1253 // Unregistered agents never apply
1254 return (applies);
1255 }
1256
1257 if (!allow_nexus &&
1258 (flags & NETAGENT_FLAG_NEXUS_PROVIDER)) {
1259 // Hide nexus providers unless allowed
1260 // Direct interfaces and direct policies are allowed to use a nexus
1261 // Delegate interfaces or re-scoped interfaces are not allowed
1262 return (applies);
1263 }
1264
1265 if (flags & NETAGENT_FLAG_SPECIFIC_USE_ONLY) {
1266 // Specific use agents only apply when required
1267 bool required = FALSE;
1268 if (parameters != NULL) {
1269 // Check required agent UUIDs
1270 for (int i = 0; i < NECP_MAX_PARSED_PARAMETERS; i++) {
1271 if (uuid_is_null(parameters->required_netagents[i])) {
1272 break;
1273 }
1274 if (uuid_compare(parameters->required_netagents[i], netagent_uuid) == 0) {
1275 required = TRUE;
1276 break;
1277 }
1278 }
1279
1280 if (!required) {
1281 // Check required agent types
1282 bool fetched_type = FALSE;
1283 char netagent_domain[NETAGENT_DOMAINSIZE];
1284 char netagent_type[NETAGENT_TYPESIZE];
1285 memset(&netagent_domain, 0, NETAGENT_DOMAINSIZE);
1286 memset(&netagent_type, 0, NETAGENT_TYPESIZE);
1287
1288 for (int i = 0; i < NECP_MAX_PARSED_PARAMETERS; i++) {
1289 if (strlen(parameters->required_netagent_types[i].netagent_domain) == 0 ||
1290 strlen(parameters->required_netagent_types[i].netagent_type) == 0) {
1291 break;
1292 }
1293
1294 if (!fetched_type) {
1295 if (netagent_get_agent_domain_and_type(netagent_uuid, netagent_domain, netagent_type)) {
1296 fetched_type = TRUE;
1297 } else {
1298 break;
1299 }
1300 }
1301
1302 if ((strlen(parameters->required_netagent_types[i].netagent_domain) == 0 ||
1303 strncmp(netagent_domain, parameters->required_netagent_types[i].netagent_domain, NETAGENT_DOMAINSIZE) == 0) &&
1304 (strlen(parameters->required_netagent_types[i].netagent_type) == 0 ||
1305 strncmp(netagent_type, parameters->required_netagent_types[i].netagent_type, NETAGENT_TYPESIZE) == 0)) {
1306 required = TRUE;
1307 break;
1308 }
1309 }
1310 }
1311 }
1312
1313 applies = required;
1314 } else {
1315 applies = TRUE;
1316 }
1317
1318
1319 return (applies);
1320 }
1321
1322 static void
1323 necp_client_add_agent_flows_for_interface(struct necp_client *client,
1324 const struct necp_client_parsed_parameters *parsed_parameters,
1325 ifnet_t ifp)
1326 {
1327 if (ifp != NULL && ifp->if_agentids != NULL) {
1328 for (u_int32_t i = 0; i < ifp->if_agentcount; i++) {
1329 if (uuid_is_null(ifp->if_agentids[i])) {
1330 continue;
1331 }
1332 u_int16_t if_flags = nstat_ifnet_to_flags(ifp);
1333 // Relies on the side effect that nexus agents that apply will create flows
1334 (void)necp_netagent_applies_to_client(client, parsed_parameters, ifp->if_agentids[i], TRUE, ifp->if_index, if_flags);
1335 }
1336 }
1337 }
1338
1339 static inline bool
1340 necp_client_address_is_valid(struct sockaddr *address)
1341 {
1342 if (address->sa_family == AF_INET) {
1343 return (address->sa_len == sizeof(struct sockaddr_in));
1344 } else if (address->sa_family == AF_INET6) {
1345 return (address->sa_len == sizeof(struct sockaddr_in6));
1346 } else {
1347 return (FALSE);
1348 }
1349 }
1350
1351 static int
1352 necp_client_parse_parameters(u_int8_t *parameters,
1353 u_int32_t parameters_size,
1354 struct necp_client_parsed_parameters *parsed_parameters)
1355 {
1356 int error = 0;
1357 size_t offset = 0;
1358
1359 u_int32_t num_prohibited_interfaces = 0;
1360 u_int32_t num_prohibited_interface_types = 0;
1361 u_int32_t num_required_agents = 0;
1362 u_int32_t num_prohibited_agents = 0;
1363 u_int32_t num_preferred_agents = 0;
1364 u_int32_t num_required_agent_types = 0;
1365 u_int32_t num_prohibited_agent_types = 0;
1366 u_int32_t num_preferred_agent_types = 0;
1367
1368 if (parsed_parameters == NULL) {
1369 return (EINVAL);
1370 }
1371
1372 memset(parsed_parameters, 0, sizeof(struct necp_client_parsed_parameters));
1373
1374 while ((offset + sizeof(struct necp_tlv_header)) <= parameters_size) {
1375 u_int8_t type = necp_buffer_get_tlv_type(parameters, offset);
1376 u_int32_t length = necp_buffer_get_tlv_length(parameters, offset);
1377
1378 if (length > (parameters_size - (offset + sizeof(struct necp_tlv_header)))) {
1379 // If the length is larger than what can fit in the remaining parameters size, bail
1380 NECPLOG(LOG_ERR, "Invalid TLV length (%u)", length);
1381 break;
1382 }
1383
1384 if (length > 0) {
1385 u_int8_t *value = necp_buffer_get_tlv_value(parameters, offset, NULL);
1386 if (value != NULL) {
1387 switch (type) {
1388 case NECP_CLIENT_PARAMETER_BOUND_INTERFACE: {
1389 if (length <= IFXNAMSIZ && length > 0) {
1390 ifnet_t bound_interface = NULL;
1391 char interface_name[IFXNAMSIZ];
1392 memcpy(interface_name, value, length);
1393 interface_name[length - 1] = 0; // Make sure the string is NULL terminated
1394 if (ifnet_find_by_name(interface_name, &bound_interface) == 0) {
1395 parsed_parameters->required_interface_index = bound_interface->if_index;
1396 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IF;
1397 ifnet_release(bound_interface);
1398 }
1399 }
1400 break;
1401 }
1402 case NECP_CLIENT_PARAMETER_LOCAL_ADDRESS: {
1403 if (length >= sizeof(struct necp_policy_condition_addr)) {
1404 struct necp_policy_condition_addr *address_struct = (struct necp_policy_condition_addr *)(void *)value;
1405 if (necp_client_address_is_valid(&address_struct->address.sa)) {
1406 memcpy(&parsed_parameters->local_addr, &address_struct->address, sizeof(address_struct->address));
1407 if (!necp_address_is_wildcard(&parsed_parameters->local_addr)) {
1408 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR;
1409 }
1410 if ((parsed_parameters->local_addr.sa.sa_family == AF_INET && parsed_parameters->local_addr.sin.sin_port) ||
1411 (parsed_parameters->local_addr.sa.sa_family == AF_INET6 && parsed_parameters->local_addr.sin6.sin6_port)) {
1412 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_LOCAL_PORT;
1413 }
1414 }
1415 }
1416 break;
1417 }
1418 case NECP_CLIENT_PARAMETER_LOCAL_ENDPOINT: {
1419 if (length >= sizeof(struct necp_client_endpoint)) {
1420 struct necp_client_endpoint *endpoint = (struct necp_client_endpoint *)(void *)value;
1421 if (necp_client_address_is_valid(&endpoint->u.sa)) {
1422 memcpy(&parsed_parameters->local_addr, &endpoint->u.sa, sizeof(union necp_sockaddr_union));
1423 if (!necp_address_is_wildcard(&parsed_parameters->local_addr)) {
1424 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR;
1425 }
1426 if ((parsed_parameters->local_addr.sa.sa_family == AF_INET && parsed_parameters->local_addr.sin.sin_port) ||
1427 (parsed_parameters->local_addr.sa.sa_family == AF_INET6 && parsed_parameters->local_addr.sin6.sin6_port)) {
1428 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_LOCAL_PORT;
1429 }
1430 }
1431 }
1432 break;
1433 }
1434 case NECP_CLIENT_PARAMETER_REMOTE_ADDRESS: {
1435 if (length >= sizeof(struct necp_policy_condition_addr)) {
1436 struct necp_policy_condition_addr *address_struct = (struct necp_policy_condition_addr *)(void *)value;
1437 if (necp_client_address_is_valid(&address_struct->address.sa)) {
1438 memcpy(&parsed_parameters->remote_addr, &address_struct->address, sizeof(address_struct->address));
1439 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REMOTE_ADDR;
1440 }
1441 }
1442 break;
1443 }
1444 case NECP_CLIENT_PARAMETER_REMOTE_ENDPOINT: {
1445 if (length >= sizeof(struct necp_client_endpoint)) {
1446 struct necp_client_endpoint *endpoint = (struct necp_client_endpoint *)(void *)value;
1447 if (necp_client_address_is_valid(&endpoint->u.sa)) {
1448 memcpy(&parsed_parameters->remote_addr, &endpoint->u.sa, sizeof(union necp_sockaddr_union));
1449 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REMOTE_ADDR;
1450 }
1451 }
1452 break;
1453 }
1454 case NECP_CLIENT_PARAMETER_PROHIBIT_INTERFACE: {
1455 if (num_prohibited_interfaces >= NECP_MAX_PARSED_PARAMETERS) {
1456 break;
1457 }
1458 if (length <= IFXNAMSIZ && length > 0) {
1459 memcpy(parsed_parameters->prohibited_interfaces[num_prohibited_interfaces], value, length);
1460 parsed_parameters->prohibited_interfaces[num_prohibited_interfaces][length - 1] = 0; // Make sure the string is NULL terminated
1461 num_prohibited_interfaces++;
1462 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IF;
1463 }
1464 break;
1465 }
1466 case NECP_CLIENT_PARAMETER_REQUIRE_IF_TYPE: {
1467 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE) {
1468 break;
1469 }
1470 if (length >= sizeof(u_int8_t)) {
1471 memcpy(&parsed_parameters->required_interface_type, value, sizeof(u_int8_t));
1472 if (parsed_parameters->required_interface_type) {
1473 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE;
1474 }
1475 }
1476 break;
1477 }
1478 case NECP_CLIENT_PARAMETER_PROHIBIT_IF_TYPE: {
1479 if (num_prohibited_interface_types >= NECP_MAX_PARSED_PARAMETERS) {
1480 break;
1481 }
1482 if (length >= sizeof(u_int8_t)) {
1483 memcpy(&parsed_parameters->prohibited_interface_types[num_prohibited_interface_types], value, sizeof(u_int8_t));
1484 num_prohibited_interface_types++;
1485 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IFTYPE;
1486 }
1487 break;
1488 }
1489 case NECP_CLIENT_PARAMETER_REQUIRE_AGENT: {
1490 if (num_required_agents >= NECP_MAX_PARSED_PARAMETERS) {
1491 break;
1492 }
1493 if (length >= sizeof(uuid_t)) {
1494 memcpy(&parsed_parameters->required_netagents[num_required_agents], value, sizeof(uuid_t));
1495 num_required_agents++;
1496 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT;
1497 }
1498 break;
1499 }
1500 case NECP_CLIENT_PARAMETER_PROHIBIT_AGENT: {
1501 if (num_prohibited_agents >= NECP_MAX_PARSED_PARAMETERS) {
1502 break;
1503 }
1504 if (length >= sizeof(uuid_t)) {
1505 memcpy(&parsed_parameters->prohibited_netagents[num_prohibited_agents], value, sizeof(uuid_t));
1506 num_prohibited_agents++;
1507 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT;
1508 }
1509 break;
1510 }
1511 case NECP_CLIENT_PARAMETER_PREFER_AGENT: {
1512 if (num_preferred_agents >= NECP_MAX_PARSED_PARAMETERS) {
1513 break;
1514 }
1515 if (length >= sizeof(uuid_t)) {
1516 memcpy(&parsed_parameters->preferred_netagents[num_preferred_agents], value, sizeof(uuid_t));
1517 num_preferred_agents++;
1518 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT;
1519 }
1520 break;
1521 }
1522 case NECP_CLIENT_PARAMETER_REQUIRE_AGENT_TYPE: {
1523 if (num_required_agent_types >= NECP_MAX_PARSED_PARAMETERS) {
1524 break;
1525 }
1526 if (length >= sizeof(struct necp_client_parameter_netagent_type)) {
1527 memcpy(&parsed_parameters->required_netagent_types[num_required_agent_types], value, sizeof(struct necp_client_parameter_netagent_type));
1528 num_required_agent_types++;
1529 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE;
1530 }
1531 break;
1532 }
1533 case NECP_CLIENT_PARAMETER_PROHIBIT_AGENT_TYPE: {
1534 if (num_prohibited_agent_types >= NECP_MAX_PARSED_PARAMETERS) {
1535 break;
1536 }
1537 if (length >= sizeof(struct necp_client_parameter_netagent_type)) {
1538 memcpy(&parsed_parameters->prohibited_netagent_types[num_prohibited_agent_types], value, sizeof(struct necp_client_parameter_netagent_type));
1539 num_prohibited_agent_types++;
1540 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT_TYPE;
1541 }
1542 break;
1543 }
1544 case NECP_CLIENT_PARAMETER_PREFER_AGENT_TYPE: {
1545 if (num_preferred_agent_types >= NECP_MAX_PARSED_PARAMETERS) {
1546 break;
1547 }
1548 if (length >= sizeof(struct necp_client_parameter_netagent_type)) {
1549 memcpy(&parsed_parameters->preferred_netagent_types[num_preferred_agent_types], value, sizeof(struct necp_client_parameter_netagent_type));
1550 num_preferred_agent_types++;
1551 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT_TYPE;
1552 }
1553 break;
1554 }
1555 case NECP_CLIENT_PARAMETER_FLAGS: {
1556 if (length >= sizeof(u_int32_t)) {
1557 memcpy(&parsed_parameters->flags, value, sizeof(parsed_parameters->flags));
1558 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_FLAGS;
1559 }
1560 break;
1561 }
1562 case NECP_CLIENT_PARAMETER_IP_PROTOCOL: {
1563 if (length >= sizeof(parsed_parameters->ip_protocol)) {
1564 memcpy(&parsed_parameters->ip_protocol, value, sizeof(parsed_parameters->ip_protocol));
1565 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_IP_PROTOCOL;
1566 }
1567 break;
1568 }
1569 case NECP_CLIENT_PARAMETER_PID: {
1570 if (length >= sizeof(parsed_parameters->effective_pid)) {
1571 memcpy(&parsed_parameters->effective_pid, value, sizeof(parsed_parameters->effective_pid));
1572 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_EFFECTIVE_PID;
1573 }
1574 break;
1575 }
1576 case NECP_CLIENT_PARAMETER_APPLICATION: {
1577 if (length >= sizeof(parsed_parameters->effective_uuid)) {
1578 memcpy(&parsed_parameters->effective_uuid, value, sizeof(parsed_parameters->effective_uuid));
1579 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_EFFECTIVE_UUID;
1580 }
1581 break;
1582 }
1583 case NECP_CLIENT_PARAMETER_TRAFFIC_CLASS: {
1584 if (length >= sizeof(parsed_parameters->traffic_class)) {
1585 memcpy(&parsed_parameters->traffic_class, value, sizeof(parsed_parameters->traffic_class));
1586 parsed_parameters->valid_fields |= NECP_PARSED_PARAMETERS_FIELD_TRAFFIC_CLASS;
1587 }
1588 break;
1589 }
1590 default: {
1591 break;
1592 }
1593 }
1594 }
1595 }
1596
1597 offset += sizeof(struct necp_tlv_header) + length;
1598 }
1599
1600 return (error);
1601 }
1602
1603 static int
1604 necp_client_parse_result(u_int8_t *result,
1605 u_int32_t result_size,
1606 union necp_sockaddr_union *local_address,
1607 union necp_sockaddr_union *remote_address)
1608 {
1609 int error = 0;
1610 size_t offset = 0;
1611
1612 while ((offset + sizeof(struct necp_tlv_header)) <= result_size) {
1613 u_int8_t type = necp_buffer_get_tlv_type(result, offset);
1614 u_int32_t length = necp_buffer_get_tlv_length(result, offset);
1615
1616 if (length > 0 && (offset + sizeof(struct necp_tlv_header) + length) <= result_size) {
1617 u_int8_t *value = necp_buffer_get_tlv_value(result, offset, NULL);
1618 if (value != NULL) {
1619 switch (type) {
1620 case NECP_CLIENT_RESULT_LOCAL_ENDPOINT: {
1621 if (length >= sizeof(struct necp_client_endpoint)) {
1622 struct necp_client_endpoint *endpoint = (struct necp_client_endpoint *)(void *)value;
1623 if (local_address != NULL && necp_client_address_is_valid(&endpoint->u.sa)) {
1624 memcpy(local_address, &endpoint->u.sa, endpoint->u.sa.sa_len);
1625 }
1626 }
1627 break;
1628 }
1629 case NECP_CLIENT_RESULT_REMOTE_ENDPOINT: {
1630 if (length >= sizeof(struct necp_client_endpoint)) {
1631 struct necp_client_endpoint *endpoint = (struct necp_client_endpoint *)(void *)value;
1632 if (remote_address != NULL && necp_client_address_is_valid(&endpoint->u.sa)) {
1633 memcpy(remote_address, &endpoint->u.sa, endpoint->u.sa.sa_len);
1634 }
1635 }
1636 break;
1637 }
1638 default: {
1639 break;
1640 }
1641 }
1642 }
1643 }
1644
1645 offset += sizeof(struct necp_tlv_header) + length;
1646 }
1647
1648 return (error);
1649 }
1650
1651 int
1652 necp_client_register_socket_flow(pid_t pid, uuid_t client_id, struct inpcb *inp)
1653 {
1654 int error = 0;
1655 bool found_client = FALSE;
1656
1657 NECP_CLIENT_TREE_LOCK_SHARED();
1658
1659 struct necp_client find;
1660 uuid_copy(find.client_id, client_id);
1661 struct necp_client *client = RB_FIND(_necp_client_global_tree, &necp_client_global_tree, &find);
1662 if (client != NULL) {
1663 NECP_CLIENT_LOCK(client);
1664
1665 if (!pid || client->proc_pid == pid) {
1666 // Found the right client!
1667 found_client = TRUE;
1668 necp_client_add_socket_flow(client, inp);
1669 }
1670
1671 NECP_CLIENT_UNLOCK(client);
1672 }
1673
1674 NECP_CLIENT_TREE_UNLOCK();
1675
1676 if (!found_client) {
1677 error = ENOENT;
1678 } else {
1679 /*
1680 * Count the sockets that have the NECP client UUID set
1681 */
1682 struct socket *so = inp->inp_socket;
1683 if (!(so->so_flags1 & SOF1_HAS_NECP_CLIENT_UUID)) {
1684 so->so_flags1 |= SOF1_HAS_NECP_CLIENT_UUID;
1685 INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_necp_clientuuid_total);
1686 }
1687 }
1688
1689 return (error);
1690 }
1691
1692 static void
1693 necp_client_add_multipath_cb(struct necp_client *client, struct mppcb *mpp)
1694 {
1695 struct necp_client_flow *flow = NULL;
1696
1697 client->interface_handle = mpp;
1698 client->interface_cb = mpp->necp_cb;
1699
1700 LIST_FOREACH(flow, &client->flow_list, flow_chain) {
1701 if (flow->nexus || flow->socket) {
1702 continue;
1703 }
1704
1705 flow->u.socket_handle = mpp;
1706 flow->u.cb = mpp->necp_cb;
1707
1708 if (flow->viable && flow->u.cb) {
1709 flow->u.cb(mpp, NECP_CLIENT_CBACTION_INITIAL, flow);
1710 }
1711 }
1712 }
1713
1714 int
1715 necp_client_register_multipath_cb(pid_t pid, uuid_t client_id, struct mppcb *mpp)
1716 {
1717 int error = 0;
1718 bool found_client = FALSE;
1719
1720 NECP_CLIENT_TREE_LOCK_SHARED();
1721
1722 struct necp_client find;
1723 uuid_copy(find.client_id, client_id);
1724 struct necp_client *client = RB_FIND(_necp_client_global_tree, &necp_client_global_tree, &find);
1725 if (client != NULL) {
1726 NECP_CLIENT_LOCK(client);
1727
1728 if (!pid || client->proc_pid == pid) {
1729 // Found the right client!
1730 found_client = TRUE;
1731 necp_client_add_multipath_cb(client, mpp);
1732 }
1733
1734 NECP_CLIENT_UNLOCK(client);
1735 }
1736
1737 NECP_CLIENT_TREE_UNLOCK();
1738
1739 if (!found_client) {
1740 error = ENOENT;
1741 }
1742
1743 return (error);
1744 }
1745
1746 #define NETAGENT_DOMAIN_NETEXT "NetworkExtension"
1747 #define NETAGENT_TYPE_PATHCTRL "PathController"
1748
1749 static int
1750 necp_client_unregister_socket_flow(uuid_t client_id, void *handle)
1751 {
1752 int error = 0;
1753 struct necp_fd_data *client_fd = NULL;
1754 bool found_client = FALSE;
1755 bool client_updated = FALSE;
1756
1757 NECP_FD_LIST_LOCK_SHARED();
1758 LIST_FOREACH(client_fd, &necp_fd_list, chain) {
1759 NECP_FD_LOCK(client_fd);
1760
1761 struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
1762 if (client != NULL) {
1763 // Found the right client!
1764 found_client = TRUE;
1765
1766 // Remove flow assignment
1767 struct necp_client_flow *search_flow = NULL;
1768 struct necp_client_flow *temp_flow = NULL;
1769 LIST_FOREACH_SAFE(search_flow, &client->flow_list, flow_chain, temp_flow) {
1770 if (search_flow->socket && search_flow->u.socket_handle == handle) {
1771 if (search_flow->assigned_results != NULL) {
1772 FREE(search_flow->assigned_results, M_NETAGENT);
1773 search_flow->assigned_results = NULL;
1774 }
1775 client_updated = TRUE;
1776 LIST_REMOVE(search_flow, flow_chain);
1777 OSDecrementAtomic(&necp_socket_flow_count);
1778 zfree(necp_flow_zone, search_flow);
1779 }
1780 }
1781
1782 NECP_CLIENT_UNLOCK(client);
1783 }
1784
1785 if (client_updated) {
1786 client->flow_result_read = FALSE;
1787 necp_fd_notify(client_fd, true);
1788 }
1789 NECP_FD_UNLOCK(client_fd);
1790
1791 if (found_client) {
1792 break;
1793 }
1794 }
1795 NECP_FD_LIST_UNLOCK();
1796
1797 if (!found_client) {
1798 error = ENOENT;
1799 }
1800
1801 return (error);
1802 }
1803
1804 static int
1805 necp_client_unregister_multipath_cb(uuid_t client_id, void *handle)
1806 {
1807 int error = 0;
1808 bool found_client = FALSE;
1809
1810 NECP_CLIENT_TREE_LOCK_SHARED();
1811
1812 struct necp_client find;
1813 uuid_copy(find.client_id, client_id);
1814 struct necp_client *client = RB_FIND(_necp_client_global_tree, &necp_client_global_tree, &find);
1815 if (client != NULL) {
1816 NECP_CLIENT_LOCK(client);
1817
1818 // Found the right client!
1819 found_client = TRUE;
1820
1821 // Remove flow assignment
1822 struct necp_client_flow *search_flow = NULL;
1823 struct necp_client_flow *temp_flow = NULL;
1824 LIST_FOREACH_SAFE(search_flow, &client->flow_list, flow_chain, temp_flow) {
1825 if (!search_flow->socket && !search_flow->nexus &&
1826 search_flow->u.socket_handle == handle) {
1827 search_flow->u.socket_handle = NULL;
1828 search_flow->u.cb = NULL;
1829 }
1830 }
1831
1832 client->interface_handle = NULL;
1833 client->interface_cb = NULL;
1834
1835 NECP_CLIENT_UNLOCK(client);
1836 }
1837
1838 NECP_CLIENT_TREE_UNLOCK();
1839
1840 if (!found_client) {
1841 error = ENOENT;
1842 }
1843
1844 return (error);
1845 }
1846
1847 int
1848 necp_client_assign_from_socket(pid_t pid, uuid_t client_id, struct inpcb *inp)
1849 {
1850 int error = 0;
1851 struct necp_fd_data *client_fd = NULL;
1852 bool found_client = FALSE;
1853 bool client_updated = FALSE;
1854
1855 NECP_FD_LIST_LOCK_SHARED();
1856 LIST_FOREACH(client_fd, &necp_fd_list, chain) {
1857 if (pid && client_fd->proc_pid != pid) {
1858 continue;
1859 }
1860
1861 proc_t proc = proc_find(client_fd->proc_pid);
1862 if (proc == PROC_NULL) {
1863 continue;
1864 }
1865
1866 NECP_FD_LOCK(client_fd);
1867
1868 struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
1869 if (client != NULL) {
1870 // Found the right client!
1871 found_client = TRUE;
1872
1873 struct necp_client_flow *flow = NULL;
1874 LIST_FOREACH(flow, &client->flow_list, flow_chain) {
1875 if (flow->socket && flow->u.socket_handle == inp) {
1876 // Release prior results and route
1877 if (flow->assigned_results != NULL) {
1878 FREE(flow->assigned_results, M_NETAGENT);
1879 flow->assigned_results = NULL;
1880 }
1881
1882 ifnet_t ifp = NULL;
1883 if ((inp->inp_flags & INP_BOUND_IF) && inp->inp_boundifp) {
1884 ifp = inp->inp_boundifp;
1885 } else {
1886 ifp = inp->inp_last_outifp;
1887 }
1888
1889 if (ifp != NULL) {
1890 flow->interface_index = ifp->if_index;
1891 } else {
1892 flow->interface_index = IFSCOPE_NONE;
1893 }
1894
1895 if (inp->inp_vflag & INP_IPV4) {
1896 flow->local_addr.sin.sin_family = AF_INET;
1897 flow->local_addr.sin.sin_len = sizeof(struct sockaddr_in);
1898 flow->local_addr.sin.sin_port = inp->inp_lport;
1899 memcpy(&flow->local_addr.sin.sin_addr, &inp->inp_laddr, sizeof(struct in_addr));
1900
1901 flow->remote_addr.sin.sin_family = AF_INET;
1902 flow->remote_addr.sin.sin_len = sizeof(struct sockaddr_in);
1903 flow->remote_addr.sin.sin_port = inp->inp_fport;
1904 memcpy(&flow->remote_addr.sin.sin_addr, &inp->inp_faddr, sizeof(struct in_addr));
1905 } else if (inp->inp_vflag & INP_IPV6) {
1906 in6_ip6_to_sockaddr(&inp->in6p_laddr, inp->inp_lport, &flow->local_addr.sin6, sizeof(flow->local_addr));
1907 in6_ip6_to_sockaddr(&inp->in6p_faddr, inp->inp_fport, &flow->remote_addr.sin6, sizeof(flow->remote_addr));
1908 }
1909
1910 flow->viable = necp_client_flow_is_viable(proc, client, flow);
1911
1912 uuid_t empty_uuid;
1913 uuid_clear(empty_uuid);
1914 flow->assigned = TRUE;
1915 flow->assigned_results = necp_create_nexus_assign_message(empty_uuid, 0, NULL, 0,
1916 (struct necp_client_endpoint *)&flow->local_addr,
1917 (struct necp_client_endpoint *)&flow->remote_addr,
1918 0, &flow->assigned_results_length);
1919 client->flow_result_read = FALSE;
1920 client_updated = TRUE;
1921 break;
1922 }
1923 }
1924
1925 NECP_CLIENT_UNLOCK(client);
1926 }
1927 if (client_updated) {
1928 necp_fd_notify(client_fd, true);
1929 }
1930 NECP_FD_UNLOCK(client_fd);
1931
1932 proc_rele(proc);
1933 proc = PROC_NULL;
1934
1935 if (found_client) {
1936 break;
1937 }
1938 }
1939 NECP_FD_LIST_UNLOCK();
1940
1941 if (!found_client) {
1942 error = ENOENT;
1943 } else if (!client_updated) {
1944 error = EINVAL;
1945 }
1946
1947 return (error);
1948 }
1949
1950 int
1951 necp_update_flow_protoctl_event(uuid_t netagent_uuid, uuid_t client_id,
1952 uint32_t protoctl_event_code, uint32_t protoctl_event_val,
1953 uint32_t protoctl_event_tcp_seq_number)
1954 {
1955 int error = 0;
1956 struct necp_fd_data *client_fd = NULL;
1957 bool found_client = FALSE;
1958 bool client_updated = FALSE;
1959
1960 NECP_FD_LIST_LOCK_SHARED();
1961 LIST_FOREACH(client_fd, &necp_fd_list, chain) {
1962 proc_t proc = proc_find(client_fd->proc_pid);
1963 if (proc == PROC_NULL) {
1964 continue;
1965 }
1966
1967 NECP_FD_LOCK(client_fd);
1968
1969 struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
1970 if (client != NULL) {
1971 /* Found the right client! */
1972 found_client = TRUE;
1973
1974 struct necp_client_flow *flow = NULL;
1975 LIST_FOREACH(flow, &client->flow_list, flow_chain) {
1976 // Verify that the client nexus agent matches
1977 if (flow->nexus &&
1978 uuid_compare(flow->u.nexus_agent,
1979 netagent_uuid) == 0) {
1980 flow->has_protoctl_event = TRUE;
1981 flow->protoctl_event.protoctl_event_code = protoctl_event_code;
1982 flow->protoctl_event.protoctl_event_val = protoctl_event_val;
1983 flow->protoctl_event.protoctl_event_tcp_seq_num = protoctl_event_tcp_seq_number;
1984 client->flow_result_read = FALSE;
1985 client_updated = TRUE;
1986 break;
1987 }
1988 }
1989
1990 NECP_CLIENT_UNLOCK(client);
1991 }
1992
1993 if (client_updated) {
1994 necp_fd_notify(client_fd, true);
1995 }
1996
1997 NECP_FD_UNLOCK(client_fd);
1998 proc_rele(proc);
1999 proc = PROC_NULL;
2000
2001 if (found_client) {
2002 break;
2003 }
2004 }
2005 NECP_FD_LIST_UNLOCK();
2006
2007 if (!found_client) {
2008 error = ENOENT;
2009 } else if (!client_updated) {
2010 error = EINVAL;
2011 }
2012 return (error);
2013 }
2014
2015 static bool
2016 necp_assign_client_result_locked(struct proc *proc, struct necp_fd_data *client_fd, struct necp_client *client, uuid_t netagent_uuid, u_int8_t *assigned_results, size_t assigned_results_length)
2017 {
2018 bool client_updated = FALSE;
2019
2020 NECP_FD_ASSERT_LOCKED(client_fd);
2021 NECP_CLIENT_ASSERT_LOCKED(client);
2022
2023 struct necp_client_flow *flow = NULL;
2024 LIST_FOREACH(flow, &client->flow_list, flow_chain) {
2025 // Verify that the client nexus agent matches
2026 if (flow->nexus &&
2027 uuid_compare(flow->u.nexus_agent, netagent_uuid) == 0) {
2028 // Release prior results and route
2029 if (flow->assigned_results != NULL) {
2030 FREE(flow->assigned_results, M_NETAGENT);
2031 flow->assigned_results = NULL;
2032 }
2033
2034 if (assigned_results != NULL && assigned_results_length > 0) {
2035 int error = necp_client_parse_result(assigned_results, (u_int32_t)assigned_results_length,
2036 &flow->local_addr, &flow->remote_addr);
2037 VERIFY(error == 0);
2038 }
2039
2040 flow->viable = necp_client_flow_is_viable(proc, client, flow);
2041
2042 flow->assigned = TRUE;
2043 flow->assigned_results = assigned_results;
2044 flow->assigned_results_length = assigned_results_length;
2045 client->flow_result_read = FALSE;
2046 client_updated = TRUE;
2047 break;
2048 }
2049 }
2050
2051 if (client_updated) {
2052 necp_fd_notify(client_fd, true);
2053 }
2054
2055 // if not updated, client must free assigned_results
2056 return (client_updated);
2057 }
2058
2059 int
2060 necp_assign_client_result(uuid_t netagent_uuid, uuid_t client_id,
2061 u_int8_t *assigned_results, size_t assigned_results_length)
2062 {
2063 int error = 0;
2064 struct necp_fd_data *client_fd = NULL;
2065 bool found_client = FALSE;
2066 bool client_updated = FALSE;
2067
2068 NECP_FD_LIST_LOCK_SHARED();
2069
2070 LIST_FOREACH(client_fd, &necp_fd_list, chain) {
2071 proc_t proc = proc_find(client_fd->proc_pid);
2072 if (proc == PROC_NULL) {
2073 continue;
2074 }
2075
2076 NECP_FD_LOCK(client_fd);
2077 struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
2078 if (client != NULL) {
2079 // Found the right client!
2080 found_client = TRUE;
2081
2082 if (necp_assign_client_result_locked(proc, client_fd, client, netagent_uuid, assigned_results, assigned_results_length)) {
2083 client_updated = TRUE;
2084 }
2085
2086 NECP_CLIENT_UNLOCK(client);
2087 }
2088 NECP_FD_UNLOCK(client_fd);
2089
2090 proc_rele(proc);
2091 proc = PROC_NULL;
2092
2093 if (found_client) {
2094 break;
2095 }
2096 }
2097
2098 NECP_FD_LIST_UNLOCK();
2099
2100 // upon error, client must free assigned_results
2101 if (!found_client) {
2102 error = ENOENT;
2103 } else if (!client_updated) {
2104 error = EINVAL;
2105 }
2106
2107 return (error);
2108 }
2109
2110 /// Client updating
2111
2112 static bool
2113 necp_update_client_result(proc_t proc,
2114 struct necp_fd_data *client_fd,
2115 struct necp_client *client,
2116 struct _necp_client_defunct_list *defunct_list)
2117 {
2118 struct necp_client_result_netagent netagent;
2119 struct necp_aggregate_result result;
2120 struct necp_client_parsed_parameters *parsed_parameters = NULL;
2121 u_int32_t flags = 0;
2122 struct rtentry *route = NULL;
2123
2124 NECP_CLIENT_ASSERT_LOCKED(client);
2125
2126 MALLOC(parsed_parameters, struct necp_client_parsed_parameters *, sizeof(*parsed_parameters), M_NECP, (M_WAITOK | M_ZERO));
2127 if (parsed_parameters == NULL) {
2128 NECPLOG0(LOG_ERR, "Failed to allocate parsed parameters");
2129 return (FALSE);
2130 }
2131
2132 // Nexus flows will be brought back if they are still valid
2133 necp_client_mark_all_nonsocket_flows_as_invalid(client);
2134
2135 int error = necp_client_parse_parameters(client->parameters, (u_int32_t)client->parameters_length, parsed_parameters);
2136 if (error != 0) {
2137 FREE(parsed_parameters, M_NECP);
2138 return (FALSE);
2139 }
2140
2141 // Update saved IP protocol
2142 client->ip_protocol = parsed_parameters->ip_protocol;
2143
2144 // Check parameters to find best interface
2145 u_int matching_if_index = 0;
2146 if (necp_find_matching_interface_index(parsed_parameters, &matching_if_index)) {
2147 if (matching_if_index != 0) {
2148 parsed_parameters->required_interface_index = matching_if_index;
2149 }
2150 // Interface found or not needed, match policy.
2151 error = necp_application_find_policy_match_internal(proc, client->parameters,
2152 (u_int32_t)client->parameters_length,
2153 &result, &flags, matching_if_index,
2154 NULL, NULL, &route, false);
2155 if (error != 0) {
2156 if (route != NULL) {
2157 rtfree(route);
2158 }
2159 FREE(parsed_parameters, M_NECP);
2160 return (FALSE);
2161 }
2162
2163 // Reset current route
2164 NECP_CLIENT_ROUTE_LOCK(client);
2165 if (client->current_route != NULL) {
2166 rtfree(client->current_route);
2167 }
2168 client->current_route = route;
2169 NECP_CLIENT_ROUTE_UNLOCK(client);
2170 } else {
2171 // Interface not found. Clear out the whole result, make everything fail.
2172 memset(&result, 0, sizeof(result));
2173 }
2174
2175 // Save the last policy id on the client
2176 client->policy_id = result.policy_id;
2177
2178 if ((parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_MULTIPATH) ||
2179 ((parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) &&
2180 result.routing_result != NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED)) {
2181 client->allow_multiple_flows = TRUE;
2182 } else {
2183 client->allow_multiple_flows = FALSE;
2184 }
2185
2186 // If the original request was scoped, and the policy result matches, make sure the result is scoped
2187 if ((result.routing_result == NECP_KERNEL_POLICY_RESULT_NONE ||
2188 result.routing_result == NECP_KERNEL_POLICY_RESULT_PASS) &&
2189 result.routed_interface_index != IFSCOPE_NONE &&
2190 parsed_parameters->required_interface_index == result.routed_interface_index) {
2191 result.routing_result = NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED;
2192 result.routing_result_parameter.scoped_interface_index = result.routed_interface_index;
2193 }
2194
2195 if (defunct_list != NULL &&
2196 result.routing_result == NECP_KERNEL_POLICY_RESULT_DROP) {
2197 // If we are forced to drop the client, defunct it if it has flows
2198 necp_defunct_client_for_policy(client, defunct_list);
2199 }
2200
2201 // Recalculate flags
2202 if (client->defunct) {
2203 flags |= NECP_CLIENT_RESULT_FLAG_DEFUNCT;
2204 }
2205 if (parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) {
2206 // Listeners are valid as long as they aren't dropped
2207 if (result.routing_result != NECP_KERNEL_POLICY_RESULT_DROP) {
2208 flags |= NECP_CLIENT_RESULT_FLAG_SATISFIED;
2209 }
2210 } else if (result.routed_interface_index != 0) {
2211 // Clients without flows determine viability based on having some routable interface
2212 flags |= NECP_CLIENT_RESULT_FLAG_SATISFIED;
2213 }
2214
2215 bool updated = FALSE;
2216 u_int8_t *cursor = client->result;
2217 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_FLAGS, sizeof(flags), &flags, &updated, client->result, sizeof(client->result));
2218 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_CLIENT_ID, sizeof(uuid_t), client->client_id, &updated,
2219 client->result, sizeof(client->result));
2220 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_POLICY_RESULT, sizeof(result.routing_result), &result.routing_result, &updated,
2221 client->result, sizeof(client->result));
2222 if (result.routing_result_parameter.tunnel_interface_index != 0) {
2223 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_POLICY_RESULT_PARAMETER,
2224 sizeof(result.routing_result_parameter), &result.routing_result_parameter, &updated,
2225 client->result, sizeof(client->result));
2226 }
2227 if (result.filter_control_unit != 0) {
2228 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_FILTER_CONTROL_UNIT,
2229 sizeof(result.filter_control_unit), &result.filter_control_unit, &updated,
2230 client->result, sizeof(client->result));
2231 }
2232 if (result.routed_interface_index != 0) {
2233 u_int routed_interface_index = result.routed_interface_index;
2234 if (result.routing_result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL &&
2235 parsed_parameters->required_interface_index != IFSCOPE_NONE &&
2236 parsed_parameters->required_interface_index != result.routed_interface_index) {
2237 routed_interface_index = parsed_parameters->required_interface_index;
2238 }
2239
2240 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE_INDEX,
2241 sizeof(routed_interface_index), &routed_interface_index, &updated,
2242 client->result, sizeof(client->result));
2243 }
2244 if (client_fd && client_fd->flags & NECP_OPEN_FLAG_BACKGROUND) {
2245 u_int32_t effective_traffic_class = SO_TC_BK_SYS;
2246 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_EFFECTIVE_TRAFFIC_CLASS,
2247 sizeof(effective_traffic_class), &effective_traffic_class, &updated,
2248 client->result, sizeof(client->result));
2249 }
2250 if (client->background_update) {
2251 u_int32_t background = client->background;
2252 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_TRAFFIC_MGMT_BG,
2253 sizeof(background), &background, &updated,
2254 client->result, sizeof(client->result));
2255 if (updated) {
2256 client->background_update = 0;
2257 }
2258 }
2259 NECP_CLIENT_ROUTE_LOCK(client);
2260 if (client->current_route != NULL) {
2261 const u_int32_t route_mtu = get_maxmtu(client->current_route);
2262 if (route_mtu != 0) {
2263 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_EFFECTIVE_MTU,
2264 sizeof(route_mtu), &route_mtu, &updated,
2265 client->result, sizeof(client->result));
2266 }
2267 }
2268 NECP_CLIENT_ROUTE_UNLOCK(client);
2269
2270 if (result.mss_recommended != 0) {
2271 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_RECOMMENDED_MSS,
2272 sizeof(result.mss_recommended), &result.mss_recommended, &updated,
2273 client->result, sizeof(client->result));
2274 }
2275
2276 for (int i = 0; i < NECP_MAX_NETAGENTS; i++) {
2277 if (uuid_is_null(result.netagents[i])) {
2278 break;
2279 }
2280 uuid_copy(netagent.netagent_uuid, result.netagents[i]);
2281 netagent.generation = netagent_get_generation(netagent.netagent_uuid);
2282 if (necp_netagent_applies_to_client(client, parsed_parameters, netagent.netagent_uuid, TRUE, 0, 0)) {
2283 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_NETAGENT, sizeof(netagent), &netagent, &updated,
2284 client->result, sizeof(client->result));
2285 }
2286 }
2287
2288 ifnet_head_lock_shared();
2289 ifnet_t direct_interface = NULL;
2290 ifnet_t delegate_interface = NULL;
2291 ifnet_t original_scoped_interface = NULL;
2292
2293 if (result.routed_interface_index != IFSCOPE_NONE && result.routed_interface_index <= (u_int32_t)if_index) {
2294 direct_interface = ifindex2ifnet[result.routed_interface_index];
2295 } else if (parsed_parameters->required_interface_index != IFSCOPE_NONE &&
2296 parsed_parameters->required_interface_index <= (u_int32_t)if_index) {
2297 // If the request was scoped, but the route didn't match, still grab the agents
2298 direct_interface = ifindex2ifnet[parsed_parameters->required_interface_index];
2299 } else if (result.routed_interface_index == IFSCOPE_NONE &&
2300 result.routing_result == NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED &&
2301 result.routing_result_parameter.scoped_interface_index != IFSCOPE_NONE) {
2302 direct_interface = ifindex2ifnet[result.routing_result_parameter.scoped_interface_index];
2303 }
2304 if (direct_interface != NULL) {
2305 delegate_interface = direct_interface->if_delegated.ifp;
2306 }
2307 if (result.routing_result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL &&
2308 parsed_parameters->required_interface_index != IFSCOPE_NONE &&
2309 parsed_parameters->required_interface_index != result.routing_result_parameter.tunnel_interface_index &&
2310 parsed_parameters->required_interface_index <= (u_int32_t)if_index) {
2311 original_scoped_interface = ifindex2ifnet[parsed_parameters->required_interface_index];
2312 }
2313 // Add interfaces
2314 if (original_scoped_interface != NULL) {
2315 struct necp_client_result_interface interface_struct;
2316 interface_struct.index = original_scoped_interface->if_index;
2317 interface_struct.generation = ifnet_get_generation(original_scoped_interface);
2318 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE, sizeof(interface_struct), &interface_struct, &updated,
2319 client->result, sizeof(client->result));
2320 }
2321 if (direct_interface != NULL) {
2322 struct necp_client_result_interface interface_struct;
2323 interface_struct.index = direct_interface->if_index;
2324 interface_struct.generation = ifnet_get_generation(direct_interface);
2325 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE, sizeof(interface_struct), &interface_struct, &updated,
2326 client->result, sizeof(client->result));
2327 }
2328 if (delegate_interface != NULL) {
2329 struct necp_client_result_interface interface_struct;
2330 interface_struct.index = delegate_interface->if_index;
2331 interface_struct.generation = ifnet_get_generation(delegate_interface);
2332 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_INTERFACE, sizeof(interface_struct), &interface_struct, &updated,
2333 client->result, sizeof(client->result));
2334 }
2335
2336 // Update multipath/listener interface flows
2337 if (parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_MULTIPATH) {
2338 // Get multipath interface options from ordered list
2339 struct ifnet *multi_interface = NULL;
2340 TAILQ_FOREACH(multi_interface, &ifnet_ordered_head, if_ordered_link) {
2341 if (necp_ifnet_matches_parameters(multi_interface, parsed_parameters, NULL, true)) {
2342 // Add multipath interface flows for kernel MPTCP
2343 necp_client_add_interface_flow_if_needed(client, multi_interface->if_index);
2344
2345 // Add nexus agents for multipath
2346 necp_client_add_agent_flows_for_interface(client, parsed_parameters, multi_interface);
2347 }
2348 }
2349 } else if ((parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) &&
2350 result.routing_result != NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED) {
2351 // Get listener interface options from global list
2352 struct ifnet *listen_interface = NULL;
2353 TAILQ_FOREACH(listen_interface, &ifnet_head, if_link) {
2354 if (necp_ifnet_matches_parameters(listen_interface, parsed_parameters, NULL, false)) {
2355 // Add nexus agents for listeners
2356 necp_client_add_agent_flows_for_interface(client, parsed_parameters, listen_interface);
2357 }
2358 }
2359 }
2360
2361 // Add agents
2362 if (original_scoped_interface != NULL) {
2363 ifnet_lock_shared(original_scoped_interface);
2364 if (original_scoped_interface->if_agentids != NULL) {
2365 for (u_int32_t i = 0; i < original_scoped_interface->if_agentcount; i++) {
2366 if (uuid_is_null(original_scoped_interface->if_agentids[i])) {
2367 continue;
2368 }
2369 u_int16_t if_flags = nstat_ifnet_to_flags(original_scoped_interface);
2370 uuid_copy(netagent.netagent_uuid, original_scoped_interface->if_agentids[i]);
2371 netagent.generation = netagent_get_generation(netagent.netagent_uuid);
2372 if (necp_netagent_applies_to_client(client, parsed_parameters, netagent.netagent_uuid, FALSE, original_scoped_interface->if_index, if_flags)) {
2373 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_NETAGENT, sizeof(netagent), &netagent, &updated,
2374 client->result, sizeof(client->result));
2375 }
2376 }
2377 }
2378 ifnet_lock_done(original_scoped_interface);
2379 }
2380 if (direct_interface != NULL) {
2381 ifnet_lock_shared(direct_interface);
2382 if (direct_interface->if_agentids != NULL) {
2383 for (u_int32_t i = 0; i < direct_interface->if_agentcount; i++) {
2384 if (uuid_is_null(direct_interface->if_agentids[i])) {
2385 continue;
2386 }
2387 u_int16_t if_flags = nstat_ifnet_to_flags(direct_interface);
2388 uuid_copy(netagent.netagent_uuid, direct_interface->if_agentids[i]);
2389 netagent.generation = netagent_get_generation(netagent.netagent_uuid);
2390 if (necp_netagent_applies_to_client(client, parsed_parameters, netagent.netagent_uuid, TRUE, direct_interface->if_index, if_flags)) {
2391 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_NETAGENT, sizeof(netagent), &netagent, &updated,
2392 client->result, sizeof(client->result));
2393 }
2394 }
2395 }
2396 ifnet_lock_done(direct_interface);
2397 }
2398 if (delegate_interface != NULL) {
2399 ifnet_lock_shared(delegate_interface);
2400 if (delegate_interface->if_agentids != NULL) {
2401 for (u_int32_t i = 0; i < delegate_interface->if_agentcount; i++) {
2402 if (uuid_is_null(delegate_interface->if_agentids[i])) {
2403 continue;
2404 }
2405 u_int16_t if_flags = nstat_ifnet_to_flags(delegate_interface);
2406 uuid_copy(netagent.netagent_uuid, delegate_interface->if_agentids[i]);
2407 netagent.generation = netagent_get_generation(netagent.netagent_uuid);
2408 if (necp_netagent_applies_to_client(client, parsed_parameters, netagent.netagent_uuid, FALSE, delegate_interface->if_index, if_flags)) {
2409 cursor = necp_buffer_write_tlv_if_different(cursor, NECP_CLIENT_RESULT_NETAGENT, sizeof(netagent), &netagent, &updated,
2410 client->result, sizeof(client->result));
2411 }
2412 }
2413 }
2414 ifnet_lock_done(delegate_interface);
2415 }
2416 ifnet_head_done();
2417
2418 size_t new_result_length = (cursor - client->result);
2419 if (new_result_length != client->result_length) {
2420 client->result_length = new_result_length;
2421 updated = TRUE;
2422 }
2423
2424 // Update flow viability/flags
2425 if (necp_client_update_flows(proc, client)) {
2426 updated = TRUE;
2427 }
2428
2429 if (updated) {
2430 client->result_read = FALSE;
2431 necp_client_update_observer_update(client);
2432 }
2433
2434 FREE(parsed_parameters, M_NECP);
2435 return (updated);
2436 }
2437
2438 static inline void
2439 necp_defunct_client_fd_locked(struct necp_fd_data *client_fd, struct _necp_client_defunct_list *defunct_list)
2440 {
2441 bool updated_result = FALSE;
2442 struct necp_client *client = NULL;
2443
2444 NECP_FD_ASSERT_LOCKED(client_fd);
2445 RB_FOREACH(client, _necp_client_tree, &client_fd->clients) {
2446 NECP_CLIENT_LOCK(client);
2447 if (!client->defunct) {
2448 updated_result = necp_set_client_defunct(client);
2449
2450 // Prepare close events to be sent to the nexus to effectively remove the flows
2451 struct necp_client_flow *search_flow = NULL;
2452 LIST_FOREACH(search_flow, &client->flow_list, flow_chain) {
2453 if (search_flow->nexus &&
2454 !uuid_is_null(search_flow->u.nexus_agent) &&
2455 search_flow->requested_nexus) {
2456
2457 struct necp_client_defunct *client_defunct;
2458
2459 // Sleeping alloc won't fail; copy only what's necessary
2460 client_defunct = _MALLOC(sizeof (struct necp_client_defunct), M_NECP, M_WAITOK | M_ZERO);
2461 uuid_copy(client_defunct->nexus_agent, search_flow->u.nexus_agent);
2462 uuid_copy(client_defunct->client_id, client->client_id);
2463 client_defunct->proc_pid = client->proc_pid;
2464
2465 // Add to the list provided by caller
2466 LIST_INSERT_HEAD(defunct_list, client_defunct, chain);
2467 }
2468 }
2469 }
2470 NECP_CLIENT_UNLOCK(client);
2471 }
2472 if (updated_result) {
2473 necp_fd_notify(client_fd, true);
2474 }
2475 }
2476
2477 static inline void
2478 necp_update_client_fd_locked(struct necp_fd_data *client_fd,
2479 proc_t proc,
2480 struct _necp_client_defunct_list *defunct_list)
2481 {
2482 struct necp_client *client = NULL;
2483 bool updated_result = FALSE;
2484 NECP_FD_ASSERT_LOCKED(client_fd);
2485 RB_FOREACH(client, _necp_client_tree, &client_fd->clients) {
2486 NECP_CLIENT_LOCK(client);
2487 if (necp_update_client_result(proc, client_fd, client, defunct_list)) {
2488 updated_result = TRUE;
2489 }
2490 NECP_CLIENT_UNLOCK(client);
2491 }
2492 if (updated_result) {
2493 necp_fd_notify(client_fd, true);
2494 }
2495 }
2496
2497
2498 static void
2499 necp_update_all_clients_callout(__unused thread_call_param_t dummy,
2500 __unused thread_call_param_t arg)
2501 {
2502 struct necp_fd_data *client_fd = NULL;
2503
2504 struct _necp_client_defunct_list defunct_list;
2505 LIST_INIT(&defunct_list);
2506
2507 NECP_FD_LIST_LOCK_SHARED();
2508
2509 LIST_FOREACH(client_fd, &necp_fd_list, chain) {
2510 proc_t proc = proc_find(client_fd->proc_pid);
2511 if (proc == PROC_NULL) {
2512 continue;
2513 }
2514
2515 // Update all clients on one fd
2516 NECP_FD_LOCK(client_fd);
2517 necp_update_client_fd_locked(client_fd, proc, &defunct_list);
2518 NECP_FD_UNLOCK(client_fd);
2519
2520 proc_rele(proc);
2521 proc = PROC_NULL;
2522 }
2523
2524 NECP_FD_LIST_UNLOCK();
2525
2526 // Handle the case in which some clients became newly defunct
2527 if (!LIST_EMPTY(&defunct_list)) {
2528 struct necp_client_defunct *client_defunct = NULL;
2529 struct necp_client_defunct *temp_client_defunct = NULL;
2530
2531 // For each newly defunct client, send a message to the nexus to remove the flow
2532 LIST_FOREACH_SAFE(client_defunct, &defunct_list, chain, temp_client_defunct) {
2533 if (!uuid_is_null(client_defunct->nexus_agent)) {
2534 int netagent_error = netagent_client_message(client_defunct->nexus_agent,
2535 client_defunct->client_id,
2536 client_defunct->proc_pid,
2537 NETAGENT_MESSAGE_TYPE_ABORT_NEXUS);
2538 if (netagent_error != 0) {
2539 NECPLOG((netagent_error == ENOENT ? LOG_DEBUG : LOG_ERR), "necp_update_client abort nexus error (%d)", netagent_error);
2540 }
2541 }
2542 LIST_REMOVE(client_defunct, chain);
2543 FREE(client_defunct, M_NECP);
2544 }
2545 }
2546 ASSERT(LIST_EMPTY(&defunct_list));
2547 }
2548
2549 void
2550 necp_update_all_clients(void)
2551 {
2552 if (necp_client_update_tcall == NULL) {
2553 // Don't try to update clients if the module is not initialized
2554 return;
2555 }
2556
2557 uint64_t deadline = 0;
2558 uint64_t leeway = 0;
2559 clock_interval_to_deadline(necp_timeout_microseconds, NSEC_PER_USEC, &deadline);
2560 clock_interval_to_absolutetime_interval(necp_timeout_leeway_microseconds, NSEC_PER_USEC, &leeway);
2561
2562 thread_call_enter_delayed_with_leeway(necp_client_update_tcall, NULL,
2563 deadline, leeway, THREAD_CALL_DELAY_LEEWAY);
2564 }
2565
2566 void
2567 necp_set_client_as_background(proc_t proc,
2568 struct fileproc *fp,
2569 bool background)
2570 {
2571 bool updated_result = FALSE;
2572 struct necp_client *client = NULL;
2573
2574 if (proc == PROC_NULL) {
2575 NECPLOG0(LOG_ERR, "NULL proc");
2576 return;
2577 }
2578
2579 if (fp == NULL) {
2580 NECPLOG0(LOG_ERR, "NULL fp");
2581 return;
2582 }
2583
2584 struct necp_fd_data *client_fd = (struct necp_fd_data *)fp->f_fglob->fg_data;
2585 if (client_fd == NULL) {
2586 NECPLOG0(LOG_ERR, "Could not find client structure for backgrounded client");
2587 return;
2588 }
2589
2590 if (client_fd->necp_fd_type != necp_fd_type_client) {
2591 // Not a client fd, ignore
2592 NECPLOG0(LOG_ERR, "Not a client fd, ignore");
2593 return;
2594 }
2595
2596 NECP_FD_LOCK(client_fd);
2597
2598 RB_FOREACH(client, _necp_client_tree, &client_fd->clients) {
2599 NECP_CLIENT_LOCK(client);
2600
2601 bool has_assigned_flow = FALSE;
2602 struct necp_client_flow *search_flow = NULL;
2603 LIST_FOREACH(search_flow, &client->flow_list, flow_chain) {
2604 if (search_flow->assigned) {
2605 has_assigned_flow = TRUE;
2606 break;
2607 }
2608 }
2609
2610 if (has_assigned_flow) {
2611 client->background = background;
2612 client->background_update = TRUE;
2613 updated_result = TRUE;
2614 }
2615
2616 NECP_CLIENT_UNLOCK(client);
2617 }
2618 if (updated_result) {
2619 necp_update_client_fd_locked(client_fd, proc, NULL);
2620 }
2621 NECP_FD_UNLOCK(client_fd);
2622 }
2623
2624 void
2625 necp_defunct_client(proc_t proc,
2626 struct fileproc *fp)
2627 {
2628 struct _necp_client_defunct_list defunct_list;
2629
2630 if (proc == PROC_NULL) {
2631 NECPLOG0(LOG_ERR, "NULL proc passed to set as background");
2632 return;
2633 }
2634
2635 if (fp == NULL) {
2636 NECPLOG0(LOG_ERR, "NULL fp passed to set as background");
2637 return;
2638 }
2639
2640 struct necp_fd_data *client_fd = (struct necp_fd_data *)fp->f_fglob->fg_data;
2641 if (client_fd == NULL) {
2642 NECPLOG0(LOG_ERR, "Could not find client structure for backgrounded client");
2643 return;
2644 }
2645
2646 if (client_fd->necp_fd_type != necp_fd_type_client) {
2647 // Not a client fd, ignore
2648 return;
2649 }
2650
2651 // Our local temporary list
2652 LIST_INIT(&defunct_list);
2653
2654 // Need to hold lock so ntstats defunct the same set of clients
2655 NECP_FD_LOCK(client_fd);
2656 necp_defunct_client_fd_locked(client_fd, &defunct_list);
2657 NECP_FD_UNLOCK(client_fd);
2658
2659 if (!LIST_EMPTY(&defunct_list)) {
2660 struct necp_client_defunct *client_defunct = NULL;
2661 struct necp_client_defunct *temp_client_defunct = NULL;
2662
2663 // For each defunct client, remove flow from the nexus
2664 LIST_FOREACH_SAFE(client_defunct, &defunct_list, chain, temp_client_defunct) {
2665 if (!uuid_is_null(client_defunct->nexus_agent)) {
2666 int netagent_error = netagent_client_message(client_defunct->nexus_agent,
2667 client_defunct->client_id,
2668 client_defunct->proc_pid,
2669 NETAGENT_MESSAGE_TYPE_ABORT_NEXUS);
2670 if (netagent_error != 0) {
2671 NECPLOG((netagent_error == ENOENT ? LOG_DEBUG : LOG_ERR), "necp_defunct_client abort nexus error (%d)", netagent_error);
2672 }
2673 }
2674 LIST_REMOVE(client_defunct, chain);
2675 FREE(client_defunct, M_NECP);
2676 }
2677 }
2678 ASSERT(LIST_EMPTY(&defunct_list));
2679 }
2680
2681 static void
2682 necp_client_remove_agent_from_result(struct necp_client *client, uuid_t netagent_uuid)
2683 {
2684 size_t offset = 0;
2685
2686 u_int8_t *result_buffer = client->result;
2687 while ((offset + sizeof(struct necp_tlv_header)) <= client->result_length) {
2688 u_int8_t type = necp_buffer_get_tlv_type(result_buffer, offset);
2689 u_int32_t length = necp_buffer_get_tlv_length(result_buffer, offset);
2690
2691 size_t tlv_total_length = (sizeof(struct necp_tlv_header) + length);
2692 if (type == NECP_CLIENT_RESULT_NETAGENT &&
2693 length == sizeof(struct necp_client_result_netagent) &&
2694 (offset + tlv_total_length) <= client->result_length) {
2695 struct necp_client_result_netagent *value = ((struct necp_client_result_netagent *)(void *)
2696 necp_buffer_get_tlv_value(result_buffer, offset, NULL));
2697 if (uuid_compare(value->netagent_uuid, netagent_uuid) == 0) {
2698 // Found a netagent to remove
2699 // Shift bytes down to remove the tlv, and adjust total length
2700 // Don't adjust the current offset
2701 memmove(result_buffer + offset,
2702 result_buffer + offset + tlv_total_length,
2703 client->result_length - (offset + tlv_total_length));
2704 client->result_length -= tlv_total_length;
2705 memset(result_buffer + client->result_length, 0, sizeof(client->result) - client->result_length);
2706 continue;
2707 }
2708 }
2709
2710 offset += tlv_total_length;
2711 }
2712 }
2713
2714 void
2715 necp_force_update_client(uuid_t client_id, uuid_t remove_netagent_uuid)
2716 {
2717 struct necp_fd_data *client_fd = NULL;
2718
2719 NECP_FD_LIST_LOCK_SHARED();
2720
2721 LIST_FOREACH(client_fd, &necp_fd_list, chain) {
2722 bool updated_result = FALSE;
2723 NECP_FD_LOCK(client_fd);
2724 struct necp_client *client = necp_client_fd_find_client_and_lock(client_fd, client_id);
2725 if (client != NULL) {
2726 if (!uuid_is_null(remove_netagent_uuid)) {
2727 necp_client_remove_agent_from_result(client, remove_netagent_uuid);
2728 }
2729 client->flow_result_read = FALSE;
2730 // Found the client, break
2731 updated_result = TRUE;
2732 NECP_CLIENT_UNLOCK(client);
2733 }
2734 if (updated_result) {
2735 necp_fd_notify(client_fd, true);
2736 }
2737 NECP_FD_UNLOCK(client_fd);
2738 if (updated_result) {
2739 // Found the client, break
2740 break;
2741 }
2742 }
2743
2744 NECP_FD_LIST_UNLOCK();
2745 }
2746
2747
2748 /// Interface matching
2749
2750 #define NECP_PARSED_PARAMETERS_INTERESTING_IFNET_FIELDS (NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR | \
2751 NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IF | \
2752 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE | \
2753 NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IFTYPE | \
2754 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT | \
2755 NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT | \
2756 NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT | \
2757 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE | \
2758 NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT_TYPE | \
2759 NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT_TYPE)
2760
2761 #define NECP_PARSED_PARAMETERS_SCOPED_IFNET_FIELDS (NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR | \
2762 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE | \
2763 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT | \
2764 NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT | \
2765 NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE | \
2766 NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT_TYPE)
2767
2768 #define NECP_PARSED_PARAMETERS_PREFERRED_IFNET_FIELDS (NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT | \
2769 NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT_TYPE)
2770
2771 static bool
2772 necp_ifnet_matches_type(struct ifnet *ifp, u_int8_t interface_type, bool check_delegates)
2773 {
2774 struct ifnet *check_ifp = ifp;
2775 while (check_ifp) {
2776 if (if_functional_type(check_ifp, TRUE) == interface_type) {
2777 return (TRUE);
2778 }
2779 if (!check_delegates) {
2780 break;
2781 }
2782 check_ifp = check_ifp->if_delegated.ifp;
2783
2784 }
2785 return (FALSE);
2786 }
2787
2788 static bool
2789 necp_ifnet_matches_name(struct ifnet *ifp, const char *interface_name, bool check_delegates)
2790 {
2791 struct ifnet *check_ifp = ifp;
2792 while (check_ifp) {
2793 if (strncmp(check_ifp->if_xname, interface_name, IFXNAMSIZ) == 0) {
2794 return (TRUE);
2795 }
2796 if (!check_delegates) {
2797 break;
2798 }
2799 check_ifp = check_ifp->if_delegated.ifp;
2800 }
2801 return (FALSE);
2802 }
2803
2804 static bool
2805 necp_ifnet_matches_agent(struct ifnet *ifp, uuid_t *agent_uuid, bool check_delegates)
2806 {
2807 struct ifnet *check_ifp = ifp;
2808
2809 while (check_ifp != NULL) {
2810 ifnet_lock_shared(check_ifp);
2811 if (check_ifp->if_agentids != NULL) {
2812 for (u_int32_t index = 0; index < check_ifp->if_agentcount; index++) {
2813 if (uuid_compare(check_ifp->if_agentids[index], *agent_uuid) == 0) {
2814 ifnet_lock_done(check_ifp);
2815 return (TRUE);
2816 }
2817 }
2818 }
2819 ifnet_lock_done(check_ifp);
2820
2821 if (!check_delegates) {
2822 break;
2823 }
2824 check_ifp = check_ifp->if_delegated.ifp;
2825 }
2826 return (FALSE);
2827 }
2828
2829 static bool
2830 necp_necp_ifnet_matches_agent_type(struct ifnet *ifp, const char *agent_domain, const char *agent_type, bool check_delegates)
2831 {
2832 struct ifnet *check_ifp = ifp;
2833
2834 while (check_ifp != NULL) {
2835 ifnet_lock_shared(check_ifp);
2836 if (check_ifp->if_agentids != NULL) {
2837 for (u_int32_t index = 0; index < check_ifp->if_agentcount; index++) {
2838 if (uuid_is_null(check_ifp->if_agentids[index])) {
2839 continue;
2840 }
2841
2842 char if_agent_domain[NETAGENT_DOMAINSIZE] = { 0 };
2843 char if_agent_type[NETAGENT_TYPESIZE] = { 0 };
2844
2845 if (netagent_get_agent_domain_and_type(check_ifp->if_agentids[index], if_agent_domain, if_agent_type)) {
2846 if ((strlen(agent_domain) == 0 ||
2847 strncmp(if_agent_domain, agent_domain, NETAGENT_DOMAINSIZE) == 0) &&
2848 (strlen(agent_type) == 0 ||
2849 strncmp(if_agent_type, agent_type, NETAGENT_TYPESIZE) == 0)) {
2850 ifnet_lock_done(check_ifp);
2851 return (TRUE);
2852 }
2853 }
2854 }
2855 }
2856 ifnet_lock_done(check_ifp);
2857
2858 if (!check_delegates) {
2859 break;
2860 }
2861 check_ifp = check_ifp->if_delegated.ifp;
2862 }
2863 return (FALSE);
2864 }
2865
2866 static bool
2867 necp_ifnet_matches_local_address(struct ifnet *ifp, struct sockaddr *sa)
2868 {
2869 struct ifaddr *ifa = NULL;
2870 bool matched_local_address = FALSE;
2871
2872 // Transform sa into the ifaddr form
2873 // IPv6 Scope IDs are always embedded in the ifaddr list
2874 struct sockaddr_storage address;
2875 u_int ifscope = IFSCOPE_NONE;
2876 (void)sa_copy(sa, &address, &ifscope);
2877 SIN(&address)->sin_port = 0;
2878 if (address.ss_family == AF_INET6) {
2879 SIN6(&address)->sin6_scope_id = 0;
2880 }
2881
2882 ifa = ifa_ifwithaddr_scoped_locked((struct sockaddr *)&address, ifp->if_index);
2883 matched_local_address = (ifa != NULL);
2884
2885 if (ifa) {
2886 ifaddr_release(ifa);
2887 }
2888
2889 return (matched_local_address);
2890 }
2891
2892 static bool
2893 necp_interface_type_is_primary_eligible(u_int8_t interface_type)
2894 {
2895 switch (interface_type) {
2896 // These types can never be primary, so a client requesting these types is allowed
2897 // to match an interface that isn't currently eligible to be primary (has default
2898 // route, dns, etc)
2899 case IFRTYPE_FUNCTIONAL_WIFI_AWDL:
2900 case IFRTYPE_FUNCTIONAL_INTCOPROC:
2901 return false;
2902 default:
2903 break;
2904 }
2905 return true;
2906 }
2907
2908 #define NECP_IFP_IS_ON_ORDERED_LIST(_ifp) ((_ifp)->if_ordered_link.tqe_next != NULL || (_ifp)->if_ordered_link.tqe_prev != NULL)
2909
2910 static bool
2911 necp_ifnet_matches_parameters(struct ifnet *ifp,
2912 struct necp_client_parsed_parameters *parsed_parameters,
2913 u_int32_t *preferred_count, bool ignore_require_if)
2914 {
2915 if (preferred_count) {
2916 *preferred_count = 0;
2917 }
2918
2919 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_LOCAL_ADDR) {
2920 if (!necp_ifnet_matches_local_address(ifp, &parsed_parameters->local_addr.sa)) {
2921 return (FALSE);
2922 }
2923 }
2924
2925 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_FLAGS) {
2926 if ((parsed_parameters->flags & NECP_CLIENT_PARAMETER_FLAG_PROHIBIT_EXPENSIVE) &&
2927 IFNET_IS_EXPENSIVE(ifp)) {
2928 return (FALSE);
2929 }
2930 }
2931
2932 if (!ignore_require_if &&
2933 (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE) &&
2934 !necp_ifnet_matches_type(ifp, parsed_parameters->required_interface_type, FALSE)) {
2935 return (FALSE);
2936 }
2937
2938 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IFTYPE) {
2939 for (int i = 0; i < NECP_MAX_PARSED_PARAMETERS; i++) {
2940 if (parsed_parameters->prohibited_interface_types[i] == 0) {
2941 break;
2942 }
2943
2944 if (necp_ifnet_matches_type(ifp, parsed_parameters->prohibited_interface_types[i], TRUE)) {
2945 return (FALSE);
2946 }
2947 }
2948 }
2949
2950 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_IF) {
2951 for (int i = 0; i < NECP_MAX_PARSED_PARAMETERS; i++) {
2952 if (strlen(parsed_parameters->prohibited_interfaces[i]) == 0) {
2953 break;
2954 }
2955
2956 if (necp_ifnet_matches_name(ifp, parsed_parameters->prohibited_interfaces[i], TRUE)) {
2957 return (FALSE);
2958 }
2959 }
2960 }
2961
2962 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT) {
2963 for (int i = 0; i < NECP_MAX_PARSED_PARAMETERS; i++) {
2964 if (uuid_is_null(parsed_parameters->required_netagents[i])) {
2965 break;
2966 }
2967
2968 if (!necp_ifnet_matches_agent(ifp, &parsed_parameters->required_netagents[i], FALSE)) {
2969 return (FALSE);
2970 }
2971 }
2972 }
2973
2974 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT) {
2975 for (int i = 0; i < NECP_MAX_PARSED_PARAMETERS; i++) {
2976 if (uuid_is_null(parsed_parameters->prohibited_netagents[i])) {
2977 break;
2978 }
2979
2980 if (necp_ifnet_matches_agent(ifp, &parsed_parameters->prohibited_netagents[i], TRUE)) {
2981 return (FALSE);
2982 }
2983 }
2984 }
2985
2986 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_AGENT_TYPE) {
2987 for (int i = 0; i < NECP_MAX_PARSED_PARAMETERS; i++) {
2988 if (strlen(parsed_parameters->required_netagent_types[i].netagent_domain) == 0 &&
2989 strlen(parsed_parameters->required_netagent_types[i].netagent_type) == 0) {
2990 break;
2991 }
2992
2993 if (!necp_necp_ifnet_matches_agent_type(ifp, parsed_parameters->required_netagent_types[i].netagent_domain, parsed_parameters->required_netagent_types[i].netagent_type, FALSE)) {
2994 return (FALSE);
2995 }
2996 }
2997 }
2998
2999 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_PROHIBITED_AGENT_TYPE) {
3000 for (int i = 0; i < NECP_MAX_PARSED_PARAMETERS; i++) {
3001 if (strlen(parsed_parameters->prohibited_netagent_types[i].netagent_domain) == 0 &&
3002 strlen(parsed_parameters->prohibited_netagent_types[i].netagent_type) == 0) {
3003 break;
3004 }
3005
3006 if (necp_necp_ifnet_matches_agent_type(ifp, parsed_parameters->prohibited_netagent_types[i].netagent_domain, parsed_parameters->prohibited_netagent_types[i].netagent_type, TRUE)) {
3007 return (FALSE);
3008 }
3009 }
3010 }
3011
3012 // Checked preferred properties
3013 if (preferred_count) {
3014 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT) {
3015 for (int i = 0; i < NECP_MAX_PARSED_PARAMETERS; i++) {
3016 if (uuid_is_null(parsed_parameters->preferred_netagents[i])) {
3017 break;
3018 }
3019
3020 if (necp_ifnet_matches_agent(ifp, &parsed_parameters->preferred_netagents[i], TRUE)) {
3021 (*preferred_count)++;
3022 }
3023 }
3024 }
3025
3026 if (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_PREFERRED_AGENT_TYPE) {
3027 for (int i = 0; i < NECP_MAX_PARSED_PARAMETERS; i++) {
3028 if (strlen(parsed_parameters->preferred_netagent_types[i].netagent_domain) == 0 &&
3029 strlen(parsed_parameters->preferred_netagent_types[i].netagent_type) == 0) {
3030 break;
3031 }
3032
3033 if (necp_necp_ifnet_matches_agent_type(ifp, parsed_parameters->preferred_netagent_types[i].netagent_domain, parsed_parameters->preferred_netagent_types[i].netagent_type, TRUE)) {
3034 (*preferred_count)++;
3035 }
3036 }
3037 }
3038 }
3039
3040 return (TRUE);
3041 }
3042
3043 static bool
3044 necp_find_matching_interface_index(struct necp_client_parsed_parameters *parsed_parameters, u_int *return_ifindex)
3045 {
3046 struct ifnet *ifp = NULL;
3047 u_int32_t best_preferred_count = 0;
3048 bool has_preferred_fields = FALSE;
3049 *return_ifindex = 0;
3050
3051 if (parsed_parameters->required_interface_index != 0) {
3052 *return_ifindex = parsed_parameters->required_interface_index;
3053 return (TRUE);
3054 }
3055
3056 if (!(parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_INTERESTING_IFNET_FIELDS)) {
3057 return (TRUE);
3058 }
3059
3060 has_preferred_fields = (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_PREFERRED_IFNET_FIELDS);
3061
3062 // We have interesting parameters to parse and find a matching interface
3063 ifnet_head_lock_shared();
3064
3065 if (!(parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_SCOPED_IFNET_FIELDS)) {
3066 // We do have fields to match, but they are only prohibitory
3067 // If the first interface in the list matches, or there are no ordered interfaces, we don't need to scope
3068 ifp = TAILQ_FIRST(&ifnet_ordered_head);
3069 if (ifp == NULL || necp_ifnet_matches_parameters(ifp, parsed_parameters, NULL, false)) {
3070 // Don't set return_ifindex, so the client doesn't need to scope
3071 ifnet_head_done();
3072 return (TRUE);
3073 }
3074 }
3075
3076 // First check the ordered interface list
3077 TAILQ_FOREACH(ifp, &ifnet_ordered_head, if_ordered_link) {
3078 u_int32_t preferred_count = 0;
3079 if (necp_ifnet_matches_parameters(ifp, parsed_parameters, &preferred_count, false)) {
3080 if (preferred_count > best_preferred_count ||
3081 *return_ifindex == 0) {
3082
3083 // Everything matched, and is most preferred. Return this interface.
3084 *return_ifindex = ifp->if_index;
3085 best_preferred_count = preferred_count;
3086
3087 if (!has_preferred_fields) {
3088 break;
3089 }
3090 }
3091 }
3092 }
3093
3094 // Then check the remaining interfaces
3095 if ((parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_SCOPED_IFNET_FIELDS) &&
3096 ((!(parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_FIELD_REQUIRED_IFTYPE)) ||
3097 !necp_interface_type_is_primary_eligible(parsed_parameters->required_interface_type)) &&
3098 *return_ifindex == 0) {
3099 TAILQ_FOREACH(ifp, &ifnet_head, if_link) {
3100 u_int32_t preferred_count = 0;
3101 if (NECP_IFP_IS_ON_ORDERED_LIST(ifp)) {
3102 // This interface was in the ordered list, skip
3103 continue;
3104 }
3105 if (necp_ifnet_matches_parameters(ifp, parsed_parameters, &preferred_count, false)) {
3106 if (preferred_count > best_preferred_count ||
3107 *return_ifindex == 0) {
3108
3109 // Everything matched, and is most preferred. Return this interface.
3110 *return_ifindex = ifp->if_index;
3111 best_preferred_count = preferred_count;
3112
3113 if (!has_preferred_fields) {
3114 break;
3115 }
3116 }
3117 }
3118 }
3119 }
3120
3121 ifnet_head_done();
3122
3123 if ((parsed_parameters->valid_fields == (parsed_parameters->valid_fields & NECP_PARSED_PARAMETERS_PREFERRED_IFNET_FIELDS)) &&
3124 best_preferred_count == 0) {
3125 // If only has preferred fields, and nothing was found, clear the interface index and return TRUE
3126 *return_ifindex = 0;
3127 return (TRUE);
3128 }
3129
3130 return (*return_ifindex != 0);
3131 }
3132
3133
3134 static int
3135 necp_skywalk_priv_check_cred(proc_t p, kauth_cred_t cred)
3136 {
3137 #pragma unused(p, cred)
3138 return (0);
3139 }
3140
3141 /// System calls
3142
3143 int
3144 necp_open(struct proc *p, struct necp_open_args *uap, int *retval)
3145 {
3146 #pragma unused(retval)
3147 int error = 0;
3148 struct necp_fd_data *fd_data = NULL;
3149 struct fileproc *fp = NULL;
3150 int fd = -1;
3151
3152 if (uap->flags & NECP_OPEN_FLAG_OBSERVER) {
3153 if (necp_skywalk_priv_check_cred(p, kauth_cred_get()) != 0 &&
3154 priv_check_cred(kauth_cred_get(), PRIV_NET_PRIVILEGED_NETWORK_STATISTICS, 0) != 0) {
3155 NECPLOG0(LOG_ERR, "Client does not hold necessary entitlement to observe other NECP clients");
3156 error = EACCES;
3157 goto done;
3158 }
3159 }
3160
3161 error = falloc(p, &fp, &fd, vfs_context_current());
3162 if (error != 0) {
3163 goto done;
3164 }
3165
3166 if ((fd_data = zalloc(necp_client_fd_zone)) == NULL) {
3167 error = ENOMEM;
3168 goto done;
3169 }
3170
3171 memset(fd_data, 0, sizeof(*fd_data));
3172
3173 fd_data->necp_fd_type = necp_fd_type_client;
3174 fd_data->flags = uap->flags;
3175 RB_INIT(&fd_data->clients);
3176 TAILQ_INIT(&fd_data->update_list);
3177 lck_mtx_init(&fd_data->fd_lock, necp_fd_mtx_grp, necp_fd_mtx_attr);
3178 klist_init(&fd_data->si.si_note);
3179 fd_data->proc_pid = proc_pid(p);
3180
3181 fp->f_fglob->fg_flag = FREAD;
3182 fp->f_fglob->fg_ops = &necp_fd_ops;
3183 fp->f_fglob->fg_data = fd_data;
3184
3185 proc_fdlock(p);
3186
3187 *fdflags(p, fd) |= (UF_EXCLOSE | UF_FORKCLOSE);
3188 procfdtbl_releasefd(p, fd, NULL);
3189 fp_drop(p, fd, fp, 1);
3190
3191 *retval = fd;
3192
3193 if (fd_data->flags & NECP_OPEN_FLAG_PUSH_OBSERVER) {
3194 NECP_OBSERVER_LIST_LOCK_EXCLUSIVE();
3195 LIST_INSERT_HEAD(&necp_fd_observer_list, fd_data, chain);
3196 OSIncrementAtomic(&necp_observer_fd_count);
3197 NECP_OBSERVER_LIST_UNLOCK();
3198
3199 // Walk all existing clients and add them
3200 NECP_CLIENT_TREE_LOCK_SHARED();
3201 struct necp_client *existing_client = NULL;
3202 RB_FOREACH(existing_client, _necp_client_global_tree, &necp_client_global_tree) {
3203 NECP_CLIENT_LOCK(existing_client);
3204 necp_client_update_observer_add_internal(fd_data, existing_client);
3205 necp_client_update_observer_update_internal(fd_data, existing_client);
3206 NECP_CLIENT_UNLOCK(existing_client);
3207 }
3208 NECP_CLIENT_TREE_UNLOCK();
3209 } else {
3210 NECP_FD_LIST_LOCK_EXCLUSIVE();
3211 LIST_INSERT_HEAD(&necp_fd_list, fd_data, chain);
3212 OSIncrementAtomic(&necp_client_fd_count);
3213 NECP_FD_LIST_UNLOCK();
3214 }
3215
3216 proc_fdunlock(p);
3217
3218 done:
3219 if (error != 0) {
3220 if (fp != NULL) {
3221 fp_free(p, fd, fp);
3222 fp = NULL;
3223 }
3224 if (fd_data != NULL) {
3225 zfree(necp_client_fd_zone, fd_data);
3226 fd_data = NULL;
3227 }
3228 }
3229
3230 return (error);
3231 }
3232
3233 static int
3234 necp_client_add(struct proc *p, struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
3235 {
3236 int error = 0;
3237 struct necp_client *client = NULL;
3238
3239 if (fd_data->flags & NECP_OPEN_FLAG_PUSH_OBSERVER) {
3240 NECPLOG0(LOG_ERR, "NECP client observers with push enabled may not add their own clients");
3241 return (EINVAL);
3242 }
3243
3244 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t) ||
3245 uap->buffer_size == 0 || uap->buffer_size > NECP_MAX_CLIENT_PARAMETERS_SIZE || uap->buffer == 0) {
3246 return (EINVAL);
3247 }
3248
3249 if ((client = _MALLOC(sizeof(struct necp_client) + uap->buffer_size, M_NECP,
3250 M_WAITOK | M_ZERO)) == NULL) {
3251 error = ENOMEM;
3252 goto done;
3253 }
3254
3255 error = copyin(uap->buffer, client->parameters, uap->buffer_size);
3256 if (error) {
3257 NECPLOG(LOG_ERR, "necp_client_add parameters copyin error (%d)", error);
3258 goto done;
3259 }
3260
3261 lck_mtx_init(&client->lock, necp_fd_mtx_grp, necp_fd_mtx_attr);
3262 lck_mtx_init(&client->route_lock, necp_fd_mtx_grp, necp_fd_mtx_attr);
3263 necp_client_retain(client); // Hold our reference until close
3264
3265 client->parameters_length = uap->buffer_size;
3266 client->proc_pid = fd_data->proc_pid; // Save off proc pid in case the client will persist past fd
3267 client->platform_binary = ((csproc_get_platform_binary(p) == 0) ? 0 : 1);
3268
3269 uuid_generate_random(client->client_id);
3270 LIST_INIT(&client->assertion_list);
3271 LIST_INIT(&client->flow_list);
3272
3273 error = copyout(client->client_id, uap->client_id, sizeof(uuid_t));
3274 if (error) {
3275 NECPLOG(LOG_ERR, "necp_client_add client_id copyout error (%d)", error);
3276 goto done;
3277 }
3278
3279 necp_client_update_observer_add(client);
3280
3281 NECP_FD_LOCK(fd_data);
3282 RB_INSERT(_necp_client_tree, &fd_data->clients, client);
3283 OSIncrementAtomic(&necp_client_count);
3284 NECP_CLIENT_TREE_LOCK_EXCLUSIVE();
3285 RB_INSERT(_necp_client_global_tree, &necp_client_global_tree, client);
3286 NECP_CLIENT_TREE_UNLOCK();
3287
3288 // Prime the client result
3289 NECP_CLIENT_LOCK(client);
3290 (void)necp_update_client_result(current_proc(), fd_data, client, NULL);
3291 NECP_CLIENT_UNLOCK(client);
3292 NECP_FD_UNLOCK(fd_data);
3293 done:
3294 if (error != 0) {
3295 if (client != NULL) {
3296 FREE(client, M_NECP);
3297 client = NULL;
3298 }
3299 }
3300 *retval = error;
3301
3302 return (error);
3303 }
3304
3305 static int
3306 necp_client_remove(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
3307 {
3308 int error = 0;
3309 struct necp_client *client = NULL;
3310 struct necp_client *temp_client = NULL;
3311 uuid_t client_id = {};
3312 struct ifnet_stats_per_flow flow_ifnet_stats = {};
3313
3314 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t)) {
3315 error = EINVAL;
3316 goto done;
3317 }
3318
3319 error = copyin(uap->client_id, client_id, sizeof(uuid_t));
3320 if (error) {
3321 NECPLOG(LOG_ERR, "necp_client_remove copyin client_id error (%d)", error);
3322 goto done;
3323 }
3324
3325 if (uap->buffer != 0 && uap->buffer_size == sizeof(flow_ifnet_stats)) {
3326 error = copyin(uap->buffer, &flow_ifnet_stats, uap->buffer_size);
3327 if (error) {
3328 NECPLOG(LOG_ERR, "necp_client_remove flow_ifnet_stats copyin error (%d)", error);
3329 // Not fatal
3330 }
3331 } else if (uap->buffer != 0) {
3332 NECPLOG(LOG_ERR, "necp_client_remove unexpected parameters length (%zu)", uap->buffer_size);
3333 }
3334
3335 struct _necp_client_tree clients_to_close;
3336 RB_INIT(&clients_to_close);
3337 NECP_FD_LOCK(fd_data);
3338 pid_t pid = fd_data->proc_pid;
3339 RB_FOREACH_SAFE(client, _necp_client_tree, &fd_data->clients, temp_client) {
3340 if (uuid_compare(client->client_id, client_id) == 0) {
3341 NECP_CLIENT_TREE_LOCK_EXCLUSIVE();
3342 RB_REMOVE(_necp_client_global_tree, &necp_client_global_tree, client);
3343 NECP_CLIENT_TREE_UNLOCK();
3344 RB_REMOVE(_necp_client_tree, &fd_data->clients, client);
3345 RB_INSERT(_necp_client_tree, &clients_to_close, client);
3346 }
3347 }
3348
3349
3350 NECP_FD_UNLOCK(fd_data);
3351
3352 RB_FOREACH_SAFE(client, _necp_client_tree, &clients_to_close, temp_client) {
3353 RB_REMOVE(_necp_client_tree, &clients_to_close, client);
3354 necp_destroy_client(client, pid, true);
3355 }
3356 done:
3357 *retval = error;
3358
3359 return (error);
3360 }
3361
3362 static int
3363 necp_client_check_tcp_heuristics(struct necp_client *client, struct necp_client_flow *flow, u_int32_t *flags, u_int8_t *tfo_cookie, u_int8_t *tfo_cookie_len)
3364 {
3365 struct necp_client_parsed_parameters parsed_parameters;
3366 int error = 0;
3367
3368 error = necp_client_parse_parameters(client->parameters,
3369 (u_int32_t)client->parameters_length,
3370 &parsed_parameters);
3371 if (error) {
3372 NECPLOG(LOG_ERR, "necp_client_parse_parameters error (%d)", error);
3373 return (error);
3374 }
3375
3376 if ((flow->remote_addr.sa.sa_family != AF_INET &&
3377 flow->remote_addr.sa.sa_family != AF_INET6) ||
3378 (flow->local_addr.sa.sa_family != AF_INET &&
3379 flow->local_addr.sa.sa_family != AF_INET6)) {
3380 return (EINVAL);
3381 }
3382
3383 NECP_CLIENT_ROUTE_LOCK(client);
3384
3385 if (client->current_route == NULL) {
3386 error = ENOENT;
3387 goto do_unlock;
3388 }
3389
3390 bool check_ecn = false;
3391 do {
3392 if ((parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_ECN_ENABLE) ==
3393 NECP_CLIENT_PARAMETER_FLAG_ECN_ENABLE) {
3394 check_ecn = true;
3395 break;
3396 }
3397
3398 if ((parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_ECN_DISABLE) ==
3399 NECP_CLIENT_PARAMETER_FLAG_ECN_DISABLE) {
3400 break;
3401 }
3402
3403 if (client->current_route != NULL) {
3404 if (client->current_route->rt_ifp->if_eflags & IFEF_ECN_ENABLE) {
3405 check_ecn = true;
3406 break;
3407 }
3408 if (client->current_route->rt_ifp->if_eflags & IFEF_ECN_DISABLE) {
3409 break;
3410 }
3411 }
3412
3413 bool inbound = ((parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) == 0);
3414 if ((inbound && tcp_ecn_inbound == 1) ||
3415 (!inbound && tcp_ecn_outbound == 1)) {
3416 check_ecn = true;
3417 }
3418 } while (false);
3419
3420 if (check_ecn) {
3421 if (tcp_heuristic_do_ecn_with_address(client->current_route->rt_ifp,
3422 (union sockaddr_in_4_6 *)&flow->local_addr)) {
3423 *flags |= NECP_CLIENT_RESULT_FLAG_ECN_ENABLED;
3424 }
3425 }
3426
3427 if ((parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_TFO_ENABLE) ==
3428 NECP_CLIENT_PARAMETER_FLAG_TFO_ENABLE) {
3429
3430 if (!tcp_heuristic_do_tfo_with_address(client->current_route->rt_ifp,
3431 (union sockaddr_in_4_6 *)&flow->local_addr,
3432 (union sockaddr_in_4_6 *)&flow->remote_addr,
3433 tfo_cookie, tfo_cookie_len)) {
3434 *flags |= NECP_CLIENT_RESULT_FLAG_FAST_OPEN_BLOCKED;
3435 *tfo_cookie_len = 0;
3436 }
3437 } else {
3438 *flags |= NECP_CLIENT_RESULT_FLAG_FAST_OPEN_BLOCKED;
3439 *tfo_cookie_len = 0;
3440 }
3441 do_unlock:
3442 NECP_CLIENT_ROUTE_UNLOCK(client);
3443
3444 return (error);
3445 }
3446
3447 static int
3448 necp_client_copy_internal(struct necp_client *client, bool client_is_observed, struct necp_client_action_args *uap, int *retval)
3449 {
3450 int error = 0;
3451 // Copy results out
3452 if (uap->action == NECP_CLIENT_ACTION_COPY_PARAMETERS) {
3453 if (uap->buffer_size < client->parameters_length) {
3454 error = EINVAL;
3455 goto done;
3456 }
3457 error = copyout(client->parameters, uap->buffer, client->parameters_length);
3458 if (error) {
3459 NECPLOG(LOG_ERR, "necp_client_copy parameters copyout error (%d)", error);
3460 goto done;
3461 }
3462 *retval = client->parameters_length;
3463 } else if (uap->action == NECP_CLIENT_ACTION_COPY_UPDATED_RESULT &&
3464 client->result_read && client->flow_result_read) {
3465 // Copy updates only, but nothing to read
3466 // Just return 0 for bytes read
3467 *retval = 0;
3468 } else if (uap->action == NECP_CLIENT_ACTION_COPY_RESULT ||
3469 uap->action == NECP_CLIENT_ACTION_COPY_UPDATED_RESULT) {
3470 size_t assigned_results_size = 0;
3471 struct necp_client_flow *flow = NULL;
3472 LIST_FOREACH(flow, &client->flow_list, flow_chain) {
3473 if (flow->nexus || (flow->socket && flow->assigned)) {
3474 size_t header_length = 0;
3475 if (flow->nexus) {
3476 header_length = sizeof(struct necp_client_nexus_flow_header);
3477 } else {
3478 header_length = sizeof(struct necp_client_flow_header);
3479 }
3480 assigned_results_size += (header_length + flow->assigned_results_length);
3481
3482 if (flow->has_protoctl_event) {
3483 assigned_results_size += sizeof(struct necp_client_flow_protoctl_event_header);
3484 }
3485 }
3486 }
3487 if (uap->buffer_size < (client->result_length + assigned_results_size)) {
3488 error = EINVAL;
3489 goto done;
3490 }
3491 error = copyout(client->result, uap->buffer, client->result_length);
3492 if (error) {
3493 NECPLOG(LOG_ERR, "necp_client_copy result copyout error (%d)", error);
3494 goto done;
3495 }
3496
3497 size_t assigned_results_cursor = 0;
3498
3499 flow = NULL;
3500 LIST_FOREACH(flow, &client->flow_list, flow_chain) {
3501 if (flow->nexus || (flow->socket && flow->assigned)) {
3502 // Write TLV headers
3503 struct necp_client_nexus_flow_header header;
3504 u_int32_t length = 0;
3505 u_int32_t flags = 0;
3506 u_int8_t tfo_cookie_len = 0;
3507 u_int8_t type = 0;
3508
3509 if (flow->nexus) {
3510 if (flow->check_tcp_heuristics) {
3511 u_int8_t tfo_cookie[NECP_TFO_COOKIE_LEN_MAX];
3512 tfo_cookie_len = NECP_TFO_COOKIE_LEN_MAX;
3513
3514 if (necp_client_check_tcp_heuristics(client, flow, &flags,
3515 tfo_cookie, &tfo_cookie_len) != 0) {
3516 tfo_cookie_len = 0;
3517 } else {
3518 flow->check_tcp_heuristics = FALSE;
3519
3520 if (tfo_cookie_len != 0) {
3521 type = NECP_CLIENT_RESULT_TFO_COOKIE;
3522 length = tfo_cookie_len;
3523 memcpy(&header.tfo_cookie_tlv_header.type, &type, sizeof(type));
3524 memcpy(&header.tfo_cookie_tlv_header.length, &length, sizeof(length));
3525 memcpy(&header.tfo_cookie_value, tfo_cookie, tfo_cookie_len);
3526 }
3527 }
3528 }
3529 }
3530
3531 size_t header_length = 0;
3532 if (flow->nexus) {
3533 if (tfo_cookie_len != 0) {
3534 header_length = sizeof(struct necp_client_nexus_flow_header) - (NECP_TFO_COOKIE_LEN_MAX - tfo_cookie_len);
3535 } else {
3536 header_length = sizeof(struct necp_client_nexus_flow_header) - sizeof(struct necp_tlv_header) - NECP_TFO_COOKIE_LEN_MAX;
3537 }
3538 } else {
3539 header_length = sizeof(struct necp_client_flow_header);
3540 }
3541
3542 type = NECP_CLIENT_RESULT_FLAGS;
3543 length = sizeof(header.flow_header.flags_value);
3544 memcpy(&header.flow_header.flags_tlv_header.type, &type, sizeof(type));
3545 memcpy(&header.flow_header.flags_tlv_header.length, &length, sizeof(length));
3546 if (flow->assigned) {
3547 flags |= NECP_CLIENT_RESULT_FLAG_FLOW_ASSIGNED;
3548 }
3549 if (flow->viable) {
3550 flags |= NECP_CLIENT_RESULT_FLAG_FLOW_VIABLE;
3551 }
3552 memcpy(&header.flow_header.flags_value, &flags, sizeof(flags));
3553
3554 type = NECP_CLIENT_RESULT_INTERFACE;
3555 length = sizeof(header.flow_header.interface_value);
3556 memcpy(&header.flow_header.interface_tlv_header.type, &type, sizeof(type));
3557 memcpy(&header.flow_header.interface_tlv_header.length, &length, sizeof(length));
3558
3559 struct necp_client_result_interface interface_struct;
3560 interface_struct.generation = 0;
3561 interface_struct.index = flow->interface_index;
3562
3563 memcpy(&header.flow_header.interface_value, &interface_struct, sizeof(interface_struct));
3564 if (flow->nexus) {
3565 type = NECP_CLIENT_RESULT_NETAGENT;
3566 length = sizeof(header.agent_value);
3567 memcpy(&header.agent_tlv_header.type, &type, sizeof(type));
3568 memcpy(&header.agent_tlv_header.length, &length, sizeof(length));
3569
3570 struct necp_client_result_netagent agent_struct;
3571 agent_struct.generation = 0;
3572 uuid_copy(agent_struct.netagent_uuid, flow->u.nexus_agent);
3573
3574 memcpy(&header.agent_value, &agent_struct, sizeof(agent_struct));
3575 }
3576
3577 // Don't include outer TLV header in length field
3578 type = NECP_CLIENT_RESULT_FLOW;
3579 length = (header_length - sizeof(struct necp_tlv_header) + flow->assigned_results_length);
3580 if (flow->has_protoctl_event) {
3581 length += sizeof(struct necp_client_flow_protoctl_event_header);
3582 }
3583 memcpy(&header.flow_header.outer_header.type, &type, sizeof(type));
3584 memcpy(&header.flow_header.outer_header.length, &length, sizeof(length));
3585
3586 error = copyout(&header, uap->buffer + client->result_length + assigned_results_cursor, header_length);
3587 if (error) {
3588 NECPLOG(LOG_ERR, "necp_client_copy assigned results tlv_header copyout error (%d)", error);
3589 goto done;
3590 }
3591 assigned_results_cursor += header_length;
3592
3593 if (flow->assigned_results && flow->assigned_results_length) {
3594 // Write inner TLVs
3595 error = copyout(flow->assigned_results, uap->buffer + client->result_length + assigned_results_cursor,
3596 flow->assigned_results_length);
3597 if (error) {
3598 NECPLOG(LOG_ERR, "necp_client_copy assigned results copyout error (%d)", error);
3599 goto done;
3600 }
3601 }
3602 assigned_results_cursor += flow->assigned_results_length;
3603
3604 /* Read the protocol event and reset it */
3605 if (flow->has_protoctl_event) {
3606 struct necp_client_flow_protoctl_event_header protoctl_event_header;
3607
3608 type = NECP_CLIENT_RESULT_PROTO_CTL_EVENT;
3609 length = sizeof(protoctl_event_header.protoctl_event);
3610
3611 memcpy(&protoctl_event_header.protoctl_tlv_header.type, &type, sizeof(type));
3612 memcpy(&protoctl_event_header.protoctl_tlv_header.length, &length, sizeof(length));
3613 memcpy(&protoctl_event_header.protoctl_event, &flow->protoctl_event,
3614 sizeof(flow->protoctl_event));
3615
3616 error = copyout(&protoctl_event_header, uap->buffer + client->result_length + assigned_results_cursor,
3617 sizeof(protoctl_event_header));
3618
3619 if (error) {
3620 NECPLOG(LOG_ERR, "necp_client_copy protocol control event results"
3621 " tlv_header copyout error (%d)", error);
3622 goto done;
3623 }
3624 assigned_results_cursor += sizeof(protoctl_event_header);
3625 flow->has_protoctl_event = FALSE;
3626 flow->protoctl_event.protoctl_event_code = 0;
3627 flow->protoctl_event.protoctl_event_val = 0;
3628 flow->protoctl_event.protoctl_event_tcp_seq_num = 0;
3629 }
3630 }
3631 }
3632
3633 *retval = client->result_length + assigned_results_cursor;
3634
3635 if (!client_is_observed) {
3636 client->result_read = TRUE;
3637 client->flow_result_read = TRUE;
3638 }
3639 }
3640
3641 done:
3642 return (error);
3643 }
3644
3645 static int
3646 necp_client_copy(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
3647 {
3648 int error = 0;
3649 struct necp_client *find_client = NULL;
3650 struct necp_client *client = NULL;
3651 uuid_t client_id;
3652 uuid_clear(client_id);
3653
3654 *retval = 0;
3655
3656 if (uap->buffer_size == 0 || uap->buffer == 0) {
3657 error = EINVAL;
3658 goto done;
3659 }
3660
3661 if (uap->action != NECP_CLIENT_ACTION_COPY_PARAMETERS &&
3662 uap->action != NECP_CLIENT_ACTION_COPY_RESULT &&
3663 uap->action != NECP_CLIENT_ACTION_COPY_UPDATED_RESULT) {
3664 error = EINVAL;
3665 goto done;
3666 }
3667
3668 if (uap->client_id) {
3669 if (uap->client_id_len != sizeof(uuid_t)) {
3670 NECPLOG(LOG_ERR, "Incorrect length (got %d, expected %d)", uap->client_id_len, sizeof(uuid_t));
3671 error = ERANGE;
3672 goto done;
3673 }
3674
3675 error = copyin(uap->client_id, client_id, sizeof(uuid_t));
3676 if (error) {
3677 NECPLOG(LOG_ERR, "necp_client_copy client_id copyin error (%d)", error);
3678 goto done;
3679 }
3680 }
3681
3682 NECP_FD_LOCK(fd_data);
3683 RB_FOREACH(find_client, _necp_client_tree, &fd_data->clients) {
3684 NECP_CLIENT_LOCK(find_client);
3685 if ((uap->action == NECP_CLIENT_ACTION_COPY_RESULT || uap->action == NECP_CLIENT_ACTION_COPY_UPDATED_RESULT) &&
3686 uuid_is_null(client_id)) {
3687 if (!find_client->result_read || !find_client->flow_result_read) {
3688 client = find_client;
3689 }
3690 } else if (uuid_compare(find_client->client_id, client_id) == 0) {
3691 client = find_client;
3692 }
3693 NECP_CLIENT_UNLOCK(find_client);
3694 if (client != NULL) {
3695 break;
3696 }
3697 }
3698
3699 if (client != NULL) {
3700 error = necp_client_copy_internal(client, FALSE, uap, retval);
3701 }
3702
3703 // Unlock our own client before moving on or returning
3704 NECP_FD_UNLOCK(fd_data);
3705
3706 if (client == NULL) {
3707 if (fd_data->flags & NECP_OPEN_FLAG_OBSERVER) {
3708 // Observers are allowed to lookup clients on other fds
3709
3710 // Lock tree
3711 NECP_CLIENT_TREE_LOCK_SHARED();
3712
3713 bool found_client = FALSE;
3714
3715 struct necp_client find;
3716 uuid_copy(find.client_id, client_id);
3717 client = RB_FIND(_necp_client_global_tree, &necp_client_global_tree, &find);
3718 if (client != NULL) {
3719 NECP_CLIENT_LOCK(client);
3720
3721 // Matched, copy out data
3722 found_client = TRUE;
3723 error = necp_client_copy_internal(client, TRUE, uap, retval);
3724
3725 NECP_CLIENT_UNLOCK(client);
3726 }
3727
3728 // Unlock tree
3729 NECP_CLIENT_TREE_UNLOCK();
3730
3731 // No client found, fail
3732 if (!found_client) {
3733 error = ENOENT;
3734 goto done;
3735 }
3736 } else {
3737 // No client found, and not allowed to search other fds, fail
3738 error = ENOENT;
3739 goto done;
3740 }
3741 }
3742
3743 done:
3744 return (error);
3745 }
3746
3747 static int
3748 necp_client_copy_client_update(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
3749 {
3750 int error = 0;
3751
3752 *retval = 0;
3753
3754 if (!(fd_data->flags & NECP_OPEN_FLAG_PUSH_OBSERVER)) {
3755 NECPLOG0(LOG_ERR, "NECP fd is not observer, cannot copy client update");
3756 return (EINVAL);
3757 }
3758
3759 if (uap->client_id_len != sizeof(uuid_t) || uap->client_id == 0) {
3760 NECPLOG0(LOG_ERR, "Client id invalid, cannot copy client update");
3761 return (EINVAL);
3762 }
3763
3764 if (uap->buffer_size == 0 || uap->buffer == 0) {
3765 NECPLOG0(LOG_ERR, "Buffer invalid, cannot copy client update");
3766 return (EINVAL);
3767 }
3768
3769 NECP_FD_LOCK(fd_data);
3770 struct necp_client_update *client_update = TAILQ_FIRST(&fd_data->update_list);
3771 if (client_update != NULL) {
3772 TAILQ_REMOVE(&fd_data->update_list, client_update, chain);
3773 VERIFY(fd_data->update_count > 0);
3774 fd_data->update_count--;
3775 }
3776 NECP_FD_UNLOCK(fd_data);
3777
3778 if (client_update != NULL) {
3779 error = copyout(client_update->client_id, uap->client_id, sizeof(uuid_t));
3780 if (error) {
3781 NECPLOG(LOG_ERR, "Copy client update copyout client id error (%d)", error);
3782 } else {
3783 if (uap->buffer_size < client_update->update_length) {
3784 NECPLOG(LOG_ERR, "Buffer size cannot hold update (%zu < %zu)", uap->buffer_size, client_update->update_length);
3785 error = EINVAL;
3786 } else {
3787 error = copyout(&client_update->update, uap->buffer, client_update->update_length);
3788 if (error) {
3789 NECPLOG(LOG_ERR, "Copy client update copyout error (%d)", error);
3790 } else {
3791 *retval = client_update->update_length;
3792 }
3793 }
3794 }
3795
3796 FREE(client_update, M_NECP);
3797 client_update = NULL;
3798 } else {
3799 error = ENOENT;
3800 }
3801
3802 return (error);
3803 }
3804
3805 static int
3806 necp_client_copy_parameters_locked(struct necp_client *client, struct necp_client_nexus_parameters *parameters)
3807 {
3808 VERIFY(parameters != NULL);
3809
3810 struct necp_client_parsed_parameters parsed_parameters = {};
3811 int error = necp_client_parse_parameters(client->parameters, (u_int32_t)client->parameters_length, &parsed_parameters);
3812
3813 parameters->pid = client->proc_pid;
3814 if (parsed_parameters.valid_fields & NECP_PARSED_PARAMETERS_FIELD_EFFECTIVE_PID) {
3815 parameters->epid = parsed_parameters.effective_pid;
3816 } else {
3817 parameters->epid = parameters->pid;
3818 }
3819 memcpy(&parameters->local_addr, &parsed_parameters.local_addr, sizeof(parameters->local_addr));
3820 memcpy(&parameters->remote_addr, &parsed_parameters.remote_addr, sizeof(parameters->remote_addr));
3821 parameters->ip_protocol = parsed_parameters.ip_protocol;
3822 parameters->traffic_class = parsed_parameters.traffic_class;
3823 uuid_copy(parameters->euuid, parsed_parameters.effective_uuid);
3824 parameters->is_listener = (parsed_parameters.flags & NECP_CLIENT_PARAMETER_FLAG_LISTENER) ? 1 : 0;
3825 parameters->policy_id = client->policy_id;
3826
3827 // parse client result flag
3828 u_int32_t client_result_flags = 0;
3829 u_int32_t value_size = 0;
3830 u_int8_t *flags_pointer = NULL;
3831 flags_pointer = necp_buffer_get_tlv_value(client->result, 0, &value_size);
3832 if (flags_pointer && value_size == sizeof(client_result_flags)) {
3833 memcpy(&client_result_flags, flags_pointer, value_size);
3834 }
3835 parameters->allow_qos_marking = (client_result_flags & NECP_CLIENT_RESULT_FLAG_ALLOW_QOS_MARKING) ? 1 : 0;
3836
3837 return (error);
3838 }
3839
3840 int
3841 necp_client_copy_parameters(uuid_t client_id, struct necp_client_nexus_parameters *parameters)
3842 {
3843 int error = 0;
3844 struct necp_client *client = NULL;
3845
3846 if (parameters == NULL) {
3847 return EINVAL;
3848 }
3849
3850 // Lock tree
3851 NECP_CLIENT_TREE_LOCK_SHARED();
3852
3853 bool found_client = FALSE;
3854 struct necp_client find;
3855 uuid_copy(find.client_id, client_id);
3856 client = RB_FIND(_necp_client_global_tree, &necp_client_global_tree, &find);
3857 if (client != NULL) {
3858 NECP_CLIENT_LOCK(client);
3859
3860 // Matched, parse parameters
3861 found_client = TRUE;
3862 error = necp_client_copy_parameters_locked(client, parameters);
3863
3864 NECP_CLIENT_UNLOCK(client);
3865 }
3866
3867 // Unlock tree
3868 NECP_CLIENT_TREE_UNLOCK();
3869
3870 // No client found, fail
3871 if (!found_client) {
3872 return ENOENT;
3873 }
3874
3875 return error;
3876 }
3877
3878 static int
3879 necp_client_list(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
3880 {
3881 int error = 0;
3882 struct necp_client *find_client = NULL;
3883 uuid_t *list = NULL;
3884 u_int32_t requested_client_count = 0;
3885 u_int32_t client_count = 0;
3886 size_t copy_buffer_size = 0;
3887
3888 if (uap->buffer_size < sizeof(requested_client_count) || uap->buffer == 0) {
3889 error = EINVAL;
3890 goto done;
3891 }
3892
3893 if (!(fd_data->flags & NECP_OPEN_FLAG_OBSERVER)) {
3894 NECPLOG0(LOG_ERR, "Client does not hold necessary entitlement to list other NECP clients");
3895 error = EACCES;
3896 goto done;
3897 }
3898
3899 error = copyin(uap->buffer, &requested_client_count, sizeof(requested_client_count));
3900 if (error) {
3901 goto done;
3902 }
3903
3904 if (os_mul_overflow(sizeof(uuid_t), requested_client_count, &copy_buffer_size)) {
3905 error = ERANGE;
3906 goto done;
3907 }
3908
3909 if (uap->buffer_size - sizeof(requested_client_count) != copy_buffer_size) {
3910 error = EINVAL;
3911 goto done;
3912 }
3913
3914 if (copy_buffer_size > NECP_MAX_CLIENT_LIST_SIZE) {
3915 error = EINVAL;
3916 goto done;
3917 }
3918
3919 if (requested_client_count > 0) {
3920 if ((list = _MALLOC(copy_buffer_size, M_NECP, M_WAITOK | M_ZERO)) == NULL) {
3921 error = ENOMEM;
3922 goto done;
3923 }
3924 }
3925
3926 // Lock tree
3927 NECP_CLIENT_TREE_LOCK_SHARED();
3928
3929 find_client = NULL;
3930 RB_FOREACH(find_client, _necp_client_global_tree, &necp_client_global_tree) {
3931 NECP_CLIENT_LOCK(find_client);
3932 if (!uuid_is_null(find_client->client_id)) {
3933 if (client_count < requested_client_count) {
3934 uuid_copy(list[client_count], find_client->client_id);
3935 }
3936 client_count++;
3937 }
3938 NECP_CLIENT_UNLOCK(find_client);
3939 }
3940
3941 // Unlock tree
3942 NECP_CLIENT_TREE_UNLOCK();
3943
3944 error = copyout(&client_count, uap->buffer, sizeof(client_count));
3945 if (error) {
3946 NECPLOG(LOG_ERR, "necp_client_list buffer copyout error (%d)", error);
3947 goto done;
3948 }
3949
3950 if (requested_client_count > 0 &&
3951 client_count > 0 &&
3952 list != NULL) {
3953 error = copyout(list, uap->buffer + sizeof(client_count), copy_buffer_size);
3954 if (error) {
3955 NECPLOG(LOG_ERR, "necp_client_list client count copyout error (%d)", error);
3956 goto done;
3957 }
3958 }
3959 done:
3960 if (list != NULL) {
3961 FREE(list, M_NECP);
3962 }
3963 *retval = error;
3964
3965 return (error);
3966 }
3967
3968
3969 static void
3970 necp_client_add_assertion(struct necp_client *client, uuid_t netagent_uuid)
3971 {
3972 struct necp_client_assertion *new_assertion = NULL;
3973
3974 MALLOC(new_assertion, struct necp_client_assertion *, sizeof(*new_assertion), M_NECP, M_WAITOK);
3975 if (new_assertion == NULL) {
3976 NECPLOG0(LOG_ERR, "Failed to allocate assertion");
3977 return;
3978 }
3979
3980 uuid_copy(new_assertion->asserted_netagent, netagent_uuid);
3981
3982 LIST_INSERT_HEAD(&client->assertion_list, new_assertion, assertion_chain);
3983 }
3984
3985 static bool
3986 necp_client_remove_assertion(struct necp_client *client, uuid_t netagent_uuid)
3987 {
3988 struct necp_client_assertion *found_assertion = NULL;
3989 struct necp_client_assertion *search_assertion = NULL;
3990 LIST_FOREACH(search_assertion, &client->assertion_list, assertion_chain) {
3991 if (uuid_compare(search_assertion->asserted_netagent, netagent_uuid) == 0) {
3992 found_assertion = search_assertion;
3993 break;
3994 }
3995 }
3996
3997 if (found_assertion == NULL) {
3998 NECPLOG0(LOG_ERR, "Netagent uuid not previously asserted");
3999 return false;
4000 }
4001
4002 LIST_REMOVE(found_assertion, assertion_chain);
4003 FREE(found_assertion, M_NECP);
4004 return true;
4005 }
4006
4007 static int
4008 necp_client_agent_action(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
4009 {
4010 int error = 0;
4011 struct necp_client *client = NULL;
4012 uuid_t client_id;
4013 bool acted_on_agent = FALSE;
4014 u_int8_t *parameters = NULL;
4015 size_t parameters_size = uap->buffer_size;
4016
4017 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t) ||
4018 uap->buffer_size == 0 || uap->buffer == 0) {
4019 error = EINVAL;
4020 goto done;
4021 }
4022
4023 error = copyin(uap->client_id, client_id, sizeof(uuid_t));
4024 if (error) {
4025 NECPLOG(LOG_ERR, "necp_client_agent_action copyin client_id error (%d)", error);
4026 goto done;
4027 }
4028
4029 if ((parameters = _MALLOC(uap->buffer_size, M_NECP, M_WAITOK | M_ZERO)) == NULL) {
4030 error = ENOMEM;
4031 goto done;
4032 }
4033
4034 error = copyin(uap->buffer, parameters, uap->buffer_size);
4035 if (error) {
4036 NECPLOG(LOG_ERR, "necp_client_agent_action parameters copyin error (%d)", error);
4037 goto done;
4038 }
4039
4040 NECP_FD_LOCK(fd_data);
4041 client = necp_client_fd_find_client_and_lock(fd_data, client_id);
4042 if (client != NULL) {
4043 size_t offset = 0;
4044 while ((offset + sizeof(struct necp_tlv_header)) <= parameters_size) {
4045 u_int8_t type = necp_buffer_get_tlv_type(parameters, offset);
4046 u_int32_t length = necp_buffer_get_tlv_length(parameters, offset);
4047
4048 if (length > (parameters_size - (offset + sizeof(struct necp_tlv_header)))) {
4049 // If the length is larger than what can fit in the remaining parameters size, bail
4050 NECPLOG(LOG_ERR, "Invalid TLV length (%u)", length);
4051 break;
4052 }
4053
4054 if (length > 0) {
4055 u_int8_t *value = necp_buffer_get_tlv_value(parameters, offset, NULL);
4056 if (length >= sizeof(uuid_t) &&
4057 value != NULL &&
4058 (type == NECP_CLIENT_PARAMETER_TRIGGER_AGENT ||
4059 type == NECP_CLIENT_PARAMETER_ASSERT_AGENT ||
4060 type == NECP_CLIENT_PARAMETER_UNASSERT_AGENT)) {
4061
4062 uuid_t agent_uuid;
4063 uuid_copy(agent_uuid, value);
4064 u_int8_t netagent_message_type = 0;
4065 if (type == NECP_CLIENT_PARAMETER_TRIGGER_AGENT) {
4066 netagent_message_type = NETAGENT_MESSAGE_TYPE_CLIENT_TRIGGER;
4067 } else if (type == NECP_CLIENT_PARAMETER_ASSERT_AGENT) {
4068 netagent_message_type = NETAGENT_MESSAGE_TYPE_CLIENT_ASSERT;
4069 } else if (type == NECP_CLIENT_PARAMETER_UNASSERT_AGENT) {
4070 netagent_message_type = NETAGENT_MESSAGE_TYPE_CLIENT_UNASSERT;
4071 }
4072
4073 // Before unasserting, verify that the assertion was already taken
4074 if (type == NECP_CLIENT_PARAMETER_UNASSERT_AGENT) {
4075 if (!necp_client_remove_assertion(client, agent_uuid)) {
4076 error = ENOENT;
4077 break;
4078 }
4079 }
4080
4081 struct necp_client_nexus_parameters parsed_parameters = {};
4082 necp_client_copy_parameters_locked(client, &parsed_parameters);
4083
4084 error = netagent_client_message_with_params(agent_uuid,
4085 client_id,
4086 fd_data->proc_pid,
4087 netagent_message_type,
4088 &parsed_parameters,
4089 NULL, NULL);
4090 if (error == 0) {
4091 acted_on_agent = TRUE;
4092 } else {
4093 break;
4094 }
4095
4096 // Only save the assertion if the action succeeded
4097 if (type == NECP_CLIENT_PARAMETER_ASSERT_AGENT) {
4098 necp_client_add_assertion(client, agent_uuid);
4099 }
4100 }
4101 }
4102
4103 offset += sizeof(struct necp_tlv_header) + length;
4104 }
4105
4106 NECP_CLIENT_UNLOCK(client);
4107 }
4108 NECP_FD_UNLOCK(fd_data);
4109
4110 if (!acted_on_agent &&
4111 error == 0) {
4112 error = ENOENT;
4113 }
4114 done:
4115 *retval = error;
4116 if (parameters != NULL) {
4117 FREE(parameters, M_NECP);
4118 parameters = NULL;
4119 }
4120
4121 return (error);
4122 }
4123
4124 static int
4125 necp_client_copy_agent(__unused struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
4126 {
4127 int error = 0;
4128 uuid_t agent_uuid;
4129
4130 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t) ||
4131 uap->buffer_size == 0 || uap->buffer == 0) {
4132 NECPLOG0(LOG_ERR, "necp_client_copy_agent bad input");
4133 error = EINVAL;
4134 goto done;
4135 }
4136
4137 error = copyin(uap->client_id, agent_uuid, sizeof(uuid_t));
4138 if (error) {
4139 NECPLOG(LOG_ERR, "necp_client_copy_agent copyin agent_uuid error (%d)", error);
4140 goto done;
4141 }
4142
4143 error = netagent_copyout(agent_uuid, uap->buffer, uap->buffer_size);
4144 if (error) {
4145 // netagent_copyout already logs appropriate errors
4146 goto done;
4147 }
4148 done:
4149 *retval = error;
4150
4151 return (error);
4152 }
4153
4154 static int
4155 necp_client_agent_use(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
4156 {
4157 int error = 0;
4158 struct necp_client *client = NULL;
4159 uuid_t client_id;
4160 struct necp_agent_use_parameters parameters;
4161
4162 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t) ||
4163 uap->buffer_size != sizeof(parameters) || uap->buffer == 0) {
4164 error = EINVAL;
4165 goto done;
4166 }
4167
4168 error = copyin(uap->client_id, client_id, sizeof(uuid_t));
4169 if (error) {
4170 NECPLOG(LOG_ERR, "Copyin client_id error (%d)", error);
4171 goto done;
4172 }
4173
4174 error = copyin(uap->buffer, &parameters, uap->buffer_size);
4175 if (error) {
4176 NECPLOG(LOG_ERR, "Parameters copyin error (%d)", error);
4177 goto done;
4178 }
4179
4180 NECP_FD_LOCK(fd_data);
4181 client = necp_client_fd_find_client_and_lock(fd_data, client_id);
4182 if (client != NULL) {
4183 error = netagent_use(parameters.agent_uuid, &parameters.out_use_count);
4184 NECP_CLIENT_UNLOCK(client);
4185 } else {
4186 error = ENOENT;
4187 }
4188
4189 NECP_FD_UNLOCK(fd_data);
4190
4191 if (error == 0) {
4192 error = copyout(&parameters, uap->buffer, uap->buffer_size);
4193 if (error) {
4194 NECPLOG(LOG_ERR, "Parameters copyout error (%d)", error);
4195 goto done;
4196 }
4197 }
4198
4199 done:
4200 *retval = error;
4201
4202 return (error);
4203 }
4204
4205 static int
4206 necp_client_copy_interface(__unused struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
4207 {
4208 int error = 0;
4209 u_int32_t interface_index = 0;
4210 struct necp_interface_details interface_details;
4211
4212 if (uap->client_id == 0 || uap->client_id_len != sizeof(u_int32_t) ||
4213 uap->buffer_size < sizeof(interface_details) || uap->buffer == 0) {
4214 NECPLOG0(LOG_ERR, "necp_client_copy_interface bad input");
4215 error = EINVAL;
4216 goto done;
4217 }
4218
4219 error = copyin(uap->client_id, &interface_index, sizeof(u_int32_t));
4220 if (error) {
4221 NECPLOG(LOG_ERR, "necp_client_copy_interface copyin interface_index error (%d)", error);
4222 goto done;
4223 }
4224
4225 if (interface_index == 0) {
4226 error = ENOENT;
4227 NECPLOG(LOG_ERR, "necp_client_copy_interface bad interface_index (%d)", interface_index);
4228 goto done;
4229 }
4230
4231 memset(&interface_details, 0, sizeof(interface_details));
4232
4233 ifnet_head_lock_shared();
4234 ifnet_t interface = NULL;
4235 if (interface_index != IFSCOPE_NONE && interface_index <= (u_int32_t)if_index) {
4236 interface = ifindex2ifnet[interface_index];
4237 }
4238
4239 if (interface != NULL) {
4240 if (interface->if_xname != NULL) {
4241 strlcpy((char *)&interface_details.name, interface->if_xname, sizeof(interface_details.name));
4242 }
4243 interface_details.index = interface->if_index;
4244 interface_details.generation = ifnet_get_generation(interface);
4245 if (interface->if_delegated.ifp != NULL) {
4246 interface_details.delegate_index = interface->if_delegated.ifp->if_index;
4247 }
4248 interface_details.functional_type = if_functional_type(interface, TRUE);
4249 if (IFNET_IS_EXPENSIVE(interface)) {
4250 interface_details.flags |= NECP_INTERFACE_FLAG_EXPENSIVE;
4251 }
4252 if ((interface->if_eflags & IFEF_TXSTART) == IFEF_TXSTART) {
4253 interface_details.flags |= NECP_INTERFACE_FLAG_TXSTART;
4254 }
4255 if ((interface->if_eflags & IFEF_NOACKPRI) == IFEF_NOACKPRI) {
4256 interface_details.flags |= NECP_INTERFACE_FLAG_NOACKPRI;
4257 }
4258 interface_details.mtu = interface->if_mtu;
4259
4260 u_int8_t ipv4_signature_len = sizeof(interface_details.ipv4_signature.signature);
4261 u_int16_t ipv4_signature_flags;
4262 if (ifnet_get_netsignature(interface, AF_INET, &ipv4_signature_len, &ipv4_signature_flags,
4263 (u_int8_t *)&interface_details.ipv4_signature) != 0) {
4264 ipv4_signature_len = 0;
4265 }
4266 interface_details.ipv4_signature.signature_len = ipv4_signature_len;
4267
4268 u_int8_t ipv6_signature_len = sizeof(interface_details.ipv6_signature.signature);
4269 u_int16_t ipv6_signature_flags;
4270 if (ifnet_get_netsignature(interface, AF_INET6, &ipv6_signature_len, &ipv6_signature_flags,
4271 (u_int8_t *)&interface_details.ipv6_signature) != 0) {
4272 ipv6_signature_len = 0;
4273 }
4274 interface_details.ipv6_signature.signature_len = ipv6_signature_len;
4275 }
4276
4277 ifnet_head_done();
4278
4279 error = copyout(&interface_details, uap->buffer, sizeof(interface_details));
4280 if (error) {
4281 NECPLOG(LOG_ERR, "necp_client_copy_interface copyout error (%d)", error);
4282 goto done;
4283 }
4284 done:
4285 *retval = error;
4286
4287 return (error);
4288 }
4289
4290
4291 static int
4292 necp_client_copy_route_statistics(__unused struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
4293 {
4294 int error = 0;
4295 struct necp_client *client = NULL;
4296 uuid_t client_id;
4297
4298 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t) ||
4299 uap->buffer_size < sizeof(struct necp_stat_counts) || uap->buffer == 0) {
4300 NECPLOG0(LOG_ERR, "necp_client_copy_route_statistics bad input");
4301 error = EINVAL;
4302 goto done;
4303 }
4304
4305 error = copyin(uap->client_id, client_id, sizeof(uuid_t));
4306 if (error) {
4307 NECPLOG(LOG_ERR, "necp_client_copy_route_statistics copyin client_id error (%d)", error);
4308 goto done;
4309 }
4310
4311 // Lock
4312 NECP_FD_LOCK(fd_data);
4313 client = necp_client_fd_find_client_and_lock(fd_data, client_id);
4314 if (client != NULL) {
4315 NECP_CLIENT_ROUTE_LOCK(client);
4316 struct nstat_counts route_stats = {};
4317 if (client->current_route != NULL && client->current_route->rt_stats != NULL) {
4318 struct nstat_counts *rt_stats = client->current_route->rt_stats;
4319 atomic_get_64(route_stats.nstat_rxpackets, &rt_stats->nstat_rxpackets);
4320 atomic_get_64(route_stats.nstat_rxbytes, &rt_stats->nstat_rxbytes);
4321 atomic_get_64(route_stats.nstat_txpackets, &rt_stats->nstat_txpackets);
4322 atomic_get_64(route_stats.nstat_txbytes, &rt_stats->nstat_txbytes);
4323 route_stats.nstat_rxduplicatebytes = rt_stats->nstat_rxduplicatebytes;
4324 route_stats.nstat_rxoutoforderbytes = rt_stats->nstat_rxoutoforderbytes;
4325 route_stats.nstat_txretransmit = rt_stats->nstat_txretransmit;
4326 route_stats.nstat_connectattempts = rt_stats->nstat_connectattempts;
4327 route_stats.nstat_connectsuccesses = rt_stats->nstat_connectsuccesses;
4328 route_stats.nstat_min_rtt = rt_stats->nstat_min_rtt;
4329 route_stats.nstat_avg_rtt = rt_stats->nstat_avg_rtt;
4330 route_stats.nstat_var_rtt = rt_stats->nstat_var_rtt;
4331 }
4332
4333 // Unlock before copying out
4334 NECP_CLIENT_ROUTE_UNLOCK(client);
4335 NECP_CLIENT_UNLOCK(client);
4336 NECP_FD_UNLOCK(fd_data);
4337
4338 error = copyout(&route_stats, uap->buffer, sizeof(route_stats));
4339 if (error) {
4340 NECPLOG(LOG_ERR, "necp_client_copy_route_statistics copyout error (%d)", error);
4341 }
4342 } else {
4343 // Unlock
4344 NECP_FD_UNLOCK(fd_data);
4345 error = ENOENT;
4346 }
4347
4348
4349 done:
4350 *retval = error;
4351 return (error);
4352 }
4353
4354 static int
4355 necp_client_update_cache(struct necp_fd_data *fd_data, struct necp_client_action_args *uap, int *retval)
4356 {
4357 int error = 0;
4358 struct necp_client *client = NULL;
4359 uuid_t client_id;
4360
4361 if (uap->client_id == 0 || uap->client_id_len != sizeof(uuid_t)) {
4362 error = EINVAL;
4363 goto done;
4364 }
4365
4366 error = copyin(uap->client_id, client_id, sizeof(uuid_t));
4367 if (error) {
4368 NECPLOG(LOG_ERR, "necp_client_update_cache copyin client_id error (%d)", error);
4369 goto done;
4370 }
4371
4372 NECP_FD_LOCK(fd_data);
4373 client = necp_client_fd_find_client_and_lock(fd_data, client_id);
4374 if (client == NULL) {
4375 NECP_FD_UNLOCK(fd_data);
4376 error = ENOENT;
4377 goto done;
4378 }
4379
4380 NECP_CLIENT_ROUTE_LOCK(client);
4381 // This needs to be changed when TFO/ECN is supported by multiple flows
4382 struct necp_client_flow *flow = LIST_FIRST(&client->flow_list);
4383 if (flow == NULL ||
4384 (flow->remote_addr.sa.sa_family != AF_INET &&
4385 flow->remote_addr.sa.sa_family != AF_INET6) ||
4386 (flow->local_addr.sa.sa_family != AF_INET &&
4387 flow->local_addr.sa.sa_family != AF_INET6)) {
4388 error = EINVAL;
4389 NECPLOG(LOG_ERR, "necp_client_update_cache no flow error (%d)", error);
4390 goto done_unlock;
4391 }
4392
4393 necp_cache_buffer cache_buffer;
4394 memset(&cache_buffer, 0, sizeof(cache_buffer));
4395
4396 if (uap->buffer_size != sizeof(necp_cache_buffer) ||
4397 uap->buffer == USER_ADDR_NULL) {
4398 error = EINVAL;
4399 goto done_unlock;
4400 }
4401
4402 error = copyin(uap->buffer, &cache_buffer, sizeof(cache_buffer));
4403 if (error) {
4404 NECPLOG(LOG_ERR, "necp_client_update_cache copyin cache buffer error (%d)", error);
4405 goto done_unlock;
4406 }
4407
4408 if (cache_buffer.necp_cache_buf_type == NECP_CLIENT_CACHE_TYPE_ECN &&
4409 cache_buffer.necp_cache_buf_ver == NECP_CLIENT_CACHE_TYPE_ECN_VER_1) {
4410 if (cache_buffer.necp_cache_buf_size != sizeof(necp_tcp_ecn_cache) ||
4411 cache_buffer.necp_cache_buf_addr == USER_ADDR_NULL) {
4412 error = EINVAL;
4413 goto done_unlock;
4414 }
4415
4416 necp_tcp_ecn_cache ecn_cache_buffer;
4417 memset(&ecn_cache_buffer, 0, sizeof(ecn_cache_buffer));
4418
4419 error = copyin(cache_buffer.necp_cache_buf_addr, &ecn_cache_buffer, sizeof(necp_tcp_ecn_cache));
4420 if (error) {
4421 NECPLOG(LOG_ERR, "necp_client_update_cache copyin ecn cache buffer error (%d)", error);
4422 goto done_unlock;
4423 }
4424
4425 if (client->current_route != NULL && client->current_route->rt_ifp != NULL) {
4426 if (!client->platform_binary) {
4427 ecn_cache_buffer.necp_tcp_ecn_heuristics_success = 0;
4428 }
4429 tcp_heuristics_ecn_update(&ecn_cache_buffer, client->current_route->rt_ifp,
4430 (union sockaddr_in_4_6 *)&flow->local_addr);
4431 }
4432 } else if (cache_buffer.necp_cache_buf_type == NECP_CLIENT_CACHE_TYPE_TFO &&
4433 cache_buffer.necp_cache_buf_ver == NECP_CLIENT_CACHE_TYPE_TFO_VER_1) {
4434 if (cache_buffer.necp_cache_buf_size != sizeof(necp_tcp_tfo_cache) ||
4435 cache_buffer.necp_cache_buf_addr == USER_ADDR_NULL) {
4436 error = EINVAL;
4437 goto done_unlock;
4438 }
4439
4440 necp_tcp_tfo_cache tfo_cache_buffer;
4441 memset(&tfo_cache_buffer, 0, sizeof(tfo_cache_buffer));
4442
4443 error = copyin(cache_buffer.necp_cache_buf_addr, &tfo_cache_buffer, sizeof(necp_tcp_tfo_cache));
4444 if (error) {
4445 NECPLOG(LOG_ERR, "necp_client_update_cache copyin tfo cache buffer error (%d)", error);
4446 goto done_unlock;
4447 }
4448
4449 if (client->current_route != NULL && client->current_route->rt_ifp != NULL) {
4450 if (!client->platform_binary) {
4451 tfo_cache_buffer.necp_tcp_tfo_heuristics_success = 0;
4452 }
4453 tcp_heuristics_tfo_update(&tfo_cache_buffer, client->current_route->rt_ifp,
4454 (union sockaddr_in_4_6 *)&flow->local_addr,
4455 (union sockaddr_in_4_6 *)&flow->remote_addr);
4456 }
4457 } else {
4458 error = EINVAL;
4459 }
4460 done_unlock:
4461 NECP_CLIENT_ROUTE_UNLOCK(client);
4462 NECP_CLIENT_UNLOCK(client);
4463 NECP_FD_UNLOCK(fd_data);
4464 done:
4465 *retval = error;
4466 return (error);
4467 }
4468
4469 int
4470 necp_client_action(struct proc *p, struct necp_client_action_args *uap, int *retval)
4471 {
4472 #pragma unused(p)
4473 int error = 0;
4474 int return_value = 0;
4475 struct necp_fd_data *fd_data = NULL;
4476 error = necp_find_fd_data(uap->necp_fd, &fd_data);
4477 if (error != 0) {
4478 NECPLOG(LOG_ERR, "necp_client_action find fd error (%d)", error);
4479 return (error);
4480 }
4481
4482 u_int32_t action = uap->action;
4483 switch (action) {
4484 case NECP_CLIENT_ACTION_ADD: {
4485 return_value = necp_client_add(p, fd_data, uap, retval);
4486 break;
4487 }
4488 case NECP_CLIENT_ACTION_REMOVE: {
4489 return_value = necp_client_remove(fd_data, uap, retval);
4490 break;
4491 }
4492 case NECP_CLIENT_ACTION_COPY_PARAMETERS:
4493 case NECP_CLIENT_ACTION_COPY_RESULT:
4494 case NECP_CLIENT_ACTION_COPY_UPDATED_RESULT: {
4495 return_value = necp_client_copy(fd_data, uap, retval);
4496 break;
4497 }
4498 case NECP_CLIENT_ACTION_COPY_LIST: {
4499 return_value = necp_client_list(fd_data, uap, retval);
4500 break;
4501 }
4502 case NECP_CLIENT_ACTION_AGENT: {
4503 return_value = necp_client_agent_action(fd_data, uap, retval);
4504 break;
4505 }
4506 case NECP_CLIENT_ACTION_COPY_AGENT: {
4507 return_value = necp_client_copy_agent(fd_data, uap, retval);
4508 break;
4509 }
4510 case NECP_CLIENT_ACTION_AGENT_USE: {
4511 return_value = necp_client_agent_use(fd_data, uap, retval);
4512 break;
4513 }
4514 case NECP_CLIENT_ACTION_COPY_INTERFACE: {
4515 return_value = necp_client_copy_interface(fd_data, uap, retval);
4516 break;
4517 }
4518 case NECP_CLIENT_ACTION_COPY_ROUTE_STATISTICS: {
4519 return_value = necp_client_copy_route_statistics(fd_data, uap, retval);
4520 break;
4521 }
4522 case NECP_CLIENT_ACTION_UPDATE_CACHE: {
4523 return_value = necp_client_update_cache(fd_data, uap, retval);
4524 break;
4525 }
4526 case NECP_CLIENT_ACTION_COPY_CLIENT_UPDATE: {
4527 return_value = necp_client_copy_client_update(fd_data, uap, retval);
4528 break;
4529 }
4530 default: {
4531 NECPLOG(LOG_ERR, "necp_client_action unknown action (%u)", action);
4532 return_value = EINVAL;
4533 break;
4534 }
4535 }
4536
4537 file_drop(uap->necp_fd);
4538
4539 return (return_value);
4540 }
4541
4542 #define NECP_MAX_MATCH_POLICY_PARAMETER_SIZE 1024
4543
4544 int
4545 necp_match_policy(struct proc *p, struct necp_match_policy_args *uap, int32_t *retval)
4546 {
4547 #pragma unused(retval)
4548 u_int8_t *parameters = NULL;
4549 struct necp_aggregate_result returned_result;
4550 int error = 0;
4551
4552 if (uap == NULL) {
4553 error = EINVAL;
4554 goto done;
4555 }
4556
4557 if (uap->parameters == 0 || uap->parameters_size == 0 || uap->parameters_size > NECP_MAX_MATCH_POLICY_PARAMETER_SIZE || uap->returned_result == 0) {
4558 error = EINVAL;
4559 goto done;
4560 }
4561
4562 MALLOC(parameters, u_int8_t *, uap->parameters_size, M_NECP, M_WAITOK | M_ZERO);
4563 if (parameters == NULL) {
4564 error = ENOMEM;
4565 goto done;
4566 }
4567 // Copy parameters in
4568 error = copyin(uap->parameters, parameters, uap->parameters_size);
4569 if (error) {
4570 goto done;
4571 }
4572
4573 error = necp_application_find_policy_match_internal(p, parameters, uap->parameters_size,
4574 &returned_result, NULL, 0, NULL, NULL, NULL, false);
4575 if (error) {
4576 goto done;
4577 }
4578
4579 // Copy return value back
4580 error = copyout(&returned_result, uap->returned_result, sizeof(struct necp_aggregate_result));
4581 if (error) {
4582 goto done;
4583 }
4584 done:
4585 if (parameters != NULL) {
4586 FREE(parameters, M_NECP);
4587 }
4588 return (error);
4589 }
4590
4591 /// Socket operations
4592 #define NECP_MAX_SOCKET_ATTRIBUTE_STRING_LENGTH 253
4593
4594 static bool
4595 necp_set_socket_attribute(u_int8_t *buffer, size_t buffer_length, u_int8_t type, char **buffer_p)
4596 {
4597 int error = 0;
4598 int cursor = 0;
4599 size_t string_size = 0;
4600 char *local_string = NULL;
4601 u_int8_t *value = NULL;
4602
4603 cursor = necp_buffer_find_tlv(buffer, buffer_length, 0, type, 0);
4604 if (cursor < 0) {
4605 // This will clear out the parameter
4606 goto done;
4607 }
4608
4609 string_size = necp_buffer_get_tlv_length(buffer, cursor);
4610 if (string_size == 0 || string_size > NECP_MAX_SOCKET_ATTRIBUTE_STRING_LENGTH) {
4611 // This will clear out the parameter
4612 goto done;
4613 }
4614
4615 MALLOC(local_string, char *, string_size + 1, M_NECP, M_WAITOK | M_ZERO);
4616 if (local_string == NULL) {
4617 NECPLOG(LOG_ERR, "Failed to allocate a socket attribute buffer (size %d)", string_size);
4618 goto fail;
4619 }
4620
4621 value = necp_buffer_get_tlv_value(buffer, cursor, NULL);
4622 if (value == NULL) {
4623 NECPLOG0(LOG_ERR, "Failed to get socket attribute");
4624 goto fail;
4625 }
4626
4627 memcpy(local_string, value, string_size);
4628 local_string[string_size] = 0;
4629
4630 done:
4631 if (*buffer_p != NULL) {
4632 FREE(*buffer_p, M_NECP);
4633 *buffer_p = NULL;
4634 }
4635
4636 *buffer_p = local_string;
4637 return (0);
4638 fail:
4639 if (local_string != NULL) {
4640 FREE(local_string, M_NECP);
4641 }
4642 return (error);
4643 }
4644
4645 errno_t
4646 necp_set_socket_attributes(struct socket *so, struct sockopt *sopt)
4647 {
4648 int error = 0;
4649 u_int8_t *buffer = NULL;
4650 struct inpcb *inp = NULL;
4651
4652 if ((SOCK_DOM(so) != PF_INET
4653 #if INET6
4654 && SOCK_DOM(so) != PF_INET6
4655 #endif
4656 )) {
4657 error = EINVAL;
4658 goto done;
4659 }
4660
4661 inp = sotoinpcb(so);
4662
4663 size_t valsize = sopt->sopt_valsize;
4664 if (valsize == 0 ||
4665 valsize > ((sizeof(struct necp_tlv_header) + NECP_MAX_SOCKET_ATTRIBUTE_STRING_LENGTH) * 2)) {
4666 goto done;
4667 }
4668
4669 MALLOC(buffer, u_int8_t *, valsize, M_NECP, M_WAITOK | M_ZERO);
4670 if (buffer == NULL) {
4671 goto done;
4672 }
4673
4674 error = sooptcopyin(sopt, buffer, valsize, 0);
4675 if (error) {
4676 goto done;
4677 }
4678
4679 error = necp_set_socket_attribute(buffer, valsize, NECP_TLV_ATTRIBUTE_DOMAIN, &inp->inp_necp_attributes.inp_domain);
4680 if (error) {
4681 NECPLOG0(LOG_ERR, "Could not set domain TLV for socket attributes");
4682 goto done;
4683 }
4684
4685 error = necp_set_socket_attribute(buffer, valsize, NECP_TLV_ATTRIBUTE_ACCOUNT, &inp->inp_necp_attributes.inp_account);
4686 if (error) {
4687 NECPLOG0(LOG_ERR, "Could not set account TLV for socket attributes");
4688 goto done;
4689 }
4690
4691 if (necp_debug) {
4692 NECPLOG(LOG_DEBUG, "Set on socket: Domain %s, Account %s", inp->inp_necp_attributes.inp_domain, inp->inp_necp_attributes.inp_account);
4693 }
4694 done:
4695 if (buffer != NULL) {
4696 FREE(buffer, M_NECP);
4697 }
4698
4699 return (error);
4700 }
4701
4702 errno_t
4703 necp_get_socket_attributes(struct socket *so, struct sockopt *sopt)
4704 {
4705 int error = 0;
4706 u_int8_t *buffer = NULL;
4707 u_int8_t *cursor = NULL;
4708 size_t valsize = 0;
4709 struct inpcb *inp = NULL;
4710
4711 if ((SOCK_DOM(so) != PF_INET
4712 #if INET6
4713 && SOCK_DOM(so) != PF_INET6
4714 #endif
4715 )) {
4716 error = EINVAL;
4717 goto done;
4718 }
4719
4720 inp = sotoinpcb(so);
4721 if (inp->inp_necp_attributes.inp_domain != NULL) {
4722 valsize += sizeof(struct necp_tlv_header) + strlen(inp->inp_necp_attributes.inp_domain);
4723 }
4724 if (inp->inp_necp_attributes.inp_account != NULL) {
4725 valsize += sizeof(struct necp_tlv_header) + strlen(inp->inp_necp_attributes.inp_account);
4726 }
4727 if (valsize == 0) {
4728 goto done;
4729 }
4730
4731 MALLOC(buffer, u_int8_t *, valsize, M_NECP, M_WAITOK | M_ZERO);
4732 if (buffer == NULL) {
4733 goto done;
4734 }
4735
4736 cursor = buffer;
4737 if (inp->inp_necp_attributes.inp_domain != NULL) {
4738 cursor = necp_buffer_write_tlv(cursor, NECP_TLV_ATTRIBUTE_DOMAIN, strlen(inp->inp_necp_attributes.inp_domain), inp->inp_necp_attributes.inp_domain,
4739 buffer, valsize);
4740 }
4741
4742 if (inp->inp_necp_attributes.inp_account != NULL) {
4743 cursor = necp_buffer_write_tlv(cursor, NECP_TLV_ATTRIBUTE_ACCOUNT, strlen(inp->inp_necp_attributes.inp_account), inp->inp_necp_attributes.inp_account,
4744 buffer, valsize);
4745 }
4746
4747 error = sooptcopyout(sopt, buffer, valsize);
4748 if (error) {
4749 goto done;
4750 }
4751 done:
4752 if (buffer != NULL) {
4753 FREE(buffer, M_NECP);
4754 }
4755
4756 return (error);
4757 }
4758
4759 void *
4760 necp_create_nexus_assign_message(uuid_t nexus_instance, u_int32_t nexus_port, void *key, uint32_t key_length,
4761 struct necp_client_endpoint *local_endpoint, struct necp_client_endpoint *remote_endpoint,
4762 u_int32_t flow_adv_index, size_t *message_length)
4763 {
4764 u_int8_t *buffer = NULL;
4765 u_int8_t *cursor = NULL;
4766 size_t valsize = 0;
4767 bool has_nexus_assignment = FALSE;
4768
4769
4770 if (!uuid_is_null(nexus_instance)) {
4771 has_nexus_assignment = TRUE;
4772 valsize += sizeof(struct necp_tlv_header) + sizeof(uuid_t);
4773 valsize += sizeof(struct necp_tlv_header) + sizeof(u_int32_t);
4774 }
4775 if (flow_adv_index != NECP_FLOWADV_IDX_INVALID) {
4776 valsize += sizeof(struct necp_tlv_header) + sizeof(u_int32_t);
4777 }
4778 if (key != NULL && key_length > 0) {
4779 valsize += sizeof(struct necp_tlv_header) + key_length;
4780 }
4781 if (local_endpoint != NULL) {
4782 valsize += sizeof(struct necp_tlv_header) + sizeof(struct necp_client_endpoint);
4783 }
4784 if (remote_endpoint != NULL) {
4785 valsize += sizeof(struct necp_tlv_header) + sizeof(struct necp_client_endpoint);
4786 }
4787 if (valsize == 0) {
4788 return (NULL);
4789 }
4790
4791 MALLOC(buffer, u_int8_t *, valsize, M_NETAGENT, M_WAITOK | M_ZERO); // Use M_NETAGENT area, since it is expected upon free
4792 if (buffer == NULL) {
4793 return (NULL);
4794 }
4795
4796 cursor = buffer;
4797 if (has_nexus_assignment) {
4798 cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_NEXUS_INSTANCE, sizeof(uuid_t), nexus_instance, buffer, valsize);
4799 cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_NEXUS_PORT, sizeof(u_int32_t), &nexus_port, buffer, valsize);
4800 }
4801 if (flow_adv_index != NECP_FLOWADV_IDX_INVALID) {
4802 cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_NEXUS_PORT_FLOW_INDEX, sizeof(u_int32_t), &flow_adv_index, buffer, valsize);
4803 }
4804 if (key != NULL && key_length > 0) {
4805 cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_PARAMETER_NEXUS_KEY, key_length, key, buffer, valsize);
4806 }
4807 if (local_endpoint != NULL) {
4808 cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_LOCAL_ENDPOINT, sizeof(struct necp_client_endpoint), local_endpoint, buffer, valsize);
4809 }
4810 if (remote_endpoint != NULL) {
4811 cursor = necp_buffer_write_tlv(cursor, NECP_CLIENT_RESULT_REMOTE_ENDPOINT, sizeof(struct necp_client_endpoint), remote_endpoint, buffer, valsize);
4812 }
4813
4814 *message_length = valsize;
4815
4816 return (buffer);
4817 }
4818
4819 void
4820 necp_inpcb_remove_cb(struct inpcb *inp)
4821 {
4822 if (!uuid_is_null(inp->necp_client_uuid)) {
4823 necp_client_unregister_socket_flow(inp->necp_client_uuid, inp);
4824 uuid_clear(inp->necp_client_uuid);
4825 }
4826 }
4827
4828 void
4829 necp_inpcb_dispose(struct inpcb *inp)
4830 {
4831 if (inp->inp_necp_attributes.inp_domain != NULL) {
4832 FREE(inp->inp_necp_attributes.inp_domain, M_NECP);
4833 inp->inp_necp_attributes.inp_domain = NULL;
4834 }
4835 if (inp->inp_necp_attributes.inp_account != NULL) {
4836 FREE(inp->inp_necp_attributes.inp_account, M_NECP);
4837 inp->inp_necp_attributes.inp_account = NULL;
4838 }
4839 }
4840
4841 void
4842 necp_mppcb_dispose(struct mppcb *mpp)
4843 {
4844 if (!uuid_is_null(mpp->necp_client_uuid)) {
4845 necp_client_unregister_multipath_cb(mpp->necp_client_uuid, mpp);
4846 uuid_clear(mpp->necp_client_uuid);
4847 }
4848 }
4849
4850 /// Module init
4851
4852 errno_t
4853 necp_client_init(void)
4854 {
4855 errno_t result = 0;
4856
4857 necp_fd_grp_attr = lck_grp_attr_alloc_init();
4858 if (necp_fd_grp_attr == NULL) {
4859 NECPLOG0(LOG_ERR, "lck_grp_attr_alloc_init failed");
4860 result = ENOMEM;
4861 goto done;
4862 }
4863
4864 necp_fd_mtx_grp = lck_grp_alloc_init("necp_fd", necp_fd_grp_attr);
4865 if (necp_fd_mtx_grp == NULL) {
4866 NECPLOG0(LOG_ERR, "lck_grp_alloc_init failed");
4867 result = ENOMEM;
4868 goto done;
4869 }
4870
4871 necp_fd_mtx_attr = lck_attr_alloc_init();
4872 if (necp_fd_mtx_attr == NULL) {
4873 NECPLOG0(LOG_ERR, "lck_attr_alloc_init failed");
4874 result = ENOMEM;
4875 goto done;
4876 }
4877
4878 necp_client_fd_size = sizeof(struct necp_fd_data);
4879 necp_client_fd_zone = zinit(necp_client_fd_size,
4880 NECP_CLIENT_FD_ZONE_MAX * necp_client_fd_size,
4881 0, NECP_CLIENT_FD_ZONE_NAME);
4882 if (necp_client_fd_zone == NULL) {
4883 NECPLOG0(LOG_ERR, "zinit(necp_client_fd) failed");
4884 result = ENOMEM;
4885 goto done;
4886 }
4887
4888 necp_flow_size = sizeof(struct necp_client_flow);
4889 necp_flow_zone = zinit(necp_flow_size,
4890 NECP_FLOW_ZONE_MAX * necp_flow_size,
4891 0, NECP_FLOW_ZONE_NAME);
4892 if (necp_flow_zone == NULL) {
4893 NECPLOG0(LOG_ERR, "zinit(necp_flow) failed");
4894 result = ENOMEM;
4895 goto done;
4896 }
4897
4898 necp_client_update_tcall = thread_call_allocate_with_options(necp_update_all_clients_callout, NULL,
4899 THREAD_CALL_PRIORITY_KERNEL, THREAD_CALL_OPTIONS_ONCE);
4900 VERIFY(necp_client_update_tcall != NULL);
4901
4902 lck_rw_init(&necp_fd_lock, necp_fd_mtx_grp, necp_fd_mtx_attr);
4903 lck_rw_init(&necp_observer_lock, necp_fd_mtx_grp, necp_fd_mtx_attr);
4904 lck_rw_init(&necp_client_tree_lock, necp_fd_mtx_grp, necp_fd_mtx_attr);
4905 lck_rw_init(&necp_collect_stats_list_lock, necp_fd_mtx_grp, necp_fd_mtx_attr);
4906
4907 LIST_INIT(&necp_fd_list);
4908 LIST_INIT(&necp_fd_observer_list);
4909 LIST_INIT(&necp_collect_stats_client_list);
4910
4911 RB_INIT(&necp_client_global_tree);
4912
4913 done:
4914 if (result != 0) {
4915 if (necp_fd_mtx_attr != NULL) {
4916 lck_attr_free(necp_fd_mtx_attr);
4917 necp_fd_mtx_attr = NULL;
4918 }
4919 if (necp_fd_mtx_grp != NULL) {
4920 lck_grp_free(necp_fd_mtx_grp);
4921 necp_fd_mtx_grp = NULL;
4922 }
4923 if (necp_fd_grp_attr != NULL) {
4924 lck_grp_attr_free(necp_fd_grp_attr);
4925 necp_fd_grp_attr = NULL;
4926 }
4927 }
4928 return (result);
4929 }