]> git.saurik.com Git - apple/xnu.git/blob - bsd/net/necp.c
6da23d1a345365b4bd555ed5c46ba961ba08ef6d
[apple/xnu.git] / bsd / net / necp.c
1 /*
2 * Copyright (c) 2013-2015 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 #include <sys/systm.h>
31 #include <sys/types.h>
32 #include <sys/syslog.h>
33 #include <sys/queue.h>
34 #include <sys/malloc.h>
35 #include <libkern/OSMalloc.h>
36 #include <sys/kernel.h>
37 #include <sys/kern_control.h>
38 #include <sys/mbuf.h>
39 #include <sys/kpi_mbuf.h>
40 #include <sys/proc_uuid_policy.h>
41 #include <net/if.h>
42 #include <sys/domain.h>
43 #include <sys/protosw.h>
44 #include <sys/socket.h>
45 #include <sys/socketvar.h>
46 #include <netinet/ip.h>
47 #include <netinet/ip6.h>
48 #include <netinet/tcp.h>
49 #include <netinet/tcp_var.h>
50 #include <netinet/udp.h>
51 #include <netinet/in_pcb.h>
52 #include <netinet6/esp.h>
53 #include <net/flowhash.h>
54 #include <net/if_var.h>
55 #include <sys/kauth.h>
56 #include <sys/sysctl.h>
57 #include <sys/sysproto.h>
58 #include <sys/priv.h>
59 #include <sys/kern_event.h>
60 #include <net/network_agent.h>
61 #include <net/necp.h>
62
63 /*
64 * NECP - Network Extension Control Policy database
65 * ------------------------------------------------
66 * The goal of this module is to allow clients connecting via a
67 * kernel control socket to create high-level policy sessions, which
68 * are ingested into low-level kernel policies that control and tag
69 * traffic at the application, socket, and IP layers.
70 *
71 * ------------------------------------------------
72 * Sessions
73 * ------------------------------------------------
74 * Each session owns a list of session policies, each of which can
75 * specify any combination of conditions and a single result. Each
76 * session also has a priority level (such as High, Default, or Low)
77 * which is requested by the client. Based on the requested level,
78 * a session order value is assigned to the session, which will be used
79 * to sort kernel policies generated by the session. The session client
80 * can specify the sub-order for each policy it creates which will be
81 * used to further sort the kernel policies.
82 *
83 * Kernel Control Socket --> 1 necp_session --> list of necp_session_policy structs
84 *
85 * ------------------------------------------------
86 * Kernel Policies
87 * ------------------------------------------------
88 * Whenever a session send the Apply command, its policies are ingested
89 * and generate kernel policies. There are two phases of kernel policy
90 * ingestion.
91 *
92 * 1. The session policy is parsed to create kernel policies at the socket
93 * and IP layers, when applicable. For example, a policy that requires
94 * all traffic from App1 to Pass will generate a socket kernel policy to
95 * match App1 and mark packets with ID1, and also an IP policy to match
96 * ID1 and let the packet pass. This is handled in necp_apply_policy. The
97 * resulting kernel policies are added to the global socket and IP layer
98 * policy lists.
99 * necp_session_policy --> necp_kernel_socket_policy and necp_kernel_ip_output_policy
100 * || ||
101 * \/ \/
102 * necp_kernel_socket_policies necp_kernel_ip_output_policies
103 *
104 * 2. Once the global lists of kernel policies have been filled out, each
105 * list is traversed to create optimized sub-lists ("Maps") which are used during
106 * data-path evaluation. IP policies are sent into necp_kernel_ip_output_policies_map,
107 * which hashes incoming packets based on marked socket-layer policies, and removes
108 * duplicate or overlapping polcies. Socket policies are sent into two maps,
109 * necp_kernel_socket_policies_map and necp_kernel_socket_policies_app_layer_map.
110 * The app layer map is used for policy checks coming in from user space, and is one
111 * list with duplicate and overlapping policies removed. The socket map hashes based
112 * on app UUID, and removes duplicate and overlapping policies.
113 * necp_kernel_socket_policy --> necp_kernel_socket_policies_app_layer_map
114 * |-> necp_kernel_socket_policies_map
115 *
116 * necp_kernel_ip_output_policies --> necp_kernel_ip_output_policies_map
117 *
118 * ------------------------------------------------
119 * Drop All Level
120 * ------------------------------------------------
121 * The Drop All Level is a sysctl that controls the level at which policies are allowed
122 * to override a global drop rule. If the value is 0, no drop rule is applied. If the value
123 * is 1, all traffic is dropped. If the value is greater than 1, all kernel policies created
124 * by a session with a priority level better than (numerically less than) the
125 * Drop All Level will allow matching traffic to not be dropped. The Drop All Level is
126 * dynamically interpreted into necp_drop_all_order, which specifies the equivalent assigned
127 * session orders to be dropped.
128 */
129
130 u_int32_t necp_drop_all_order = 0;
131 u_int32_t necp_drop_all_level = 0;
132
133 u_int32_t necp_pass_loopback = 1; // 0=Off, 1=On
134 u_int32_t necp_pass_keepalives = 1; // 0=Off, 1=On
135
136 u_int32_t necp_debug = 0; // 0=None, 1=Basic, 2=EveryMatch
137
138 u_int32_t necp_session_count = 0;
139
140 #define NECPLOG(level, format, ...) do { \
141 log((level > LOG_NOTICE ? LOG_NOTICE : level), "%s: " format "\n", __FUNCTION__, __VA_ARGS__); \
142 } while (0)
143
144 #define NECPLOG0(level, msg) do { \
145 log((level > LOG_NOTICE ? LOG_NOTICE : level), "%s: %s\n", __FUNCTION__, msg); \
146 } while (0)
147
148 #define LIST_INSERT_SORTED_ASCENDING(head, elm, field, sortfield, tmpelm) do { \
149 if (LIST_EMPTY((head)) || (LIST_FIRST(head)->sortfield >= (elm)->sortfield)) { \
150 LIST_INSERT_HEAD((head), elm, field); \
151 } else { \
152 LIST_FOREACH(tmpelm, head, field) { \
153 if (LIST_NEXT(tmpelm, field) == NULL || LIST_NEXT(tmpelm, field)->sortfield >= (elm)->sortfield) { \
154 LIST_INSERT_AFTER(tmpelm, elm, field); \
155 break; \
156 } \
157 } \
158 } \
159 } while (0)
160
161 #define LIST_INSERT_SORTED_TWICE_ASCENDING(head, elm, field, firstsortfield, secondsortfield, tmpelm) do { \
162 if (LIST_EMPTY((head)) || (LIST_FIRST(head)->firstsortfield > (elm)->firstsortfield) || ((LIST_FIRST(head)->firstsortfield == (elm)->firstsortfield) && (LIST_FIRST(head)->secondsortfield >= (elm)->secondsortfield))) { \
163 LIST_INSERT_HEAD((head), elm, field); \
164 } else { \
165 LIST_FOREACH(tmpelm, head, field) { \
166 if (LIST_NEXT(tmpelm, field) == NULL || (LIST_NEXT(tmpelm, field)->firstsortfield > (elm)->firstsortfield) || ((LIST_NEXT(tmpelm, field)->firstsortfield == (elm)->firstsortfield) && (LIST_NEXT(tmpelm, field)->secondsortfield >= (elm)->secondsortfield))) { \
167 LIST_INSERT_AFTER(tmpelm, elm, field); \
168 break; \
169 } \
170 } \
171 } \
172 } while (0)
173
174 #define LIST_INSERT_SORTED_THRICE_ASCENDING(head, elm, field, firstsortfield, secondsortfield, thirdsortfield, tmpelm) do { \
175 if (LIST_EMPTY((head)) || (LIST_FIRST(head)->firstsortfield > (elm)->firstsortfield) || ((LIST_FIRST(head)->firstsortfield == (elm)->firstsortfield) && (LIST_FIRST(head)->secondsortfield >= (elm)->secondsortfield)) || ((LIST_FIRST(head)->firstsortfield == (elm)->firstsortfield) && (LIST_FIRST(head)->secondsortfield == (elm)->secondsortfield) && (LIST_FIRST(head)->thirdsortfield >= (elm)->thirdsortfield))) { \
176 LIST_INSERT_HEAD((head), elm, field); \
177 } else { \
178 LIST_FOREACH(tmpelm, head, field) { \
179 if (LIST_NEXT(tmpelm, field) == NULL || (LIST_NEXT(tmpelm, field)->firstsortfield > (elm)->firstsortfield) || ((LIST_NEXT(tmpelm, field)->firstsortfield == (elm)->firstsortfield) && (LIST_NEXT(tmpelm, field)->secondsortfield >= (elm)->secondsortfield)) || ((LIST_NEXT(tmpelm, field)->firstsortfield == (elm)->firstsortfield) && (LIST_NEXT(tmpelm, field)->secondsortfield == (elm)->secondsortfield) && (LIST_NEXT(tmpelm, field)->thirdsortfield >= (elm)->thirdsortfield))) { \
180 LIST_INSERT_AFTER(tmpelm, elm, field); \
181 break; \
182 } \
183 } \
184 } \
185 } while (0)
186
187 #define NECP_KERNEL_CONDITION_ALL_INTERFACES 0x00001
188 #define NECP_KERNEL_CONDITION_BOUND_INTERFACE 0x00002
189 #define NECP_KERNEL_CONDITION_PROTOCOL 0x00004
190 #define NECP_KERNEL_CONDITION_LOCAL_START 0x00008
191 #define NECP_KERNEL_CONDITION_LOCAL_END 0x00010
192 #define NECP_KERNEL_CONDITION_LOCAL_PREFIX 0x00020
193 #define NECP_KERNEL_CONDITION_REMOTE_START 0x00040
194 #define NECP_KERNEL_CONDITION_REMOTE_END 0x00080
195 #define NECP_KERNEL_CONDITION_REMOTE_PREFIX 0x00100
196 #define NECP_KERNEL_CONDITION_APP_ID 0x00200
197 #define NECP_KERNEL_CONDITION_REAL_APP_ID 0x00400
198 #define NECP_KERNEL_CONDITION_DOMAIN 0x00800
199 #define NECP_KERNEL_CONDITION_ACCOUNT_ID 0x01000
200 #define NECP_KERNEL_CONDITION_POLICY_ID 0x02000
201 #define NECP_KERNEL_CONDITION_PID 0x04000
202 #define NECP_KERNEL_CONDITION_UID 0x08000
203 #define NECP_KERNEL_CONDITION_LAST_INTERFACE 0x10000 // Only set from packets looping between interfaces
204 #define NECP_KERNEL_CONDITION_TRAFFIC_CLASS 0x20000
205 #define NECP_KERNEL_CONDITION_ENTITLEMENT 0x40000
206
207 struct necp_service_registration {
208 LIST_ENTRY(necp_service_registration) session_chain;
209 LIST_ENTRY(necp_service_registration) kernel_chain;
210 u_int32_t service_id;
211 };
212
213 struct necp_session {
214 u_int32_t control_unit;
215 u_int32_t session_priority; // Descriptive priority rating
216 u_int32_t session_order;
217
218 bool proc_locked; // Messages must come from proc_uuid
219 uuid_t proc_uuid;
220 int proc_pid;
221
222 bool dirty;
223 LIST_HEAD(_policies, necp_session_policy) policies;
224
225 LIST_HEAD(_services, necp_service_registration) services;
226 };
227
228 struct necp_socket_info {
229 pid_t pid;
230 uid_t uid;
231 union necp_sockaddr_union local_addr;
232 union necp_sockaddr_union remote_addr;
233 u_int32_t bound_interface_index;
234 u_int32_t traffic_class;
235 u_int16_t protocol;
236 u_int32_t application_id;
237 u_int32_t real_application_id;
238 u_int32_t account_id;
239 char *domain;
240 errno_t cred_result;
241 };
242
243 static kern_ctl_ref necp_kctlref;
244 static u_int32_t necp_family;
245 static OSMallocTag necp_malloc_tag;
246 static lck_grp_attr_t *necp_kernel_policy_grp_attr = NULL;
247 static lck_attr_t *necp_kernel_policy_mtx_attr = NULL;
248 static lck_grp_t *necp_kernel_policy_mtx_grp = NULL;
249 decl_lck_rw_data(static, necp_kernel_policy_lock);
250
251 static lck_grp_attr_t *necp_route_rule_grp_attr = NULL;
252 static lck_attr_t *necp_route_rule_mtx_attr = NULL;
253 static lck_grp_t *necp_route_rule_mtx_grp = NULL;
254 decl_lck_rw_data(static, necp_route_rule_lock);
255
256 static necp_policy_id necp_last_policy_id = 0;
257 static necp_kernel_policy_id necp_last_kernel_policy_id = 0;
258 static u_int32_t necp_last_uuid_id = 0;
259 static u_int32_t necp_last_string_id = 0;
260 static u_int32_t necp_last_route_rule_id = 0;
261 static u_int32_t necp_last_aggregate_route_rule_id = 0;
262
263 /*
264 * On modification, invalidate cached lookups by bumping the generation count.
265 * Other calls will need to take the slowpath of taking
266 * the subsystem lock.
267 */
268 static volatile int32_t necp_kernel_socket_policies_gencount;
269 #define BUMP_KERNEL_SOCKET_POLICIES_GENERATION_COUNT() do { \
270 if (OSIncrementAtomic(&necp_kernel_socket_policies_gencount) == (INT32_MAX - 1)) { \
271 necp_kernel_socket_policies_gencount = 1; \
272 } \
273 } while (0)
274
275 static u_int32_t necp_kernel_application_policies_condition_mask;
276 static size_t necp_kernel_application_policies_count;
277 static u_int32_t necp_kernel_socket_policies_condition_mask;
278 static size_t necp_kernel_socket_policies_count;
279 static size_t necp_kernel_socket_policies_non_app_count;
280 static LIST_HEAD(_necpkernelsocketconnectpolicies, necp_kernel_socket_policy) necp_kernel_socket_policies;
281 #define NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS 5
282 #define NECP_SOCKET_MAP_APP_ID_TO_BUCKET(appid) (appid ? (appid%(NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS - 1) + 1) : 0)
283 static struct necp_kernel_socket_policy **necp_kernel_socket_policies_map[NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS];
284 static struct necp_kernel_socket_policy **necp_kernel_socket_policies_app_layer_map;
285 /*
286 * A note on policy 'maps': these are used for boosting efficiency when matching policies. For each dimension of the map,
287 * such as an ID, the 0 bucket is reserved for sockets/packets that do not have this parameter, while the other
288 * buckets lead to an array of policy pointers that form the list applicable when the (parameter%(NUM_BUCKETS - 1) + 1) == bucket_index.
289 *
290 * For example, a packet with policy ID of 7, when there are 4 ID buckets, will map to bucket (7%3 + 1) = 2.
291 */
292
293 static u_int32_t necp_kernel_ip_output_policies_condition_mask;
294 static size_t necp_kernel_ip_output_policies_count;
295 static size_t necp_kernel_ip_output_policies_non_id_count;
296 static LIST_HEAD(_necpkernelipoutputpolicies, necp_kernel_ip_output_policy) necp_kernel_ip_output_policies;
297 #define NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS 5
298 #define NECP_IP_OUTPUT_MAP_ID_TO_BUCKET(id) (id ? (id%(NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS - 1) + 1) : 0)
299 static struct necp_kernel_ip_output_policy **necp_kernel_ip_output_policies_map[NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS];
300
301 static struct necp_session *necp_create_session(u_int32_t control_unit);
302 static void necp_delete_session(struct necp_session *session);
303
304 static void necp_handle_policy_add(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset);
305 static void necp_handle_policy_get(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset);
306 static void necp_handle_policy_delete(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset);
307 static void necp_handle_policy_apply_all(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset);
308 static void necp_handle_policy_list_all(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset);
309 static void necp_handle_policy_delete_all(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset);
310 static void necp_handle_set_session_priority(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset);
311 static void necp_handle_lock_session_to_proc(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset);
312 static void necp_handle_register_service(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset);
313 static void necp_handle_unregister_service(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset);
314
315 static struct necp_session_policy *necp_policy_create(struct necp_session *session, necp_policy_order order, u_int8_t *conditions_array, u_int32_t conditions_array_size, u_int8_t *route_rules_array, u_int32_t route_rules_array_size, u_int8_t *result, u_int32_t result_size);
316 static struct necp_session_policy *necp_policy_find(struct necp_session *session, necp_policy_id policy_id);
317 static bool necp_policy_mark_for_deletion(struct necp_session *session, struct necp_session_policy *policy);
318 static bool necp_policy_mark_all_for_deletion(struct necp_session *session);
319 static bool necp_policy_delete(struct necp_session *session, struct necp_session_policy *policy);
320 static void necp_policy_apply_all(struct necp_session *session);
321
322 static necp_kernel_policy_id necp_kernel_socket_policy_add(necp_policy_id parent_policy_id, necp_policy_order order, u_int32_t session_order, int session_pid, u_int32_t condition_mask, u_int32_t condition_negated_mask, necp_app_id cond_app_id, necp_app_id cond_real_app_id, u_int32_t cond_account_id, char *domain, pid_t cond_pid, uid_t cond_uid, ifnet_t cond_bound_interface, struct necp_policy_condition_tc_range cond_traffic_class, u_int16_t cond_protocol, union necp_sockaddr_union *cond_local_start, union necp_sockaddr_union *cond_local_end, u_int8_t cond_local_prefix, union necp_sockaddr_union *cond_remote_start, union necp_sockaddr_union *cond_remote_end, u_int8_t cond_remote_prefix, necp_kernel_policy_result result, necp_kernel_policy_result_parameter result_parameter);
323 static bool necp_kernel_socket_policy_delete(necp_kernel_policy_id policy_id);
324 static bool necp_kernel_socket_policies_reprocess(void);
325 static bool necp_kernel_socket_policies_update_uuid_table(void);
326 static inline struct necp_kernel_socket_policy *necp_socket_find_policy_match_with_info_locked(struct necp_kernel_socket_policy **policy_search_array, struct necp_socket_info *info, necp_kernel_policy_filter *return_filter, u_int32_t *return_route_rule_id, necp_kernel_policy_result *return_service_action, necp_kernel_policy_service *return_service, u_int32_t *return_netagent_array, size_t netagent_array_count);
327
328 static necp_kernel_policy_id necp_kernel_ip_output_policy_add(necp_policy_id parent_policy_id, necp_policy_order order, necp_policy_order suborder, u_int32_t session_order, int session_pid, u_int32_t condition_mask, u_int32_t condition_negated_mask, necp_kernel_policy_id cond_policy_id, ifnet_t cond_bound_interface, u_int32_t cond_last_interface_index, u_int16_t cond_protocol, union necp_sockaddr_union *cond_local_start, union necp_sockaddr_union *cond_local_end, u_int8_t cond_local_prefix, union necp_sockaddr_union *cond_remote_start, union necp_sockaddr_union *cond_remote_end, u_int8_t cond_remote_prefix, necp_kernel_policy_result result, necp_kernel_policy_result_parameter result_parameter);
329 static bool necp_kernel_ip_output_policy_delete(necp_kernel_policy_id policy_id);
330 static bool necp_kernel_ip_output_policies_reprocess(void);
331
332 static bool necp_is_addr_in_range(struct sockaddr *addr, struct sockaddr *range_start, struct sockaddr *range_end);
333 static bool necp_is_range_in_range(struct sockaddr *inner_range_start, struct sockaddr *inner_range_end, struct sockaddr *range_start, struct sockaddr *range_end);
334 static bool necp_is_addr_in_subnet(struct sockaddr *addr, struct sockaddr *subnet_addr, u_int8_t subnet_prefix);
335 static int necp_addr_compare(struct sockaddr *sa1, struct sockaddr *sa2, int check_port);
336 static bool necp_buffer_compare_with_bit_prefix(u_int8_t *p1, u_int8_t *p2, u_int32_t bits);
337 static bool necp_is_loopback(struct sockaddr *local_addr, struct sockaddr *remote_addr, struct inpcb *inp, struct mbuf *packet);
338
339 struct necp_uuid_id_mapping {
340 LIST_ENTRY(necp_uuid_id_mapping) chain;
341 uuid_t uuid;
342 u_int32_t id;
343 u_int32_t refcount;
344 u_int32_t table_refcount; // Add to UUID policy table count
345 };
346 static size_t necp_num_uuid_app_id_mappings;
347 static bool necp_uuid_app_id_mappings_dirty;
348 #define NECP_UUID_APP_ID_HASH_SIZE 64
349 static u_long necp_uuid_app_id_hash_mask;
350 static u_long necp_uuid_app_id_hash_num_buckets;
351 static LIST_HEAD(necp_uuid_id_mapping_head, necp_uuid_id_mapping) *necp_uuid_app_id_hashtbl, necp_uuid_service_id_list; // App map is real hash table, service map is just mapping
352 #define APPUUIDHASH(uuid) (&necp_uuid_app_id_hashtbl[uuid[0] & necp_uuid_app_id_hash_mask]) // Assume first byte of UUIDs are evenly distributed
353 static u_int32_t necp_create_uuid_app_id_mapping(uuid_t uuid, bool *allocated_mapping, bool uuid_policy_table);
354 static bool necp_remove_uuid_app_id_mapping(uuid_t uuid, bool *removed_mapping, bool uuid_policy_table);
355
356 static struct necp_uuid_id_mapping *necp_uuid_lookup_service_id_locked(uuid_t uuid);
357 static struct necp_uuid_id_mapping *necp_uuid_lookup_uuid_with_service_id_locked(u_int32_t local_id);
358 static u_int32_t necp_create_uuid_service_id_mapping(uuid_t uuid);
359 static bool necp_remove_uuid_service_id_mapping(uuid_t uuid);
360
361 struct necp_string_id_mapping {
362 LIST_ENTRY(necp_string_id_mapping) chain;
363 char *string;
364 necp_app_id id;
365 u_int32_t refcount;
366 };
367 static LIST_HEAD(necp_string_id_mapping_list, necp_string_id_mapping) necp_account_id_list;
368 static u_int32_t necp_create_string_to_id_mapping(struct necp_string_id_mapping_list *list, char *domain);
369 static bool necp_remove_string_to_id_mapping(struct necp_string_id_mapping_list *list, char *domain);
370
371 static LIST_HEAD(_necp_kernel_service_list, necp_service_registration) necp_registered_service_list;
372
373 static char *necp_create_trimmed_domain(char *string, size_t length);
374 static inline int necp_count_dots(char *string, size_t length);
375
376 #define ROUTE_RULE_IS_AGGREGATE(ruleid) (ruleid > UINT16_MAX)
377
378 #define MAX_ROUTE_RULE_INTERFACES 10
379 struct necp_route_rule {
380 LIST_ENTRY(necp_route_rule) chain;
381 u_int32_t id;
382 u_int32_t default_action;
383 u_int8_t cellular_action;
384 u_int8_t wifi_action;
385 u_int8_t wired_action;
386 u_int8_t expensive_action;
387 u_int exception_if_indices[MAX_ROUTE_RULE_INTERFACES];
388 u_int8_t exception_if_actions[MAX_ROUTE_RULE_INTERFACES];
389 u_int32_t refcount;
390 };
391 static LIST_HEAD(necp_route_rule_list, necp_route_rule) necp_route_rules;
392 static u_int32_t necp_create_route_rule(struct necp_route_rule_list *list, u_int8_t *route_rules_array, u_int32_t route_rules_array_size);
393 static bool necp_remove_route_rule(struct necp_route_rule_list *list, u_int32_t route_rule_id);
394 static bool necp_route_is_allowed(struct rtentry *route, ifnet_t interface, u_int32_t route_rule_id, bool *cellular_denied);
395 static struct necp_route_rule *necp_lookup_route_rule_locked(struct necp_route_rule_list *list, u_int32_t route_rule_id);
396
397 #define MAX_AGGREGATE_ROUTE_RULES 16
398 struct necp_aggregate_route_rule {
399 LIST_ENTRY(necp_aggregate_route_rule) chain;
400 u_int32_t id;
401 u_int32_t rule_ids[MAX_AGGREGATE_ROUTE_RULES];
402 };
403 static LIST_HEAD(necp_aggregate_route_rule_list, necp_aggregate_route_rule) necp_aggregate_route_rules;
404 static u_int32_t necp_create_aggregate_route_rule(u_int32_t *rule_ids);
405
406 // Sysctl definitions
407 static int sysctl_handle_necp_level SYSCTL_HANDLER_ARGS;
408
409 SYSCTL_NODE(_net, OID_AUTO, necp, CTLFLAG_RW | CTLFLAG_LOCKED, 0, "NECP");
410 SYSCTL_INT(_net_necp, NECPCTL_PASS_LOOPBACK, pass_loopback, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_pass_loopback, 0, "");
411 SYSCTL_INT(_net_necp, NECPCTL_PASS_KEEPALIVES, pass_keepalives, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_pass_keepalives, 0, "");
412 SYSCTL_INT(_net_necp, NECPCTL_DEBUG, debug, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_debug, 0, "");
413 SYSCTL_PROC(_net_necp, NECPCTL_DROP_ALL_LEVEL, drop_all_level, CTLTYPE_INT | CTLFLAG_LOCKED | CTLFLAG_RW, &necp_drop_all_level, 0, &sysctl_handle_necp_level, "IU", "");
414 SYSCTL_LONG(_net_necp, NECPCTL_SOCKET_POLICY_COUNT, socket_policy_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_kernel_socket_policies_count, "");
415 SYSCTL_LONG(_net_necp, NECPCTL_SOCKET_NON_APP_POLICY_COUNT, socket_non_app_policy_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_kernel_socket_policies_non_app_count, "");
416 SYSCTL_LONG(_net_necp, NECPCTL_IP_POLICY_COUNT, ip_policy_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_kernel_ip_output_policies_count, "");
417 SYSCTL_INT(_net_necp, NECPCTL_SESSION_COUNT, session_count, CTLFLAG_LOCKED | CTLFLAG_RD, &necp_session_count, 0, "");
418
419 // Session order allocation
420 static u_int32_t
421 necp_allocate_new_session_order(u_int32_t priority, u_int32_t control_unit)
422 {
423 u_int32_t new_order = 0;
424
425 // For now, just allocate 1000 orders for each priority
426 if (priority == NECP_SESSION_PRIORITY_UNKNOWN || priority > NECP_SESSION_NUM_PRIORITIES) {
427 priority = NECP_SESSION_PRIORITY_DEFAULT;
428 }
429
430 // Use the control unit to decide the offset into the priority list
431 new_order = (control_unit) + ((priority - 1) * 1000);
432
433 return (new_order);
434 }
435
436 static inline u_int32_t
437 necp_get_first_order_for_priority(u_int32_t priority)
438 {
439 return (((priority - 1) * 1000) + 1);
440 }
441
442 // Sysctl handler
443 static int
444 sysctl_handle_necp_level SYSCTL_HANDLER_ARGS
445 {
446 #pragma unused(arg1, arg2)
447 int error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
448 if (necp_drop_all_level == 0) {
449 necp_drop_all_order = 0;
450 } else {
451 necp_drop_all_order = necp_get_first_order_for_priority(necp_drop_all_level);
452 }
453 return (error);
454 }
455
456
457 // Kernel Control functions
458 static errno_t necp_register_control(void);
459 static errno_t necp_ctl_connect(kern_ctl_ref kctlref, struct sockaddr_ctl *sac, void **unitinfo);
460 static errno_t necp_ctl_disconnect(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo);
461 static errno_t necp_ctl_send(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo, mbuf_t m, int flags);
462 static void necp_ctl_rcvd(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo, int flags);
463 static errno_t necp_ctl_getopt(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo, int opt, void *data, size_t *len);
464 static errno_t necp_ctl_setopt(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo, int opt, void *data, size_t len);
465
466 static bool necp_send_ctl_data(struct necp_session *session, u_int8_t *buffer, size_t buffer_size);
467
468 errno_t
469 necp_init(void)
470 {
471 errno_t result = 0;
472
473 result = necp_register_control();
474 if (result != 0) {
475 goto done;
476 }
477
478 necp_kernel_policy_grp_attr = lck_grp_attr_alloc_init();
479 if (necp_kernel_policy_grp_attr == NULL) {
480 NECPLOG0(LOG_ERR, "lck_grp_attr_alloc_init failed");
481 result = ENOMEM;
482 goto done;
483 }
484
485 necp_kernel_policy_mtx_grp = lck_grp_alloc_init(NECP_CONTROL_NAME, necp_kernel_policy_grp_attr);
486 if (necp_kernel_policy_mtx_grp == NULL) {
487 NECPLOG0(LOG_ERR, "lck_grp_alloc_init failed");
488 result = ENOMEM;
489 goto done;
490 }
491
492 necp_kernel_policy_mtx_attr = lck_attr_alloc_init();
493 if (necp_kernel_policy_mtx_attr == NULL) {
494 NECPLOG0(LOG_ERR, "lck_attr_alloc_init failed");
495 result = ENOMEM;
496 goto done;
497 }
498
499 lck_rw_init(&necp_kernel_policy_lock, necp_kernel_policy_mtx_grp, necp_kernel_policy_mtx_attr);
500
501 necp_route_rule_grp_attr = lck_grp_attr_alloc_init();
502 if (necp_route_rule_grp_attr == NULL) {
503 NECPLOG0(LOG_ERR, "lck_grp_attr_alloc_init failed");
504 result = ENOMEM;
505 goto done;
506 }
507
508 necp_route_rule_mtx_grp = lck_grp_alloc_init("necp_route_rule", necp_route_rule_grp_attr);
509 if (necp_route_rule_mtx_grp == NULL) {
510 NECPLOG0(LOG_ERR, "lck_grp_alloc_init failed");
511 result = ENOMEM;
512 goto done;
513 }
514
515 necp_route_rule_mtx_attr = lck_attr_alloc_init();
516 if (necp_route_rule_mtx_attr == NULL) {
517 NECPLOG0(LOG_ERR, "lck_attr_alloc_init failed");
518 result = ENOMEM;
519 goto done;
520 }
521
522 lck_rw_init(&necp_route_rule_lock, necp_route_rule_mtx_grp, necp_route_rule_mtx_attr);
523
524 LIST_INIT(&necp_kernel_socket_policies);
525 LIST_INIT(&necp_kernel_ip_output_policies);
526
527 LIST_INIT(&necp_account_id_list);
528
529 LIST_INIT(&necp_uuid_service_id_list);
530
531 LIST_INIT(&necp_registered_service_list);
532
533 LIST_INIT(&necp_route_rules);
534 LIST_INIT(&necp_aggregate_route_rules);
535
536 necp_uuid_app_id_hashtbl = hashinit(NECP_UUID_APP_ID_HASH_SIZE, M_NECP, &necp_uuid_app_id_hash_mask);
537 necp_uuid_app_id_hash_num_buckets = necp_uuid_app_id_hash_mask + 1;
538 necp_num_uuid_app_id_mappings = 0;
539 necp_uuid_app_id_mappings_dirty = FALSE;
540
541 necp_kernel_application_policies_condition_mask = 0;
542 necp_kernel_socket_policies_condition_mask = 0;
543 necp_kernel_ip_output_policies_condition_mask = 0;
544
545 necp_kernel_application_policies_count = 0;
546 necp_kernel_socket_policies_count = 0;
547 necp_kernel_socket_policies_non_app_count = 0;
548 necp_kernel_ip_output_policies_count = 0;
549 necp_kernel_ip_output_policies_non_id_count = 0;
550
551 necp_last_policy_id = 0;
552 necp_last_kernel_policy_id = 0;
553 necp_last_uuid_id = 0;
554 necp_last_string_id = 0;
555 necp_last_route_rule_id = 0;
556 necp_last_aggregate_route_rule_id = 0;
557
558 necp_kernel_socket_policies_gencount = 1;
559
560 memset(&necp_kernel_socket_policies_map, 0, sizeof(necp_kernel_socket_policies_map));
561 memset(&necp_kernel_ip_output_policies_map, 0, sizeof(necp_kernel_ip_output_policies_map));
562 necp_kernel_socket_policies_app_layer_map = NULL;
563
564 done:
565 if (result != 0) {
566 if (necp_kernel_policy_mtx_attr != NULL) {
567 lck_attr_free(necp_kernel_policy_mtx_attr);
568 necp_kernel_policy_mtx_attr = NULL;
569 }
570 if (necp_kernel_policy_mtx_grp != NULL) {
571 lck_grp_free(necp_kernel_policy_mtx_grp);
572 necp_kernel_policy_mtx_grp = NULL;
573 }
574 if (necp_kernel_policy_grp_attr != NULL) {
575 lck_grp_attr_free(necp_kernel_policy_grp_attr);
576 necp_kernel_policy_grp_attr = NULL;
577 }
578 if (necp_route_rule_mtx_attr != NULL) {
579 lck_attr_free(necp_route_rule_mtx_attr);
580 necp_route_rule_mtx_attr = NULL;
581 }
582 if (necp_route_rule_mtx_grp != NULL) {
583 lck_grp_free(necp_route_rule_mtx_grp);
584 necp_route_rule_mtx_grp = NULL;
585 }
586 if (necp_route_rule_grp_attr != NULL) {
587 lck_grp_attr_free(necp_route_rule_grp_attr);
588 necp_route_rule_grp_attr = NULL;
589 }
590 if (necp_kctlref != NULL) {
591 ctl_deregister(necp_kctlref);
592 necp_kctlref = NULL;
593 }
594 }
595 return (result);
596 }
597
598 static errno_t
599 necp_register_control(void)
600 {
601 struct kern_ctl_reg kern_ctl;
602 errno_t result = 0;
603
604 // Create a tag to allocate memory
605 necp_malloc_tag = OSMalloc_Tagalloc(NECP_CONTROL_NAME, OSMT_DEFAULT);
606
607 // Find a unique value for our interface family
608 result = mbuf_tag_id_find(NECP_CONTROL_NAME, &necp_family);
609 if (result != 0) {
610 NECPLOG(LOG_ERR, "mbuf_tag_id_find_internal failed: %d", result);
611 return (result);
612 }
613
614 bzero(&kern_ctl, sizeof(kern_ctl));
615 strlcpy(kern_ctl.ctl_name, NECP_CONTROL_NAME, sizeof(kern_ctl.ctl_name));
616 kern_ctl.ctl_name[sizeof(kern_ctl.ctl_name) - 1] = 0;
617 kern_ctl.ctl_flags = CTL_FLAG_PRIVILEGED; // Require root
618 kern_ctl.ctl_sendsize = 64 * 1024;
619 kern_ctl.ctl_recvsize = 64 * 1024;
620 kern_ctl.ctl_connect = necp_ctl_connect;
621 kern_ctl.ctl_disconnect = necp_ctl_disconnect;
622 kern_ctl.ctl_send = necp_ctl_send;
623 kern_ctl.ctl_rcvd = necp_ctl_rcvd;
624 kern_ctl.ctl_setopt = necp_ctl_setopt;
625 kern_ctl.ctl_getopt = necp_ctl_getopt;
626
627 result = ctl_register(&kern_ctl, &necp_kctlref);
628 if (result != 0) {
629 NECPLOG(LOG_ERR, "ctl_register failed: %d", result);
630 return (result);
631 }
632
633 return (0);
634 }
635
636 static void
637 necp_post_change_event(struct kev_necp_policies_changed_data *necp_event_data)
638 {
639 struct kev_msg ev_msg;
640 memset(&ev_msg, 0, sizeof(ev_msg));
641
642 ev_msg.vendor_code = KEV_VENDOR_APPLE;
643 ev_msg.kev_class = KEV_NETWORK_CLASS;
644 ev_msg.kev_subclass = KEV_NECP_SUBCLASS;
645 ev_msg.event_code = KEV_NECP_POLICIES_CHANGED;
646
647 ev_msg.dv[0].data_ptr = necp_event_data;
648 ev_msg.dv[0].data_length = sizeof(necp_event_data->changed_count);
649 ev_msg.dv[1].data_length = 0;
650
651 kev_post_msg(&ev_msg);
652 }
653
654 static errno_t
655 necp_ctl_connect(kern_ctl_ref kctlref, struct sockaddr_ctl *sac, void **unitinfo)
656 {
657 #pragma unused(kctlref)
658 *unitinfo = necp_create_session(sac->sc_unit);
659 if (*unitinfo == NULL) {
660 // Could not allocate session
661 return (ENOBUFS);
662 }
663
664 return (0);
665 }
666
667 static errno_t
668 necp_ctl_disconnect(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo)
669 {
670 #pragma unused(kctlref, unit)
671 struct necp_session *session = (struct necp_session *)unitinfo;
672 if (session != NULL) {
673 necp_policy_mark_all_for_deletion(session);
674 necp_policy_apply_all(session);
675 necp_delete_session((struct necp_session *)unitinfo);
676 }
677
678 return (0);
679 }
680
681
682 // Message handling
683 static int
684 necp_packet_find_tlv(mbuf_t packet, int offset, u_int8_t type, int *err, int next)
685 {
686 size_t cursor = offset;
687 int error = 0;
688 u_int32_t curr_length;
689 u_int8_t curr_type;
690
691 *err = 0;
692
693 do {
694 if (!next) {
695 error = mbuf_copydata(packet, cursor, sizeof(curr_type), &curr_type);
696 if (error) {
697 *err = ENOENT;
698 return (-1);
699 }
700 } else {
701 next = 0;
702 curr_type = NECP_TLV_NIL;
703 }
704
705 if (curr_type != type) {
706 cursor += sizeof(curr_type);
707 error = mbuf_copydata(packet, cursor, sizeof(curr_length), &curr_length);
708 if (error) {
709 *err = error;
710 return (-1);
711 }
712 cursor += (sizeof(curr_length) + curr_length);
713 }
714 } while (curr_type != type);
715
716 return (cursor);
717 }
718
719 static int
720 necp_packet_get_tlv_at_offset(mbuf_t packet, int tlv_offset, u_int32_t buff_len, void *buff, u_int32_t *value_size)
721 {
722 int error = 0;
723 u_int32_t length;
724
725 if (tlv_offset < 0) {
726 return (error);
727 }
728
729 error = mbuf_copydata(packet, tlv_offset + sizeof(u_int8_t), sizeof(length), &length);
730 if (error) {
731 return (error);
732 }
733
734 u_int32_t total_len = m_length2(packet, NULL);
735 if (total_len < (tlv_offset + sizeof(u_int8_t) + sizeof(length) + length)) {
736 NECPLOG(LOG_ERR, "Got a bad TLV, length (%u) + offset (%d) < total length (%u)",
737 length, (tlv_offset + sizeof(u_int8_t) + sizeof(length)), total_len);
738 return (EINVAL);
739 }
740
741 if (value_size != NULL) {
742 *value_size = length;
743 }
744
745 if (buff != NULL && buff_len > 0) {
746 u_int32_t to_copy = (length < buff_len) ? length : buff_len;
747 error = mbuf_copydata(packet, tlv_offset + sizeof(u_int8_t) + sizeof(length), to_copy, buff);
748 if (error) {
749 return (error);
750 }
751 }
752
753 return (0);
754 }
755
756 static int
757 necp_packet_get_tlv(mbuf_t packet, int offset, u_int8_t type, u_int32_t buff_len, void *buff, u_int32_t *value_size)
758 {
759 int error = 0;
760 int tlv_offset;
761
762 tlv_offset = necp_packet_find_tlv(packet, offset, type, &error, 0);
763 if (tlv_offset < 0) {
764 return (error);
765 }
766
767 return (necp_packet_get_tlv_at_offset(packet, tlv_offset, buff_len, buff, value_size));
768 }
769
770 static u_int8_t *
771 necp_buffer_write_packet_header(u_int8_t *buffer, u_int8_t packet_type, u_int8_t flags, u_int32_t message_id)
772 {
773 ((struct necp_packet_header *)(void *)buffer)->packet_type = packet_type;
774 ((struct necp_packet_header *)(void *)buffer)->flags = flags;
775 ((struct necp_packet_header *)(void *)buffer)->message_id = message_id;
776 return (buffer + sizeof(struct necp_packet_header));
777 }
778
779 static u_int8_t *
780 necp_buffer_write_tlv(u_int8_t *buffer, u_int8_t type, u_int32_t length, const void *value)
781 {
782 *(u_int8_t *)(buffer) = type;
783 *(u_int32_t *)(void *)(buffer + sizeof(type)) = length;
784 if (length > 0) {
785 memcpy((u_int8_t *)(buffer + sizeof(type) + sizeof(length)), value, length);
786 }
787
788 return ((u_int8_t *)(buffer + sizeof(type) + sizeof(length) + length));
789 }
790
791 static u_int8_t
792 necp_buffer_get_tlv_type(u_int8_t *buffer, int tlv_offset)
793 {
794 u_int8_t *type = NULL;
795
796 if (buffer == NULL) {
797 return (0);
798 }
799
800 type = (u_int8_t *)((u_int8_t *)buffer + tlv_offset);
801 return (type ? *type : 0);
802 }
803
804 static u_int32_t
805 necp_buffer_get_tlv_length(u_int8_t *buffer, int tlv_offset)
806 {
807 u_int32_t *length = NULL;
808
809 if (buffer == NULL) {
810 return (0);
811 }
812
813 length = (u_int32_t *)(void *)((u_int8_t *)buffer + tlv_offset + sizeof(u_int8_t));
814 return (length ? *length : 0);
815 }
816
817 static u_int8_t *
818 necp_buffer_get_tlv_value(u_int8_t *buffer, int tlv_offset, u_int32_t *value_size)
819 {
820 u_int8_t *value = NULL;
821 u_int32_t length = necp_buffer_get_tlv_length(buffer, tlv_offset);
822 if (length == 0) {
823 return (value);
824 }
825
826 if (value_size) {
827 *value_size = length;
828 }
829
830 value = (u_int8_t *)((u_int8_t *)buffer + tlv_offset + sizeof(u_int8_t) + sizeof(u_int32_t));
831 return (value);
832 }
833
834 static int
835 necp_buffer_find_tlv(u_int8_t *buffer, u_int32_t buffer_length, int offset, u_int8_t type, int next)
836 {
837 if (offset < 0) {
838 return (-1);
839 }
840 int cursor = offset;
841 int next_cursor;
842 u_int32_t curr_length;
843 u_int8_t curr_type;
844
845 while (TRUE) {
846 if ((((u_int32_t)cursor) + sizeof(curr_type) + sizeof(curr_length)) > buffer_length) {
847 return (-1);
848 }
849 if (!next) {
850 curr_type = necp_buffer_get_tlv_type(buffer, cursor);
851 } else {
852 next = 0;
853 curr_type = NECP_TLV_NIL;
854 }
855 curr_length = necp_buffer_get_tlv_length(buffer, cursor);
856 next_cursor = (cursor + sizeof(curr_type) + sizeof(curr_length) + curr_length);
857 if (curr_type == type) {
858 // check if entire TLV fits inside buffer
859 if (((u_int32_t)next_cursor) <= buffer_length) {
860 return (cursor);
861 } else {
862 return (-1);
863 }
864 }
865 cursor = next_cursor;
866 }
867 }
868
869 static bool
870 necp_send_ctl_data(struct necp_session *session, u_int8_t *buffer, size_t buffer_size)
871 {
872 int error;
873
874 if (necp_kctlref == NULL || session == NULL || buffer == NULL || buffer_size == 0) {
875 return (FALSE);
876 }
877
878 error = ctl_enqueuedata(necp_kctlref, session->control_unit, buffer, buffer_size, CTL_DATA_EOR);
879
880 return (error == 0);
881 }
882
883 static bool
884 necp_send_success_response(struct necp_session *session, u_int8_t packet_type, u_int32_t message_id)
885 {
886 bool success = TRUE;
887 u_int8_t *response = NULL;
888 u_int8_t *cursor = NULL;
889 size_t response_size = sizeof(struct necp_packet_header) + sizeof(u_int8_t) + sizeof(u_int32_t);
890 MALLOC(response, u_int8_t *, response_size, M_NECP, M_WAITOK);
891 if (response == NULL) {
892 return (FALSE);
893 }
894 cursor = response;
895 cursor = necp_buffer_write_packet_header(cursor, packet_type, NECP_PACKET_FLAGS_RESPONSE, message_id);
896 cursor = necp_buffer_write_tlv(cursor, NECP_TLV_NIL, 0, NULL);
897
898 if (!(success = necp_send_ctl_data(session, (u_int8_t *)response, response_size))) {
899 NECPLOG0(LOG_ERR, "Failed to send response");
900 }
901
902 FREE(response, M_NECP);
903 return (success);
904 }
905
906 static bool
907 necp_send_error_response(struct necp_session *session, u_int8_t packet_type, u_int32_t message_id, u_int32_t error)
908 {
909 bool success = TRUE;
910 u_int8_t *response = NULL;
911 u_int8_t *cursor = NULL;
912 size_t response_size = sizeof(struct necp_packet_header) + sizeof(u_int8_t) + sizeof(u_int32_t) + sizeof(u_int32_t);
913 MALLOC(response, u_int8_t *, response_size, M_NECP, M_WAITOK);
914 if (response == NULL) {
915 return (FALSE);
916 }
917 cursor = response;
918 cursor = necp_buffer_write_packet_header(cursor, packet_type, NECP_PACKET_FLAGS_RESPONSE, message_id);
919 cursor = necp_buffer_write_tlv(cursor, NECP_TLV_ERROR, sizeof(error), &error);
920
921 if (!(success = necp_send_ctl_data(session, (u_int8_t *)response, response_size))) {
922 NECPLOG0(LOG_ERR, "Failed to send response");
923 }
924
925 FREE(response, M_NECP);
926 return (success);
927 }
928
929 static bool
930 necp_send_policy_id_response(struct necp_session *session, u_int8_t packet_type, u_int32_t message_id, necp_policy_id policy_id)
931 {
932 bool success = TRUE;
933 u_int8_t *response = NULL;
934 u_int8_t *cursor = NULL;
935 size_t response_size = sizeof(struct necp_packet_header) + sizeof(u_int8_t) + sizeof(u_int32_t) + sizeof(u_int32_t);
936 MALLOC(response, u_int8_t *, response_size, M_NECP, M_WAITOK);
937 if (response == NULL) {
938 return (FALSE);
939 }
940 cursor = response;
941 cursor = necp_buffer_write_packet_header(cursor, packet_type, NECP_PACKET_FLAGS_RESPONSE, message_id);
942 cursor = necp_buffer_write_tlv(cursor, NECP_TLV_POLICY_ID, sizeof(policy_id), &policy_id);
943
944 if (!(success = necp_send_ctl_data(session, (u_int8_t *)response, response_size))) {
945 NECPLOG0(LOG_ERR, "Failed to send response");
946 }
947
948 FREE(response, M_NECP);
949 return (success);
950 }
951
952 static errno_t
953 necp_ctl_send(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo, mbuf_t packet, int flags)
954 {
955 #pragma unused(kctlref, unit, flags)
956 struct necp_session *session = (struct necp_session *)unitinfo;
957 struct necp_packet_header header;
958 int error = 0;
959
960 if (session == NULL) {
961 NECPLOG0(LOG_ERR, "Got a NULL session");
962 error = EINVAL;
963 goto done;
964 }
965
966 if (mbuf_pkthdr_len(packet) < sizeof(header)) {
967 NECPLOG(LOG_ERR, "Got a bad packet, length (%lu) < sizeof header (%lu)", mbuf_pkthdr_len(packet), sizeof(header));
968 error = EINVAL;
969 goto done;
970 }
971
972 error = mbuf_copydata(packet, 0, sizeof(header), &header);
973 if (error) {
974 NECPLOG(LOG_ERR, "mbuf_copydata failed for the header: %d", error);
975 error = ENOBUFS;
976 goto done;
977 }
978
979 if (session->proc_locked) {
980 // Verify that the calling process is allowed to send messages
981 uuid_t proc_uuid;
982 proc_getexecutableuuid(current_proc(), proc_uuid, sizeof(proc_uuid));
983 if (uuid_compare(proc_uuid, session->proc_uuid) != 0) {
984 necp_send_error_response(session, header.packet_type, header.message_id, NECP_ERROR_INVALID_PROCESS);
985 goto done;
986 }
987 } else {
988 // If not locked, update the proc_uuid and proc_pid of the session
989 proc_getexecutableuuid(current_proc(), session->proc_uuid, sizeof(session->proc_uuid));
990 session->proc_pid = proc_pid(current_proc());
991 }
992
993 switch (header.packet_type) {
994 case NECP_PACKET_TYPE_POLICY_ADD: {
995 necp_handle_policy_add(session, header.message_id, packet, sizeof(header));
996 break;
997 }
998 case NECP_PACKET_TYPE_POLICY_GET: {
999 necp_handle_policy_get(session, header.message_id, packet, sizeof(header));
1000 break;
1001 }
1002 case NECP_PACKET_TYPE_POLICY_DELETE: {
1003 necp_handle_policy_delete(session, header.message_id, packet, sizeof(header));
1004 break;
1005 }
1006 case NECP_PACKET_TYPE_POLICY_APPLY_ALL: {
1007 necp_handle_policy_apply_all(session, header.message_id, packet, sizeof(header));
1008 break;
1009 }
1010 case NECP_PACKET_TYPE_POLICY_LIST_ALL: {
1011 necp_handle_policy_list_all(session, header.message_id, packet, sizeof(header));
1012 break;
1013 }
1014 case NECP_PACKET_TYPE_POLICY_DELETE_ALL: {
1015 necp_handle_policy_delete_all(session, header.message_id, packet, sizeof(header));
1016 break;
1017 }
1018 case NECP_PACKET_TYPE_SET_SESSION_PRIORITY: {
1019 necp_handle_set_session_priority(session, header.message_id, packet, sizeof(header));
1020 break;
1021 }
1022 case NECP_PACKET_TYPE_LOCK_SESSION_TO_PROC: {
1023 necp_handle_lock_session_to_proc(session, header.message_id, packet, sizeof(header));
1024 break;
1025 }
1026 case NECP_PACKET_TYPE_REGISTER_SERVICE: {
1027 necp_handle_register_service(session, header.message_id, packet, sizeof(header));
1028 break;
1029 }
1030 case NECP_PACKET_TYPE_UNREGISTER_SERVICE: {
1031 necp_handle_unregister_service(session, header.message_id, packet, sizeof(header));
1032 break;
1033 }
1034 default: {
1035 NECPLOG(LOG_ERR, "Received unknown message type %d", header.packet_type);
1036 necp_send_error_response(session, header.packet_type, header.message_id, NECP_ERROR_UNKNOWN_PACKET_TYPE);
1037 break;
1038 }
1039 }
1040
1041 done:
1042 mbuf_freem(packet);
1043 return (error);
1044 }
1045
1046 static void
1047 necp_ctl_rcvd(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo, int flags)
1048 {
1049 #pragma unused(kctlref, unit, unitinfo, flags)
1050 return;
1051 }
1052
1053 static errno_t
1054 necp_ctl_getopt(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo, int opt, void *data, size_t *len)
1055 {
1056 #pragma unused(kctlref, unit, unitinfo, opt, data, len)
1057 return (0);
1058 }
1059
1060 static errno_t
1061 necp_ctl_setopt(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo, int opt, void *data, size_t len)
1062 {
1063 #pragma unused(kctlref, unit, unitinfo, opt, data, len)
1064 return (0);
1065 }
1066
1067 // Session Management
1068 static struct necp_session *
1069 necp_create_session(u_int32_t control_unit)
1070 {
1071 struct necp_session *new_session = NULL;
1072
1073 MALLOC(new_session, struct necp_session *, sizeof(*new_session), M_NECP, M_WAITOK);
1074 if (new_session == NULL) {
1075 goto done;
1076 }
1077 if (necp_debug) {
1078 NECPLOG(LOG_DEBUG, "Create NECP session, control unit %d", control_unit);
1079 }
1080 memset(new_session, 0, sizeof(*new_session));
1081 new_session->session_priority = NECP_SESSION_PRIORITY_UNKNOWN;
1082 new_session->session_order = necp_allocate_new_session_order(new_session->session_priority, control_unit);
1083 new_session->control_unit = control_unit;
1084 new_session->dirty = FALSE;
1085 LIST_INIT(&new_session->policies);
1086
1087 lck_rw_lock_exclusive(&necp_kernel_policy_lock);
1088 necp_session_count++;
1089 lck_rw_done(&necp_kernel_policy_lock);
1090
1091 done:
1092 return (new_session);
1093 }
1094
1095 static void
1096 necp_delete_session(struct necp_session *session)
1097 {
1098 if (session != NULL) {
1099 struct necp_service_registration *service = NULL;
1100 struct necp_service_registration *temp_service = NULL;
1101 LIST_FOREACH_SAFE(service, &session->services, session_chain, temp_service) {
1102 LIST_REMOVE(service, session_chain);
1103 lck_rw_lock_exclusive(&necp_kernel_policy_lock);
1104 LIST_REMOVE(service, kernel_chain);
1105 lck_rw_done(&necp_kernel_policy_lock);
1106 FREE(service, M_NECP);
1107 }
1108 if (necp_debug) {
1109 NECPLOG0(LOG_DEBUG, "Deleted NECP session");
1110 }
1111 FREE(session, M_NECP);
1112
1113 lck_rw_lock_exclusive(&necp_kernel_policy_lock);
1114 necp_session_count--;
1115 lck_rw_done(&necp_kernel_policy_lock);
1116 }
1117 }
1118
1119 // Session Policy Management
1120 static inline u_int8_t
1121 necp_policy_result_get_type_from_buffer(u_int8_t *buffer, u_int32_t length)
1122 {
1123 return ((buffer && length >= sizeof(u_int8_t)) ? buffer[0] : 0);
1124 }
1125
1126 static inline u_int32_t
1127 necp_policy_result_get_parameter_length_from_buffer(u_int8_t *buffer, u_int32_t length)
1128 {
1129 return ((buffer && length > sizeof(u_int8_t)) ? (length - sizeof(u_int8_t)) : 0);
1130 }
1131
1132 static inline u_int8_t *
1133 necp_policy_result_get_parameter_pointer_from_buffer(u_int8_t *buffer, u_int32_t length)
1134 {
1135 return ((buffer && length > sizeof(u_int8_t)) ? (buffer + sizeof(u_int8_t)) : NULL);
1136 }
1137
1138 static bool
1139 necp_policy_result_requires_route_rules(u_int8_t *buffer, u_int32_t length)
1140 {
1141 u_int8_t type = necp_policy_result_get_type_from_buffer(buffer, length);
1142 if (type == NECP_POLICY_RESULT_ROUTE_RULES) {
1143 return (TRUE);
1144 }
1145 return (FALSE);
1146 }
1147
1148 static bool
1149 necp_policy_result_is_valid(u_int8_t *buffer, u_int32_t length)
1150 {
1151 bool validated = FALSE;
1152 u_int8_t type = necp_policy_result_get_type_from_buffer(buffer, length);
1153 u_int32_t parameter_length = necp_policy_result_get_parameter_length_from_buffer(buffer, length);
1154 switch (type) {
1155 case NECP_POLICY_RESULT_PASS: {
1156 validated = TRUE;
1157 break;
1158 }
1159 case NECP_POLICY_RESULT_SKIP: {
1160 if (parameter_length >= sizeof(u_int32_t)) {
1161 validated = TRUE;
1162 }
1163 break;
1164 }
1165 case NECP_POLICY_RESULT_DROP: {
1166 validated = TRUE;
1167 break;
1168 }
1169 case NECP_POLICY_RESULT_SOCKET_DIVERT: {
1170 if (parameter_length >= sizeof(u_int32_t)) {
1171 validated = TRUE;
1172 }
1173 break;
1174 }
1175 case NECP_POLICY_RESULT_SOCKET_SCOPED: {
1176 if (parameter_length > 0) {
1177 validated = TRUE;
1178 }
1179 break;
1180 }
1181 case NECP_POLICY_RESULT_IP_TUNNEL: {
1182 if (parameter_length > sizeof(u_int32_t)) {
1183 validated = TRUE;
1184 }
1185 break;
1186 }
1187 case NECP_POLICY_RESULT_SOCKET_FILTER: {
1188 if (parameter_length >= sizeof(u_int32_t)) {
1189 validated = TRUE;
1190 }
1191 break;
1192 }
1193 case NECP_POLICY_RESULT_ROUTE_RULES: {
1194 validated = TRUE;
1195 break;
1196 }
1197 case NECP_POLICY_RESULT_TRIGGER:
1198 case NECP_POLICY_RESULT_TRIGGER_IF_NEEDED:
1199 case NECP_POLICY_RESULT_TRIGGER_SCOPED:
1200 case NECP_POLICY_RESULT_NO_TRIGGER_SCOPED:
1201 case NECP_POLICY_RESULT_USE_NETAGENT: {
1202 if (parameter_length >= sizeof(uuid_t)) {
1203 validated = TRUE;
1204 }
1205 break;
1206 }
1207 default: {
1208 validated = FALSE;
1209 break;
1210 }
1211 }
1212
1213 if (necp_debug) {
1214 NECPLOG(LOG_DEBUG, "Policy result type %d, valid %d", type, validated);
1215 }
1216
1217 return (validated);
1218 }
1219
1220 static inline u_int8_t
1221 necp_policy_condition_get_type_from_buffer(u_int8_t *buffer, u_int32_t length)
1222 {
1223 return ((buffer && length >= sizeof(u_int8_t)) ? buffer[0] : 0);
1224 }
1225
1226 static inline u_int8_t
1227 necp_policy_condition_get_flags_from_buffer(u_int8_t *buffer, u_int32_t length)
1228 {
1229 return ((buffer && length >= (2 * sizeof(u_int8_t))) ? buffer[1] : 0);
1230 }
1231
1232 static inline u_int32_t
1233 necp_policy_condition_get_value_length_from_buffer(u_int8_t *buffer, u_int32_t length)
1234 {
1235 return ((buffer && length >= (2 * sizeof(u_int8_t))) ? (length - (2 * sizeof(u_int8_t))) : 0);
1236 }
1237
1238 static inline u_int8_t *
1239 necp_policy_condition_get_value_pointer_from_buffer(u_int8_t *buffer, u_int32_t length)
1240 {
1241 return ((buffer && length > (2 * sizeof(u_int8_t))) ? (buffer + (2 * sizeof(u_int8_t))) : NULL);
1242 }
1243
1244 static inline bool
1245 necp_policy_condition_is_default(u_int8_t *buffer, u_int32_t length)
1246 {
1247 return (necp_policy_condition_get_type_from_buffer(buffer, length) == NECP_POLICY_CONDITION_DEFAULT);
1248 }
1249
1250 static inline bool
1251 necp_policy_condition_is_application(u_int8_t *buffer, u_int32_t length)
1252 {
1253 return (necp_policy_condition_get_type_from_buffer(buffer, length) == NECP_POLICY_CONDITION_APPLICATION);
1254 }
1255
1256 static inline bool
1257 necp_policy_condition_requires_application(u_int8_t *buffer, u_int32_t length)
1258 {
1259 u_int8_t type = necp_policy_condition_get_type_from_buffer(buffer, length);
1260 return (type == NECP_POLICY_CONDITION_REAL_APPLICATION ||
1261 type == NECP_POLICY_CONDITION_ENTITLEMENT);
1262 }
1263
1264 static bool
1265 necp_policy_condition_is_valid(u_int8_t *buffer, u_int32_t length, u_int8_t policy_result_type)
1266 {
1267 bool validated = FALSE;
1268 bool result_cannot_have_ip_layer = (policy_result_type == NECP_POLICY_RESULT_SOCKET_DIVERT ||
1269 policy_result_type == NECP_POLICY_RESULT_SOCKET_FILTER ||
1270 policy_result_type == NECP_POLICY_RESULT_TRIGGER ||
1271 policy_result_type == NECP_POLICY_RESULT_TRIGGER_IF_NEEDED ||
1272 policy_result_type == NECP_POLICY_RESULT_TRIGGER_SCOPED ||
1273 policy_result_type == NECP_POLICY_RESULT_NO_TRIGGER_SCOPED ||
1274 policy_result_type == NECP_POLICY_RESULT_SOCKET_SCOPED ||
1275 policy_result_type == NECP_POLICY_RESULT_ROUTE_RULES ||
1276 policy_result_type == NECP_POLICY_RESULT_USE_NETAGENT) ? TRUE : FALSE;
1277 u_int32_t condition_length = necp_policy_condition_get_value_length_from_buffer(buffer, length);
1278 u_int8_t *condition_value = necp_policy_condition_get_value_pointer_from_buffer(buffer, length);
1279 u_int8_t type = necp_policy_condition_get_type_from_buffer(buffer, length);
1280 u_int8_t flags = necp_policy_condition_get_flags_from_buffer(buffer, length);
1281 switch (type) {
1282 case NECP_POLICY_CONDITION_APPLICATION:
1283 case NECP_POLICY_CONDITION_REAL_APPLICATION: {
1284 if (!(flags & NECP_POLICY_CONDITION_FLAGS_NEGATIVE) &&
1285 condition_length >= sizeof(uuid_t) &&
1286 condition_value != NULL &&
1287 !uuid_is_null(condition_value)) {
1288 validated = TRUE;
1289 }
1290 break;
1291 }
1292 case NECP_POLICY_CONDITION_DOMAIN:
1293 case NECP_POLICY_CONDITION_ACCOUNT:
1294 case NECP_POLICY_CONDITION_BOUND_INTERFACE: {
1295 if (condition_length > 0) {
1296 validated = TRUE;
1297 }
1298 break;
1299 }
1300 case NECP_POLICY_CONDITION_TRAFFIC_CLASS: {
1301 if (condition_length >= sizeof(struct necp_policy_condition_tc_range)) {
1302 validated = TRUE;
1303 }
1304 break;
1305 }
1306 case NECP_POLICY_CONDITION_DEFAULT:
1307 case NECP_POLICY_CONDITION_ALL_INTERFACES:
1308 case NECP_POLICY_CONDITION_ENTITLEMENT: {
1309 if (!(flags & NECP_POLICY_CONDITION_FLAGS_NEGATIVE)) {
1310 validated = TRUE;
1311 }
1312 break;
1313 }
1314 case NECP_POLICY_CONDITION_IP_PROTOCOL: {
1315 if (condition_length >= sizeof(u_int16_t)) {
1316 validated = TRUE;
1317 }
1318 break;
1319 }
1320 case NECP_POLICY_CONDITION_PID: {
1321 if (condition_length >= sizeof(pid_t) &&
1322 condition_value != NULL &&
1323 *((pid_t *)(void *)condition_value) != 0) {
1324 validated = TRUE;
1325 }
1326 break;
1327 }
1328 case NECP_POLICY_CONDITION_UID: {
1329 if (condition_length >= sizeof(uid_t)) {
1330 validated = TRUE;
1331 }
1332 break;
1333 }
1334 case NECP_POLICY_CONDITION_LOCAL_ADDR:
1335 case NECP_POLICY_CONDITION_REMOTE_ADDR: {
1336 if (!result_cannot_have_ip_layer && condition_length >= sizeof(struct necp_policy_condition_addr)) {
1337 validated = TRUE;
1338 }
1339 break;
1340 }
1341 case NECP_POLICY_CONDITION_LOCAL_ADDR_RANGE:
1342 case NECP_POLICY_CONDITION_REMOTE_ADDR_RANGE: {
1343 if (!result_cannot_have_ip_layer && condition_length >= sizeof(struct necp_policy_condition_addr_range)) {
1344 validated = TRUE;
1345 }
1346 break;
1347 }
1348 default: {
1349 validated = FALSE;
1350 break;
1351 }
1352 }
1353
1354 if (necp_debug) {
1355 NECPLOG(LOG_DEBUG, "Policy condition type %d, valid %d", type, validated);
1356 }
1357
1358 return (validated);
1359 }
1360
1361 static bool
1362 necp_policy_route_rule_is_default(u_int8_t *buffer, u_int32_t length)
1363 {
1364 return (necp_policy_condition_get_value_length_from_buffer(buffer, length) == 0 &&
1365 necp_policy_condition_get_flags_from_buffer(buffer, length) == 0);
1366 }
1367
1368 static bool
1369 necp_policy_route_rule_is_valid(u_int8_t *buffer, u_int32_t length)
1370 {
1371 bool validated = FALSE;
1372 u_int8_t type = necp_policy_condition_get_type_from_buffer(buffer, length);
1373 switch (type) {
1374 case NECP_ROUTE_RULE_ALLOW_INTERFACE: {
1375 validated = TRUE;
1376 break;
1377 }
1378 case NECP_ROUTE_RULE_DENY_INTERFACE: {
1379 validated = TRUE;
1380 break;
1381 }
1382 default: {
1383 validated = FALSE;
1384 break;
1385 }
1386 }
1387
1388 if (necp_debug) {
1389 NECPLOG(LOG_DEBUG, "Policy route rule type %d, valid %d", type, validated);
1390 }
1391
1392 return (validated);
1393 }
1394
1395 static void
1396 necp_handle_set_session_priority(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset)
1397 {
1398 int error;
1399 struct necp_session_policy *policy = NULL;
1400 struct necp_session_policy *temp_policy = NULL;
1401 u_int32_t response_error = NECP_ERROR_INTERNAL;
1402 u_int32_t requested_session_priority = NECP_SESSION_PRIORITY_UNKNOWN;
1403
1404 // Read policy id
1405 error = necp_packet_get_tlv(packet, offset, NECP_TLV_SESSION_PRIORITY, sizeof(requested_session_priority), &requested_session_priority, NULL);
1406 if (error) {
1407 NECPLOG(LOG_ERR, "Failed to get session priority: %d", error);
1408 response_error = NECP_ERROR_INVALID_TLV;
1409 goto fail;
1410 }
1411
1412 if (session == NULL) {
1413 NECPLOG0(LOG_ERR, "Failed to find session");
1414 response_error = NECP_ERROR_INTERNAL;
1415 goto fail;
1416 }
1417
1418 // Enforce special session priorities with entitlements
1419 if (requested_session_priority == NECP_SESSION_PRIORITY_CONTROL ||
1420 requested_session_priority == NECP_SESSION_PRIORITY_PRIVILEGED_TUNNEL) {
1421 errno_t cred_result = priv_check_cred(kauth_cred_get(), PRIV_NET_PRIVILEGED_NECP_POLICIES, 0);
1422 if (cred_result != 0) {
1423 NECPLOG(LOG_ERR, "Session does not hold necessary entitlement to claim priority level %d", requested_session_priority);
1424 goto fail;
1425 }
1426 }
1427
1428 if (session->session_priority != requested_session_priority) {
1429 session->session_priority = requested_session_priority;
1430 session->session_order = necp_allocate_new_session_order(session->session_priority, session->control_unit);
1431 session->dirty = TRUE;
1432
1433 // Mark all policies as needing updates
1434 LIST_FOREACH_SAFE(policy, &session->policies, chain, temp_policy) {
1435 policy->pending_update = TRUE;
1436 }
1437 }
1438
1439 necp_send_success_response(session, NECP_PACKET_TYPE_SET_SESSION_PRIORITY, message_id);
1440 return;
1441
1442 fail:
1443 necp_send_error_response(session, NECP_PACKET_TYPE_SET_SESSION_PRIORITY, message_id, response_error);
1444 }
1445
1446 static void
1447 necp_handle_lock_session_to_proc(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset)
1448 {
1449 #pragma unused(packet, offset)
1450 // proc_uuid already filled out
1451 session->proc_locked = TRUE;
1452 necp_send_success_response(session, NECP_PACKET_TYPE_LOCK_SESSION_TO_PROC, message_id);
1453 }
1454
1455 static void
1456 necp_handle_register_service(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset)
1457 {
1458 int error;
1459 struct necp_service_registration *new_service = NULL;
1460 u_int32_t response_error = NECP_ERROR_INTERNAL;
1461 uuid_t service_uuid;
1462 uuid_clear(service_uuid);
1463
1464 if (session == NULL) {
1465 NECPLOG0(LOG_ERR, "Failed to find session");
1466 response_error = NECP_ERROR_INTERNAL;
1467 goto fail;
1468 }
1469
1470 // Enforce entitlements
1471 errno_t cred_result = priv_check_cred(kauth_cred_get(), PRIV_NET_PRIVILEGED_NECP_POLICIES, 0);
1472 if (cred_result != 0) {
1473 NECPLOG0(LOG_ERR, "Session does not hold necessary entitlement to register service");
1474 goto fail;
1475 }
1476
1477 // Read service uuid
1478 error = necp_packet_get_tlv(packet, offset, NECP_TLV_SERVICE_UUID, sizeof(uuid_t), service_uuid, NULL);
1479 if (error) {
1480 NECPLOG(LOG_ERR, "Failed to get service UUID: %d", error);
1481 response_error = NECP_ERROR_INVALID_TLV;
1482 goto fail;
1483 }
1484
1485 MALLOC(new_service, struct necp_service_registration *, sizeof(*new_service), M_NECP, M_WAITOK);
1486 if (new_service == NULL) {
1487 NECPLOG0(LOG_ERR, "Failed to allocate service registration");
1488 response_error = NECP_ERROR_INTERNAL;
1489 goto fail;
1490 }
1491
1492 lck_rw_lock_exclusive(&necp_kernel_policy_lock);
1493 memset(new_service, 0, sizeof(*new_service));
1494 new_service->service_id = necp_create_uuid_service_id_mapping(service_uuid);
1495 LIST_INSERT_HEAD(&session->services, new_service, session_chain);
1496 LIST_INSERT_HEAD(&necp_registered_service_list, new_service, kernel_chain);
1497 lck_rw_done(&necp_kernel_policy_lock);
1498
1499 necp_send_success_response(session, NECP_PACKET_TYPE_REGISTER_SERVICE, message_id);
1500 return;
1501 fail:
1502 necp_send_error_response(session, NECP_PACKET_TYPE_REGISTER_SERVICE, message_id, response_error);
1503 }
1504
1505 static void
1506 necp_handle_unregister_service(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset)
1507 {
1508 int error;
1509 struct necp_service_registration *service = NULL;
1510 struct necp_service_registration *temp_service = NULL;
1511 u_int32_t response_error = NECP_ERROR_INTERNAL;
1512 struct necp_uuid_id_mapping *mapping = NULL;
1513 uuid_t service_uuid;
1514 uuid_clear(service_uuid);
1515
1516 if (session == NULL) {
1517 NECPLOG0(LOG_ERR, "Failed to find session");
1518 response_error = NECP_ERROR_INTERNAL;
1519 goto fail;
1520 }
1521
1522 // Read service uuid
1523 error = necp_packet_get_tlv(packet, offset, NECP_TLV_SERVICE_UUID, sizeof(uuid_t), service_uuid, NULL);
1524 if (error) {
1525 NECPLOG(LOG_ERR, "Failed to get service UUID: %d", error);
1526 response_error = NECP_ERROR_INVALID_TLV;
1527 goto fail;
1528 }
1529
1530 // Mark remove all matching services for this session
1531 lck_rw_lock_exclusive(&necp_kernel_policy_lock);
1532 mapping = necp_uuid_lookup_service_id_locked(service_uuid);
1533 if (mapping != NULL) {
1534 LIST_FOREACH_SAFE(service, &session->services, session_chain, temp_service) {
1535 if (service->service_id == mapping->id) {
1536 LIST_REMOVE(service, session_chain);
1537 LIST_REMOVE(service, kernel_chain);
1538 FREE(service, M_NECP);
1539 }
1540 }
1541 necp_remove_uuid_service_id_mapping(service_uuid);
1542 }
1543 lck_rw_done(&necp_kernel_policy_lock);
1544
1545 necp_send_success_response(session, NECP_PACKET_TYPE_UNREGISTER_SERVICE, message_id);
1546 return;
1547 fail:
1548 necp_send_error_response(session, NECP_PACKET_TYPE_UNREGISTER_SERVICE, message_id, response_error);
1549 }
1550
1551 static void
1552 necp_handle_policy_add(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset)
1553 {
1554 bool has_default_condition = FALSE;
1555 bool has_non_default_condition = FALSE;
1556 bool has_application_condition = FALSE;
1557 bool requires_application_condition = FALSE;
1558 u_int8_t *conditions_array = NULL;
1559 u_int32_t conditions_array_size = 0;
1560 int conditions_array_cursor;
1561
1562 bool has_default_route_rule = FALSE;
1563 u_int8_t *route_rules_array = NULL;
1564 u_int32_t route_rules_array_size = 0;
1565 int route_rules_array_cursor;
1566
1567 int cursor;
1568 int error = 0;
1569 u_int32_t response_error = NECP_ERROR_INTERNAL;
1570
1571 necp_policy_order order = 0;
1572 struct necp_session_policy *policy = NULL;
1573 u_int8_t *policy_result = NULL;
1574 u_int32_t policy_result_size = 0;
1575
1576 // Read policy order
1577 error = necp_packet_get_tlv(packet, offset, NECP_TLV_POLICY_ORDER, sizeof(order), &order, NULL);
1578 if (error) {
1579 NECPLOG(LOG_ERR, "Failed to get policy order: %d", error);
1580 response_error = NECP_ERROR_INVALID_TLV;
1581 goto fail;
1582 }
1583
1584 // Read policy result
1585 cursor = necp_packet_find_tlv(packet, offset, NECP_TLV_POLICY_RESULT, &error, 0);
1586 error = necp_packet_get_tlv_at_offset(packet, cursor, 0, NULL, &policy_result_size);
1587 if (error || policy_result_size == 0) {
1588 NECPLOG(LOG_ERR, "Failed to get policy result length: %d", error);
1589 response_error = NECP_ERROR_INVALID_TLV;
1590 goto fail;
1591 }
1592 MALLOC(policy_result, u_int8_t *, policy_result_size, M_NECP, M_WAITOK);
1593 if (policy_result == NULL) {
1594 NECPLOG(LOG_ERR, "Failed to allocate a policy result buffer (size %d)", policy_result_size);
1595 response_error = NECP_ERROR_INTERNAL;
1596 goto fail;
1597 }
1598 error = necp_packet_get_tlv_at_offset(packet, cursor, policy_result_size, policy_result, NULL);
1599 if (error) {
1600 NECPLOG(LOG_ERR, "Failed to get policy result: %d", error);
1601 response_error = NECP_ERROR_POLICY_RESULT_INVALID;
1602 goto fail;
1603 }
1604 if (!necp_policy_result_is_valid(policy_result, policy_result_size)) {
1605 NECPLOG0(LOG_ERR, "Failed to validate policy result");
1606 response_error = NECP_ERROR_POLICY_RESULT_INVALID;
1607 goto fail;
1608 }
1609
1610 if (necp_policy_result_requires_route_rules(policy_result, policy_result_size)) {
1611 // Read route rules conditions
1612 for (cursor = necp_packet_find_tlv(packet, offset, NECP_TLV_ROUTE_RULE, &error, 0);
1613 cursor >= 0;
1614 cursor = necp_packet_find_tlv(packet, cursor, NECP_TLV_ROUTE_RULE, &error, 1)) {
1615 u_int32_t route_rule_size = 0;
1616 necp_packet_get_tlv_at_offset(packet, cursor, 0, NULL, &route_rule_size);
1617 if (route_rule_size > 0) {
1618 route_rules_array_size += (sizeof(u_int8_t) + sizeof(u_int32_t) + route_rule_size);
1619 }
1620 }
1621
1622 if (route_rules_array_size == 0) {
1623 NECPLOG0(LOG_ERR, "Failed to get policy route rules");
1624 response_error = NECP_ERROR_INVALID_TLV;
1625 goto fail;
1626 }
1627
1628 MALLOC(route_rules_array, u_int8_t *, route_rules_array_size, M_NECP, M_WAITOK);
1629 if (route_rules_array == NULL) {
1630 NECPLOG(LOG_ERR, "Failed to allocate a policy route rules array (size %d)", route_rules_array_size);
1631 response_error = NECP_ERROR_INTERNAL;
1632 goto fail;
1633 }
1634
1635 route_rules_array_cursor = 0;
1636 for (cursor = necp_packet_find_tlv(packet, offset, NECP_TLV_ROUTE_RULE, &error, 0);
1637 cursor >= 0;
1638 cursor = necp_packet_find_tlv(packet, cursor, NECP_TLV_ROUTE_RULE, &error, 1)) {
1639 u_int8_t route_rule_type = NECP_TLV_ROUTE_RULE;
1640 u_int32_t route_rule_size = 0;
1641 necp_packet_get_tlv_at_offset(packet, cursor, 0, NULL, &route_rule_size);
1642 if (route_rule_size > 0 && route_rule_size <= (route_rules_array_size - route_rules_array_cursor)) {
1643 // Add type
1644 memcpy((route_rules_array + route_rules_array_cursor), &route_rule_type, sizeof(route_rule_type));
1645 route_rules_array_cursor += sizeof(route_rule_type);
1646
1647 // Add length
1648 memcpy((route_rules_array + route_rules_array_cursor), &route_rule_size, sizeof(route_rule_size));
1649 route_rules_array_cursor += sizeof(route_rule_size);
1650
1651 // Add value
1652 necp_packet_get_tlv_at_offset(packet, cursor, route_rule_size, (route_rules_array + route_rules_array_cursor), NULL);
1653
1654 if (!necp_policy_route_rule_is_valid((route_rules_array + route_rules_array_cursor), route_rule_size)) {
1655 NECPLOG0(LOG_ERR, "Failed to validate policy route rule");
1656 response_error = NECP_ERROR_ROUTE_RULES_INVALID;
1657 goto fail;
1658 }
1659
1660 if (necp_policy_route_rule_is_default((route_rules_array + route_rules_array_cursor), route_rule_size)) {
1661 if (has_default_route_rule) {
1662 NECPLOG0(LOG_ERR, "Failed to validate route rule; contained multiple default route rules");
1663 response_error = NECP_ERROR_ROUTE_RULES_INVALID;
1664 goto fail;
1665 }
1666 has_default_route_rule = TRUE;
1667 }
1668
1669 route_rules_array_cursor += route_rule_size;
1670 }
1671 }
1672 }
1673
1674 // Read policy conditions
1675 for (cursor = necp_packet_find_tlv(packet, offset, NECP_TLV_POLICY_CONDITION, &error, 0);
1676 cursor >= 0;
1677 cursor = necp_packet_find_tlv(packet, cursor, NECP_TLV_POLICY_CONDITION, &error, 1)) {
1678 u_int32_t condition_size = 0;
1679 necp_packet_get_tlv_at_offset(packet, cursor, 0, NULL, &condition_size);
1680
1681 if (condition_size > 0) {
1682 conditions_array_size += (sizeof(u_int8_t) + sizeof(u_int32_t) + condition_size);
1683 }
1684 }
1685
1686 if (conditions_array_size == 0) {
1687 NECPLOG0(LOG_ERR, "Failed to get policy conditions");
1688 response_error = NECP_ERROR_INVALID_TLV;
1689 goto fail;
1690 }
1691 MALLOC(conditions_array, u_int8_t *, conditions_array_size, M_NECP, M_WAITOK);
1692 if (conditions_array == NULL) {
1693 NECPLOG(LOG_ERR, "Failed to allocate a policy conditions array (size %d)", conditions_array_size);
1694 response_error = NECP_ERROR_INTERNAL;
1695 goto fail;
1696 }
1697
1698 conditions_array_cursor = 0;
1699 for (cursor = necp_packet_find_tlv(packet, offset, NECP_TLV_POLICY_CONDITION, &error, 0);
1700 cursor >= 0;
1701 cursor = necp_packet_find_tlv(packet, cursor, NECP_TLV_POLICY_CONDITION, &error, 1)) {
1702 u_int8_t condition_type = NECP_TLV_POLICY_CONDITION;
1703 u_int32_t condition_size = 0;
1704 necp_packet_get_tlv_at_offset(packet, cursor, 0, NULL, &condition_size);
1705 if (condition_size > 0 && condition_size <= (conditions_array_size - conditions_array_cursor)) {
1706 // Add type
1707 memcpy((conditions_array + conditions_array_cursor), &condition_type, sizeof(condition_type));
1708 conditions_array_cursor += sizeof(condition_type);
1709
1710 // Add length
1711 memcpy((conditions_array + conditions_array_cursor), &condition_size, sizeof(condition_size));
1712 conditions_array_cursor += sizeof(condition_size);
1713
1714 // Add value
1715 necp_packet_get_tlv_at_offset(packet, cursor, condition_size, (conditions_array + conditions_array_cursor), NULL);
1716 if (!necp_policy_condition_is_valid((conditions_array + conditions_array_cursor), condition_size, necp_policy_result_get_type_from_buffer(policy_result, policy_result_size))) {
1717 NECPLOG0(LOG_ERR, "Failed to validate policy condition");
1718 response_error = NECP_ERROR_POLICY_CONDITIONS_INVALID;
1719 goto fail;
1720 }
1721
1722 if (necp_policy_condition_is_default((conditions_array + conditions_array_cursor), condition_size)) {
1723 has_default_condition = TRUE;
1724 } else {
1725 has_non_default_condition = TRUE;
1726 }
1727 if (has_default_condition && has_non_default_condition) {
1728 NECPLOG0(LOG_ERR, "Failed to validate conditions; contained default and non-default conditions");
1729 response_error = NECP_ERROR_POLICY_CONDITIONS_INVALID;
1730 goto fail;
1731 }
1732
1733 if (necp_policy_condition_is_application((conditions_array + conditions_array_cursor), condition_size)) {
1734 has_application_condition = TRUE;
1735 }
1736
1737 if (necp_policy_condition_requires_application((conditions_array + conditions_array_cursor), condition_size)) {
1738 requires_application_condition = TRUE;
1739 }
1740
1741 conditions_array_cursor += condition_size;
1742 }
1743 }
1744
1745 if (requires_application_condition && !has_application_condition) {
1746 NECPLOG0(LOG_ERR, "Failed to validate conditions; did not contain application condition");
1747 response_error = NECP_ERROR_POLICY_CONDITIONS_INVALID;
1748 goto fail;
1749 }
1750
1751 if ((policy = necp_policy_create(session, order, conditions_array, conditions_array_size, route_rules_array, route_rules_array_size, policy_result, policy_result_size)) == NULL) {
1752 response_error = NECP_ERROR_INTERNAL;
1753 goto fail;
1754 }
1755
1756 necp_send_policy_id_response(session, NECP_PACKET_TYPE_POLICY_ADD, message_id, policy->id);
1757 return;
1758
1759 fail:
1760 if (policy_result != NULL) {
1761 FREE(policy_result, M_NECP);
1762 }
1763 if (conditions_array != NULL) {
1764 FREE(conditions_array, M_NECP);
1765 }
1766 if (route_rules_array != NULL) {
1767 FREE(route_rules_array, M_NECP);
1768 }
1769
1770 necp_send_error_response(session, NECP_PACKET_TYPE_POLICY_ADD, message_id, response_error);
1771 }
1772
1773 static void
1774 necp_handle_policy_get(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset)
1775 {
1776 #pragma unused(offset)
1777 int error;
1778 u_int8_t *response = NULL;
1779 u_int8_t *cursor = NULL;
1780 u_int32_t response_error = NECP_ERROR_INTERNAL;
1781 necp_policy_id policy_id = 0;
1782 u_int32_t order_tlv_size = 0;
1783 u_int32_t result_tlv_size = 0;
1784 u_int32_t response_size = 0;
1785
1786 struct necp_session_policy *policy = NULL;
1787
1788 // Read policy id
1789 error = necp_packet_get_tlv(packet, offset, NECP_TLV_POLICY_ID, sizeof(policy_id), &policy_id, NULL);
1790 if (error) {
1791 NECPLOG(LOG_ERR, "Failed to get policy id: %d", error);
1792 response_error = NECP_ERROR_INVALID_TLV;
1793 goto fail;
1794 }
1795
1796 policy = necp_policy_find(session, policy_id);
1797 if (policy == NULL || policy->pending_deletion) {
1798 NECPLOG(LOG_ERR, "Failed to find policy with id %d", policy_id);
1799 response_error = NECP_ERROR_POLICY_ID_NOT_FOUND;
1800 goto fail;
1801 }
1802
1803 order_tlv_size = sizeof(u_int8_t) + sizeof(u_int32_t) + sizeof(necp_policy_order);
1804 result_tlv_size = (policy->result_size ? (sizeof(u_int8_t) + sizeof(u_int32_t) + policy->result_size) : 0);
1805 response_size = sizeof(struct necp_packet_header) + order_tlv_size + result_tlv_size + policy->conditions_size;
1806 MALLOC(response, u_int8_t *, response_size, M_NECP, M_WAITOK);
1807 if (response == NULL) {
1808 necp_send_error_response(session, NECP_PACKET_TYPE_POLICY_LIST_ALL, message_id, NECP_ERROR_INTERNAL);
1809 return;
1810 }
1811
1812 cursor = response;
1813 cursor = necp_buffer_write_packet_header(cursor, NECP_PACKET_TYPE_POLICY_GET, NECP_PACKET_FLAGS_RESPONSE, message_id);
1814 cursor = necp_buffer_write_tlv(cursor, NECP_TLV_POLICY_ORDER, sizeof(necp_policy_order), &policy->order);
1815
1816 if (result_tlv_size) {
1817 cursor = necp_buffer_write_tlv(cursor, NECP_TLV_POLICY_RESULT, policy->result_size, &policy->result);
1818 }
1819 if (policy->conditions_size) {
1820 memcpy(((u_int8_t *)(void *)(cursor)), policy->conditions, policy->conditions_size);
1821 }
1822
1823 if (!necp_send_ctl_data(session, (u_int8_t *)response, response_size)) {
1824 NECPLOG0(LOG_ERR, "Failed to send response");
1825 }
1826
1827 FREE(response, M_NECP);
1828 return;
1829
1830 fail:
1831 necp_send_error_response(session, NECP_PACKET_TYPE_POLICY_GET, message_id, response_error);
1832 }
1833
1834 static void
1835 necp_handle_policy_delete(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset)
1836 {
1837 int error;
1838 u_int32_t response_error = NECP_ERROR_INTERNAL;
1839 necp_policy_id policy_id = 0;
1840
1841 struct necp_session_policy *policy = NULL;
1842
1843 // Read policy id
1844 error = necp_packet_get_tlv(packet, offset, NECP_TLV_POLICY_ID, sizeof(policy_id), &policy_id, NULL);
1845 if (error) {
1846 NECPLOG(LOG_ERR, "Failed to get policy id: %d", error);
1847 response_error = NECP_ERROR_INVALID_TLV;
1848 goto fail;
1849 }
1850
1851 policy = necp_policy_find(session, policy_id);
1852 if (policy == NULL || policy->pending_deletion) {
1853 NECPLOG(LOG_ERR, "Failed to find policy with id %d", policy_id);
1854 response_error = NECP_ERROR_POLICY_ID_NOT_FOUND;
1855 goto fail;
1856 }
1857
1858 necp_policy_mark_for_deletion(session, policy);
1859
1860 necp_send_success_response(session, NECP_PACKET_TYPE_POLICY_DELETE, message_id);
1861 return;
1862
1863 fail:
1864 necp_send_error_response(session, NECP_PACKET_TYPE_POLICY_DELETE, message_id, response_error);
1865 }
1866
1867 static void
1868 necp_handle_policy_apply_all(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset)
1869 {
1870 #pragma unused(packet, offset)
1871 necp_policy_apply_all(session);
1872 necp_send_success_response(session, NECP_PACKET_TYPE_POLICY_APPLY_ALL, message_id);
1873 }
1874
1875 static void
1876 necp_handle_policy_list_all(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset)
1877 {
1878 #pragma unused(packet, offset)
1879 u_int32_t tlv_size = (sizeof(u_int8_t) + sizeof(u_int32_t) + sizeof(u_int32_t));
1880 u_int32_t response_size = 0;
1881 u_int8_t *response = NULL;
1882 u_int8_t *cursor = NULL;
1883 int num_policies = 0;
1884 int cur_policy_index = 0;
1885 struct necp_session_policy *policy;
1886
1887 LIST_FOREACH(policy, &session->policies, chain) {
1888 if (!policy->pending_deletion) {
1889 num_policies++;
1890 }
1891 }
1892
1893 // Create a response with one Policy ID TLV for each policy
1894 response_size = sizeof(struct necp_packet_header) + num_policies * tlv_size;
1895 MALLOC(response, u_int8_t *, response_size, M_NECP, M_WAITOK);
1896 if (response == NULL) {
1897 necp_send_error_response(session, NECP_PACKET_TYPE_POLICY_LIST_ALL, message_id, NECP_ERROR_INTERNAL);
1898 return;
1899 }
1900
1901 cursor = response;
1902 cursor = necp_buffer_write_packet_header(cursor, NECP_PACKET_TYPE_POLICY_LIST_ALL, NECP_PACKET_FLAGS_RESPONSE, message_id);
1903
1904 LIST_FOREACH(policy, &session->policies, chain) {
1905 if (!policy->pending_deletion && cur_policy_index < num_policies) {
1906 cursor = necp_buffer_write_tlv(cursor, NECP_TLV_POLICY_ID, sizeof(u_int32_t), &policy->id);
1907 cur_policy_index++;
1908 }
1909 }
1910
1911 if (!necp_send_ctl_data(session, (u_int8_t *)response, response_size)) {
1912 NECPLOG0(LOG_ERR, "Failed to send response");
1913 }
1914
1915 FREE(response, M_NECP);
1916 }
1917
1918 static void
1919 necp_handle_policy_delete_all(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset)
1920 {
1921 #pragma unused(packet, offset)
1922 necp_policy_mark_all_for_deletion(session);
1923 necp_send_success_response(session, NECP_PACKET_TYPE_POLICY_DELETE_ALL, message_id);
1924 }
1925
1926 static necp_policy_id
1927 necp_policy_get_new_id(void)
1928 {
1929 necp_policy_id newid = 0;
1930
1931 lck_rw_lock_exclusive(&necp_kernel_policy_lock);
1932
1933 necp_last_policy_id++;
1934 if (necp_last_policy_id < 1) {
1935 necp_last_policy_id = 1;
1936 }
1937
1938 newid = necp_last_policy_id;
1939 lck_rw_done(&necp_kernel_policy_lock);
1940
1941 if (newid == 0) {
1942 NECPLOG0(LOG_DEBUG, "Allocate policy id failed.\n");
1943 return (0);
1944 }
1945
1946 return (newid);
1947 }
1948
1949 static struct necp_session_policy *
1950 necp_policy_create(struct necp_session *session, necp_policy_order order, u_int8_t *conditions_array, u_int32_t conditions_array_size, u_int8_t *route_rules_array, u_int32_t route_rules_array_size, u_int8_t *result, u_int32_t result_size)
1951 {
1952 struct necp_session_policy *new_policy = NULL;
1953 struct necp_session_policy *tmp_policy = NULL;
1954
1955 if (session == NULL || conditions_array == NULL || result == NULL || result_size == 0) {
1956 goto done;
1957 }
1958
1959 MALLOC_ZONE(new_policy, struct necp_session_policy *, sizeof(*new_policy), M_NECP_SESSION_POLICY, M_WAITOK);
1960 if (new_policy == NULL) {
1961 goto done;
1962 }
1963
1964 memset(new_policy, 0, sizeof(*new_policy));
1965 new_policy->applied = FALSE;
1966 new_policy->pending_deletion = FALSE;
1967 new_policy->pending_update = FALSE;
1968 new_policy->order = order;
1969 new_policy->conditions = conditions_array;
1970 new_policy->conditions_size = conditions_array_size;
1971 new_policy->route_rules = route_rules_array;
1972 new_policy->route_rules_size = route_rules_array_size;
1973 new_policy->result = result;
1974 new_policy->result_size = result_size;
1975 new_policy->id = necp_policy_get_new_id();
1976
1977 LIST_INSERT_SORTED_ASCENDING(&session->policies, new_policy, chain, order, tmp_policy);
1978
1979 session->dirty = TRUE;
1980
1981 if (necp_debug) {
1982 NECPLOG(LOG_DEBUG, "Created NECP policy, order %d", order);
1983 }
1984 done:
1985 return (new_policy);
1986 }
1987
1988 static struct necp_session_policy *
1989 necp_policy_find(struct necp_session *session, necp_policy_id policy_id)
1990 {
1991 struct necp_session_policy *policy = NULL;
1992 if (policy_id == 0) {
1993 return (NULL);
1994 }
1995
1996 LIST_FOREACH(policy, &session->policies, chain) {
1997 if (policy->id == policy_id) {
1998 return (policy);
1999 }
2000 }
2001
2002 return (NULL);
2003 }
2004
2005 static inline u_int8_t
2006 necp_policy_get_result_type(struct necp_session_policy *policy)
2007 {
2008 return (policy ? necp_policy_result_get_type_from_buffer(policy->result, policy->result_size) : 0);
2009 }
2010
2011 static inline u_int32_t
2012 necp_policy_get_result_parameter_length(struct necp_session_policy *policy)
2013 {
2014 return (policy ? necp_policy_result_get_parameter_length_from_buffer(policy->result, policy->result_size) : 0);
2015 }
2016
2017 static bool
2018 necp_policy_get_result_parameter(struct necp_session_policy *policy, u_int8_t *parameter_buffer, u_int32_t parameter_buffer_length)
2019 {
2020 if (policy) {
2021 u_int32_t parameter_length = necp_policy_result_get_parameter_length_from_buffer(policy->result, policy->result_size);
2022 if (parameter_buffer_length >= parameter_length) {
2023 u_int8_t *parameter = necp_policy_result_get_parameter_pointer_from_buffer(policy->result, policy->result_size);
2024 if (parameter && parameter_buffer) {
2025 memcpy(parameter_buffer, parameter, parameter_length);
2026 return (TRUE);
2027 }
2028 }
2029 }
2030
2031 return (FALSE);
2032 }
2033
2034 static bool
2035 necp_policy_mark_for_deletion(struct necp_session *session, struct necp_session_policy *policy)
2036 {
2037 if (session == NULL || policy == NULL) {
2038 return (FALSE);
2039 }
2040
2041 policy->pending_deletion = TRUE;
2042 session->dirty = TRUE;
2043
2044 if (necp_debug) {
2045 NECPLOG0(LOG_DEBUG, "Marked NECP policy for removal");
2046 }
2047 return (TRUE);
2048 }
2049
2050 static bool
2051 necp_policy_mark_all_for_deletion(struct necp_session *session)
2052 {
2053 struct necp_session_policy *policy = NULL;
2054 struct necp_session_policy *temp_policy = NULL;
2055
2056 LIST_FOREACH_SAFE(policy, &session->policies, chain, temp_policy) {
2057 necp_policy_mark_for_deletion(session, policy);
2058 }
2059
2060 return (TRUE);
2061 }
2062
2063 static bool
2064 necp_policy_delete(struct necp_session *session, struct necp_session_policy *policy)
2065 {
2066 if (session == NULL || policy == NULL) {
2067 return (FALSE);
2068 }
2069
2070 LIST_REMOVE(policy, chain);
2071
2072 if (policy->result) {
2073 FREE(policy->result, M_NECP);
2074 policy->result = NULL;
2075 }
2076
2077 if (policy->conditions) {
2078 FREE(policy->conditions, M_NECP);
2079 policy->conditions = NULL;
2080 }
2081
2082 FREE_ZONE(policy, sizeof(*policy), M_NECP_SESSION_POLICY);
2083
2084 if (necp_debug) {
2085 NECPLOG0(LOG_DEBUG, "Removed NECP policy");
2086 }
2087 return (TRUE);
2088 }
2089
2090 static bool
2091 necp_policy_unapply(struct necp_session_policy *policy)
2092 {
2093 int i = 0;
2094 if (policy == NULL) {
2095 return (FALSE);
2096 }
2097
2098 lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);
2099
2100 // Release local uuid mappings
2101 if (!uuid_is_null(policy->applied_app_uuid)) {
2102 bool removed_mapping = FALSE;
2103 if (necp_remove_uuid_app_id_mapping(policy->applied_app_uuid, &removed_mapping, TRUE) && removed_mapping) {
2104 necp_uuid_app_id_mappings_dirty = TRUE;
2105 necp_num_uuid_app_id_mappings--;
2106 }
2107 uuid_clear(policy->applied_app_uuid);
2108 }
2109 if (!uuid_is_null(policy->applied_real_app_uuid)) {
2110 necp_remove_uuid_app_id_mapping(policy->applied_real_app_uuid, NULL, FALSE);
2111 uuid_clear(policy->applied_real_app_uuid);
2112 }
2113 if (!uuid_is_null(policy->applied_result_uuid)) {
2114 necp_remove_uuid_service_id_mapping(policy->applied_result_uuid);
2115 uuid_clear(policy->applied_result_uuid);
2116 }
2117
2118 // Release string mappings
2119 if (policy->applied_account != NULL) {
2120 necp_remove_string_to_id_mapping(&necp_account_id_list, policy->applied_account);
2121 FREE(policy->applied_account, M_NECP);
2122 policy->applied_account = NULL;
2123 }
2124
2125 // Release route rule
2126 if (policy->applied_route_rules_id != 0) {
2127 necp_remove_route_rule(&necp_route_rules, policy->applied_route_rules_id);
2128 policy->applied_route_rules_id = 0;
2129 }
2130
2131 // Remove socket policies
2132 for (i = 0; i < MAX_KERNEL_SOCKET_POLICIES; i++) {
2133 if (policy->kernel_socket_policies[i] != 0) {
2134 necp_kernel_socket_policy_delete(policy->kernel_socket_policies[i]);
2135 policy->kernel_socket_policies[i] = 0;
2136 }
2137 }
2138
2139 // Remove IP output policies
2140 for (i = 0; i < MAX_KERNEL_IP_OUTPUT_POLICIES; i++) {
2141 if (policy->kernel_ip_output_policies[i] != 0) {
2142 necp_kernel_ip_output_policy_delete(policy->kernel_ip_output_policies[i]);
2143 policy->kernel_ip_output_policies[i] = 0;
2144 }
2145 }
2146
2147 policy->applied = FALSE;
2148
2149 return (TRUE);
2150 }
2151
2152 static inline bool
2153 necp_address_is_valid(struct sockaddr *address)
2154 {
2155 if (address->sa_family == AF_INET) {
2156 return (address->sa_len == sizeof(struct sockaddr_in));
2157 } else if (address->sa_family == AF_INET6) {
2158 return (address->sa_len == sizeof(struct sockaddr_in6));
2159 } else {
2160 return (FALSE);
2161 }
2162 }
2163
2164 #define NECP_KERNEL_POLICY_SUBORDER_ID_TUNNEL_CONDITION 0
2165 #define NECP_KERNEL_POLICY_SUBORDER_NON_ID_TUNNEL_CONDITION 1
2166 #define NECP_KERNEL_POLICY_SUBORDER_ID_CONDITION 2
2167 #define NECP_KERNEL_POLICY_SUBORDER_NON_ID_CONDITIONS 3
2168 struct necp_policy_result_ip_tunnel {
2169 u_int32_t secondary_result;
2170 char interface_name[IFXNAMSIZ];
2171 } __attribute__((__packed__));
2172
2173 struct necp_policy_result_service {
2174 uuid_t identifier;
2175 u_int32_t data;
2176 } __attribute__((__packed__));
2177
2178 static bool
2179 necp_policy_apply(struct necp_session *session, struct necp_session_policy *policy)
2180 {
2181 bool socket_only_conditions = FALSE;
2182 bool socket_ip_conditions = FALSE;
2183
2184 bool socket_layer_non_id_conditions = FALSE;
2185 bool ip_output_layer_non_id_conditions = FALSE;
2186 bool ip_output_layer_id_condition = FALSE;
2187 bool ip_output_layer_tunnel_condition_from_id = FALSE;
2188 bool ip_output_layer_tunnel_condition_from_non_id = FALSE;
2189 necp_kernel_policy_id cond_ip_output_layer_id = NECP_KERNEL_POLICY_ID_NONE;
2190
2191 u_int32_t master_condition_mask = 0;
2192 u_int32_t master_condition_negated_mask = 0;
2193 ifnet_t cond_bound_interface = NULL;
2194 u_int32_t cond_account_id = 0;
2195 char *cond_domain = NULL;
2196 pid_t cond_pid = 0;
2197 uid_t cond_uid = 0;
2198 necp_app_id cond_app_id = 0;
2199 necp_app_id cond_real_app_id = 0;
2200 struct necp_policy_condition_tc_range cond_traffic_class;
2201 cond_traffic_class.start_tc = 0;
2202 cond_traffic_class.end_tc = 0;
2203 u_int16_t cond_protocol = 0;
2204 union necp_sockaddr_union cond_local_start;
2205 union necp_sockaddr_union cond_local_end;
2206 u_int8_t cond_local_prefix = 0;
2207 union necp_sockaddr_union cond_remote_start;
2208 union necp_sockaddr_union cond_remote_end;
2209 u_int8_t cond_remote_prefix = 0;
2210 u_int32_t offset = 0;
2211 u_int8_t ultimate_result = 0;
2212 u_int32_t secondary_result = 0;
2213 necp_kernel_policy_result_parameter secondary_result_parameter;
2214 memset(&secondary_result_parameter, 0, sizeof(secondary_result_parameter));
2215 u_int32_t cond_last_interface_index = 0;
2216 necp_kernel_policy_result_parameter ultimate_result_parameter;
2217 memset(&ultimate_result_parameter, 0, sizeof(ultimate_result_parameter));
2218
2219 if (policy == NULL) {
2220 return (FALSE);
2221 }
2222
2223 lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);
2224
2225 // Process conditions
2226 while (offset < policy->conditions_size) {
2227 u_int32_t length = 0;
2228 u_int8_t *value = necp_buffer_get_tlv_value(policy->conditions, offset, &length);
2229
2230 u_int8_t condition_type = necp_policy_condition_get_type_from_buffer(value, length);
2231 u_int8_t condition_flags = necp_policy_condition_get_flags_from_buffer(value, length);
2232 bool condition_is_negative = condition_flags & NECP_POLICY_CONDITION_FLAGS_NEGATIVE;
2233 u_int32_t condition_length = necp_policy_condition_get_value_length_from_buffer(value, length);
2234 u_int8_t *condition_value = necp_policy_condition_get_value_pointer_from_buffer(value, length);
2235 switch (condition_type) {
2236 case NECP_POLICY_CONDITION_DEFAULT: {
2237 socket_ip_conditions = TRUE;
2238 break;
2239 }
2240 case NECP_POLICY_CONDITION_ALL_INTERFACES: {
2241 master_condition_mask |= NECP_KERNEL_CONDITION_ALL_INTERFACES;
2242 socket_ip_conditions = TRUE;
2243 break;
2244 }
2245 case NECP_POLICY_CONDITION_ENTITLEMENT: {
2246 master_condition_mask |= NECP_KERNEL_CONDITION_ENTITLEMENT;
2247 socket_only_conditions = TRUE;
2248 break;
2249 }
2250 case NECP_POLICY_CONDITION_DOMAIN: {
2251 // Make sure there is only one such rule
2252 if (condition_length > 0 && cond_domain == NULL) {
2253 cond_domain = necp_create_trimmed_domain((char *)condition_value, condition_length);
2254 if (cond_domain != NULL) {
2255 master_condition_mask |= NECP_KERNEL_CONDITION_DOMAIN;
2256 if (condition_is_negative) {
2257 master_condition_negated_mask |= NECP_KERNEL_CONDITION_DOMAIN;
2258 }
2259 socket_only_conditions = TRUE;
2260 }
2261 }
2262 break;
2263 }
2264 case NECP_POLICY_CONDITION_ACCOUNT: {
2265 // Make sure there is only one such rule
2266 if (condition_length > 0 && cond_account_id == 0 && policy->applied_account == NULL) {
2267 char *string = NULL;
2268 MALLOC(string, char *, condition_length + 1, M_NECP, M_WAITOK);
2269 if (string != NULL) {
2270 memcpy(string, condition_value, condition_length);
2271 string[condition_length] = 0;
2272 cond_account_id = necp_create_string_to_id_mapping(&necp_account_id_list, string);
2273 if (cond_account_id != 0) {
2274 policy->applied_account = string; // Save the string in parent policy
2275 master_condition_mask |= NECP_KERNEL_CONDITION_ACCOUNT_ID;
2276 if (condition_is_negative) {
2277 master_condition_negated_mask |= NECP_KERNEL_CONDITION_ACCOUNT_ID;
2278 }
2279 socket_only_conditions = TRUE;
2280 } else {
2281 FREE(string, M_NECP);
2282 }
2283 }
2284 }
2285 break;
2286 }
2287 case NECP_POLICY_CONDITION_APPLICATION: {
2288 // Make sure there is only one such rule, because we save the uuid in the policy
2289 if (condition_length >= sizeof(uuid_t) && cond_app_id == 0) {
2290 bool allocated_mapping = FALSE;
2291 uuid_t application_uuid;
2292 memcpy(application_uuid, condition_value, sizeof(uuid_t));
2293 cond_app_id = necp_create_uuid_app_id_mapping(application_uuid, &allocated_mapping, TRUE);
2294 if (cond_app_id != 0) {
2295 if (allocated_mapping) {
2296 necp_uuid_app_id_mappings_dirty = TRUE;
2297 necp_num_uuid_app_id_mappings++;
2298 }
2299 uuid_copy(policy->applied_app_uuid, application_uuid);
2300 master_condition_mask |= NECP_KERNEL_CONDITION_APP_ID;
2301 if (condition_is_negative) {
2302 master_condition_negated_mask |= NECP_KERNEL_CONDITION_APP_ID;
2303 }
2304 socket_only_conditions = TRUE;
2305 }
2306 }
2307 break;
2308 }
2309 case NECP_POLICY_CONDITION_REAL_APPLICATION: {
2310 // Make sure there is only one such rule, because we save the uuid in the policy
2311 if (condition_length >= sizeof(uuid_t) && cond_real_app_id == 0) {
2312 uuid_t real_application_uuid;
2313 memcpy(real_application_uuid, condition_value, sizeof(uuid_t));
2314 cond_real_app_id = necp_create_uuid_app_id_mapping(real_application_uuid, NULL, FALSE);
2315 if (cond_real_app_id != 0) {
2316 uuid_copy(policy->applied_real_app_uuid, real_application_uuid);
2317 master_condition_mask |= NECP_KERNEL_CONDITION_REAL_APP_ID;
2318 if (condition_is_negative) {
2319 master_condition_negated_mask |= NECP_KERNEL_CONDITION_REAL_APP_ID;
2320 }
2321 socket_only_conditions = TRUE;
2322 }
2323 }
2324 break;
2325 }
2326 case NECP_POLICY_CONDITION_PID: {
2327 if (condition_length >= sizeof(pid_t)) {
2328 master_condition_mask |= NECP_KERNEL_CONDITION_PID;
2329 if (condition_is_negative) {
2330 master_condition_negated_mask |= NECP_KERNEL_CONDITION_PID;
2331 }
2332 memcpy(&cond_pid, condition_value, sizeof(cond_pid));
2333 socket_only_conditions = TRUE;
2334 }
2335 break;
2336 }
2337 case NECP_POLICY_CONDITION_UID: {
2338 if (condition_length >= sizeof(uid_t)) {
2339 master_condition_mask |= NECP_KERNEL_CONDITION_UID;
2340 if (condition_is_negative) {
2341 master_condition_negated_mask |= NECP_KERNEL_CONDITION_UID;
2342 }
2343 memcpy(&cond_uid, condition_value, sizeof(cond_uid));
2344 socket_only_conditions = TRUE;
2345 }
2346 break;
2347 }
2348 case NECP_POLICY_CONDITION_TRAFFIC_CLASS: {
2349 if (condition_length >= sizeof(struct necp_policy_condition_tc_range)) {
2350 master_condition_mask |= NECP_KERNEL_CONDITION_TRAFFIC_CLASS;
2351 if (condition_is_negative) {
2352 master_condition_negated_mask |= NECP_KERNEL_CONDITION_TRAFFIC_CLASS;
2353 }
2354 memcpy(&cond_traffic_class, condition_value, sizeof(cond_traffic_class));
2355 socket_only_conditions = TRUE;
2356 }
2357 break;
2358 }
2359 case NECP_POLICY_CONDITION_BOUND_INTERFACE: {
2360 if (condition_length <= IFXNAMSIZ && condition_length > 0) {
2361 char interface_name[IFXNAMSIZ];
2362 memcpy(interface_name, condition_value, condition_length);
2363 interface_name[condition_length - 1] = 0; // Make sure the string is NULL terminated
2364 if (ifnet_find_by_name(interface_name, &cond_bound_interface) == 0) {
2365 master_condition_mask |= NECP_KERNEL_CONDITION_BOUND_INTERFACE;
2366 if (condition_is_negative) {
2367 master_condition_negated_mask |= NECP_KERNEL_CONDITION_BOUND_INTERFACE;
2368 }
2369 }
2370 socket_ip_conditions = TRUE;
2371 }
2372 break;
2373 }
2374 case NECP_POLICY_CONDITION_IP_PROTOCOL: {
2375 if (condition_length >= sizeof(u_int16_t)) {
2376 master_condition_mask |= NECP_KERNEL_CONDITION_PROTOCOL;
2377 if (condition_is_negative) {
2378 master_condition_negated_mask |= NECP_KERNEL_CONDITION_PROTOCOL;
2379 }
2380 memcpy(&cond_protocol, condition_value, sizeof(cond_protocol));
2381 socket_ip_conditions = TRUE;
2382 }
2383 break;
2384 }
2385 case NECP_POLICY_CONDITION_LOCAL_ADDR: {
2386 struct necp_policy_condition_addr *address_struct = (struct necp_policy_condition_addr *)(void *)condition_value;
2387 if (!necp_address_is_valid(&address_struct->address.sa)) {
2388 break;
2389 }
2390
2391 cond_local_prefix = address_struct->prefix;
2392 memcpy(&cond_local_start, &address_struct->address, sizeof(address_struct->address));
2393 master_condition_mask |= NECP_KERNEL_CONDITION_LOCAL_START;
2394 master_condition_mask |= NECP_KERNEL_CONDITION_LOCAL_PREFIX;
2395 if (condition_is_negative) {
2396 master_condition_negated_mask |= NECP_KERNEL_CONDITION_LOCAL_START;
2397 master_condition_negated_mask |= NECP_KERNEL_CONDITION_LOCAL_PREFIX;
2398 }
2399 socket_ip_conditions = TRUE;
2400 break;
2401 }
2402 case NECP_POLICY_CONDITION_REMOTE_ADDR: {
2403 struct necp_policy_condition_addr *address_struct = (struct necp_policy_condition_addr *)(void *)condition_value;
2404 if (!necp_address_is_valid(&address_struct->address.sa)) {
2405 break;
2406 }
2407
2408 cond_remote_prefix = address_struct->prefix;
2409 memcpy(&cond_remote_start, &address_struct->address, sizeof(address_struct->address));
2410 master_condition_mask |= NECP_KERNEL_CONDITION_REMOTE_START;
2411 master_condition_mask |= NECP_KERNEL_CONDITION_REMOTE_PREFIX;
2412 if (condition_is_negative) {
2413 master_condition_negated_mask |= NECP_KERNEL_CONDITION_REMOTE_START;
2414 master_condition_negated_mask |= NECP_KERNEL_CONDITION_REMOTE_PREFIX;
2415 }
2416 socket_ip_conditions = TRUE;
2417 break;
2418 }
2419 case NECP_POLICY_CONDITION_LOCAL_ADDR_RANGE: {
2420 struct necp_policy_condition_addr_range *address_struct = (struct necp_policy_condition_addr_range *)(void *)condition_value;
2421 if (!necp_address_is_valid(&address_struct->start_address.sa) ||
2422 !necp_address_is_valid(&address_struct->end_address.sa)) {
2423 break;
2424 }
2425
2426 memcpy(&cond_local_start, &address_struct->start_address, sizeof(address_struct->start_address));
2427 memcpy(&cond_local_end, &address_struct->end_address, sizeof(address_struct->end_address));
2428 master_condition_mask |= NECP_KERNEL_CONDITION_LOCAL_START;
2429 master_condition_mask |= NECP_KERNEL_CONDITION_LOCAL_END;
2430 if (condition_is_negative) {
2431 master_condition_negated_mask |= NECP_KERNEL_CONDITION_LOCAL_START;
2432 master_condition_negated_mask |= NECP_KERNEL_CONDITION_LOCAL_END;
2433 }
2434 socket_ip_conditions = TRUE;
2435 break;
2436 }
2437 case NECP_POLICY_CONDITION_REMOTE_ADDR_RANGE: {
2438 struct necp_policy_condition_addr_range *address_struct = (struct necp_policy_condition_addr_range *)(void *)condition_value;
2439 if (!necp_address_is_valid(&address_struct->start_address.sa) ||
2440 !necp_address_is_valid(&address_struct->end_address.sa)) {
2441 break;
2442 }
2443
2444 memcpy(&cond_remote_start, &address_struct->start_address, sizeof(address_struct->start_address));
2445 memcpy(&cond_remote_end, &address_struct->end_address, sizeof(address_struct->end_address));
2446 master_condition_mask |= NECP_KERNEL_CONDITION_REMOTE_START;
2447 master_condition_mask |= NECP_KERNEL_CONDITION_REMOTE_END;
2448 if (condition_is_negative) {
2449 master_condition_negated_mask |= NECP_KERNEL_CONDITION_REMOTE_START;
2450 master_condition_negated_mask |= NECP_KERNEL_CONDITION_REMOTE_END;
2451 }
2452 socket_ip_conditions = TRUE;
2453 break;
2454 }
2455 default: {
2456 break;
2457 }
2458 }
2459
2460 offset += sizeof(u_int8_t) + sizeof(u_int32_t) + length;
2461 }
2462
2463 // Process result
2464 ultimate_result = necp_policy_get_result_type(policy);
2465 switch (ultimate_result) {
2466 case NECP_POLICY_RESULT_PASS: {
2467 if (socket_only_conditions) { // socket_ip_conditions can be TRUE or FALSE
2468 socket_layer_non_id_conditions = TRUE;
2469 ip_output_layer_id_condition = TRUE;
2470 } else if (socket_ip_conditions) {
2471 socket_layer_non_id_conditions = TRUE;
2472 ip_output_layer_id_condition = TRUE;
2473 ip_output_layer_non_id_conditions = TRUE;
2474 }
2475 break;
2476 }
2477 case NECP_POLICY_RESULT_DROP: {
2478 if (socket_only_conditions) { // socket_ip_conditions can be TRUE or FALSE
2479 socket_layer_non_id_conditions = TRUE;
2480 } else if (socket_ip_conditions) {
2481 socket_layer_non_id_conditions = TRUE;
2482 ip_output_layer_non_id_conditions = TRUE;
2483 }
2484 break;
2485 }
2486 case NECP_POLICY_RESULT_SKIP: {
2487 u_int32_t skip_policy_order = 0;
2488 if (necp_policy_get_result_parameter(policy, (u_int8_t *)&skip_policy_order, sizeof(skip_policy_order))) {
2489 ultimate_result_parameter.skip_policy_order = skip_policy_order;
2490 }
2491
2492 if (socket_only_conditions) { // socket_ip_conditions can be TRUE or FALSE
2493 socket_layer_non_id_conditions = TRUE;
2494 ip_output_layer_id_condition = TRUE;
2495 } else if (socket_ip_conditions) {
2496 socket_layer_non_id_conditions = TRUE;
2497 ip_output_layer_non_id_conditions = TRUE;
2498 }
2499 break;
2500 }
2501 case NECP_POLICY_RESULT_SOCKET_DIVERT:
2502 case NECP_POLICY_RESULT_SOCKET_FILTER: {
2503 u_int32_t control_unit = 0;
2504 if (necp_policy_get_result_parameter(policy, (u_int8_t *)&control_unit, sizeof(control_unit))) {
2505 ultimate_result_parameter.flow_divert_control_unit = control_unit;
2506 }
2507 socket_layer_non_id_conditions = TRUE;
2508 break;
2509 }
2510 case NECP_POLICY_RESULT_IP_TUNNEL: {
2511 struct necp_policy_result_ip_tunnel tunnel_parameters;
2512 u_int32_t tunnel_parameters_length = necp_policy_get_result_parameter_length(policy);
2513 if (tunnel_parameters_length > sizeof(u_int32_t) &&
2514 tunnel_parameters_length <= sizeof(struct necp_policy_result_ip_tunnel) &&
2515 necp_policy_get_result_parameter(policy, (u_int8_t *)&tunnel_parameters, sizeof(tunnel_parameters))) {
2516 ifnet_t tunnel_interface = NULL;
2517 tunnel_parameters.interface_name[tunnel_parameters_length - sizeof(u_int32_t) - 1] = 0; // Make sure the string is NULL terminated
2518 if (ifnet_find_by_name(tunnel_parameters.interface_name, &tunnel_interface) == 0) {
2519 ultimate_result_parameter.tunnel_interface_index = tunnel_interface->if_index;
2520 }
2521
2522 secondary_result = tunnel_parameters.secondary_result;
2523 if (secondary_result) {
2524 cond_last_interface_index = ultimate_result_parameter.tunnel_interface_index;
2525 }
2526 }
2527
2528 if (socket_only_conditions) { // socket_ip_conditions can be TRUE or FALSE
2529 socket_layer_non_id_conditions = TRUE;
2530 ip_output_layer_id_condition = TRUE;
2531 if (secondary_result) {
2532 ip_output_layer_tunnel_condition_from_id = TRUE;
2533 }
2534 } else if (socket_ip_conditions) {
2535 socket_layer_non_id_conditions = TRUE;
2536 ip_output_layer_id_condition = TRUE;
2537 ip_output_layer_non_id_conditions = TRUE;
2538 if (secondary_result) {
2539 ip_output_layer_tunnel_condition_from_id = TRUE;
2540 ip_output_layer_tunnel_condition_from_non_id = TRUE;
2541 }
2542 }
2543 break;
2544 }
2545 case NECP_POLICY_RESULT_TRIGGER:
2546 case NECP_POLICY_RESULT_TRIGGER_IF_NEEDED:
2547 case NECP_POLICY_RESULT_TRIGGER_SCOPED:
2548 case NECP_POLICY_RESULT_NO_TRIGGER_SCOPED: {
2549 struct necp_policy_result_service service_parameters;
2550 u_int32_t service_result_length = necp_policy_get_result_parameter_length(policy);
2551 bool has_extra_service_data = FALSE;
2552 if (service_result_length >= (sizeof(service_parameters))) {
2553 has_extra_service_data = TRUE;
2554 }
2555 if (necp_policy_get_result_parameter(policy, (u_int8_t *)&service_parameters, sizeof(service_parameters))) {
2556 ultimate_result_parameter.service.identifier = necp_create_uuid_service_id_mapping(service_parameters.identifier);
2557 if (ultimate_result_parameter.service.identifier != 0) {
2558 uuid_copy(policy->applied_result_uuid, service_parameters.identifier);
2559 socket_layer_non_id_conditions = TRUE;
2560 if (has_extra_service_data) {
2561 ultimate_result_parameter.service.data = service_parameters.data;
2562 } else {
2563 ultimate_result_parameter.service.data = 0;
2564 }
2565 }
2566 }
2567 break;
2568 }
2569 case NECP_POLICY_RESULT_USE_NETAGENT: {
2570 uuid_t netagent_uuid;
2571 if (necp_policy_get_result_parameter(policy, (u_int8_t *)&netagent_uuid, sizeof(netagent_uuid))) {
2572 ultimate_result_parameter.netagent_id = necp_create_uuid_service_id_mapping(netagent_uuid);
2573 if (ultimate_result_parameter.netagent_id != 0) {
2574 uuid_copy(policy->applied_result_uuid, netagent_uuid);
2575 socket_layer_non_id_conditions = TRUE;
2576 }
2577 }
2578 break;
2579 }
2580 case NECP_POLICY_RESULT_SOCKET_SCOPED: {
2581 u_int32_t interface_name_length = necp_policy_get_result_parameter_length(policy);
2582 if (interface_name_length <= IFXNAMSIZ && interface_name_length > 0) {
2583 char interface_name[IFXNAMSIZ];
2584 ifnet_t scope_interface = NULL;
2585 necp_policy_get_result_parameter(policy, (u_int8_t *)interface_name, interface_name_length);
2586 interface_name[interface_name_length - 1] = 0; // Make sure the string is NULL terminated
2587 if (ifnet_find_by_name(interface_name, &scope_interface) == 0) {
2588 ultimate_result_parameter.scoped_interface_index = scope_interface->if_index;
2589 socket_layer_non_id_conditions = TRUE;
2590 }
2591 }
2592 }
2593 case NECP_POLICY_RESULT_ROUTE_RULES: {
2594 if (policy->route_rules != NULL && policy->route_rules_size > 0) {
2595 u_int32_t route_rule_id = necp_create_route_rule(&necp_route_rules, policy->route_rules, policy->route_rules_size);
2596 if (route_rule_id > 0) {
2597 policy->applied_route_rules_id = route_rule_id;
2598 ultimate_result_parameter.route_rule_id = route_rule_id;
2599 socket_layer_non_id_conditions = TRUE;
2600 }
2601 }
2602 }
2603 default: {
2604 break;
2605 }
2606 }
2607
2608 if (socket_layer_non_id_conditions) {
2609 necp_kernel_policy_id policy_id = necp_kernel_socket_policy_add(policy->id, policy->order, session->session_order, session->proc_pid, master_condition_mask, master_condition_negated_mask, cond_app_id, cond_real_app_id, cond_account_id, cond_domain, cond_pid, cond_uid, cond_bound_interface, cond_traffic_class, cond_protocol, &cond_local_start, &cond_local_end, cond_local_prefix, &cond_remote_start, &cond_remote_end, cond_remote_prefix, ultimate_result, ultimate_result_parameter);
2610
2611 if (policy_id == 0) {
2612 NECPLOG0(LOG_DEBUG, "Error applying socket kernel policy");
2613 goto fail;
2614 }
2615
2616 cond_ip_output_layer_id = policy_id;
2617 policy->kernel_socket_policies[0] = policy_id;
2618 }
2619
2620 if (ip_output_layer_non_id_conditions) {
2621 necp_kernel_policy_id policy_id = necp_kernel_ip_output_policy_add(policy->id, policy->order, NECP_KERNEL_POLICY_SUBORDER_NON_ID_CONDITIONS, session->session_order, session->proc_pid, master_condition_mask, master_condition_negated_mask, NECP_KERNEL_POLICY_ID_NONE, cond_bound_interface, 0, cond_protocol, &cond_local_start, &cond_local_end, cond_local_prefix, &cond_remote_start, &cond_remote_end, cond_remote_prefix, ultimate_result, ultimate_result_parameter);
2622
2623 if (policy_id == 0) {
2624 NECPLOG0(LOG_DEBUG, "Error applying IP output kernel policy");
2625 goto fail;
2626 }
2627
2628 policy->kernel_ip_output_policies[NECP_KERNEL_POLICY_SUBORDER_NON_ID_CONDITIONS] = policy_id;
2629 }
2630
2631 if (ip_output_layer_id_condition) {
2632 necp_kernel_policy_id policy_id = necp_kernel_ip_output_policy_add(policy->id, policy->order, NECP_KERNEL_POLICY_SUBORDER_ID_CONDITION, session->session_order, session->proc_pid, NECP_KERNEL_CONDITION_POLICY_ID | NECP_KERNEL_CONDITION_ALL_INTERFACES, 0, cond_ip_output_layer_id, NULL, 0, 0, NULL, NULL, 0, NULL, NULL, 0, ultimate_result, ultimate_result_parameter);
2633
2634 if (policy_id == 0) {
2635 NECPLOG0(LOG_DEBUG, "Error applying IP output kernel policy");
2636 goto fail;
2637 }
2638
2639 policy->kernel_ip_output_policies[NECP_KERNEL_POLICY_SUBORDER_ID_CONDITION] = policy_id;
2640 }
2641
2642 // Extra policies for IP Output tunnels for when packets loop back
2643 if (ip_output_layer_tunnel_condition_from_id) {
2644 necp_kernel_policy_id policy_id = necp_kernel_ip_output_policy_add(policy->id, policy->order, NECP_KERNEL_POLICY_SUBORDER_NON_ID_TUNNEL_CONDITION, session->session_order, session->proc_pid, NECP_KERNEL_CONDITION_POLICY_ID | NECP_KERNEL_CONDITION_LAST_INTERFACE | NECP_KERNEL_CONDITION_ALL_INTERFACES, 0, policy->kernel_ip_output_policies[NECP_KERNEL_POLICY_SUBORDER_NON_ID_CONDITIONS], NULL, cond_last_interface_index, 0, NULL, NULL, 0, NULL, NULL, 0, secondary_result, secondary_result_parameter);
2645
2646 if (policy_id == 0) {
2647 NECPLOG0(LOG_DEBUG, "Error applying IP output kernel policy");
2648 goto fail;
2649 }
2650
2651 policy->kernel_ip_output_policies[NECP_KERNEL_POLICY_SUBORDER_NON_ID_TUNNEL_CONDITION] = policy_id;
2652 }
2653
2654 if (ip_output_layer_tunnel_condition_from_id) {
2655 necp_kernel_policy_id policy_id = necp_kernel_ip_output_policy_add(policy->id, policy->order, NECP_KERNEL_POLICY_SUBORDER_ID_TUNNEL_CONDITION, session->session_order, session->proc_pid, NECP_KERNEL_CONDITION_POLICY_ID | NECP_KERNEL_CONDITION_LAST_INTERFACE | NECP_KERNEL_CONDITION_ALL_INTERFACES, 0, policy->kernel_ip_output_policies[NECP_KERNEL_POLICY_SUBORDER_ID_CONDITION], NULL, cond_last_interface_index, 0, NULL, NULL, 0, NULL, NULL, 0, secondary_result, secondary_result_parameter);
2656
2657 if (policy_id == 0) {
2658 NECPLOG0(LOG_DEBUG, "Error applying IP output kernel policy");
2659 goto fail;
2660 }
2661
2662 policy->kernel_ip_output_policies[NECP_KERNEL_POLICY_SUBORDER_ID_TUNNEL_CONDITION] = policy_id;
2663 }
2664
2665 policy->applied = TRUE;
2666 policy->pending_update = FALSE;
2667 return (TRUE);
2668
2669 fail:
2670 return (FALSE);
2671 }
2672
2673 static void
2674 necp_policy_apply_all(struct necp_session *session)
2675 {
2676 struct necp_session_policy *policy = NULL;
2677 struct necp_session_policy *temp_policy = NULL;
2678 struct kev_necp_policies_changed_data kev_data;
2679 kev_data.changed_count = 0;
2680
2681 lck_rw_lock_exclusive(&necp_kernel_policy_lock);
2682
2683 // Remove exisiting applied policies
2684 if (session->dirty) {
2685 LIST_FOREACH_SAFE(policy, &session->policies, chain, temp_policy) {
2686 if (policy->pending_deletion) {
2687 if (policy->applied) {
2688 necp_policy_unapply(policy);
2689 }
2690 // Delete the policy
2691 necp_policy_delete(session, policy);
2692 } else if (!policy->applied) {
2693 necp_policy_apply(session, policy);
2694 } else if (policy->pending_update) {
2695 // Must have been applied, but needs an update. Remove and re-add.
2696 necp_policy_unapply(policy);
2697 necp_policy_apply(session, policy);
2698 }
2699 }
2700
2701 necp_kernel_socket_policies_update_uuid_table();
2702 necp_kernel_socket_policies_reprocess();
2703 necp_kernel_ip_output_policies_reprocess();
2704
2705 // Clear dirty bit flags
2706 session->dirty = FALSE;
2707 }
2708
2709 lck_rw_done(&necp_kernel_policy_lock);
2710
2711 necp_post_change_event(&kev_data);
2712
2713 if (necp_debug) {
2714 NECPLOG0(LOG_DEBUG, "Applied NECP policies");
2715 }
2716 }
2717
2718 // Kernel Policy Management
2719 // ---------------------
2720 // Kernel policies are derived from session policies
2721 static necp_kernel_policy_id
2722 necp_kernel_policy_get_new_id(void)
2723 {
2724 necp_kernel_policy_id newid = NECP_KERNEL_POLICY_ID_NONE;
2725
2726 lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);
2727
2728 necp_last_kernel_policy_id++;
2729 if (necp_last_kernel_policy_id < NECP_KERNEL_POLICY_ID_FIRST_VALID) {
2730 necp_last_kernel_policy_id = NECP_KERNEL_POLICY_ID_FIRST_VALID;
2731 }
2732
2733 newid = necp_last_kernel_policy_id;
2734 if (newid == NECP_KERNEL_POLICY_ID_NONE) {
2735 NECPLOG0(LOG_DEBUG, "Allocate kernel policy id failed.\n");
2736 return (0);
2737 }
2738
2739 return (newid);
2740 }
2741
2742 #define NECP_KERNEL_VALID_SOCKET_CONDITIONS (NECP_KERNEL_CONDITION_APP_ID | NECP_KERNEL_CONDITION_REAL_APP_ID | NECP_KERNEL_CONDITION_DOMAIN | NECP_KERNEL_CONDITION_ACCOUNT_ID | NECP_KERNEL_CONDITION_PID | NECP_KERNEL_CONDITION_UID | NECP_KERNEL_CONDITION_ALL_INTERFACES | NECP_KERNEL_CONDITION_BOUND_INTERFACE | NECP_KERNEL_CONDITION_TRAFFIC_CLASS | NECP_KERNEL_CONDITION_PROTOCOL | NECP_KERNEL_CONDITION_LOCAL_START | NECP_KERNEL_CONDITION_LOCAL_END | NECP_KERNEL_CONDITION_LOCAL_PREFIX | NECP_KERNEL_CONDITION_REMOTE_START | NECP_KERNEL_CONDITION_REMOTE_END | NECP_KERNEL_CONDITION_REMOTE_PREFIX | NECP_KERNEL_CONDITION_ENTITLEMENT)
2743 static necp_kernel_policy_id
2744 necp_kernel_socket_policy_add(necp_policy_id parent_policy_id, necp_policy_order order, u_int32_t session_order, int session_pid, u_int32_t condition_mask, u_int32_t condition_negated_mask, necp_app_id cond_app_id, necp_app_id cond_real_app_id, u_int32_t cond_account_id, char *cond_domain, pid_t cond_pid, uid_t cond_uid, ifnet_t cond_bound_interface, struct necp_policy_condition_tc_range cond_traffic_class, u_int16_t cond_protocol, union necp_sockaddr_union *cond_local_start, union necp_sockaddr_union *cond_local_end, u_int8_t cond_local_prefix, union necp_sockaddr_union *cond_remote_start, union necp_sockaddr_union *cond_remote_end, u_int8_t cond_remote_prefix, necp_kernel_policy_result result, necp_kernel_policy_result_parameter result_parameter)
2745 {
2746 struct necp_kernel_socket_policy *new_kernel_policy = NULL;
2747 struct necp_kernel_socket_policy *tmp_kernel_policy = NULL;
2748
2749 MALLOC_ZONE(new_kernel_policy, struct necp_kernel_socket_policy *, sizeof(*new_kernel_policy), M_NECP_SOCKET_POLICY, M_WAITOK);
2750 if (new_kernel_policy == NULL) {
2751 goto done;
2752 }
2753
2754 memset(new_kernel_policy, 0, sizeof(*new_kernel_policy));
2755 new_kernel_policy->parent_policy_id = parent_policy_id;
2756 new_kernel_policy->id = necp_kernel_policy_get_new_id();
2757 new_kernel_policy->order = order;
2758 new_kernel_policy->session_order = session_order;
2759 new_kernel_policy->session_pid = session_pid;
2760
2761 // Sanitize condition mask
2762 new_kernel_policy->condition_mask = (condition_mask & NECP_KERNEL_VALID_SOCKET_CONDITIONS);
2763 if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES) && (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE)) {
2764 new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_BOUND_INTERFACE;
2765 }
2766 if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REAL_APP_ID) && !(new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_APP_ID)) {
2767 new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_REAL_APP_ID;
2768 }
2769 if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ENTITLEMENT) && !(new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_APP_ID)) {
2770 new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_ENTITLEMENT;
2771 }
2772 if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) && (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX)) {
2773 new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_LOCAL_PREFIX;
2774 }
2775 if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) && (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX)) {
2776 new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_REMOTE_PREFIX;
2777 }
2778 new_kernel_policy->condition_negated_mask = condition_negated_mask & new_kernel_policy->condition_mask;
2779
2780 // Set condition values
2781 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_APP_ID) {
2782 new_kernel_policy->cond_app_id = cond_app_id;
2783 }
2784 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REAL_APP_ID) {
2785 new_kernel_policy->cond_real_app_id = cond_real_app_id;
2786 }
2787 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ACCOUNT_ID) {
2788 new_kernel_policy->cond_account_id = cond_account_id;
2789 }
2790 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_DOMAIN) {
2791 new_kernel_policy->cond_domain = cond_domain;
2792 new_kernel_policy->cond_domain_dot_count = necp_count_dots(cond_domain, strlen(cond_domain));
2793 }
2794 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_PID) {
2795 new_kernel_policy->cond_pid = cond_pid;
2796 }
2797 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_UID) {
2798 new_kernel_policy->cond_uid = cond_uid;
2799 }
2800 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE) {
2801 if (cond_bound_interface) {
2802 ifnet_reference(cond_bound_interface);
2803 }
2804 new_kernel_policy->cond_bound_interface = cond_bound_interface;
2805 }
2806 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_TRAFFIC_CLASS) {
2807 new_kernel_policy->cond_traffic_class = cond_traffic_class;
2808 }
2809 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_PROTOCOL) {
2810 new_kernel_policy->cond_protocol = cond_protocol;
2811 }
2812 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_START) {
2813 memcpy(&new_kernel_policy->cond_local_start, cond_local_start, cond_local_start->sa.sa_len);
2814 }
2815 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
2816 memcpy(&new_kernel_policy->cond_local_end, cond_local_end, cond_local_end->sa.sa_len);
2817 }
2818 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX) {
2819 new_kernel_policy->cond_local_prefix = cond_local_prefix;
2820 }
2821 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_START) {
2822 memcpy(&new_kernel_policy->cond_remote_start, cond_remote_start, cond_remote_start->sa.sa_len);
2823 }
2824 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
2825 memcpy(&new_kernel_policy->cond_remote_end, cond_remote_end, cond_remote_end->sa.sa_len);
2826 }
2827 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX) {
2828 new_kernel_policy->cond_remote_prefix = cond_remote_prefix;
2829 }
2830
2831 new_kernel_policy->result = result;
2832 memcpy(&new_kernel_policy->result_parameter, &result_parameter, sizeof(result_parameter));
2833
2834 if (necp_debug) {
2835 NECPLOG(LOG_DEBUG, "Added kernel policy: socket, id=%d, mask=%x\n", new_kernel_policy->id, new_kernel_policy->condition_mask);
2836 }
2837 LIST_INSERT_SORTED_TWICE_ASCENDING(&necp_kernel_socket_policies, new_kernel_policy, chain, session_order, order, tmp_kernel_policy);
2838 done:
2839 return (new_kernel_policy ? new_kernel_policy->id : 0);
2840 }
2841
2842 static struct necp_kernel_socket_policy *
2843 necp_kernel_socket_policy_find(necp_kernel_policy_id policy_id)
2844 {
2845 struct necp_kernel_socket_policy *kernel_policy = NULL;
2846 struct necp_kernel_socket_policy *tmp_kernel_policy = NULL;
2847
2848 if (policy_id == 0) {
2849 return (NULL);
2850 }
2851
2852 LIST_FOREACH_SAFE(kernel_policy, &necp_kernel_socket_policies, chain, tmp_kernel_policy) {
2853 if (kernel_policy->id == policy_id) {
2854 return (kernel_policy);
2855 }
2856 }
2857
2858 return (NULL);
2859 }
2860
2861 static bool
2862 necp_kernel_socket_policy_delete(necp_kernel_policy_id policy_id)
2863 {
2864 struct necp_kernel_socket_policy *policy = NULL;
2865
2866 lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);
2867
2868 policy = necp_kernel_socket_policy_find(policy_id);
2869 if (policy) {
2870 LIST_REMOVE(policy, chain);
2871
2872 if (policy->cond_bound_interface) {
2873 ifnet_release(policy->cond_bound_interface);
2874 policy->cond_bound_interface = NULL;
2875 }
2876
2877 if (policy->cond_domain) {
2878 FREE(policy->cond_domain, M_NECP);
2879 policy->cond_domain = NULL;
2880 }
2881
2882 FREE_ZONE(policy, sizeof(*policy), M_NECP_SOCKET_POLICY);
2883 return (TRUE);
2884 }
2885
2886 return (FALSE);
2887 }
2888
2889 #define MAX_RESULT_STRING_LEN 64
2890 static inline const char *
2891 necp_get_result_description(char *result_string, necp_kernel_policy_result result, necp_kernel_policy_result_parameter result_parameter)
2892 {
2893 uuid_string_t uuid_string;
2894 switch (result) {
2895 case NECP_KERNEL_POLICY_RESULT_NONE: {
2896 return ("None");
2897 }
2898 case NECP_KERNEL_POLICY_RESULT_PASS: {
2899 return ("Pass");
2900 }
2901 case NECP_KERNEL_POLICY_RESULT_SKIP: {
2902 return ("Skip");
2903 }
2904 case NECP_KERNEL_POLICY_RESULT_DROP: {
2905 return ("Drop");
2906 }
2907 case NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT: {
2908 snprintf(result_string, MAX_RESULT_STRING_LEN, "SocketDivert (%d)", result_parameter.flow_divert_control_unit);
2909 break;
2910 }
2911 case NECP_KERNEL_POLICY_RESULT_SOCKET_FILTER: {
2912 snprintf(result_string, MAX_RESULT_STRING_LEN, "SocketFilter (%d)", result_parameter.filter_control_unit);
2913 break;
2914 }
2915 case NECP_KERNEL_POLICY_RESULT_IP_TUNNEL: {
2916 ifnet_t interface = ifindex2ifnet[result_parameter.tunnel_interface_index];
2917 snprintf(result_string, MAX_RESULT_STRING_LEN, "IPTunnel (%s%d)", ifnet_name(interface), ifnet_unit(interface));
2918 break;
2919 }
2920 case NECP_KERNEL_POLICY_RESULT_IP_FILTER: {
2921 return ("IPFilter");
2922 }
2923 case NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED: {
2924 ifnet_t interface = ifindex2ifnet[result_parameter.scoped_interface_index];
2925 snprintf(result_string, MAX_RESULT_STRING_LEN, "SocketScoped (%s%d)", ifnet_name(interface), ifnet_unit(interface));
2926 break;
2927 }
2928 case NECP_KERNEL_POLICY_RESULT_ROUTE_RULES: {
2929 int index = 0;
2930 char interface_names[IFXNAMSIZ][MAX_ROUTE_RULE_INTERFACES];
2931 struct necp_route_rule *route_rule = necp_lookup_route_rule_locked(&necp_route_rules, result_parameter.route_rule_id);
2932 if (route_rule != NULL) {
2933 bool default_drop = (route_rule->default_action == NECP_ROUTE_RULE_DENY_INTERFACE);
2934 for (index = 0; index < MAX_ROUTE_RULE_INTERFACES; index++) {
2935 if (route_rule->exception_if_indices[index] != 0) {
2936 ifnet_t interface = ifindex2ifnet[route_rule->exception_if_indices[index]];
2937 snprintf(interface_names[index], IFXNAMSIZ, "%s%d", ifnet_name(interface), ifnet_unit(interface));
2938 } else {
2939 memset(interface_names[index], 0, IFXNAMSIZ);
2940 }
2941 }
2942 if (default_drop) {
2943 snprintf(result_string, MAX_RESULT_STRING_LEN, "RouteRules (Only %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s)",
2944 (route_rule->cellular_action == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? "Cell " : "",
2945 (route_rule->wifi_action == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? "WiFi " : "",
2946 (route_rule->wired_action == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? "Wired " : "",
2947 (route_rule->expensive_action == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? "Exp " : "",
2948 (route_rule->exception_if_actions[0] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? interface_names[0] : "",
2949 (route_rule->exception_if_actions[0] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? " " : "",
2950 (route_rule->exception_if_actions[1] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? interface_names[1] : "",
2951 (route_rule->exception_if_actions[1] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? " " : "",
2952 (route_rule->exception_if_actions[2] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? interface_names[2] : "",
2953 (route_rule->exception_if_actions[2] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? " " : "",
2954 (route_rule->exception_if_actions[3] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? interface_names[3] : "",
2955 (route_rule->exception_if_actions[3] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? " " : "",
2956 (route_rule->exception_if_actions[4] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? interface_names[4] : "",
2957 (route_rule->exception_if_actions[4] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? " " : "",
2958 (route_rule->exception_if_actions[5] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? interface_names[5] : "",
2959 (route_rule->exception_if_actions[5] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? " " : "",
2960 (route_rule->exception_if_actions[6] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? interface_names[6] : "",
2961 (route_rule->exception_if_actions[6] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? " " : "",
2962 (route_rule->exception_if_actions[7] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? interface_names[7] : "",
2963 (route_rule->exception_if_actions[7] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? " " : "",
2964 (route_rule->exception_if_actions[8] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? interface_names[8] : "",
2965 (route_rule->exception_if_actions[8] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? " " : "",
2966 (route_rule->exception_if_actions[9] == NECP_ROUTE_RULE_ALLOW_INTERFACE) ? interface_names[9] : "");
2967 } else {
2968 snprintf(result_string, MAX_RESULT_STRING_LEN, "RouteRules (%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s)",
2969 (route_rule->cellular_action == NECP_ROUTE_RULE_DENY_INTERFACE) ? "!Cell " : "",
2970 (route_rule->wifi_action == NECP_ROUTE_RULE_DENY_INTERFACE) ? "!WiFi " : "",
2971 (route_rule->wired_action == NECP_ROUTE_RULE_DENY_INTERFACE) ? "!Wired " : "",
2972 (route_rule->expensive_action == NECP_ROUTE_RULE_DENY_INTERFACE) ? "!Exp " : "",
2973 (route_rule->exception_if_actions[0] == NECP_ROUTE_RULE_DENY_INTERFACE) ? "!" : "",
2974 (route_rule->exception_if_actions[0] == NECP_ROUTE_RULE_DENY_INTERFACE) ? interface_names[0] : "",
2975 (route_rule->exception_if_actions[1] == NECP_ROUTE_RULE_DENY_INTERFACE) ? "!" : "",
2976 (route_rule->exception_if_actions[1] == NECP_ROUTE_RULE_DENY_INTERFACE) ? interface_names[1] : "",
2977 (route_rule->exception_if_actions[2] == NECP_ROUTE_RULE_DENY_INTERFACE) ? "!" : "",
2978 (route_rule->exception_if_actions[2] == NECP_ROUTE_RULE_DENY_INTERFACE) ? interface_names[2] : "",
2979 (route_rule->exception_if_actions[3] == NECP_ROUTE_RULE_DENY_INTERFACE) ? "!" : "",
2980 (route_rule->exception_if_actions[3] == NECP_ROUTE_RULE_DENY_INTERFACE) ? interface_names[3] : "",
2981 (route_rule->exception_if_actions[4] == NECP_ROUTE_RULE_DENY_INTERFACE) ? "!" : "",
2982 (route_rule->exception_if_actions[4] == NECP_ROUTE_RULE_DENY_INTERFACE) ? interface_names[4] : "",
2983 (route_rule->exception_if_actions[5] == NECP_ROUTE_RULE_DENY_INTERFACE) ? "!" : "",
2984 (route_rule->exception_if_actions[5] == NECP_ROUTE_RULE_DENY_INTERFACE) ? interface_names[5] : "",
2985 (route_rule->exception_if_actions[6] == NECP_ROUTE_RULE_DENY_INTERFACE) ? "!" : "",
2986 (route_rule->exception_if_actions[6] == NECP_ROUTE_RULE_DENY_INTERFACE) ? interface_names[6] : "",
2987 (route_rule->exception_if_actions[7] == NECP_ROUTE_RULE_DENY_INTERFACE) ? "!" : "",
2988 (route_rule->exception_if_actions[7] == NECP_ROUTE_RULE_DENY_INTERFACE) ? interface_names[7] : "",
2989 (route_rule->exception_if_actions[8] == NECP_ROUTE_RULE_DENY_INTERFACE) ? "!" : "",
2990 (route_rule->exception_if_actions[8] == NECP_ROUTE_RULE_DENY_INTERFACE) ? interface_names[8] : "",
2991 (route_rule->exception_if_actions[9] == NECP_ROUTE_RULE_DENY_INTERFACE) ? "!" : "",
2992 (route_rule->exception_if_actions[9] == NECP_ROUTE_RULE_DENY_INTERFACE) ? interface_names[9] : "");
2993 }
2994 } else {
2995 snprintf(result_string, MAX_RESULT_STRING_LEN, "RouteRules (Unknown)");
2996 }
2997 break;
2998 }
2999 case NECP_KERNEL_POLICY_RESULT_USE_NETAGENT: {
3000 bool found_mapping = FALSE;
3001 struct necp_uuid_id_mapping *mapping = necp_uuid_lookup_uuid_with_service_id_locked(result_parameter.netagent_id);
3002 if (mapping != NULL) {
3003 uuid_unparse(mapping->uuid, uuid_string);
3004 found_mapping = TRUE;
3005 }
3006 snprintf(result_string, MAX_RESULT_STRING_LEN, "UseNetAgent (%s)", found_mapping ? uuid_string : "Unknown");
3007 break;
3008 }
3009 case NECP_POLICY_RESULT_TRIGGER: {
3010 bool found_mapping = FALSE;
3011 struct necp_uuid_id_mapping *mapping = necp_uuid_lookup_uuid_with_service_id_locked(result_parameter.service.identifier);
3012 if (mapping != NULL) {
3013 uuid_unparse(mapping->uuid, uuid_string);
3014 found_mapping = TRUE;
3015 }
3016 snprintf(result_string, MAX_RESULT_STRING_LEN, "Trigger (%s.%d)", found_mapping ? uuid_string : "Unknown", result_parameter.service.data);
3017 break;
3018 }
3019 case NECP_POLICY_RESULT_TRIGGER_IF_NEEDED: {
3020 bool found_mapping = FALSE;
3021 struct necp_uuid_id_mapping *mapping = necp_uuid_lookup_uuid_with_service_id_locked(result_parameter.service.identifier);
3022 if (mapping != NULL) {
3023 uuid_unparse(mapping->uuid, uuid_string);
3024 found_mapping = TRUE;
3025 }
3026 snprintf(result_string, MAX_RESULT_STRING_LEN, "TriggerIfNeeded (%s.%d)", found_mapping ? uuid_string : "Unknown", result_parameter.service.data);
3027 break;
3028 }
3029 case NECP_POLICY_RESULT_TRIGGER_SCOPED: {
3030 bool found_mapping = FALSE;
3031 struct necp_uuid_id_mapping *mapping = necp_uuid_lookup_uuid_with_service_id_locked(result_parameter.service.identifier);
3032 if (mapping != NULL) {
3033 uuid_unparse(mapping->uuid, uuid_string);
3034 found_mapping = TRUE;
3035 }
3036 snprintf(result_string, MAX_RESULT_STRING_LEN, "TriggerScoped (%s.%d)", found_mapping ? uuid_string : "Unknown", result_parameter.service.data);
3037 break;
3038 }
3039 case NECP_POLICY_RESULT_NO_TRIGGER_SCOPED: {
3040 bool found_mapping = FALSE;
3041 struct necp_uuid_id_mapping *mapping = necp_uuid_lookup_uuid_with_service_id_locked(result_parameter.service.identifier);
3042 if (mapping != NULL) {
3043 uuid_unparse(mapping->uuid, uuid_string);
3044 found_mapping = TRUE;
3045 }
3046 snprintf(result_string, MAX_RESULT_STRING_LEN, "NoTriggerScoped (%s.%d)", found_mapping ? uuid_string : "Unknown", result_parameter.service.data);
3047 break;
3048 }
3049 default: {
3050 snprintf(result_string, MAX_RESULT_STRING_LEN, "Unknown %d (%d)", result, result_parameter.tunnel_interface_index);
3051 break;
3052 }
3053 }
3054 return (result_string);
3055 }
3056
3057 static void
3058 necp_kernel_socket_policies_dump_all(void)
3059 {
3060 if (necp_debug) {
3061 struct necp_kernel_socket_policy *policy = NULL;
3062 int policy_i;
3063 int app_i;
3064 char result_string[MAX_RESULT_STRING_LEN];
3065 char proc_name_string[MAXCOMLEN + 1];
3066 memset(result_string, 0, MAX_RESULT_STRING_LEN);
3067 memset(proc_name_string, 0, MAXCOMLEN + 1);
3068
3069 NECPLOG0(LOG_DEBUG, "NECP Application Policies:\n");
3070 NECPLOG0(LOG_DEBUG, "-----------\n");
3071 for (policy_i = 0; necp_kernel_socket_policies_app_layer_map != NULL && necp_kernel_socket_policies_app_layer_map[policy_i] != NULL; policy_i++) {
3072 policy = necp_kernel_socket_policies_app_layer_map[policy_i];
3073 proc_name(policy->session_pid, proc_name_string, MAXCOMLEN);
3074 NECPLOG(LOG_DEBUG, "\t%3d. Policy ID: %5d\tProcess: %10.10s\tOrder: %04d.%04d\tMask: %5x\tResult: %s\n", policy_i, policy->id, proc_name_string, policy->session_order, policy->order, policy->condition_mask, necp_get_result_description(result_string, policy->result, policy->result_parameter));
3075 }
3076 if (necp_kernel_socket_policies_app_layer_map[0] != NULL) {
3077 NECPLOG0(LOG_DEBUG, "-----------\n");
3078 }
3079
3080 NECPLOG0(LOG_DEBUG, "NECP Socket Policies:\n");
3081 NECPLOG0(LOG_DEBUG, "-----------\n");
3082 for (app_i = 0; app_i < NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS; app_i++) {
3083 NECPLOG(LOG_DEBUG, "\tApp Bucket: %d\n", app_i);
3084 for (policy_i = 0; necp_kernel_socket_policies_map[app_i] != NULL && (necp_kernel_socket_policies_map[app_i])[policy_i] != NULL; policy_i++) {
3085 policy = (necp_kernel_socket_policies_map[app_i])[policy_i];
3086 proc_name(policy->session_pid, proc_name_string, MAXCOMLEN);
3087 NECPLOG(LOG_DEBUG, "\t%3d. Policy ID: %5d\tProcess: %10.10s\tOrder: %04d.%04d\tMask: %5x\tResult: %s\n", policy_i, policy->id, proc_name_string, policy->session_order, policy->order, policy->condition_mask, necp_get_result_description(result_string, policy->result, policy->result_parameter));
3088 }
3089 NECPLOG0(LOG_DEBUG, "-----------\n");
3090 }
3091 }
3092 }
3093
3094 static inline bool
3095 necp_kernel_socket_result_is_trigger_service_type(struct necp_kernel_socket_policy *kernel_policy)
3096 {
3097 return (kernel_policy->result >= NECP_KERNEL_POLICY_RESULT_TRIGGER && kernel_policy->result <= NECP_KERNEL_POLICY_RESULT_NO_TRIGGER_SCOPED);
3098 }
3099
3100 static inline bool
3101 necp_kernel_socket_policy_results_overlap(struct necp_kernel_socket_policy *upper_policy, struct necp_kernel_socket_policy *lower_policy)
3102 {
3103 if (upper_policy->result == NECP_KERNEL_POLICY_RESULT_DROP) {
3104 // Drop always cancels out lower policies
3105 return (TRUE);
3106 } else if (upper_policy->result == NECP_KERNEL_POLICY_RESULT_SOCKET_FILTER ||
3107 upper_policy->result == NECP_KERNEL_POLICY_RESULT_ROUTE_RULES ||
3108 upper_policy->result == NECP_KERNEL_POLICY_RESULT_USE_NETAGENT) {
3109 // Filters and route rules never cancel out lower policies
3110 return (FALSE);
3111 } else if (necp_kernel_socket_result_is_trigger_service_type(upper_policy)) {
3112 // Trigger/Scoping policies can overlap one another, but not other results
3113 return (necp_kernel_socket_result_is_trigger_service_type(lower_policy));
3114 } else if (upper_policy->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
3115 if (upper_policy->session_order != lower_policy->session_order) {
3116 // A skip cannot override a policy of a different session
3117 return (FALSE);
3118 } else {
3119 if (upper_policy->result_parameter.skip_policy_order == 0 ||
3120 lower_policy->order >= upper_policy->result_parameter.skip_policy_order) {
3121 // This policy is beyond the skip
3122 return (FALSE);
3123 } else {
3124 // This policy is inside the skip
3125 return (TRUE);
3126 }
3127 }
3128 }
3129
3130 // A hard pass, flow divert, tunnel, or scope will currently block out lower policies
3131 return (TRUE);
3132 }
3133
3134 static bool
3135 necp_kernel_socket_policy_is_unnecessary(struct necp_kernel_socket_policy *policy, struct necp_kernel_socket_policy **policy_array, int valid_indices)
3136 {
3137 bool can_skip = FALSE;
3138 u_int32_t highest_skip_session_order = 0;
3139 u_int32_t highest_skip_order = 0;
3140 int i;
3141 for (i = 0; i < valid_indices; i++) {
3142 struct necp_kernel_socket_policy *compared_policy = policy_array[i];
3143
3144 // For policies in a skip window, we can't mark conflicting policies as unnecessary
3145 if (can_skip) {
3146 if (highest_skip_session_order != compared_policy->session_order ||
3147 (highest_skip_order != 0 && compared_policy->order >= highest_skip_order)) {
3148 // If we've moved on to the next session, or passed the skip window
3149 highest_skip_session_order = 0;
3150 highest_skip_order = 0;
3151 can_skip = FALSE;
3152 } else {
3153 // If this policy is also a skip, in can increase the skip window
3154 if (compared_policy->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
3155 if (compared_policy->result_parameter.skip_policy_order > highest_skip_order) {
3156 highest_skip_order = compared_policy->result_parameter.skip_policy_order;
3157 }
3158 }
3159 continue;
3160 }
3161 }
3162
3163 if (compared_policy->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
3164 // This policy is a skip. Set the skip window accordingly
3165 can_skip = TRUE;
3166 highest_skip_session_order = compared_policy->session_order;
3167 highest_skip_order = compared_policy->result_parameter.skip_policy_order;
3168 }
3169
3170 // The result of the compared policy must be able to block out this policy result
3171 if (!necp_kernel_socket_policy_results_overlap(compared_policy, policy)) {
3172 continue;
3173 }
3174
3175 // If new policy matches All Interfaces, compared policy must also
3176 if ((policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES) && !(compared_policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES)) {
3177 continue;
3178 }
3179
3180 // Default makes lower policies unecessary always
3181 if (compared_policy->condition_mask == 0) {
3182 return (TRUE);
3183 }
3184
3185 // Compared must be more general than policy, and include only conditions within policy
3186 if ((policy->condition_mask & compared_policy->condition_mask) != compared_policy->condition_mask) {
3187 continue;
3188 }
3189
3190 // Negative conditions must match for the overlapping conditions
3191 if ((policy->condition_negated_mask & compared_policy->condition_mask) != (compared_policy->condition_negated_mask & compared_policy->condition_mask)) {
3192 continue;
3193 }
3194
3195 if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_DOMAIN &&
3196 strcmp(compared_policy->cond_domain, policy->cond_domain) != 0) {
3197 continue;
3198 }
3199
3200 if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_ACCOUNT_ID &&
3201 compared_policy->cond_account_id != policy->cond_account_id) {
3202 continue;
3203 }
3204
3205 if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_POLICY_ID &&
3206 compared_policy->cond_policy_id != policy->cond_policy_id) {
3207 continue;
3208 }
3209
3210 if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_APP_ID &&
3211 compared_policy->cond_app_id != policy->cond_app_id) {
3212 continue;
3213 }
3214
3215 if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_REAL_APP_ID &&
3216 compared_policy->cond_real_app_id != policy->cond_real_app_id) {
3217 continue;
3218 }
3219
3220 if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_PID &&
3221 compared_policy->cond_pid != policy->cond_pid) {
3222 continue;
3223 }
3224
3225 if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_UID &&
3226 compared_policy->cond_uid != policy->cond_uid) {
3227 continue;
3228 }
3229
3230 if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE &&
3231 compared_policy->cond_bound_interface != policy->cond_bound_interface) {
3232 continue;
3233 }
3234
3235 if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_PROTOCOL &&
3236 compared_policy->cond_protocol != policy->cond_protocol) {
3237 continue;
3238 }
3239
3240 if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_TRAFFIC_CLASS &&
3241 !(compared_policy->cond_traffic_class.start_tc <= policy->cond_traffic_class.start_tc &&
3242 compared_policy->cond_traffic_class.end_tc >= policy->cond_traffic_class.end_tc)) {
3243 continue;
3244 }
3245
3246 if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_START) {
3247 if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
3248 if (!necp_is_range_in_range((struct sockaddr *)&policy->cond_local_start, (struct sockaddr *)&policy->cond_local_end, (struct sockaddr *)&compared_policy->cond_local_start, (struct sockaddr *)&compared_policy->cond_local_end)) {
3249 continue;
3250 }
3251 } else if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX) {
3252 if (compared_policy->cond_local_prefix > policy->cond_local_prefix ||
3253 !necp_is_addr_in_subnet((struct sockaddr *)&policy->cond_local_start, (struct sockaddr *)&compared_policy->cond_local_start, compared_policy->cond_local_prefix)) {
3254 continue;
3255 }
3256 }
3257 }
3258
3259 if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_START) {
3260 if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
3261 if (!necp_is_range_in_range((struct sockaddr *)&policy->cond_remote_start, (struct sockaddr *)&policy->cond_remote_end, (struct sockaddr *)&compared_policy->cond_remote_start, (struct sockaddr *)&compared_policy->cond_remote_end)) {
3262 continue;
3263 }
3264 } else if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX) {
3265 if (compared_policy->cond_remote_prefix > policy->cond_remote_prefix ||
3266 !necp_is_addr_in_subnet((struct sockaddr *)&policy->cond_remote_start, (struct sockaddr *)&compared_policy->cond_remote_start, compared_policy->cond_remote_prefix)) {
3267 continue;
3268 }
3269 }
3270 }
3271
3272 return (TRUE);
3273 }
3274
3275 return (FALSE);
3276 }
3277
3278 static bool
3279 necp_kernel_socket_policies_reprocess(void)
3280 {
3281 int app_i;
3282 int bucket_allocation_counts[NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS];
3283 int bucket_current_free_index[NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS];
3284 int app_layer_allocation_count = 0;
3285 int app_layer_current_free_index = 0;
3286 struct necp_kernel_socket_policy *kernel_policy = NULL;
3287
3288 lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);
3289
3290 // Reset mask to 0
3291 necp_kernel_application_policies_condition_mask = 0;
3292 necp_kernel_socket_policies_condition_mask = 0;
3293 necp_kernel_application_policies_count = 0;
3294 necp_kernel_socket_policies_count = 0;
3295 necp_kernel_socket_policies_non_app_count = 0;
3296
3297 // Reset all maps to NULL
3298 for (app_i = 0; app_i < NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS; app_i++) {
3299 if (necp_kernel_socket_policies_map[app_i] != NULL) {
3300 FREE(necp_kernel_socket_policies_map[app_i], M_NECP);
3301 necp_kernel_socket_policies_map[app_i] = NULL;
3302 }
3303
3304 // Init counts
3305 bucket_allocation_counts[app_i] = 0;
3306 }
3307 if (necp_kernel_socket_policies_app_layer_map != NULL) {
3308 FREE(necp_kernel_socket_policies_app_layer_map, M_NECP);
3309 necp_kernel_socket_policies_app_layer_map = NULL;
3310 }
3311
3312 // Create masks and counts
3313 LIST_FOREACH(kernel_policy, &necp_kernel_socket_policies, chain) {
3314 // App layer mask/count
3315 necp_kernel_application_policies_condition_mask |= kernel_policy->condition_mask;
3316 necp_kernel_application_policies_count++;
3317 app_layer_allocation_count++;
3318
3319 // Update socket layer bucket mask/counts
3320 necp_kernel_socket_policies_condition_mask |= kernel_policy->condition_mask;
3321 necp_kernel_socket_policies_count++;
3322
3323 if (!(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_APP_ID) ||
3324 kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_APP_ID) {
3325 necp_kernel_socket_policies_non_app_count++;
3326 for (app_i = 0; app_i < NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS; app_i++) {
3327 bucket_allocation_counts[app_i]++;
3328 }
3329 } else {
3330 bucket_allocation_counts[NECP_SOCKET_MAP_APP_ID_TO_BUCKET(kernel_policy->cond_app_id)]++;
3331 }
3332 }
3333
3334 // Allocate maps
3335 for (app_i = 0; app_i < NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS; app_i++) {
3336 if (bucket_allocation_counts[app_i] > 0) {
3337 // Allocate a NULL-terminated array of policy pointers for each bucket
3338 MALLOC(necp_kernel_socket_policies_map[app_i], struct necp_kernel_socket_policy **, sizeof(struct necp_kernel_socket_policy *) * (bucket_allocation_counts[app_i] + 1), M_NECP, M_WAITOK);
3339 if (necp_kernel_socket_policies_map[app_i] == NULL) {
3340 goto fail;
3341 }
3342
3343 // Initialize the first entry to NULL
3344 (necp_kernel_socket_policies_map[app_i])[0] = NULL;
3345 }
3346 bucket_current_free_index[app_i] = 0;
3347 }
3348 MALLOC(necp_kernel_socket_policies_app_layer_map, struct necp_kernel_socket_policy **, sizeof(struct necp_kernel_socket_policy *) * (app_layer_allocation_count + 1), M_NECP, M_WAITOK);
3349 if (necp_kernel_socket_policies_app_layer_map == NULL) {
3350 goto fail;
3351 }
3352 necp_kernel_socket_policies_app_layer_map[0] = NULL;
3353
3354 // Fill out maps
3355 LIST_FOREACH(kernel_policy, &necp_kernel_socket_policies, chain) {
3356 // Insert pointers into map
3357 if (!(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_APP_ID) ||
3358 kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_APP_ID) {
3359 for (app_i = 0; app_i < NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS; app_i++) {
3360 if (!necp_kernel_socket_policy_is_unnecessary(kernel_policy, necp_kernel_socket_policies_map[app_i], bucket_current_free_index[app_i])) {
3361 (necp_kernel_socket_policies_map[app_i])[(bucket_current_free_index[app_i])] = kernel_policy;
3362 bucket_current_free_index[app_i]++;
3363 (necp_kernel_socket_policies_map[app_i])[(bucket_current_free_index[app_i])] = NULL;
3364 }
3365 }
3366 } else {
3367 app_i = NECP_SOCKET_MAP_APP_ID_TO_BUCKET(kernel_policy->cond_app_id);
3368 if (!necp_kernel_socket_policy_is_unnecessary(kernel_policy, necp_kernel_socket_policies_map[app_i], bucket_current_free_index[app_i])) {
3369 (necp_kernel_socket_policies_map[app_i])[(bucket_current_free_index[app_i])] = kernel_policy;
3370 bucket_current_free_index[app_i]++;
3371 (necp_kernel_socket_policies_map[app_i])[(bucket_current_free_index[app_i])] = NULL;
3372 }
3373 }
3374
3375 if (!necp_kernel_socket_policy_is_unnecessary(kernel_policy, necp_kernel_socket_policies_app_layer_map, app_layer_current_free_index)) {
3376 necp_kernel_socket_policies_app_layer_map[app_layer_current_free_index] = kernel_policy;
3377 app_layer_current_free_index++;
3378 necp_kernel_socket_policies_app_layer_map[app_layer_current_free_index] = NULL;
3379 }
3380 }
3381 necp_kernel_socket_policies_dump_all();
3382 BUMP_KERNEL_SOCKET_POLICIES_GENERATION_COUNT();
3383 return (TRUE);
3384
3385 fail:
3386 // Free memory, reset masks to 0
3387 necp_kernel_application_policies_condition_mask = 0;
3388 necp_kernel_socket_policies_condition_mask = 0;
3389 necp_kernel_application_policies_count = 0;
3390 necp_kernel_socket_policies_count = 0;
3391 necp_kernel_socket_policies_non_app_count = 0;
3392 for (app_i = 0; app_i < NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS; app_i++) {
3393 if (necp_kernel_socket_policies_map[app_i] != NULL) {
3394 FREE(necp_kernel_socket_policies_map[app_i], M_NECP);
3395 necp_kernel_socket_policies_map[app_i] = NULL;
3396 }
3397 }
3398 if (necp_kernel_socket_policies_app_layer_map != NULL) {
3399 FREE(necp_kernel_socket_policies_app_layer_map, M_NECP);
3400 necp_kernel_socket_policies_app_layer_map = NULL;
3401 }
3402 return (FALSE);
3403 }
3404
3405 static u_int32_t
3406 necp_get_new_string_id(void)
3407 {
3408 u_int32_t newid = 0;
3409
3410 lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);
3411
3412 necp_last_string_id++;
3413 if (necp_last_string_id < 1) {
3414 necp_last_string_id = 1;
3415 }
3416
3417 newid = necp_last_string_id;
3418 if (newid == 0) {
3419 NECPLOG0(LOG_DEBUG, "Allocate string id failed.\n");
3420 return (0);
3421 }
3422
3423 return (newid);
3424 }
3425
3426 static struct necp_string_id_mapping *
3427 necp_lookup_string_to_id_locked(struct necp_string_id_mapping_list *list, char *string)
3428 {
3429 struct necp_string_id_mapping *searchentry = NULL;
3430 struct necp_string_id_mapping *foundentry = NULL;
3431
3432 LIST_FOREACH(searchentry, list, chain) {
3433 if (strcmp(searchentry->string, string) == 0) {
3434 foundentry = searchentry;
3435 break;
3436 }
3437 }
3438
3439 return (foundentry);
3440 }
3441
3442 static u_int32_t
3443 necp_create_string_to_id_mapping(struct necp_string_id_mapping_list *list, char *string)
3444 {
3445 u_int32_t string_id = 0;
3446 struct necp_string_id_mapping *existing_mapping = NULL;
3447
3448 lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);
3449
3450 existing_mapping = necp_lookup_string_to_id_locked(list, string);
3451 if (existing_mapping != NULL) {
3452 string_id = existing_mapping->id;
3453 existing_mapping->refcount++;
3454 } else {
3455 struct necp_string_id_mapping *new_mapping = NULL;
3456 MALLOC(new_mapping, struct necp_string_id_mapping *, sizeof(struct necp_string_id_mapping), M_NECP, M_WAITOK);
3457 if (new_mapping != NULL) {
3458 memset(new_mapping, 0, sizeof(struct necp_string_id_mapping));
3459
3460 size_t length = strlen(string) + 1;
3461 MALLOC(new_mapping->string, char *, length, M_NECP, M_WAITOK);
3462 if (new_mapping->string != NULL) {
3463 memcpy(new_mapping->string, string, length);
3464 new_mapping->id = necp_get_new_string_id();
3465 new_mapping->refcount = 1;
3466 LIST_INSERT_HEAD(list, new_mapping, chain);
3467 string_id = new_mapping->id;
3468 } else {
3469 FREE(new_mapping, M_NECP);
3470 new_mapping = NULL;
3471 }
3472 }
3473 }
3474 return (string_id);
3475 }
3476
3477 static bool
3478 necp_remove_string_to_id_mapping(struct necp_string_id_mapping_list *list, char *string)
3479 {
3480 struct necp_string_id_mapping *existing_mapping = NULL;
3481
3482 lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);
3483
3484 existing_mapping = necp_lookup_string_to_id_locked(list, string);
3485 if (existing_mapping != NULL) {
3486 if (--existing_mapping->refcount == 0) {
3487 LIST_REMOVE(existing_mapping, chain);
3488 FREE(existing_mapping->string, M_NECP);
3489 FREE(existing_mapping, M_NECP);
3490 }
3491 return (TRUE);
3492 }
3493
3494 return (FALSE);
3495 }
3496
3497 static u_int32_t
3498 necp_get_new_route_rule_id(void)
3499 {
3500 u_int32_t newid = 0;
3501
3502 lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);
3503
3504 necp_last_route_rule_id++;
3505 if (necp_last_route_rule_id < 1 || necp_last_route_rule_id > UINT16_MAX) {
3506 necp_last_route_rule_id = 1;
3507 }
3508
3509 newid = necp_last_route_rule_id;
3510 if (newid == 0) {
3511 NECPLOG0(LOG_DEBUG, "Allocate route rule id failed.\n");
3512 return (0);
3513 }
3514
3515 return (newid);
3516 }
3517
3518 static u_int32_t
3519 necp_get_new_aggregate_route_rule_id(void)
3520 {
3521 u_int32_t newid = 0;
3522
3523 lck_rw_assert(&necp_route_rule_lock, LCK_RW_ASSERT_EXCLUSIVE);
3524
3525 necp_last_aggregate_route_rule_id++;
3526 if (necp_last_aggregate_route_rule_id <= UINT16_MAX) {
3527 necp_last_aggregate_route_rule_id = UINT16_MAX + 1;
3528 }
3529
3530 newid = necp_last_aggregate_route_rule_id;
3531 if (newid == 0) {
3532 NECPLOG0(LOG_DEBUG, "Allocate aggregate route rule id failed.\n");
3533 return (0);
3534 }
3535
3536 return (newid);
3537 }
3538
3539 static struct necp_route_rule *
3540 necp_lookup_route_rule_locked(struct necp_route_rule_list *list, u_int32_t route_rule_id)
3541 {
3542 struct necp_route_rule *searchentry = NULL;
3543 struct necp_route_rule *foundentry = NULL;
3544
3545 LIST_FOREACH(searchentry, list, chain) {
3546 if (searchentry->id == route_rule_id) {
3547 foundentry = searchentry;
3548 break;
3549 }
3550 }
3551
3552 return (foundentry);
3553 }
3554
3555 static struct necp_route_rule *
3556 necp_lookup_route_rule_by_contents_locked(struct necp_route_rule_list *list, u_int32_t default_action, u_int8_t cellular_action, u_int8_t wifi_action, u_int8_t wired_action, u_int8_t expensive_action, u_int32_t *if_indices, u_int8_t *if_actions)
3557 {
3558 struct necp_route_rule *searchentry = NULL;
3559 struct necp_route_rule *foundentry = NULL;
3560
3561 LIST_FOREACH(searchentry, list, chain) {
3562 if (searchentry->default_action == default_action &&
3563 searchentry->cellular_action == cellular_action &&
3564 searchentry->wifi_action == wifi_action &&
3565 searchentry->wired_action == wired_action &&
3566 searchentry->expensive_action == expensive_action) {
3567 bool match_failed = FALSE;
3568 size_t index_a = 0;
3569 size_t index_b = 0;
3570 size_t count_a = 0;
3571 size_t count_b = 0;
3572 for (index_a = 0; index_a < MAX_ROUTE_RULE_INTERFACES; index_a++) {
3573 bool found_index = FALSE;
3574 if (searchentry->exception_if_indices[index_a] == 0) {
3575 break;
3576 }
3577 count_a++;
3578 for (index_b = 0; index_b < MAX_ROUTE_RULE_INTERFACES; index_b++) {
3579 if (if_indices[index_b] == 0) {
3580 break;
3581 }
3582 if (index_b >= count_b) {
3583 count_b = index_b + 1;
3584 }
3585 if (searchentry->exception_if_indices[index_a] == if_indices[index_b] &&
3586 searchentry->exception_if_actions[index_a] == if_actions[index_b]) {
3587 found_index = TRUE;
3588 break;
3589 }
3590 }
3591 if (!found_index) {
3592 match_failed = TRUE;
3593 break;
3594 }
3595 }
3596 if (!match_failed && count_a == count_b) {
3597 foundentry = searchentry;
3598 break;
3599 }
3600 }
3601 }
3602
3603 return (foundentry);
3604 }
3605
3606 static u_int32_t
3607 necp_create_route_rule(struct necp_route_rule_list *list, u_int8_t *route_rules_array, u_int32_t route_rules_array_size)
3608 {
3609 size_t offset = 0;
3610 u_int32_t route_rule_id = 0;
3611 struct necp_route_rule *existing_rule = NULL;
3612 u_int32_t default_action = NECP_ROUTE_RULE_ALLOW_INTERFACE;
3613 u_int8_t cellular_action = NECP_ROUTE_RULE_NONE;
3614 u_int8_t wifi_action = NECP_ROUTE_RULE_NONE;
3615 u_int8_t wired_action = NECP_ROUTE_RULE_NONE;
3616 u_int8_t expensive_action = NECP_ROUTE_RULE_NONE;
3617 u_int32_t if_indices[MAX_ROUTE_RULE_INTERFACES];
3618 size_t num_valid_indices = 0;
3619 memset(&if_indices, 0, sizeof(if_indices));
3620 u_int8_t if_actions[MAX_ROUTE_RULE_INTERFACES];
3621 memset(&if_actions, 0, sizeof(if_actions));
3622
3623 lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);
3624
3625 if (route_rules_array == NULL || route_rules_array_size == 0) {
3626 return (0);
3627 }
3628
3629 // Process rules
3630 while (offset < route_rules_array_size) {
3631 ifnet_t rule_interface = NULL;
3632 char interface_name[IFXNAMSIZ];
3633 u_int32_t length = 0;
3634 u_int8_t *value = necp_buffer_get_tlv_value(route_rules_array, offset, &length);
3635
3636 u_int8_t rule_type = necp_policy_condition_get_type_from_buffer(value, length);
3637 u_int8_t rule_flags = necp_policy_condition_get_flags_from_buffer(value, length);
3638 u_int32_t rule_length = necp_policy_condition_get_value_length_from_buffer(value, length);
3639 u_int8_t *rule_value = necp_policy_condition_get_value_pointer_from_buffer(value, length);
3640
3641 if (rule_type == NECP_ROUTE_RULE_NONE) {
3642 // Don't allow an explicit rule to be None action
3643 continue;
3644 }
3645
3646 if (rule_length == 0) {
3647 if (rule_flags & NECP_ROUTE_RULE_FLAG_CELLULAR) {
3648 cellular_action = rule_type;
3649 }
3650 if (rule_flags & NECP_ROUTE_RULE_FLAG_WIFI) {
3651 wifi_action = rule_type;
3652 }
3653 if (rule_flags & NECP_ROUTE_RULE_FLAG_WIRED) {
3654 wired_action = rule_type;
3655 }
3656 if (rule_flags & NECP_ROUTE_RULE_FLAG_EXPENSIVE) {
3657 expensive_action = rule_type;
3658 }
3659 if (rule_flags == 0) {
3660 default_action = rule_type;
3661 }
3662 offset += sizeof(u_int8_t) + sizeof(u_int32_t) + length;
3663 continue;
3664 }
3665
3666 if (num_valid_indices >= MAX_ROUTE_RULE_INTERFACES) {
3667 offset += sizeof(u_int8_t) + sizeof(u_int32_t) + length;
3668 continue;
3669 }
3670
3671 memcpy(interface_name, rule_value, rule_length);
3672 interface_name[length - 1] = 0; // Make sure the string is NULL terminated
3673 if (ifnet_find_by_name(interface_name, &rule_interface) == 0) {
3674 if_actions[num_valid_indices] = rule_type;
3675 if_indices[num_valid_indices++] = rule_interface->if_index;
3676 }
3677
3678 offset += sizeof(u_int8_t) + sizeof(u_int32_t) + length;
3679 }
3680
3681 existing_rule = necp_lookup_route_rule_by_contents_locked(list, default_action, cellular_action, wifi_action, wired_action, expensive_action, if_indices, if_actions);
3682 if (existing_rule != NULL) {
3683 route_rule_id = existing_rule->id;
3684 existing_rule->refcount++;
3685 } else {
3686 struct necp_route_rule *new_rule = NULL;
3687 MALLOC(new_rule, struct necp_route_rule *, sizeof(struct necp_route_rule), M_NECP, M_WAITOK);
3688 if (new_rule != NULL) {
3689 memset(new_rule, 0, sizeof(struct necp_route_rule));
3690 route_rule_id = new_rule->id = necp_get_new_route_rule_id();
3691 new_rule->default_action = default_action;
3692 new_rule->cellular_action = cellular_action;
3693 new_rule->wifi_action = wifi_action;
3694 new_rule->wired_action = wired_action;
3695 new_rule->expensive_action = expensive_action;
3696 memcpy(&new_rule->exception_if_indices, &if_indices, sizeof(if_indices));
3697 memcpy(&new_rule->exception_if_actions, &if_actions, sizeof(if_actions));
3698 new_rule->refcount = 1;
3699 LIST_INSERT_HEAD(list, new_rule, chain);
3700 }
3701 }
3702 return (route_rule_id);
3703 }
3704
3705 static void
3706 necp_remove_aggregate_route_rule_for_id(u_int32_t rule_id)
3707 {
3708 if (rule_id) {
3709 lck_rw_lock_exclusive(&necp_route_rule_lock);
3710
3711 struct necp_aggregate_route_rule *existing_rule = NULL;
3712 struct necp_aggregate_route_rule *tmp_rule = NULL;
3713
3714 LIST_FOREACH_SAFE(existing_rule, &necp_aggregate_route_rules, chain, tmp_rule) {
3715 int index = 0;
3716 for (index = 0; index < MAX_AGGREGATE_ROUTE_RULES; index++) {
3717 u_int32_t route_rule_id = existing_rule->rule_ids[index];
3718 if (route_rule_id == rule_id) {
3719 LIST_REMOVE(existing_rule, chain);
3720 FREE(existing_rule, M_NECP);
3721 break;
3722 }
3723 }
3724 }
3725
3726 lck_rw_done(&necp_route_rule_lock);
3727 }
3728 }
3729
3730 static bool
3731 necp_remove_route_rule(struct necp_route_rule_list *list, u_int32_t route_rule_id)
3732 {
3733 struct necp_route_rule *existing_rule = NULL;
3734
3735 lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);
3736
3737 existing_rule = necp_lookup_route_rule_locked(list, route_rule_id);
3738 if (existing_rule != NULL) {
3739 if (--existing_rule->refcount == 0) {
3740 necp_remove_aggregate_route_rule_for_id(existing_rule->id);
3741 LIST_REMOVE(existing_rule, chain);
3742 FREE(existing_rule, M_NECP);
3743 }
3744 return (TRUE);
3745 }
3746
3747 return (FALSE);
3748 }
3749
3750 static struct necp_aggregate_route_rule *
3751 necp_lookup_aggregate_route_rule_locked(u_int32_t route_rule_id)
3752 {
3753 struct necp_aggregate_route_rule *searchentry = NULL;
3754 struct necp_aggregate_route_rule *foundentry = NULL;
3755
3756 lck_rw_lock_shared(&necp_route_rule_lock);
3757
3758 LIST_FOREACH(searchentry, &necp_aggregate_route_rules, chain) {
3759 if (searchentry->id == route_rule_id) {
3760 foundentry = searchentry;
3761 break;
3762 }
3763 }
3764
3765 lck_rw_done(&necp_route_rule_lock);
3766
3767 return (foundentry);
3768 }
3769
3770 static u_int32_t
3771 necp_create_aggregate_route_rule(u_int32_t *rule_ids)
3772 {
3773 u_int32_t aggregate_route_rule_id = 0;
3774 struct necp_aggregate_route_rule *new_rule = NULL;
3775 struct necp_aggregate_route_rule *existing_rule = NULL;
3776
3777 LIST_FOREACH(existing_rule, &necp_aggregate_route_rules, chain) {
3778 if (memcmp(existing_rule->rule_ids, rule_ids, (sizeof(u_int32_t) * MAX_AGGREGATE_ROUTE_RULES)) == 0) {
3779 return (existing_rule->id);
3780 }
3781 }
3782
3783 lck_rw_lock_exclusive(&necp_route_rule_lock);
3784
3785 LIST_FOREACH(existing_rule, &necp_aggregate_route_rules, chain) {
3786 // Re-check, in case something else created the rule while we are waiting to lock
3787 if (memcmp(existing_rule->rule_ids, rule_ids, (sizeof(u_int32_t) * MAX_AGGREGATE_ROUTE_RULES)) == 0) {
3788 lck_rw_done(&necp_route_rule_lock);
3789 return (existing_rule->id);
3790 }
3791 }
3792
3793 MALLOC(new_rule, struct necp_aggregate_route_rule *, sizeof(struct necp_aggregate_route_rule), M_NECP, M_WAITOK);
3794 if (new_rule != NULL) {
3795 memset(new_rule, 0, sizeof(struct necp_aggregate_route_rule));
3796 aggregate_route_rule_id = new_rule->id = necp_get_new_aggregate_route_rule_id();
3797 new_rule->id = aggregate_route_rule_id;
3798 memcpy(new_rule->rule_ids, rule_ids, (sizeof(u_int32_t) * MAX_AGGREGATE_ROUTE_RULES));
3799 LIST_INSERT_HEAD(&necp_aggregate_route_rules, new_rule, chain);
3800 }
3801 lck_rw_done(&necp_route_rule_lock);
3802
3803 return (aggregate_route_rule_id);
3804 }
3805
3806 #define NECP_NULL_SERVICE_ID 1
3807 static u_int32_t
3808 necp_get_new_uuid_id(void)
3809 {
3810 u_int32_t newid = 0;
3811
3812 lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);
3813
3814 necp_last_uuid_id++;
3815 if (necp_last_uuid_id < (NECP_NULL_SERVICE_ID + 1)) {
3816 necp_last_uuid_id = (NECP_NULL_SERVICE_ID + 1);
3817 }
3818
3819 newid = necp_last_uuid_id;
3820 if (newid == 0) {
3821 NECPLOG0(LOG_DEBUG, "Allocate uuid id failed.\n");
3822 return (0);
3823 }
3824
3825 return (newid);
3826 }
3827
3828 static struct necp_uuid_id_mapping *
3829 necp_uuid_lookup_app_id_locked(uuid_t uuid)
3830 {
3831 struct necp_uuid_id_mapping *searchentry = NULL;
3832 struct necp_uuid_id_mapping *foundentry = NULL;
3833
3834 LIST_FOREACH(searchentry, APPUUIDHASH(uuid), chain) {
3835 if (uuid_compare(searchentry->uuid, uuid) == 0) {
3836 foundentry = searchentry;
3837 break;
3838 }
3839 }
3840
3841 return (foundentry);
3842 }
3843
3844 static u_int32_t
3845 necp_create_uuid_app_id_mapping(uuid_t uuid, bool *allocated_mapping, bool uuid_policy_table)
3846 {
3847 u_int32_t local_id = 0;
3848 struct necp_uuid_id_mapping *existing_mapping = NULL;
3849
3850 lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);
3851
3852 if (allocated_mapping) {
3853 *allocated_mapping = FALSE;
3854 }
3855
3856 existing_mapping = necp_uuid_lookup_app_id_locked(uuid);
3857 if (existing_mapping != NULL) {
3858 local_id = existing_mapping->id;
3859 existing_mapping->refcount++;
3860 if (uuid_policy_table) {
3861 existing_mapping->table_refcount++;
3862 }
3863 } else {
3864 struct necp_uuid_id_mapping *new_mapping = NULL;
3865 MALLOC(new_mapping, struct necp_uuid_id_mapping *, sizeof(*new_mapping), M_NECP, M_WAITOK);
3866 if (new_mapping != NULL) {
3867 uuid_copy(new_mapping->uuid, uuid);
3868 new_mapping->id = necp_get_new_uuid_id();
3869 new_mapping->refcount = 1;
3870 if (uuid_policy_table) {
3871 new_mapping->table_refcount = 1;
3872 } else {
3873 new_mapping->table_refcount = 0;
3874 }
3875
3876 LIST_INSERT_HEAD(APPUUIDHASH(uuid), new_mapping, chain);
3877
3878 if (allocated_mapping) {
3879 *allocated_mapping = TRUE;
3880 }
3881
3882 local_id = new_mapping->id;
3883 }
3884 }
3885
3886 return (local_id);
3887 }
3888
3889 static bool
3890 necp_remove_uuid_app_id_mapping(uuid_t uuid, bool *removed_mapping, bool uuid_policy_table)
3891 {
3892 struct necp_uuid_id_mapping *existing_mapping = NULL;
3893
3894 lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);
3895
3896 if (removed_mapping) {
3897 *removed_mapping = FALSE;
3898 }
3899
3900 existing_mapping = necp_uuid_lookup_app_id_locked(uuid);
3901 if (existing_mapping != NULL) {
3902 if (uuid_policy_table) {
3903 existing_mapping->table_refcount--;
3904 }
3905 if (--existing_mapping->refcount == 0) {
3906 LIST_REMOVE(existing_mapping, chain);
3907 FREE(existing_mapping, M_NECP);
3908 if (removed_mapping) {
3909 *removed_mapping = TRUE;
3910 }
3911 }
3912 return (TRUE);
3913 }
3914
3915 return (FALSE);
3916 }
3917
3918 static struct necp_uuid_id_mapping *
3919 necp_uuid_get_null_service_id_mapping(void)
3920 {
3921 static struct necp_uuid_id_mapping null_mapping;
3922 uuid_clear(null_mapping.uuid);
3923 null_mapping.id = NECP_NULL_SERVICE_ID;
3924
3925 return (&null_mapping);
3926 }
3927
3928 static struct necp_uuid_id_mapping *
3929 necp_uuid_lookup_service_id_locked(uuid_t uuid)
3930 {
3931 struct necp_uuid_id_mapping *searchentry = NULL;
3932 struct necp_uuid_id_mapping *foundentry = NULL;
3933
3934 if (uuid_is_null(uuid)) {
3935 return necp_uuid_get_null_service_id_mapping();
3936 }
3937
3938 LIST_FOREACH(searchentry, &necp_uuid_service_id_list, chain) {
3939 if (uuid_compare(searchentry->uuid, uuid) == 0) {
3940 foundentry = searchentry;
3941 break;
3942 }
3943 }
3944
3945 return (foundentry);
3946 }
3947
3948 static struct necp_uuid_id_mapping *
3949 necp_uuid_lookup_uuid_with_service_id_locked(u_int32_t local_id)
3950 {
3951 struct necp_uuid_id_mapping *searchentry = NULL;
3952 struct necp_uuid_id_mapping *foundentry = NULL;
3953
3954 if (local_id == NECP_NULL_SERVICE_ID) {
3955 return necp_uuid_get_null_service_id_mapping();
3956 }
3957
3958 LIST_FOREACH(searchentry, &necp_uuid_service_id_list, chain) {
3959 if (searchentry->id == local_id) {
3960 foundentry = searchentry;
3961 break;
3962 }
3963 }
3964
3965 return (foundentry);
3966 }
3967
3968 static u_int32_t
3969 necp_create_uuid_service_id_mapping(uuid_t uuid)
3970 {
3971 u_int32_t local_id = 0;
3972 struct necp_uuid_id_mapping *existing_mapping = NULL;
3973
3974 if (uuid_is_null(uuid)) {
3975 return (NECP_NULL_SERVICE_ID);
3976 }
3977
3978 lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);
3979
3980 existing_mapping = necp_uuid_lookup_service_id_locked(uuid);
3981 if (existing_mapping != NULL) {
3982 local_id = existing_mapping->id;
3983 existing_mapping->refcount++;
3984 } else {
3985 struct necp_uuid_id_mapping *new_mapping = NULL;
3986 MALLOC(new_mapping, struct necp_uuid_id_mapping *, sizeof(*new_mapping), M_NECP, M_WAITOK);
3987 if (new_mapping != NULL) {
3988 uuid_copy(new_mapping->uuid, uuid);
3989 new_mapping->id = necp_get_new_uuid_id();
3990 new_mapping->refcount = 1;
3991
3992 LIST_INSERT_HEAD(&necp_uuid_service_id_list, new_mapping, chain);
3993
3994 local_id = new_mapping->id;
3995 }
3996 }
3997
3998 return (local_id);
3999 }
4000
4001 static bool
4002 necp_remove_uuid_service_id_mapping(uuid_t uuid)
4003 {
4004 struct necp_uuid_id_mapping *existing_mapping = NULL;
4005
4006 if (uuid_is_null(uuid)) {
4007 return (TRUE);
4008 }
4009
4010 lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);
4011
4012 existing_mapping = necp_uuid_lookup_app_id_locked(uuid);
4013 if (existing_mapping != NULL) {
4014 if (--existing_mapping->refcount == 0) {
4015 LIST_REMOVE(existing_mapping, chain);
4016 FREE(existing_mapping, M_NECP);
4017 }
4018 return (TRUE);
4019 }
4020
4021 return (FALSE);
4022 }
4023
4024
4025 static bool
4026 necp_kernel_socket_policies_update_uuid_table(void)
4027 {
4028 lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);
4029
4030 if (necp_uuid_app_id_mappings_dirty) {
4031 if (proc_uuid_policy_kernel(PROC_UUID_POLICY_OPERATION_CLEAR, NULL, PROC_UUID_NECP_APP_POLICY) < 0) {
4032 NECPLOG0(LOG_DEBUG, "Error clearing uuids from policy table\n");
4033 return (FALSE);
4034 }
4035
4036 if (necp_num_uuid_app_id_mappings > 0) {
4037 struct necp_uuid_id_mapping_head *uuid_list_head = NULL;
4038 for (uuid_list_head = &necp_uuid_app_id_hashtbl[necp_uuid_app_id_hash_num_buckets - 1]; uuid_list_head >= necp_uuid_app_id_hashtbl; uuid_list_head--) {
4039 struct necp_uuid_id_mapping *mapping = NULL;
4040 LIST_FOREACH(mapping, uuid_list_head, chain) {
4041 if (mapping->table_refcount > 0 &&
4042 proc_uuid_policy_kernel(PROC_UUID_POLICY_OPERATION_ADD, mapping->uuid, PROC_UUID_NECP_APP_POLICY) < 0) {
4043 NECPLOG0(LOG_DEBUG, "Error adding uuid to policy table\n");
4044 }
4045 }
4046 }
4047 }
4048
4049 necp_uuid_app_id_mappings_dirty = FALSE;
4050 }
4051
4052 return (TRUE);
4053 }
4054
4055 #define NECP_KERNEL_VALID_IP_OUTPUT_CONDITIONS (NECP_KERNEL_CONDITION_ALL_INTERFACES | NECP_KERNEL_CONDITION_BOUND_INTERFACE | NECP_KERNEL_CONDITION_PROTOCOL | NECP_KERNEL_CONDITION_LOCAL_START | NECP_KERNEL_CONDITION_LOCAL_END | NECP_KERNEL_CONDITION_LOCAL_PREFIX | NECP_KERNEL_CONDITION_REMOTE_START | NECP_KERNEL_CONDITION_REMOTE_END | NECP_KERNEL_CONDITION_REMOTE_PREFIX | NECP_KERNEL_CONDITION_POLICY_ID | NECP_KERNEL_CONDITION_LAST_INTERFACE)
4056 static necp_kernel_policy_id
4057 necp_kernel_ip_output_policy_add(necp_policy_id parent_policy_id, necp_policy_order order, necp_policy_order suborder, u_int32_t session_order, int session_pid, u_int32_t condition_mask, u_int32_t condition_negated_mask, necp_kernel_policy_id cond_policy_id, ifnet_t cond_bound_interface, u_int32_t cond_last_interface_index, u_int16_t cond_protocol, union necp_sockaddr_union *cond_local_start, union necp_sockaddr_union *cond_local_end, u_int8_t cond_local_prefix, union necp_sockaddr_union *cond_remote_start, union necp_sockaddr_union *cond_remote_end, u_int8_t cond_remote_prefix, necp_kernel_policy_result result, necp_kernel_policy_result_parameter result_parameter)
4058 {
4059 struct necp_kernel_ip_output_policy *new_kernel_policy = NULL;
4060 struct necp_kernel_ip_output_policy *tmp_kernel_policy = NULL;
4061
4062 MALLOC_ZONE(new_kernel_policy, struct necp_kernel_ip_output_policy *, sizeof(*new_kernel_policy), M_NECP_IP_POLICY, M_WAITOK);
4063 if (new_kernel_policy == NULL) {
4064 goto done;
4065 }
4066
4067 memset(new_kernel_policy, 0, sizeof(*new_kernel_policy));
4068 new_kernel_policy->parent_policy_id = parent_policy_id;
4069 new_kernel_policy->id = necp_kernel_policy_get_new_id();
4070 new_kernel_policy->suborder = suborder;
4071 new_kernel_policy->order = order;
4072 new_kernel_policy->session_order = session_order;
4073 new_kernel_policy->session_pid = session_pid;
4074
4075 // Sanitize condition mask
4076 new_kernel_policy->condition_mask = (condition_mask & NECP_KERNEL_VALID_IP_OUTPUT_CONDITIONS);
4077 if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES) && (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE)) {
4078 new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_BOUND_INTERFACE;
4079 }
4080 if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) && (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX)) {
4081 new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_LOCAL_PREFIX;
4082 }
4083 if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) && (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX)) {
4084 new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_REMOTE_PREFIX;
4085 }
4086 new_kernel_policy->condition_negated_mask = condition_negated_mask & new_kernel_policy->condition_mask;
4087
4088 // Set condition values
4089 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_POLICY_ID) {
4090 new_kernel_policy->cond_policy_id = cond_policy_id;
4091 }
4092 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE) {
4093 if (cond_bound_interface) {
4094 ifnet_reference(cond_bound_interface);
4095 }
4096 new_kernel_policy->cond_bound_interface = cond_bound_interface;
4097 }
4098 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LAST_INTERFACE) {
4099 new_kernel_policy->cond_last_interface_index = cond_last_interface_index;
4100 }
4101 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_PROTOCOL) {
4102 new_kernel_policy->cond_protocol = cond_protocol;
4103 }
4104 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_START) {
4105 memcpy(&new_kernel_policy->cond_local_start, cond_local_start, cond_local_start->sa.sa_len);
4106 }
4107 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
4108 memcpy(&new_kernel_policy->cond_local_end, cond_local_end, cond_local_end->sa.sa_len);
4109 }
4110 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX) {
4111 new_kernel_policy->cond_local_prefix = cond_local_prefix;
4112 }
4113 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_START) {
4114 memcpy(&new_kernel_policy->cond_remote_start, cond_remote_start, cond_remote_start->sa.sa_len);
4115 }
4116 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
4117 memcpy(&new_kernel_policy->cond_remote_end, cond_remote_end, cond_remote_end->sa.sa_len);
4118 }
4119 if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX) {
4120 new_kernel_policy->cond_remote_prefix = cond_remote_prefix;
4121 }
4122
4123 new_kernel_policy->result = result;
4124 memcpy(&new_kernel_policy->result_parameter, &result_parameter, sizeof(result_parameter));
4125
4126 if (necp_debug) {
4127 NECPLOG(LOG_DEBUG, "Added kernel policy: ip output, id=%d, mask=%x\n", new_kernel_policy->id, new_kernel_policy->condition_mask);
4128 }
4129 LIST_INSERT_SORTED_THRICE_ASCENDING(&necp_kernel_ip_output_policies, new_kernel_policy, chain, session_order, order, suborder, tmp_kernel_policy);
4130 done:
4131 return (new_kernel_policy ? new_kernel_policy->id : 0);
4132 }
4133
4134 static struct necp_kernel_ip_output_policy *
4135 necp_kernel_ip_output_policy_find(necp_kernel_policy_id policy_id)
4136 {
4137 struct necp_kernel_ip_output_policy *kernel_policy = NULL;
4138 struct necp_kernel_ip_output_policy *tmp_kernel_policy = NULL;
4139
4140 if (policy_id == 0) {
4141 return (NULL);
4142 }
4143
4144 LIST_FOREACH_SAFE(kernel_policy, &necp_kernel_ip_output_policies, chain, tmp_kernel_policy) {
4145 if (kernel_policy->id == policy_id) {
4146 return (kernel_policy);
4147 }
4148 }
4149
4150 return (NULL);
4151 }
4152
4153 static bool
4154 necp_kernel_ip_output_policy_delete(necp_kernel_policy_id policy_id)
4155 {
4156 struct necp_kernel_ip_output_policy *policy = NULL;
4157
4158 lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);
4159
4160 policy = necp_kernel_ip_output_policy_find(policy_id);
4161 if (policy) {
4162 LIST_REMOVE(policy, chain);
4163
4164 if (policy->cond_bound_interface) {
4165 ifnet_release(policy->cond_bound_interface);
4166 policy->cond_bound_interface = NULL;
4167 }
4168
4169 FREE_ZONE(policy, sizeof(*policy), M_NECP_IP_POLICY);
4170 return (TRUE);
4171 }
4172
4173 return (FALSE);
4174 }
4175
4176 static void
4177 necp_kernel_ip_output_policies_dump_all(void)
4178 {
4179 if (necp_debug) {
4180 struct necp_kernel_ip_output_policy *policy = NULL;
4181 int policy_i;
4182 int id_i;
4183 char result_string[MAX_RESULT_STRING_LEN];
4184 char proc_name_string[MAXCOMLEN + 1];
4185 memset(result_string, 0, MAX_RESULT_STRING_LEN);
4186 memset(proc_name_string, 0, MAXCOMLEN + 1);
4187
4188 NECPLOG0(LOG_DEBUG, "NECP IP Output Policies:\n");
4189 NECPLOG0(LOG_DEBUG, "-----------\n");
4190 for (id_i = 0; id_i < NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS; id_i++) {
4191 NECPLOG(LOG_DEBUG, " ID Bucket: %d\n", id_i);
4192 for (policy_i = 0; necp_kernel_ip_output_policies_map[id_i] != NULL && (necp_kernel_ip_output_policies_map[id_i])[policy_i] != NULL; policy_i++) {
4193 policy = (necp_kernel_ip_output_policies_map[id_i])[policy_i];
4194 proc_name(policy->session_pid, proc_name_string, MAXCOMLEN);
4195 NECPLOG(LOG_DEBUG, "\t%3d. Policy ID: %5d\tProcess: %10.10s\tOrder: %04d.%04d.%d\tMask: %5x\tResult: %s\n", policy_i, policy->id, proc_name_string, policy->session_order, policy->order, policy->suborder, policy->condition_mask, necp_get_result_description(result_string, policy->result, policy->result_parameter));
4196 }
4197 NECPLOG0(LOG_DEBUG, "-----------\n");
4198 }
4199 }
4200 }
4201
4202 static inline bool
4203 necp_kernel_ip_output_policy_results_overlap(struct necp_kernel_ip_output_policy *upper_policy, struct necp_kernel_ip_output_policy *lower_policy)
4204 {
4205 if (upper_policy->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
4206 if (upper_policy->session_order != lower_policy->session_order) {
4207 // A skip cannot override a policy of a different session
4208 return (FALSE);
4209 } else {
4210 if (upper_policy->result_parameter.skip_policy_order == 0 ||
4211 lower_policy->order >= upper_policy->result_parameter.skip_policy_order) {
4212 // This policy is beyond the skip
4213 return (FALSE);
4214 } else {
4215 // This policy is inside the skip
4216 return (TRUE);
4217 }
4218 }
4219 }
4220
4221 // All other IP Output policy results (drop, tunnel, hard pass) currently overlap
4222 return (TRUE);
4223 }
4224
4225 static bool
4226 necp_kernel_ip_output_policy_is_unnecessary(struct necp_kernel_ip_output_policy *policy, struct necp_kernel_ip_output_policy **policy_array, int valid_indices)
4227 {
4228 bool can_skip = FALSE;
4229 u_int32_t highest_skip_session_order = 0;
4230 u_int32_t highest_skip_order = 0;
4231 int i;
4232 for (i = 0; i < valid_indices; i++) {
4233 struct necp_kernel_ip_output_policy *compared_policy = policy_array[i];
4234
4235 // For policies in a skip window, we can't mark conflicting policies as unnecessary
4236 if (can_skip) {
4237 if (highest_skip_session_order != compared_policy->session_order ||
4238 (highest_skip_order != 0 && compared_policy->order >= highest_skip_order)) {
4239 // If we've moved on to the next session, or passed the skip window
4240 highest_skip_session_order = 0;
4241 highest_skip_order = 0;
4242 can_skip = FALSE;
4243 } else {
4244 // If this policy is also a skip, in can increase the skip window
4245 if (compared_policy->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
4246 if (compared_policy->result_parameter.skip_policy_order > highest_skip_order) {
4247 highest_skip_order = compared_policy->result_parameter.skip_policy_order;
4248 }
4249 }
4250 continue;
4251 }
4252 }
4253
4254 if (compared_policy->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
4255 // This policy is a skip. Set the skip window accordingly
4256 can_skip = TRUE;
4257 highest_skip_session_order = compared_policy->session_order;
4258 highest_skip_order = compared_policy->result_parameter.skip_policy_order;
4259 }
4260
4261 // The result of the compared policy must be able to block out this policy result
4262 if (!necp_kernel_ip_output_policy_results_overlap(compared_policy, policy)) {
4263 continue;
4264 }
4265
4266 // If new policy matches All Interfaces, compared policy must also
4267 if ((policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES) && !(compared_policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES)) {
4268 continue;
4269 }
4270
4271 // Default makes lower policies unecessary always
4272 if (compared_policy->condition_mask == 0) {
4273 return (TRUE);
4274 }
4275
4276 // Compared must be more general than policy, and include only conditions within policy
4277 if ((policy->condition_mask & compared_policy->condition_mask) != compared_policy->condition_mask) {
4278 continue;
4279 }
4280
4281 // Negative conditions must match for the overlapping conditions
4282 if ((policy->condition_negated_mask & compared_policy->condition_mask) != (compared_policy->condition_negated_mask & compared_policy->condition_mask)) {
4283 continue;
4284 }
4285
4286 if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_POLICY_ID &&
4287 compared_policy->cond_policy_id != policy->cond_policy_id) {
4288 continue;
4289 }
4290
4291 if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE &&
4292 compared_policy->cond_bound_interface != policy->cond_bound_interface) {
4293 continue;
4294 }
4295
4296 if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_PROTOCOL &&
4297 compared_policy->cond_protocol != policy->cond_protocol) {
4298 continue;
4299 }
4300
4301 if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_START) {
4302 if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
4303 if (!necp_is_range_in_range((struct sockaddr *)&policy->cond_local_start, (struct sockaddr *)&policy->cond_local_end, (struct sockaddr *)&compared_policy->cond_local_start, (struct sockaddr *)&compared_policy->cond_local_end)) {
4304 continue;
4305 }
4306 } else if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX) {
4307 if (compared_policy->cond_local_prefix > policy->cond_local_prefix ||
4308 !necp_is_addr_in_subnet((struct sockaddr *)&policy->cond_local_start, (struct sockaddr *)&compared_policy->cond_local_start, compared_policy->cond_local_prefix)) {
4309 continue;
4310 }
4311 }
4312 }
4313
4314 if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_START) {
4315 if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
4316 if (!necp_is_range_in_range((struct sockaddr *)&policy->cond_remote_start, (struct sockaddr *)&policy->cond_remote_end, (struct sockaddr *)&compared_policy->cond_remote_start, (struct sockaddr *)&compared_policy->cond_remote_end)) {
4317 continue;
4318 }
4319 } else if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX) {
4320 if (compared_policy->cond_remote_prefix > policy->cond_remote_prefix ||
4321 !necp_is_addr_in_subnet((struct sockaddr *)&policy->cond_remote_start, (struct sockaddr *)&compared_policy->cond_remote_start, compared_policy->cond_remote_prefix)) {
4322 continue;
4323 }
4324 }
4325 }
4326
4327 return (TRUE);
4328 }
4329
4330 return (FALSE);
4331 }
4332
4333 static bool
4334 necp_kernel_ip_output_policies_reprocess(void)
4335 {
4336 int i;
4337 int bucket_allocation_counts[NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS];
4338 int bucket_current_free_index[NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS];
4339 struct necp_kernel_ip_output_policy *kernel_policy = NULL;
4340
4341 lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);
4342
4343 // Reset mask to 0
4344 necp_kernel_ip_output_policies_condition_mask = 0;
4345 necp_kernel_ip_output_policies_count = 0;
4346 necp_kernel_ip_output_policies_non_id_count = 0;
4347
4348 for (i = 0; i < NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS; i++) {
4349 if (necp_kernel_ip_output_policies_map[i] != NULL) {
4350 FREE(necp_kernel_ip_output_policies_map[i], M_NECP);
4351 necp_kernel_ip_output_policies_map[i] = NULL;
4352 }
4353
4354 // Init counts
4355 bucket_allocation_counts[i] = 0;
4356 }
4357
4358 LIST_FOREACH(kernel_policy, &necp_kernel_ip_output_policies, chain) {
4359 // Update mask
4360 necp_kernel_ip_output_policies_condition_mask |= kernel_policy->condition_mask;
4361 necp_kernel_ip_output_policies_count++;
4362
4363 // Update bucket counts
4364 if (!(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_POLICY_ID)) {
4365 necp_kernel_ip_output_policies_non_id_count++;
4366 for (i = 0; i < NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS; i++) {
4367 bucket_allocation_counts[i]++;
4368 }
4369 } else {
4370 bucket_allocation_counts[NECP_IP_OUTPUT_MAP_ID_TO_BUCKET(kernel_policy->cond_policy_id)]++;
4371 }
4372 }
4373
4374 for (i = 0; i < NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS; i++) {
4375 if (bucket_allocation_counts[i] > 0) {
4376 // Allocate a NULL-terminated array of policy pointers for each bucket
4377 MALLOC(necp_kernel_ip_output_policies_map[i], struct necp_kernel_ip_output_policy **, sizeof(struct necp_kernel_ip_output_policy *) * (bucket_allocation_counts[i] + 1), M_NECP, M_WAITOK);
4378 if (necp_kernel_ip_output_policies_map[i] == NULL) {
4379 goto fail;
4380 }
4381
4382 // Initialize the first entry to NULL
4383 (necp_kernel_ip_output_policies_map[i])[0] = NULL;
4384 }
4385 bucket_current_free_index[i] = 0;
4386 }
4387
4388 LIST_FOREACH(kernel_policy, &necp_kernel_ip_output_policies, chain) {
4389 // Insert pointers into map
4390 if (!(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_POLICY_ID)) {
4391 for (i = 0; i < NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS; i++) {
4392 if (!necp_kernel_ip_output_policy_is_unnecessary(kernel_policy, necp_kernel_ip_output_policies_map[i], bucket_current_free_index[i])) {
4393 (necp_kernel_ip_output_policies_map[i])[(bucket_current_free_index[i])] = kernel_policy;
4394 bucket_current_free_index[i]++;
4395 (necp_kernel_ip_output_policies_map[i])[(bucket_current_free_index[i])] = NULL;
4396 }
4397 }
4398 } else {
4399 i = NECP_IP_OUTPUT_MAP_ID_TO_BUCKET(kernel_policy->cond_policy_id);
4400 if (!necp_kernel_ip_output_policy_is_unnecessary(kernel_policy, necp_kernel_ip_output_policies_map[i], bucket_current_free_index[i])) {
4401 (necp_kernel_ip_output_policies_map[i])[(bucket_current_free_index[i])] = kernel_policy;
4402 bucket_current_free_index[i]++;
4403 (necp_kernel_ip_output_policies_map[i])[(bucket_current_free_index[i])] = NULL;
4404 }
4405 }
4406 }
4407 necp_kernel_ip_output_policies_dump_all();
4408 return (TRUE);
4409
4410 fail:
4411 // Free memory, reset mask to 0
4412 necp_kernel_ip_output_policies_condition_mask = 0;
4413 necp_kernel_ip_output_policies_count = 0;
4414 necp_kernel_ip_output_policies_non_id_count = 0;
4415 for (i = 0; i < NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS; i++) {
4416 if (necp_kernel_ip_output_policies_map[i] != NULL) {
4417 FREE(necp_kernel_ip_output_policies_map[i], M_NECP);
4418 necp_kernel_ip_output_policies_map[i] = NULL;
4419 }
4420 }
4421 return (FALSE);
4422 }
4423
4424 // Outbound Policy Matching
4425 // ---------------------
4426 struct substring {
4427 char *string;
4428 size_t length;
4429 };
4430
4431 static struct substring
4432 necp_trim_dots_and_stars(char *string, size_t length)
4433 {
4434 struct substring sub;
4435 sub.string = string;
4436 sub.length = string ? length : 0;
4437
4438 while (sub.length && (sub.string[0] == '.' || sub.string[0] == '*')) {
4439 sub.string++;
4440 sub.length--;
4441 }
4442
4443 while (sub.length && (sub.string[sub.length - 1] == '.' || sub.string[sub.length - 1] == '*')) {
4444 sub.length--;
4445 }
4446
4447 return (sub);
4448 }
4449
4450 static char *
4451 necp_create_trimmed_domain(char *string, size_t length)
4452 {
4453 char *trimmed_domain = NULL;
4454 struct substring sub = necp_trim_dots_and_stars(string, length);
4455
4456 MALLOC(trimmed_domain, char *, sub.length + 1, M_NECP, M_WAITOK);
4457 if (trimmed_domain == NULL) {
4458 return (NULL);
4459 }
4460
4461 memcpy(trimmed_domain, sub.string, sub.length);
4462 trimmed_domain[sub.length] = 0;
4463
4464 return (trimmed_domain);
4465 }
4466
4467 static inline int
4468 necp_count_dots(char *string, size_t length)
4469 {
4470 int dot_count = 0;
4471 size_t i = 0;
4472
4473 for (i = 0; i < length; i++) {
4474 if (string[i] == '.') {
4475 dot_count++;
4476 }
4477 }
4478
4479 return (dot_count);
4480 }
4481
4482 static bool
4483 necp_check_suffix(struct substring parent, struct substring suffix, bool require_dot_before_suffix)
4484 {
4485 if (parent.length <= suffix.length) {
4486 return (FALSE);
4487 }
4488
4489 size_t length_difference = (parent.length - suffix.length);
4490
4491 if (require_dot_before_suffix) {
4492 if (((char *)(parent.string + length_difference - 1))[0] != '.') {
4493 return (FALSE);
4494 }
4495 }
4496
4497 return (memcmp(parent.string + length_difference, suffix.string, suffix.length) == 0);
4498 }
4499
4500 static bool
4501 necp_hostname_matches_domain(struct substring hostname_substring, u_int8_t hostname_dot_count, char *domain, u_int8_t domain_dot_count)
4502 {
4503 if (hostname_substring.string == NULL || domain == NULL) {
4504 return (hostname_substring.string == domain);
4505 }
4506
4507 struct substring domain_substring;
4508 domain_substring.string = domain;
4509 domain_substring.length = strlen(domain);
4510
4511 if (hostname_dot_count == domain_dot_count) {
4512 if (hostname_substring.length == domain_substring.length &&
4513 memcmp(hostname_substring.string, domain_substring.string, hostname_substring.length) == 0) {
4514 return (TRUE);
4515 }
4516 } else if (domain_dot_count < hostname_dot_count) {
4517 if (necp_check_suffix(hostname_substring, domain_substring, TRUE)) {
4518 return (TRUE);
4519 }
4520 }
4521
4522 return (FALSE);
4523 }
4524
4525 #define NECP_KERNEL_ADDRESS_TYPE_CONDITIONS (NECP_KERNEL_CONDITION_LOCAL_START | NECP_KERNEL_CONDITION_LOCAL_END | NECP_KERNEL_CONDITION_LOCAL_PREFIX | NECP_KERNEL_CONDITION_REMOTE_START | NECP_KERNEL_CONDITION_REMOTE_END | NECP_KERNEL_CONDITION_REMOTE_PREFIX)
4526 static void
4527 necp_application_fillout_info_locked(uuid_t application_uuid, uuid_t real_application_uuid, char *account, char *domain, pid_t pid, uid_t uid, u_int16_t protocol, u_int32_t bound_interface_index, u_int32_t traffic_class, union necp_sockaddr_union *local_addr, union necp_sockaddr_union *remote_addr, struct necp_socket_info *info)
4528 {
4529 memset(info, 0, sizeof(struct necp_socket_info));
4530
4531 info->pid = pid;
4532 info->uid = uid;
4533 info->protocol = protocol;
4534 info->bound_interface_index = bound_interface_index;
4535 info->traffic_class = traffic_class;
4536 info->cred_result = 0; // Don't check the entitlement here, only in the socket layer
4537
4538 if (necp_kernel_application_policies_condition_mask & NECP_KERNEL_CONDITION_APP_ID && !uuid_is_null(application_uuid)) {
4539 struct necp_uuid_id_mapping *existing_mapping = necp_uuid_lookup_app_id_locked(application_uuid);
4540 if (existing_mapping) {
4541 info->application_id = existing_mapping->id;
4542 }
4543 }
4544
4545 if (necp_kernel_application_policies_condition_mask & NECP_KERNEL_CONDITION_REAL_APP_ID && !uuid_is_null(real_application_uuid)) {
4546 if (uuid_compare(application_uuid, real_application_uuid) == 0) {
4547 info->real_application_id = info->application_id;
4548 } else {
4549 struct necp_uuid_id_mapping *existing_mapping = necp_uuid_lookup_app_id_locked(real_application_uuid);
4550 if (existing_mapping) {
4551 info->real_application_id = existing_mapping->id;
4552 }
4553 }
4554 }
4555
4556 if (necp_kernel_application_policies_condition_mask & NECP_KERNEL_CONDITION_ACCOUNT_ID && account != NULL) {
4557 struct necp_string_id_mapping *existing_mapping = necp_lookup_string_to_id_locked(&necp_account_id_list, account);
4558 if (existing_mapping) {
4559 info->account_id = existing_mapping->id;
4560 }
4561 }
4562
4563 if (necp_kernel_application_policies_condition_mask & NECP_KERNEL_CONDITION_DOMAIN) {
4564 info->domain = domain;
4565 }
4566
4567 if (necp_kernel_application_policies_condition_mask & NECP_KERNEL_ADDRESS_TYPE_CONDITIONS) {
4568 if (local_addr && local_addr->sa.sa_len > 0) {
4569 memcpy(&info->local_addr, local_addr, local_addr->sa.sa_len);
4570 }
4571 if (remote_addr && remote_addr->sa.sa_len > 0) {
4572 memcpy(&info->remote_addr, remote_addr, remote_addr->sa.sa_len);
4573 }
4574 }
4575 }
4576
4577 static void
4578 necp_send_application_cell_denied_event(pid_t pid, uuid_t proc_uuid)
4579 {
4580 struct kev_netpolicy_ifdenied ev_ifdenied;
4581
4582 bzero(&ev_ifdenied, sizeof(ev_ifdenied));
4583
4584 ev_ifdenied.ev_data.epid = pid;
4585 uuid_copy(ev_ifdenied.ev_data.euuid, proc_uuid);
4586
4587 netpolicy_post_msg(KEV_NETPOLICY_IFDENIED, &ev_ifdenied.ev_data, sizeof(ev_ifdenied));
4588 }
4589
4590 static int
4591 necp_application_find_policy_match_internal(u_int8_t *parameters, u_int32_t parameters_size, struct necp_aggregate_result *returned_result)
4592 {
4593 int error = 0;
4594 size_t offset = 0;
4595
4596 struct necp_kernel_socket_policy *matched_policy = NULL;
4597 struct necp_socket_info info;
4598 necp_kernel_policy_filter filter_control_unit = 0;
4599 u_int32_t route_rule_id = 0;
4600 necp_kernel_policy_result service_action = 0;
4601 necp_kernel_policy_service service = { 0, 0 };
4602
4603 pid_t pid = 0;
4604 uid_t uid = 0;
4605 u_int16_t protocol = 0;
4606 u_int32_t bound_interface_index = 0;
4607 u_int32_t traffic_class = 0;
4608 union necp_sockaddr_union local_addr;
4609 union necp_sockaddr_union remote_addr;
4610 bool no_remote_addr = FALSE;
4611
4612 memset(&local_addr, 0, sizeof(local_addr));
4613 memset(&remote_addr, 0, sizeof(remote_addr));
4614 uuid_t application_uuid;
4615 uuid_clear(application_uuid);
4616 uuid_t real_application_uuid;
4617 uuid_clear(real_application_uuid);
4618 char *domain = NULL;
4619 char *account = NULL;
4620
4621 u_int32_t netagent_ids[NECP_MAX_NETAGENTS];
4622 memset(&netagent_ids, 0, sizeof(netagent_ids));
4623 int netagent_cursor;
4624
4625 if (returned_result == NULL) {
4626 return (EINVAL);
4627 }
4628
4629 memset(returned_result, 0, sizeof(struct necp_aggregate_result));
4630
4631 lck_rw_lock_shared(&necp_kernel_policy_lock);
4632 if (necp_kernel_application_policies_count == 0) {
4633 if (necp_drop_all_order > 0) {
4634 returned_result->routing_result = NECP_KERNEL_POLICY_RESULT_DROP;
4635 lck_rw_done(&necp_kernel_policy_lock);
4636 return (0);
4637 }
4638 }
4639 lck_rw_done(&necp_kernel_policy_lock);
4640
4641 while ((offset + sizeof(u_int8_t) + sizeof(u_int32_t)) <= parameters_size) {
4642 u_int8_t type = necp_buffer_get_tlv_type(parameters, offset);
4643 u_int32_t length = necp_buffer_get_tlv_length(parameters, offset);
4644
4645 if (length > 0 && (offset + sizeof(u_int8_t) + sizeof(u_int32_t) + length) <= parameters_size) {
4646 u_int8_t *value = necp_buffer_get_tlv_value(parameters, offset, NULL);
4647 if (value != NULL) {
4648 switch (type) {
4649 case NECP_POLICY_CONDITION_APPLICATION: {
4650 if (length >= sizeof(uuid_t)) {
4651 uuid_copy(application_uuid, value);
4652 }
4653 break;
4654 }
4655 case NECP_POLICY_CONDITION_REAL_APPLICATION: {
4656 if (length >= sizeof(uuid_t)) {
4657 uuid_copy(real_application_uuid, value);
4658 }
4659 break;
4660 }
4661 case NECP_POLICY_CONDITION_DOMAIN: {
4662 domain = (char *)value;
4663 domain[length - 1] = 0;
4664 break;
4665 }
4666 case NECP_POLICY_CONDITION_ACCOUNT: {
4667 account = (char *)value;
4668 account[length - 1] = 0;
4669 break;
4670 }
4671 case NECP_POLICY_CONDITION_TRAFFIC_CLASS: {
4672 if (length >= sizeof(u_int32_t)) {
4673 memcpy(&traffic_class, value, sizeof(u_int32_t));
4674 }
4675 break;
4676 }
4677 case NECP_POLICY_CONDITION_PID: {
4678 if (length >= sizeof(pid_t)) {
4679 memcpy(&pid, value, sizeof(pid_t));
4680 }
4681 break;
4682 }
4683 case NECP_POLICY_CONDITION_UID: {
4684 if (length >= sizeof(uid_t)) {
4685 memcpy(&uid, value, sizeof(uid_t));
4686 }
4687 break;
4688 }
4689 case NECP_POLICY_CONDITION_IP_PROTOCOL: {
4690 if (length >= sizeof(u_int16_t)) {
4691 memcpy(&protocol, value, sizeof(u_int16_t));
4692 }
4693 break;
4694 }
4695 case NECP_POLICY_CONDITION_BOUND_INTERFACE: {
4696 if (length <= IFXNAMSIZ && length > 0) {
4697 ifnet_t bound_interface = NULL;
4698 char interface_name[IFXNAMSIZ];
4699 memcpy(interface_name, value, length);
4700 interface_name[length - 1] = 0; // Make sure the string is NULL terminated
4701 if (ifnet_find_by_name(interface_name, &bound_interface) == 0) {
4702 bound_interface_index = bound_interface->if_index;
4703 }
4704 }
4705 break;
4706 }
4707 case NECP_POLICY_CONDITION_LOCAL_ADDR: {
4708 if (length >= sizeof(struct necp_policy_condition_addr)) {
4709 struct necp_policy_condition_addr *address_struct = (struct necp_policy_condition_addr *)(void *)value;
4710 memcpy(&local_addr, &address_struct->address, sizeof(address_struct->address));
4711 }
4712 break;
4713 }
4714 case NECP_POLICY_CONDITION_REMOTE_ADDR: {
4715 if (length >= sizeof(struct necp_policy_condition_addr)) {
4716 struct necp_policy_condition_addr *address_struct = (struct necp_policy_condition_addr *)(void *)value;
4717 memcpy(&remote_addr, &address_struct->address, sizeof(address_struct->address));
4718 }
4719 break;
4720 }
4721 default: {
4722 break;
4723 }
4724 }
4725 }
4726 }
4727
4728 offset += sizeof(u_int8_t) + sizeof(u_int32_t) + length;
4729 }
4730
4731 // Lock
4732 lck_rw_lock_shared(&necp_kernel_policy_lock);
4733
4734 necp_application_fillout_info_locked(application_uuid, real_application_uuid, account, domain, pid, uid, protocol, bound_interface_index, traffic_class, &local_addr, &remote_addr, &info);
4735 matched_policy = necp_socket_find_policy_match_with_info_locked(necp_kernel_socket_policies_app_layer_map, &info, &filter_control_unit, &route_rule_id, &service_action, &service, netagent_ids, NECP_MAX_NETAGENTS);
4736 if (matched_policy) {
4737 returned_result->policy_id = matched_policy->id;
4738 returned_result->routing_result = matched_policy->result;
4739 memcpy(&returned_result->routing_result_parameter, &matched_policy->result_parameter, sizeof(returned_result->routing_result_parameter));
4740 } else {
4741 returned_result->policy_id = 0;
4742 returned_result->routing_result = NECP_KERNEL_POLICY_RESULT_NONE;
4743 }
4744 returned_result->filter_control_unit = filter_control_unit;
4745 returned_result->service_action = service_action;
4746
4747 // Handle trigger service
4748 if (service.identifier != 0) {
4749 struct necp_uuid_id_mapping *mapping = necp_uuid_lookup_uuid_with_service_id_locked(service.identifier);
4750 if (mapping != NULL) {
4751 struct necp_service_registration *service_registration = NULL;
4752 uuid_copy(returned_result->service_uuid, mapping->uuid);
4753 returned_result->service_data = service.data;
4754 if (service.identifier == NECP_NULL_SERVICE_ID) {
4755 // NULL service is always 'registered'
4756 returned_result->service_flags |= NECP_SERVICE_FLAGS_REGISTERED;
4757 } else {
4758 LIST_FOREACH(service_registration, &necp_registered_service_list, kernel_chain) {
4759 if (service.identifier == service_registration->service_id) {
4760 returned_result->service_flags |= NECP_SERVICE_FLAGS_REGISTERED;
4761 break;
4762 }
4763 }
4764 }
4765 }
4766 }
4767
4768 // Handle netagents
4769 for (netagent_cursor = 0; netagent_cursor < NECP_MAX_NETAGENTS; netagent_cursor++) {
4770 struct necp_uuid_id_mapping *mapping = NULL;
4771 u_int32_t netagent_id = netagent_ids[netagent_cursor];
4772 if (netagent_id == 0) {
4773 break;
4774 }
4775 mapping = necp_uuid_lookup_uuid_with_service_id_locked(netagent_id);
4776 if (mapping != NULL) {
4777 uuid_copy(returned_result->netagents[netagent_cursor], mapping->uuid);
4778 returned_result->netagent_flags[netagent_cursor] = netagent_get_flags(mapping->uuid);
4779 }
4780 }
4781
4782 // Do routing evaluation
4783 u_int output_bound_interface = bound_interface_index;
4784 if (returned_result->routing_result == NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED) {
4785 output_bound_interface = returned_result->routing_result_parameter.scoped_interface_index;
4786 } else if (returned_result->routing_result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL) {
4787 output_bound_interface = returned_result->routing_result_parameter.tunnel_interface_index;
4788 }
4789
4790 if (remote_addr.sa.sa_len == 0) {
4791 no_remote_addr = TRUE;
4792 // Default to 0.0.0.0:0
4793 remote_addr.sa.sa_family = AF_INET;
4794 remote_addr.sa.sa_len = sizeof(struct sockaddr_in);
4795 }
4796
4797 struct rtentry *rt = NULL;
4798 rt = rtalloc1_scoped((struct sockaddr *)&remote_addr, 0, 0, output_bound_interface);
4799
4800 if (no_remote_addr &&
4801 (rt == NULL || rt->rt_ifp == NULL)) {
4802 // Route lookup for default IPv4 failed, try IPv6
4803
4804 // Cleanup old route if necessary
4805 if (rt != NULL) {
4806 rtfree(rt);
4807 rt = NULL;
4808 }
4809
4810 // Reset address to ::
4811 memset(&remote_addr, 0, sizeof(remote_addr));
4812 remote_addr.sa.sa_family = AF_INET6;
4813 remote_addr.sa.sa_len = sizeof(struct sockaddr_in6);
4814
4815 // Get route
4816 rt = rtalloc1_scoped((struct sockaddr *)&remote_addr, 0, 0, output_bound_interface);
4817 }
4818
4819 returned_result->routed_interface_index = 0;
4820 if (rt != NULL &&
4821 rt->rt_ifp != NULL) {
4822 returned_result->routed_interface_index = rt->rt_ifp->if_index;
4823 /*
4824 * For local addresses, we allow the interface scope to be
4825 * either the loopback interface or the interface hosting the
4826 * local address.
4827 */
4828 if (bound_interface_index != IFSCOPE_NONE &&
4829 rt->rt_ifa != NULL && rt->rt_ifa->ifa_ifp &&
4830 (output_bound_interface == lo_ifp->if_index ||
4831 rt->rt_ifp->if_index == lo_ifp->if_index ||
4832 rt->rt_ifa->ifa_ifp->if_index == bound_interface_index)) {
4833 struct sockaddr_storage dst;
4834 unsigned int ifscope = bound_interface_index;
4835
4836 /*
4837 * Transform dst into the internal routing table form
4838 */
4839 (void) sa_copy((struct sockaddr *)&remote_addr,
4840 &dst, &ifscope);
4841
4842 if ((rt->rt_ifp->if_index == lo_ifp->if_index) ||
4843 rt_ifa_is_dst((struct sockaddr *)&dst, rt->rt_ifa))
4844 returned_result->routed_interface_index =
4845 bound_interface_index;
4846 }
4847 }
4848
4849 bool cellular_denied = FALSE;
4850 bool route_is_allowed = necp_route_is_allowed(rt, NULL, route_rule_id, &cellular_denied);
4851 if (!route_is_allowed) {
4852 // If the route is blocked, treat the lookup as a drop
4853 returned_result->routing_result = NECP_KERNEL_POLICY_RESULT_DROP;
4854 memset(&returned_result->routing_result_parameter, 0, sizeof(returned_result->routing_result_parameter));
4855
4856 if (cellular_denied) {
4857 necp_send_application_cell_denied_event(pid, application_uuid);
4858 }
4859 }
4860
4861 if (rt != NULL) {
4862 rtfree(rt);
4863 rt = NULL;
4864 }
4865 // Unlock
4866 lck_rw_done(&necp_kernel_policy_lock);
4867
4868 return (error);
4869 }
4870
4871 #define NECP_MAX_MATCH_POLICY_PARAMETER_SIZE 1024
4872
4873 int
4874 necp_match_policy(struct proc *p, struct necp_match_policy_args *uap, int32_t *retval)
4875 {
4876 #pragma unused(p, retval)
4877 u_int8_t *parameters = NULL;
4878 struct necp_aggregate_result returned_result;
4879 int error = 0;
4880
4881 if (uap == NULL) {
4882 error = EINVAL;
4883 goto done;
4884 }
4885
4886 if (uap->parameters == 0 || uap->parameters_size == 0 || uap->parameters_size > NECP_MAX_MATCH_POLICY_PARAMETER_SIZE || uap->returned_result == 0) {
4887 error = EINVAL;
4888 goto done;
4889 }
4890
4891 MALLOC(parameters, u_int8_t *, uap->parameters_size, M_NECP, M_WAITOK);
4892 if (parameters == NULL) {
4893 error = ENOMEM;
4894 goto done;
4895 }
4896 // Copy parameters in
4897 error = copyin(uap->parameters, parameters, uap->parameters_size);
4898 if (error) {
4899 goto done;
4900 }
4901
4902 error = necp_application_find_policy_match_internal(parameters, uap->parameters_size, &returned_result);
4903 if (error) {
4904 goto done;
4905 }
4906
4907 // Copy return value back
4908 error = copyout(&returned_result, uap->returned_result, sizeof(struct necp_aggregate_result));
4909 if (error) {
4910 goto done;
4911 }
4912 done:
4913 if (parameters != NULL) {
4914 FREE(parameters, M_NECP);
4915 }
4916 return (error);
4917 }
4918
4919 static bool
4920 necp_socket_check_policy(struct necp_kernel_socket_policy *kernel_policy, necp_app_id app_id, necp_app_id real_app_id, errno_t cred_result, u_int32_t account_id, struct substring domain, u_int8_t domain_dot_count, pid_t pid, uid_t uid, u_int32_t bound_interface_index, u_int32_t traffic_class, u_int16_t protocol, union necp_sockaddr_union *local, union necp_sockaddr_union *remote)
4921 {
4922 if (!(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES)) {
4923 if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE) {
4924 u_int32_t cond_bound_interface_index = kernel_policy->cond_bound_interface ? kernel_policy->cond_bound_interface->if_index : 0;
4925 if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE) {
4926 if (bound_interface_index == cond_bound_interface_index) {
4927 // No match, matches forbidden interface
4928 return (FALSE);
4929 }
4930 } else {
4931 if (bound_interface_index != cond_bound_interface_index) {
4932 // No match, does not match required interface
4933 return (FALSE);
4934 }
4935 }
4936 } else {
4937 if (bound_interface_index != 0) {
4938 // No match, requires a non-bound packet
4939 return (FALSE);
4940 }
4941 }
4942 }
4943
4944 if (kernel_policy->condition_mask == 0) {
4945 return (TRUE);
4946 }
4947
4948 if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_APP_ID) {
4949 if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_APP_ID) {
4950 if (app_id == kernel_policy->cond_app_id) {
4951 // No match, matches forbidden application
4952 return (FALSE);
4953 }
4954 } else {
4955 if (app_id != kernel_policy->cond_app_id) {
4956 // No match, does not match required application
4957 return (FALSE);
4958 }
4959 }
4960 }
4961
4962 if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REAL_APP_ID) {
4963 if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_REAL_APP_ID) {
4964 if (real_app_id == kernel_policy->cond_real_app_id) {
4965 // No match, matches forbidden application
4966 return (FALSE);
4967 }
4968 } else {
4969 if (real_app_id != kernel_policy->cond_real_app_id) {
4970 // No match, does not match required application
4971 return (FALSE);
4972 }
4973 }
4974 }
4975
4976 if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ENTITLEMENT) {
4977 if (cred_result != 0) {
4978 // Process is missing entitlement
4979 return (FALSE);
4980 }
4981 }
4982
4983 if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_DOMAIN) {
4984 bool domain_matches = necp_hostname_matches_domain(domain, domain_dot_count, kernel_policy->cond_domain, kernel_policy->cond_domain_dot_count);
4985 if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_DOMAIN) {
4986 if (domain_matches) {
4987 // No match, matches forbidden domain
4988 return (FALSE);
4989 }
4990 } else {
4991 if (!domain_matches) {
4992 // No match, does not match required domain
4993 return (FALSE);
4994 }
4995 }
4996 }
4997
4998 if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ACCOUNT_ID) {
4999 if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_ACCOUNT_ID) {
5000 if (account_id == kernel_policy->cond_account_id) {
5001 // No match, matches forbidden account
5002 return (FALSE);
5003 }
5004 } else {
5005 if (account_id != kernel_policy->cond_account_id) {
5006 // No match, does not match required account
5007 return (FALSE);
5008 }
5009 }
5010 }
5011
5012 if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_PID) {
5013 if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_PID) {
5014 if (pid == kernel_policy->cond_pid) {
5015 // No match, matches forbidden pid
5016 return (FALSE);
5017 }
5018 } else {
5019 if (pid != kernel_policy->cond_pid) {
5020 // No match, does not match required pid
5021 return (FALSE);
5022 }
5023 }
5024 }
5025
5026 if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_UID) {
5027 if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_UID) {
5028 if (uid == kernel_policy->cond_uid) {
5029 // No match, matches forbidden uid
5030 return (FALSE);
5031 }
5032 } else {
5033 if (uid != kernel_policy->cond_uid) {
5034 // No match, does not match required uid
5035 return (FALSE);
5036 }
5037 }
5038 }
5039
5040 if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_TRAFFIC_CLASS) {
5041 if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_TRAFFIC_CLASS) {
5042 if (traffic_class >= kernel_policy->cond_traffic_class.start_tc &&
5043 traffic_class <= kernel_policy->cond_traffic_class.end_tc) {
5044 // No match, matches forbidden traffic class
5045 return (FALSE);
5046 }
5047 } else {
5048 if (traffic_class < kernel_policy->cond_traffic_class.start_tc ||
5049 traffic_class > kernel_policy->cond_traffic_class.end_tc) {
5050 // No match, does not match required traffic class
5051 return (FALSE);
5052 }
5053 }
5054 }
5055
5056 if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_PROTOCOL) {
5057 if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_PROTOCOL) {
5058 if (protocol == kernel_policy->cond_protocol) {
5059 // No match, matches forbidden protocol
5060 return (FALSE);
5061 }
5062 } else {
5063 if (protocol != kernel_policy->cond_protocol) {
5064 // No match, does not match required protocol
5065 return (FALSE);
5066 }
5067 }
5068 }
5069
5070 if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_START) {
5071 if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
5072 bool inRange = necp_is_addr_in_range((struct sockaddr *)local, (struct sockaddr *)&kernel_policy->cond_local_start, (struct sockaddr *)&kernel_policy->cond_local_end);
5073 if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
5074 if (inRange) {
5075 return (FALSE);
5076 }
5077 } else {
5078 if (!inRange) {
5079 return (FALSE);
5080 }
5081 }
5082 } else if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX) {
5083 bool inSubnet = necp_is_addr_in_subnet((struct sockaddr *)local, (struct sockaddr *)&kernel_policy->cond_local_start, kernel_policy->cond_local_prefix);
5084 if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX) {
5085 if (inSubnet) {
5086 return (FALSE);
5087 }
5088 } else {
5089 if (!inSubnet) {
5090 return (FALSE);
5091 }
5092 }
5093 }
5094 }
5095
5096 if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_START) {
5097 if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
5098 bool inRange = necp_is_addr_in_range((struct sockaddr *)remote, (struct sockaddr *)&kernel_policy->cond_remote_start, (struct sockaddr *)&kernel_policy->cond_remote_end);
5099 if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
5100 if (inRange) {
5101 return (FALSE);
5102 }
5103 } else {
5104 if (!inRange) {
5105 return (FALSE);
5106 }
5107 }
5108 } else if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX) {
5109 bool inSubnet = necp_is_addr_in_subnet((struct sockaddr *)remote, (struct sockaddr *)&kernel_policy->cond_remote_start, kernel_policy->cond_remote_prefix);
5110 if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX) {
5111 if (inSubnet) {
5112 return (FALSE);
5113 }
5114 } else {
5115 if (!inSubnet) {
5116 return (FALSE);
5117 }
5118 }
5119 }
5120 }
5121
5122 return (TRUE);
5123 }
5124
5125 static inline u_int32_t
5126 necp_socket_calc_flowhash_locked(struct necp_socket_info *info)
5127 {
5128 return (net_flowhash(info, sizeof(*info), necp_kernel_socket_policies_gencount));
5129 }
5130
5131 static void
5132 necp_socket_fillout_info_locked(struct inpcb *inp, struct sockaddr *override_local_addr, struct sockaddr *override_remote_addr, u_int32_t override_bound_interface, struct necp_socket_info *info)
5133 {
5134 struct socket *so = NULL;
5135
5136 memset(info, 0, sizeof(struct necp_socket_info));
5137
5138 so = inp->inp_socket;
5139
5140 if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_PID) {
5141 info->pid = ((so->so_flags & SOF_DELEGATED) ? so->e_pid : so->last_pid);
5142 }
5143
5144 if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_UID) {
5145 info->uid = kauth_cred_getuid(so->so_cred);
5146 }
5147
5148 if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_TRAFFIC_CLASS) {
5149 info->traffic_class = so->so_traffic_class;
5150 }
5151
5152 if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_PROTOCOL) {
5153 if (inp->inp_ip_p) {
5154 info->protocol = inp->inp_ip_p;
5155 } else {
5156 info->protocol = SOCK_PROTO(so);
5157 }
5158 }
5159
5160 if (inp->inp_flags2 & INP2_WANT_APP_POLICY && necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_APP_ID) {
5161 struct necp_uuid_id_mapping *existing_mapping = necp_uuid_lookup_app_id_locked(((so->so_flags & SOF_DELEGATED) ? so->e_uuid : so->last_uuid));
5162 if (existing_mapping) {
5163 info->application_id = existing_mapping->id;
5164 }
5165
5166 if (!(so->so_flags & SOF_DELEGATED)) {
5167 info->real_application_id = info->application_id;
5168 } else if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_REAL_APP_ID) {
5169 struct necp_uuid_id_mapping *real_existing_mapping = necp_uuid_lookup_app_id_locked(so->last_uuid);
5170 if (real_existing_mapping) {
5171 info->real_application_id = real_existing_mapping->id;
5172 }
5173 }
5174
5175 if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_ENTITLEMENT) {
5176 info->cred_result = priv_check_cred(so->so_cred, PRIV_NET_PRIVILEGED_NECP_MATCH, 0);
5177 }
5178 }
5179
5180 if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_ACCOUNT_ID && inp->inp_necp_attributes.inp_account != NULL) {
5181 struct necp_string_id_mapping *existing_mapping = necp_lookup_string_to_id_locked(&necp_account_id_list, inp->inp_necp_attributes.inp_account);
5182 if (existing_mapping) {
5183 info->account_id = existing_mapping->id;
5184 }
5185 }
5186
5187 if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_DOMAIN) {
5188 info->domain = inp->inp_necp_attributes.inp_domain;
5189 }
5190
5191 if (override_bound_interface) {
5192 info->bound_interface_index = override_bound_interface;
5193 } else {
5194 if ((inp->inp_flags & INP_BOUND_IF) && inp->inp_boundifp) {
5195 info->bound_interface_index = inp->inp_boundifp->if_index;
5196 }
5197 }
5198
5199 if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_ADDRESS_TYPE_CONDITIONS) {
5200 if (inp->inp_vflag & INP_IPV4) {
5201 if (override_local_addr) {
5202 if (override_local_addr->sa_len <= sizeof(struct sockaddr_in)) {
5203 memcpy(&info->local_addr, override_local_addr, override_local_addr->sa_len);
5204 }
5205 } else {
5206 ((struct sockaddr_in *)&info->local_addr)->sin_family = AF_INET;
5207 ((struct sockaddr_in *)&info->local_addr)->sin_len = sizeof(struct sockaddr_in);
5208 ((struct sockaddr_in *)&info->local_addr)->sin_port = inp->inp_lport;
5209 memcpy(&((struct sockaddr_in *)&info->local_addr)->sin_addr, &inp->inp_laddr, sizeof(struct in_addr));
5210 }
5211
5212 if (override_remote_addr) {
5213 if (override_remote_addr->sa_len <= sizeof(struct sockaddr_in)) {
5214 memcpy(&info->remote_addr, override_remote_addr, override_remote_addr->sa_len);
5215 }
5216 } else {
5217 ((struct sockaddr_in *)&info->remote_addr)->sin_family = AF_INET;
5218 ((struct sockaddr_in *)&info->remote_addr)->sin_len = sizeof(struct sockaddr_in);
5219 ((struct sockaddr_in *)&info->remote_addr)->sin_port = inp->inp_fport;
5220 memcpy(&((struct sockaddr_in *)&info->remote_addr)->sin_addr, &inp->inp_faddr, sizeof(struct in_addr));
5221 }
5222 } else if (inp->inp_vflag & INP_IPV6) {
5223 if (override_local_addr) {
5224 if (override_local_addr->sa_len <= sizeof(struct sockaddr_in6)) {
5225 memcpy(&info->local_addr, override_local_addr, override_local_addr->sa_len);
5226 }
5227 } else {
5228 ((struct sockaddr_in6 *)&info->local_addr)->sin6_family = AF_INET6;
5229 ((struct sockaddr_in6 *)&info->local_addr)->sin6_len = sizeof(struct sockaddr_in6);
5230 ((struct sockaddr_in6 *)&info->local_addr)->sin6_port = inp->inp_lport;
5231 memcpy(&((struct sockaddr_in6 *)&info->local_addr)->sin6_addr, &inp->in6p_laddr, sizeof(struct in6_addr));
5232 }
5233
5234 if (override_remote_addr) {
5235 if (override_remote_addr->sa_len <= sizeof(struct sockaddr_in6)) {
5236 memcpy(&info->remote_addr, override_remote_addr, override_remote_addr->sa_len);
5237 }
5238 } else {
5239 ((struct sockaddr_in6 *)&info->remote_addr)->sin6_family = AF_INET6;
5240 ((struct sockaddr_in6 *)&info->remote_addr)->sin6_len = sizeof(struct sockaddr_in6);
5241 ((struct sockaddr_in6 *)&info->remote_addr)->sin6_port = inp->inp_fport;
5242 memcpy(&((struct sockaddr_in6 *)&info->remote_addr)->sin6_addr, &inp->in6p_faddr, sizeof(struct in6_addr));
5243 }
5244 }
5245 }
5246 }
5247
5248 static inline struct necp_kernel_socket_policy *
5249 necp_socket_find_policy_match_with_info_locked(struct necp_kernel_socket_policy **policy_search_array, struct necp_socket_info *info, necp_kernel_policy_filter *return_filter, u_int32_t *return_route_rule_id, necp_kernel_policy_result *return_service_action, necp_kernel_policy_service *return_service, u_int32_t *return_netagent_array, size_t netagent_array_count)
5250 {
5251 struct necp_kernel_socket_policy *matched_policy = NULL;
5252 u_int32_t skip_order = 0;
5253 u_int32_t skip_session_order = 0;
5254 u_int32_t route_rule_id_array[MAX_AGGREGATE_ROUTE_RULES];
5255 size_t route_rule_id_count = 0;
5256 int i;
5257 size_t netagent_cursor = 0;
5258
5259 // Pre-process domain for quick matching
5260 struct substring domain_substring = necp_trim_dots_and_stars(info->domain, info->domain ? strlen(info->domain) : 0);
5261 u_int8_t domain_dot_count = necp_count_dots(domain_substring.string, domain_substring.length);
5262
5263 if (return_filter) {
5264 *return_filter = 0;
5265 }
5266
5267 if (return_route_rule_id) {
5268 *return_route_rule_id = 0;
5269 }
5270
5271 if (return_service_action) {
5272 *return_service_action = 0;
5273 }
5274
5275 if (return_service) {
5276 return_service->identifier = 0;
5277 return_service->data = 0;
5278 }
5279
5280 if (policy_search_array != NULL) {
5281 for (i = 0; policy_search_array[i] != NULL; i++) {
5282 if (necp_drop_all_order != 0 && policy_search_array[i]->session_order >= necp_drop_all_order) {
5283 // We've hit a drop all rule
5284 break;
5285 }
5286 if (skip_session_order && policy_search_array[i]->session_order >= skip_session_order) {
5287 // Done skipping
5288 skip_order = 0;
5289 skip_session_order = 0;
5290 }
5291 if (skip_order) {
5292 if (policy_search_array[i]->order < skip_order) {
5293 // Skip this policy
5294 continue;
5295 } else {
5296 // Done skipping
5297 skip_order = 0;
5298 skip_session_order = 0;
5299 }
5300 } else if (skip_session_order) {
5301 // Skip this policy
5302 continue;
5303 }
5304 if (necp_socket_check_policy(policy_search_array[i], info->application_id, info->real_application_id, info->cred_result, info->account_id, domain_substring, domain_dot_count, info->pid, info->uid, info->bound_interface_index, info->traffic_class, info->protocol, &info->local_addr, &info->remote_addr)) {
5305 if (policy_search_array[i]->result == NECP_KERNEL_POLICY_RESULT_SOCKET_FILTER) {
5306 if (return_filter && *return_filter == 0) {
5307 *return_filter = policy_search_array[i]->result_parameter.filter_control_unit;
5308 if (necp_debug > 1) {
5309 NECPLOG(LOG_DEBUG, "Socket Policy: (Application %d Real Application %d BoundInterface %d Proto %d) Filter %d", info->application_id, info->real_application_id, info->bound_interface_index, info->protocol, policy_search_array[i]->result_parameter.filter_control_unit);
5310 }
5311 }
5312 continue;
5313 } else if (policy_search_array[i]->result == NECP_KERNEL_POLICY_RESULT_ROUTE_RULES) {
5314 if (return_route_rule_id && route_rule_id_count < MAX_AGGREGATE_ROUTE_RULES) {
5315 route_rule_id_array[route_rule_id_count++] = policy_search_array[i]->result_parameter.route_rule_id;
5316 if (necp_debug > 1) {
5317 NECPLOG(LOG_DEBUG, "Socket Policy: (Application %d Real Application %d BoundInterface %d Proto %d) Route Rule %d", info->application_id, info->real_application_id, info->bound_interface_index, info->protocol, policy_search_array[i]->result_parameter.route_rule_id);
5318 }
5319 }
5320 continue;
5321 } else if (necp_kernel_socket_result_is_trigger_service_type(policy_search_array[i])) {
5322 if (return_service_action && *return_service_action == 0) {
5323 *return_service_action = policy_search_array[i]->result;
5324 if (necp_debug > 1) {
5325 NECPLOG(LOG_DEBUG, "Socket Policy: (Application %d Real Application %d BoundInterface %d Proto %d) Service Action %d", info->application_id, info->real_application_id, info->bound_interface_index, info->protocol, policy_search_array[i]->result);
5326 }
5327 }
5328 if (return_service && return_service->identifier == 0) {
5329 return_service->identifier = policy_search_array[i]->result_parameter.service.identifier;
5330 return_service->data = policy_search_array[i]->result_parameter.service.data;
5331 if (necp_debug > 1) {
5332 NECPLOG(LOG_DEBUG, "Socket Policy: (Application %d Real Application %d BoundInterface %d Proto %d) Service ID %d Data %d", info->application_id, info->real_application_id, info->bound_interface_index, info->protocol, policy_search_array[i]->result_parameter.service.identifier, policy_search_array[i]->result_parameter.service.data);
5333 }
5334 }
5335 continue;
5336 } else if (policy_search_array[i]->result == NECP_KERNEL_POLICY_RESULT_USE_NETAGENT) {
5337 if (return_netagent_array != NULL &&
5338 netagent_cursor < netagent_array_count) {
5339 return_netagent_array[netagent_cursor] = policy_search_array[i]->result_parameter.netagent_id;
5340 netagent_cursor++;
5341 if (necp_debug > 1) {
5342 NECPLOG(LOG_DEBUG, "Socket Policy: (Application %d Real Application %d BoundInterface %d Proto %d) Use Netagent %d", info->application_id, info->real_application_id, info->bound_interface_index, info->protocol, policy_search_array[i]->result_parameter.netagent_id);
5343 }
5344 }
5345 continue;
5346 }
5347
5348 // Passed all tests, found a match
5349 matched_policy = policy_search_array[i];
5350 if (policy_search_array[i]->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
5351 skip_order = policy_search_array[i]->result_parameter.skip_policy_order;
5352 skip_session_order = policy_search_array[i]->session_order + 1;
5353 continue;
5354 }
5355 break;
5356 }
5357 }
5358 }
5359
5360 if (route_rule_id_count == 1) {
5361 *return_route_rule_id = route_rule_id_array[0];
5362 } else if (route_rule_id_count > 1) {
5363 *return_route_rule_id = necp_create_aggregate_route_rule(route_rule_id_array);
5364 }
5365 return (matched_policy);
5366 }
5367
5368 static bool
5369 necp_socket_uses_interface(struct inpcb *inp, u_int32_t interface_index)
5370 {
5371 bool found_match = FALSE;
5372 errno_t result = 0;
5373 ifaddr_t *addresses = NULL;
5374 union necp_sockaddr_union address_storage;
5375 int i;
5376 int family = AF_INET;
5377 ifnet_t interface = ifindex2ifnet[interface_index];
5378
5379 if (inp == NULL || interface == NULL) {
5380 return (FALSE);
5381 }
5382
5383 if (inp->inp_vflag & INP_IPV4) {
5384 family = AF_INET;
5385 } else if (inp->inp_vflag & INP_IPV6) {
5386 family = AF_INET6;
5387 }
5388
5389 result = ifnet_get_address_list_family(interface, &addresses, family);
5390 if (result != 0) {
5391 NECPLOG(LOG_ERR, "Failed to get address list for %s%d", ifnet_name(interface), ifnet_unit(interface));
5392 return (FALSE);
5393 }
5394
5395 for (i = 0; addresses[i] != NULL; i++) {
5396 if (ifaddr_address(addresses[i], &address_storage.sa, sizeof(address_storage)) == 0) {
5397 if (family == AF_INET) {
5398 if (memcmp(&address_storage.sin.sin_addr, &inp->inp_laddr, sizeof(inp->inp_laddr)) == 0) {
5399 found_match = TRUE;
5400 goto done;
5401 }
5402 } else if (family == AF_INET6) {
5403 if (memcmp(&address_storage.sin6.sin6_addr, &inp->in6p_laddr, sizeof(inp->in6p_laddr)) == 0) {
5404 found_match = TRUE;
5405 goto done;
5406 }
5407 }
5408 }
5409 }
5410
5411 done:
5412 ifnet_free_address_list(addresses);
5413 addresses = NULL;
5414 return (found_match);
5415 }
5416
5417 static inline bool
5418 necp_socket_is_connected(struct inpcb *inp)
5419 {
5420 return (inp->inp_socket->so_state & (SS_ISCONNECTING | SS_ISCONNECTED | SS_ISDISCONNECTING));
5421 }
5422
5423 necp_kernel_policy_id
5424 necp_socket_find_policy_match(struct inpcb *inp, struct sockaddr *override_local_addr, struct sockaddr *override_remote_addr, u_int32_t override_bound_interface)
5425 {
5426 struct socket *so = NULL;
5427 necp_kernel_policy_filter filter_control_unit = 0;
5428 u_int32_t route_rule_id = 0;
5429 struct necp_kernel_socket_policy *matched_policy = NULL;
5430 necp_kernel_policy_id matched_policy_id = NECP_KERNEL_POLICY_ID_NONE;
5431 necp_kernel_policy_result service_action = 0;
5432 necp_kernel_policy_service service = { 0, 0 };
5433
5434 u_int32_t netagent_ids[NECP_MAX_NETAGENTS];
5435 memset(&netagent_ids, 0, sizeof(netagent_ids));
5436 int netagent_cursor;
5437
5438 struct necp_socket_info info;
5439
5440 if (inp == NULL) {
5441 return (NECP_KERNEL_POLICY_ID_NONE);
5442 }
5443
5444 so = inp->inp_socket;
5445
5446 // Don't lock. Possible race condition, but we don't want the performance hit.
5447 if (necp_kernel_socket_policies_count == 0 ||
5448 (!(inp->inp_flags2 & INP2_WANT_APP_POLICY) && necp_kernel_socket_policies_non_app_count == 0)) {
5449 if (necp_drop_all_order > 0) {
5450 inp->inp_policyresult.policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
5451 inp->inp_policyresult.policy_gencount = 0;
5452 inp->inp_policyresult.flowhash = 0;
5453 inp->inp_policyresult.results.filter_control_unit = 0;
5454 inp->inp_policyresult.results.route_rule_id = 0;
5455 if (necp_pass_loopback > 0 &&
5456 necp_is_loopback(override_local_addr, override_remote_addr, inp, NULL)) {
5457 inp->inp_policyresult.results.result = NECP_KERNEL_POLICY_RESULT_PASS;
5458 } else {
5459 inp->inp_policyresult.results.result = NECP_KERNEL_POLICY_RESULT_DROP;
5460 }
5461 }
5462 return (NECP_KERNEL_POLICY_ID_NONE);
5463 }
5464
5465 // Check for loopback exception
5466 if (necp_pass_loopback > 0 &&
5467 necp_is_loopback(override_local_addr, override_remote_addr, inp, NULL)) {
5468 // Mark socket as a pass
5469 inp->inp_policyresult.policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
5470 inp->inp_policyresult.policy_gencount = 0;
5471 inp->inp_policyresult.flowhash = 0;
5472 inp->inp_policyresult.results.filter_control_unit = 0;
5473 inp->inp_policyresult.results.route_rule_id = 0;
5474 inp->inp_policyresult.results.result = NECP_KERNEL_POLICY_RESULT_PASS;
5475 return (NECP_KERNEL_POLICY_ID_NONE);
5476 }
5477
5478 // Lock
5479 lck_rw_lock_shared(&necp_kernel_policy_lock);
5480
5481 necp_socket_fillout_info_locked(inp, override_local_addr, override_remote_addr, override_bound_interface, &info);
5482
5483 // Check info
5484 u_int32_t flowhash = necp_socket_calc_flowhash_locked(&info);
5485 if (inp->inp_policyresult.policy_id != NECP_KERNEL_POLICY_ID_NONE &&
5486 inp->inp_policyresult.policy_gencount == necp_kernel_socket_policies_gencount &&
5487 inp->inp_policyresult.flowhash == flowhash) {
5488 // If already matched this socket on this generation of table, skip
5489
5490 // Unlock
5491 lck_rw_done(&necp_kernel_policy_lock);
5492
5493 return (inp->inp_policyresult.policy_id);
5494 }
5495
5496 // Match socket to policy
5497 matched_policy = necp_socket_find_policy_match_with_info_locked(necp_kernel_socket_policies_map[NECP_SOCKET_MAP_APP_ID_TO_BUCKET(info.application_id)], &info, &filter_control_unit, &route_rule_id, &service_action, &service, netagent_ids, NECP_MAX_NETAGENTS);
5498 // If the socket matched a scoped service policy, mark as Drop if not registered.
5499 // This covers the cases in which a service is required (on demand) but hasn't started yet.
5500 if ((service_action == NECP_KERNEL_POLICY_RESULT_TRIGGER_SCOPED ||
5501 service_action == NECP_KERNEL_POLICY_RESULT_NO_TRIGGER_SCOPED) &&
5502 service.identifier != 0 &&
5503 service.identifier != NECP_NULL_SERVICE_ID) {
5504 bool service_is_registered = FALSE;
5505 struct necp_service_registration *service_registration = NULL;
5506 LIST_FOREACH(service_registration, &necp_registered_service_list, kernel_chain) {
5507 if (service.identifier == service_registration->service_id) {
5508 service_is_registered = TRUE;
5509 break;
5510 }
5511 }
5512 if (!service_is_registered) {
5513 // Mark socket as a drop if service is not registered
5514 inp->inp_policyresult.policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
5515 inp->inp_policyresult.policy_gencount = necp_kernel_socket_policies_gencount;
5516 inp->inp_policyresult.flowhash = flowhash;
5517 inp->inp_policyresult.results.filter_control_unit = 0;
5518 inp->inp_policyresult.results.route_rule_id = 0;
5519 inp->inp_policyresult.results.result = NECP_KERNEL_POLICY_RESULT_DROP;
5520
5521 if (necp_debug > 1) {
5522 NECPLOG(LOG_DEBUG, "Socket Policy: (BoundInterface %d Proto %d) Dropping packet because service is not registered", info.bound_interface_index, info.protocol);
5523 }
5524
5525 // Unlock
5526 lck_rw_done(&necp_kernel_policy_lock);
5527 return (NECP_KERNEL_POLICY_ID_NONE);
5528 }
5529 }
5530 // Verify netagents
5531 for (netagent_cursor = 0; netagent_cursor < NECP_MAX_NETAGENTS; netagent_cursor++) {
5532 struct necp_uuid_id_mapping *mapping = NULL;
5533 u_int32_t netagent_id = netagent_ids[netagent_cursor];
5534 if (netagent_id == 0) {
5535 break;
5536 }
5537 mapping = necp_uuid_lookup_uuid_with_service_id_locked(netagent_id);
5538 if (mapping != NULL) {
5539 u_int32_t agent_flags = 0;
5540 agent_flags = netagent_get_flags(mapping->uuid);
5541 if (agent_flags & NETAGENT_FLAG_REGISTERED) {
5542 if (agent_flags & NETAGENT_FLAG_ACTIVE) {
5543 continue;
5544 } else if ((agent_flags & NETAGENT_FLAG_VOLUNTARY) == 0) {
5545 if (agent_flags & NETAGENT_FLAG_KERNEL_ACTIVATED) {
5546 int trigger_error = 0;
5547 trigger_error = netagent_kernel_trigger(mapping->uuid);
5548 if (necp_debug > 1) {
5549 NECPLOG(LOG_DEBUG, "Socket Policy: Triggering inactive agent, error %d", trigger_error);
5550 }
5551 }
5552
5553 // Mark socket as a drop if required agent is not active
5554 inp->inp_policyresult.policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
5555 inp->inp_policyresult.policy_gencount = necp_kernel_socket_policies_gencount;
5556 inp->inp_policyresult.flowhash = flowhash;
5557 inp->inp_policyresult.results.filter_control_unit = 0;
5558 inp->inp_policyresult.results.route_rule_id = 0;
5559 inp->inp_policyresult.results.result = NECP_KERNEL_POLICY_RESULT_DROP;
5560
5561 if (necp_debug > 1) {
5562 NECPLOG(LOG_DEBUG, "Socket Policy: (BoundInterface %d Proto %d) Dropping packet because agent is not active", info.bound_interface_index, info.protocol);
5563 }
5564
5565 // Unlock
5566 lck_rw_done(&necp_kernel_policy_lock);
5567 return (NECP_KERNEL_POLICY_ID_NONE);
5568 }
5569 }
5570 }
5571 }
5572 if (matched_policy) {
5573 matched_policy_id = matched_policy->id;
5574 inp->inp_policyresult.policy_id = matched_policy->id;
5575 inp->inp_policyresult.policy_gencount = necp_kernel_socket_policies_gencount;
5576 inp->inp_policyresult.flowhash = flowhash;
5577 inp->inp_policyresult.results.filter_control_unit = filter_control_unit;
5578 inp->inp_policyresult.results.route_rule_id = route_rule_id;
5579 inp->inp_policyresult.results.result = matched_policy->result;
5580 memcpy(&inp->inp_policyresult.results.result_parameter, &matched_policy->result_parameter, sizeof(matched_policy->result_parameter));
5581
5582 if (necp_socket_is_connected(inp) &&
5583 (matched_policy->result == NECP_KERNEL_POLICY_RESULT_DROP ||
5584 (matched_policy->result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL && !necp_socket_uses_interface(inp, matched_policy->result_parameter.tunnel_interface_index)))) {
5585 if (necp_debug) {
5586 NECPLOG(LOG_DEBUG, "Marking socket in state %d as defunct", so->so_state);
5587 }
5588 sosetdefunct(current_proc(), so, SHUTDOWN_SOCKET_LEVEL_DISCONNECT_ALL, TRUE);
5589 } else if (necp_socket_is_connected(inp) &&
5590 matched_policy->result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL &&
5591 info.protocol == IPPROTO_TCP) {
5592 // Reset MSS on TCP socket if tunnel policy changes
5593 tcp_mtudisc(inp, 0);
5594 }
5595
5596 if (necp_debug > 1) {
5597 NECPLOG(LOG_DEBUG, "Socket Policy: %p (BoundInterface %d Proto %d) Policy %d Result %d Parameter %d", inp->inp_socket, info.bound_interface_index, info.protocol, matched_policy->id, matched_policy->result, matched_policy->result_parameter.tunnel_interface_index);
5598 }
5599 } else if (necp_drop_all_order > 0) {
5600 // Mark socket as a drop if set
5601 inp->inp_policyresult.policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
5602 inp->inp_policyresult.policy_gencount = necp_kernel_socket_policies_gencount;
5603 inp->inp_policyresult.flowhash = flowhash;
5604 inp->inp_policyresult.results.filter_control_unit = 0;
5605 inp->inp_policyresult.results.route_rule_id = 0;
5606 inp->inp_policyresult.results.result = NECP_KERNEL_POLICY_RESULT_DROP;
5607 } else {
5608 // Mark non-matching socket so we don't re-check it
5609 inp->inp_policyresult.policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
5610 inp->inp_policyresult.policy_gencount = necp_kernel_socket_policies_gencount;
5611 inp->inp_policyresult.flowhash = flowhash;
5612 inp->inp_policyresult.results.filter_control_unit = filter_control_unit; // We may have matched a filter, so mark it!
5613 inp->inp_policyresult.results.route_rule_id = route_rule_id; // We may have matched a route rule, so mark it!
5614 inp->inp_policyresult.results.result = NECP_KERNEL_POLICY_RESULT_NONE;
5615 }
5616
5617 // Unlock
5618 lck_rw_done(&necp_kernel_policy_lock);
5619
5620 return (matched_policy_id);
5621 }
5622
5623 static bool
5624 necp_ip_output_check_policy(struct necp_kernel_ip_output_policy *kernel_policy, necp_kernel_policy_id socket_policy_id, u_int32_t bound_interface_index, u_int32_t last_interface_index, u_int16_t protocol, union necp_sockaddr_union *local, union necp_sockaddr_union *remote)
5625 {
5626 if (!(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES)) {
5627 if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE) {
5628 u_int32_t cond_bound_interface_index = kernel_policy->cond_bound_interface ? kernel_policy->cond_bound_interface->if_index : 0;
5629 if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE) {
5630 if (bound_interface_index == cond_bound_interface_index) {
5631 // No match, matches forbidden interface
5632 return (FALSE);
5633 }
5634 } else {
5635 if (bound_interface_index != cond_bound_interface_index) {
5636 // No match, does not match required interface
5637 return (FALSE);
5638 }
5639 }
5640 } else {
5641 if (bound_interface_index != 0) {
5642 // No match, requires a non-bound packet
5643 return (FALSE);
5644 }
5645 }
5646 }
5647
5648 if (kernel_policy->condition_mask == 0) {
5649 return (TRUE);
5650 }
5651
5652 if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_POLICY_ID) {
5653 if (socket_policy_id != kernel_policy->cond_policy_id) {
5654 // No match, does not match required id
5655 return (FALSE);
5656 }
5657 }
5658
5659 if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LAST_INTERFACE) {
5660 if (last_interface_index != kernel_policy->cond_last_interface_index) {
5661 return (FALSE);
5662 }
5663 }
5664
5665 if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_PROTOCOL) {
5666 if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_PROTOCOL) {
5667 if (protocol == kernel_policy->cond_protocol) {
5668 // No match, matches forbidden protocol
5669 return (FALSE);
5670 }
5671 } else {
5672 if (protocol != kernel_policy->cond_protocol) {
5673 // No match, does not match required protocol
5674 return (FALSE);
5675 }
5676 }
5677 }
5678
5679 if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_START) {
5680 if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
5681 bool inRange = necp_is_addr_in_range((struct sockaddr *)local, (struct sockaddr *)&kernel_policy->cond_local_start, (struct sockaddr *)&kernel_policy->cond_local_end);
5682 if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
5683 if (inRange) {
5684 return (FALSE);
5685 }
5686 } else {
5687 if (!inRange) {
5688 return (FALSE);
5689 }
5690 }
5691 } else if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX) {
5692 bool inSubnet = necp_is_addr_in_subnet((struct sockaddr *)local, (struct sockaddr *)&kernel_policy->cond_local_start, kernel_policy->cond_local_prefix);
5693 if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX) {
5694 if (inSubnet) {
5695 return (FALSE);
5696 }
5697 } else {
5698 if (!inSubnet) {
5699 return (FALSE);
5700 }
5701 }
5702 }
5703 }
5704
5705 if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_START) {
5706 if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
5707 bool inRange = necp_is_addr_in_range((struct sockaddr *)remote, (struct sockaddr *)&kernel_policy->cond_remote_start, (struct sockaddr *)&kernel_policy->cond_remote_end);
5708 if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
5709 if (inRange) {
5710 return (FALSE);
5711 }
5712 } else {
5713 if (!inRange) {
5714 return (FALSE);
5715 }
5716 }
5717 } else if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX) {
5718 bool inSubnet = necp_is_addr_in_subnet((struct sockaddr *)remote, (struct sockaddr *)&kernel_policy->cond_remote_start, kernel_policy->cond_remote_prefix);
5719 if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX) {
5720 if (inSubnet) {
5721 return (FALSE);
5722 }
5723 } else {
5724 if (!inSubnet) {
5725 return (FALSE);
5726 }
5727 }
5728 }
5729 }
5730
5731 return (TRUE);
5732 }
5733
5734 static inline struct necp_kernel_ip_output_policy *
5735 necp_ip_output_find_policy_match_locked(necp_kernel_policy_id socket_policy_id, u_int32_t bound_interface_index, u_int32_t last_interface_index, u_int16_t protocol, union necp_sockaddr_union *local_addr, union necp_sockaddr_union *remote_addr)
5736 {
5737 u_int32_t skip_order = 0;
5738 u_int32_t skip_session_order = 0;
5739 int i;
5740 struct necp_kernel_ip_output_policy *matched_policy = NULL;
5741 struct necp_kernel_ip_output_policy **policy_search_array = necp_kernel_ip_output_policies_map[NECP_IP_OUTPUT_MAP_ID_TO_BUCKET(socket_policy_id)];
5742 if (policy_search_array != NULL) {
5743 for (i = 0; policy_search_array[i] != NULL; i++) {
5744 if (necp_drop_all_order != 0 && policy_search_array[i]->session_order >= necp_drop_all_order) {
5745 // We've hit a drop all rule
5746 break;
5747 }
5748 if (skip_session_order && policy_search_array[i]->session_order >= skip_session_order) {
5749 // Done skipping
5750 skip_order = 0;
5751 skip_session_order = 0;
5752 }
5753 if (skip_order) {
5754 if (policy_search_array[i]->order < skip_order) {
5755 // Skip this policy
5756 continue;
5757 } else {
5758 // Done skipping
5759 skip_order = 0;
5760 skip_session_order = 0;
5761 }
5762 } else if (skip_session_order) {
5763 // Skip this policy
5764 continue;
5765 }
5766 if (necp_ip_output_check_policy(policy_search_array[i], socket_policy_id, bound_interface_index, last_interface_index, protocol, local_addr, remote_addr)) {
5767 // Passed all tests, found a match
5768 matched_policy = policy_search_array[i];
5769
5770 if (policy_search_array[i]->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
5771 skip_order = policy_search_array[i]->result_parameter.skip_policy_order;
5772 skip_session_order = policy_search_array[i]->session_order + 1;
5773 continue;
5774 }
5775
5776 break;
5777 }
5778 }
5779 }
5780
5781 return (matched_policy);
5782 }
5783
5784 necp_kernel_policy_id
5785 necp_ip_output_find_policy_match(struct mbuf *packet, int flags, struct ip_out_args *ipoa, necp_kernel_policy_result *result, necp_kernel_policy_result_parameter *result_parameter)
5786 {
5787 struct ip *ip = NULL;
5788 int hlen = sizeof(struct ip);
5789 necp_kernel_policy_id socket_policy_id = NECP_KERNEL_POLICY_ID_NONE;
5790 necp_kernel_policy_id matched_policy_id = NECP_KERNEL_POLICY_ID_NONE;
5791 struct necp_kernel_ip_output_policy *matched_policy = NULL;
5792 u_int16_t protocol = 0;
5793 u_int32_t bound_interface_index = 0;
5794 u_int32_t last_interface_index = 0;
5795 union necp_sockaddr_union local_addr;
5796 union necp_sockaddr_union remote_addr;
5797
5798 if (result) {
5799 *result = 0;
5800 }
5801
5802 if (result_parameter) {
5803 memset(result_parameter, 0, sizeof(*result_parameter));
5804 }
5805
5806 if (packet == NULL) {
5807 return (NECP_KERNEL_POLICY_ID_NONE);
5808 }
5809
5810 socket_policy_id = necp_get_policy_id_from_packet(packet);
5811
5812 // Exit early for an empty list
5813 // Don't lock. Possible race condition, but we don't want the performance hit.
5814 if (necp_kernel_ip_output_policies_count == 0 ||
5815 ((socket_policy_id == NECP_KERNEL_POLICY_ID_NONE) && necp_kernel_ip_output_policies_non_id_count == 0)) {
5816 if (necp_drop_all_order > 0) {
5817 matched_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
5818 if (result) {
5819 if ((necp_pass_loopback > 0 &&
5820 necp_is_loopback(NULL, NULL, NULL, packet)) ||
5821 (necp_pass_keepalives > 0 &&
5822 necp_get_is_keepalive_from_packet(packet))) {
5823 *result = NECP_KERNEL_POLICY_RESULT_PASS;
5824 } else {
5825 *result = NECP_KERNEL_POLICY_RESULT_DROP;
5826 }
5827 }
5828 }
5829
5830 return (matched_policy_id);
5831 }
5832
5833 // Check for loopback exception
5834 if ((necp_pass_loopback > 0 &&
5835 necp_is_loopback(NULL, NULL, NULL, packet)) ||
5836 (necp_pass_keepalives > 0 &&
5837 necp_get_is_keepalive_from_packet(packet))) {
5838 matched_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
5839 if (result) {
5840 *result = NECP_KERNEL_POLICY_RESULT_PASS;
5841 }
5842 return (matched_policy_id);
5843 }
5844
5845 last_interface_index = necp_get_last_interface_index_from_packet(packet);
5846
5847 // Process packet to get relevant fields
5848 ip = mtod(packet, struct ip *);
5849 #ifdef _IP_VHL
5850 hlen = _IP_VHL_HL(ip->ip_vhl) << 2;
5851 #else
5852 hlen = ip->ip_hl << 2;
5853 #endif
5854
5855 protocol = ip->ip_p;
5856
5857 if ((flags & IP_OUTARGS) && (ipoa != NULL) &&
5858 (ipoa->ipoa_flags & IPOAF_BOUND_IF) &&
5859 ipoa->ipoa_boundif != IFSCOPE_NONE) {
5860 bound_interface_index = ipoa->ipoa_boundif;
5861 }
5862
5863 local_addr.sin.sin_family = AF_INET;
5864 local_addr.sin.sin_len = sizeof(struct sockaddr_in);
5865 memcpy(&local_addr.sin.sin_addr, &ip->ip_src, sizeof(ip->ip_src));
5866
5867 remote_addr.sin.sin_family = AF_INET;
5868 remote_addr.sin.sin_len = sizeof(struct sockaddr_in);
5869 memcpy(&((struct sockaddr_in *)&remote_addr)->sin_addr, &ip->ip_dst, sizeof(ip->ip_dst));
5870
5871 switch (protocol) {
5872 case IPPROTO_TCP: {
5873 struct tcphdr th;
5874 if ((int)(hlen + sizeof(th)) <= packet->m_pkthdr.len) {
5875 m_copydata(packet, hlen, sizeof(th), (u_int8_t *)&th);
5876 ((struct sockaddr_in *)&local_addr)->sin_port = th.th_sport;
5877 ((struct sockaddr_in *)&remote_addr)->sin_port = th.th_dport;
5878 }
5879 break;
5880 }
5881 case IPPROTO_UDP: {
5882 struct udphdr uh;
5883 if ((int)(hlen + sizeof(uh)) <= packet->m_pkthdr.len) {
5884 m_copydata(packet, hlen, sizeof(uh), (u_int8_t *)&uh);
5885 ((struct sockaddr_in *)&local_addr)->sin_port = uh.uh_sport;
5886 ((struct sockaddr_in *)&remote_addr)->sin_port = uh.uh_dport;
5887 }
5888 break;
5889 }
5890 default: {
5891 ((struct sockaddr_in *)&local_addr)->sin_port = 0;
5892 ((struct sockaddr_in *)&remote_addr)->sin_port = 0;
5893 break;
5894 }
5895 }
5896
5897 // Match packet to policy
5898 lck_rw_lock_shared(&necp_kernel_policy_lock);
5899 matched_policy = necp_ip_output_find_policy_match_locked(socket_policy_id, bound_interface_index, last_interface_index, protocol, &local_addr, &remote_addr);
5900 if (matched_policy) {
5901 matched_policy_id = matched_policy->id;
5902 if (result) {
5903 *result = matched_policy->result;
5904 }
5905
5906 if (result_parameter) {
5907 memcpy(result_parameter, &matched_policy->result_parameter, sizeof(matched_policy->result_parameter));
5908 }
5909
5910 if (necp_debug > 1) {
5911 NECPLOG(LOG_DEBUG, "IP Output: (ID %d BoundInterface %d LastInterface %d Proto %d) Policy %d Result %d Parameter %d", socket_policy_id, bound_interface_index, last_interface_index, protocol, matched_policy->id, matched_policy->result, matched_policy->result_parameter.tunnel_interface_index);
5912 }
5913 } else if (necp_drop_all_order > 0) {
5914 matched_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
5915 if (result) {
5916 *result = NECP_KERNEL_POLICY_RESULT_DROP;
5917 }
5918 }
5919
5920 lck_rw_done(&necp_kernel_policy_lock);
5921
5922 return (matched_policy_id);
5923 }
5924
5925 necp_kernel_policy_id
5926 necp_ip6_output_find_policy_match(struct mbuf *packet, int flags, struct ip6_out_args *ip6oa, necp_kernel_policy_result *result, necp_kernel_policy_result_parameter *result_parameter)
5927 {
5928 struct ip6_hdr *ip6 = NULL;
5929 int next = -1;
5930 int offset = 0;
5931 necp_kernel_policy_id socket_policy_id = NECP_KERNEL_POLICY_ID_NONE;
5932 necp_kernel_policy_id matched_policy_id = NECP_KERNEL_POLICY_ID_NONE;
5933 struct necp_kernel_ip_output_policy *matched_policy = NULL;
5934 u_int16_t protocol = 0;
5935 u_int32_t bound_interface_index = 0;
5936 u_int32_t last_interface_index = 0;
5937 union necp_sockaddr_union local_addr;
5938 union necp_sockaddr_union remote_addr;
5939
5940 if (result) {
5941 *result = 0;
5942 }
5943
5944 if (result_parameter) {
5945 memset(result_parameter, 0, sizeof(*result_parameter));
5946 }
5947
5948 if (packet == NULL) {
5949 return (NECP_KERNEL_POLICY_ID_NONE);
5950 }
5951
5952 socket_policy_id = necp_get_policy_id_from_packet(packet);
5953
5954 // Exit early for an empty list
5955 // Don't lock. Possible race condition, but we don't want the performance hit.
5956 if (necp_kernel_ip_output_policies_count == 0 ||
5957 ((socket_policy_id == NECP_KERNEL_POLICY_ID_NONE) && necp_kernel_ip_output_policies_non_id_count == 0)) {
5958 if (necp_drop_all_order > 0) {
5959 matched_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
5960 if (result) {
5961 if ((necp_pass_loopback > 0 &&
5962 necp_is_loopback(NULL, NULL, NULL, packet)) ||
5963 (necp_pass_keepalives > 0 &&
5964 necp_get_is_keepalive_from_packet(packet))) {
5965 *result = NECP_KERNEL_POLICY_RESULT_PASS;
5966 } else {
5967 *result = NECP_KERNEL_POLICY_RESULT_DROP;
5968 }
5969 }
5970 }
5971
5972 return (matched_policy_id);
5973 }
5974
5975 // Check for loopback exception
5976 if ((necp_pass_loopback > 0 &&
5977 necp_is_loopback(NULL, NULL, NULL, packet)) ||
5978 (necp_pass_keepalives > 0 &&
5979 necp_get_is_keepalive_from_packet(packet))) {
5980 matched_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
5981 if (result) {
5982 *result = NECP_KERNEL_POLICY_RESULT_PASS;
5983 }
5984 return (matched_policy_id);
5985 }
5986
5987 last_interface_index = necp_get_last_interface_index_from_packet(packet);
5988
5989 // Process packet to get relevant fields
5990 ip6 = mtod(packet, struct ip6_hdr *);
5991
5992 if ((flags & IPV6_OUTARGS) && (ip6oa != NULL) &&
5993 (ip6oa->ip6oa_flags & IP6OAF_BOUND_IF) &&
5994 ip6oa->ip6oa_boundif != IFSCOPE_NONE) {
5995 bound_interface_index = ip6oa->ip6oa_boundif;
5996 }
5997
5998 ((struct sockaddr_in6 *)&local_addr)->sin6_family = AF_INET6;
5999 ((struct sockaddr_in6 *)&local_addr)->sin6_len = sizeof(struct sockaddr_in6);
6000 memcpy(&((struct sockaddr_in6 *)&local_addr)->sin6_addr, &ip6->ip6_src, sizeof(ip6->ip6_src));
6001
6002 ((struct sockaddr_in6 *)&remote_addr)->sin6_family = AF_INET6;
6003 ((struct sockaddr_in6 *)&remote_addr)->sin6_len = sizeof(struct sockaddr_in6);
6004 memcpy(&((struct sockaddr_in6 *)&remote_addr)->sin6_addr, &ip6->ip6_dst, sizeof(ip6->ip6_dst));
6005
6006 offset = ip6_lasthdr(packet, 0, IPPROTO_IPV6, &next);
6007 if (offset >= 0 && packet->m_pkthdr.len >= offset) {
6008 protocol = next;
6009 switch (protocol) {
6010 case IPPROTO_TCP: {
6011 struct tcphdr th;
6012 if ((int)(offset + sizeof(th)) <= packet->m_pkthdr.len) {
6013 m_copydata(packet, offset, sizeof(th), (u_int8_t *)&th);
6014 ((struct sockaddr_in6 *)&local_addr)->sin6_port = th.th_sport;
6015 ((struct sockaddr_in6 *)&remote_addr)->sin6_port = th.th_dport;
6016 }
6017 break;
6018 }
6019 case IPPROTO_UDP: {
6020 struct udphdr uh;
6021 if ((int)(offset + sizeof(uh)) <= packet->m_pkthdr.len) {
6022 m_copydata(packet, offset, sizeof(uh), (u_int8_t *)&uh);
6023 ((struct sockaddr_in6 *)&local_addr)->sin6_port = uh.uh_sport;
6024 ((struct sockaddr_in6 *)&remote_addr)->sin6_port = uh.uh_dport;
6025 }
6026 break;
6027 }
6028 default: {
6029 ((struct sockaddr_in6 *)&local_addr)->sin6_port = 0;
6030 ((struct sockaddr_in6 *)&remote_addr)->sin6_port = 0;
6031 break;
6032 }
6033 }
6034 }
6035
6036 // Match packet to policy
6037 lck_rw_lock_shared(&necp_kernel_policy_lock);
6038 matched_policy = necp_ip_output_find_policy_match_locked(socket_policy_id, bound_interface_index, last_interface_index, protocol, &local_addr, &remote_addr);
6039 if (matched_policy) {
6040 matched_policy_id = matched_policy->id;
6041 if (result) {
6042 *result = matched_policy->result;
6043 }
6044
6045 if (result_parameter) {
6046 memcpy(result_parameter, &matched_policy->result_parameter, sizeof(matched_policy->result_parameter));
6047 }
6048
6049 if (necp_debug > 1) {
6050 NECPLOG(LOG_DEBUG, "IP6 Output: (ID %d BoundInterface %d LastInterface %d Proto %d) Policy %d Result %d Parameter %d", socket_policy_id, bound_interface_index, last_interface_index, protocol, matched_policy->id, matched_policy->result, matched_policy->result_parameter.tunnel_interface_index);
6051 }
6052 } else if (necp_drop_all_order > 0) {
6053 matched_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
6054 if (result) {
6055 *result = NECP_KERNEL_POLICY_RESULT_DROP;
6056 }
6057 }
6058
6059 lck_rw_done(&necp_kernel_policy_lock);
6060
6061 return (matched_policy_id);
6062 }
6063
6064 // Utilities
6065 static bool
6066 necp_is_addr_in_range(struct sockaddr *addr, struct sockaddr *range_start, struct sockaddr *range_end)
6067 {
6068 int cmp = 0;
6069
6070 if (addr == NULL || range_start == NULL || range_end == NULL) {
6071 return (FALSE);
6072 }
6073
6074 /* Must be greater than or equal to start */
6075 cmp = necp_addr_compare(addr, range_start, 1);
6076 if (cmp != 0 && cmp != 1) {
6077 return (FALSE);
6078 }
6079
6080 /* Must be less than or equal to end */
6081 cmp = necp_addr_compare(addr, range_end, 1);
6082 if (cmp != 0 && cmp != -1) {
6083 return (FALSE);
6084 }
6085
6086 return (TRUE);
6087 }
6088
6089 static bool
6090 necp_is_range_in_range(struct sockaddr *inner_range_start, struct sockaddr *inner_range_end, struct sockaddr *range_start, struct sockaddr *range_end)
6091 {
6092 int cmp = 0;
6093
6094 if (inner_range_start == NULL || inner_range_end == NULL || range_start == NULL || range_end == NULL) {
6095 return (FALSE);
6096 }
6097
6098 /* Must be greater than or equal to start */
6099 cmp = necp_addr_compare(inner_range_start, range_start, 1);
6100 if (cmp != 0 && cmp != 1) {
6101 return (FALSE);
6102 }
6103
6104 /* Must be less than or equal to end */
6105 cmp = necp_addr_compare(inner_range_end, range_end, 1);
6106 if (cmp != 0 && cmp != -1) {
6107 return (FALSE);
6108 }
6109
6110 return (TRUE);
6111 }
6112
6113 static bool
6114 necp_is_addr_in_subnet(struct sockaddr *addr, struct sockaddr *subnet_addr, u_int8_t subnet_prefix)
6115 {
6116 if (addr == NULL || subnet_addr == NULL) {
6117 return (FALSE);
6118 }
6119
6120 if (addr->sa_family != subnet_addr->sa_family || addr->sa_len != subnet_addr->sa_len) {
6121 return (FALSE);
6122 }
6123
6124 switch (addr->sa_family) {
6125 case AF_INET: {
6126 if (satosin(subnet_addr)->sin_port != 0 &&
6127 satosin(addr)->sin_port != satosin(subnet_addr)->sin_port) {
6128 return (FALSE);
6129 }
6130 return (necp_buffer_compare_with_bit_prefix((u_int8_t *)&satosin(addr)->sin_addr, (u_int8_t *)&satosin(subnet_addr)->sin_addr, subnet_prefix));
6131 }
6132 case AF_INET6: {
6133 if (satosin6(subnet_addr)->sin6_port != 0 &&
6134 satosin6(addr)->sin6_port != satosin6(subnet_addr)->sin6_port) {
6135 return (FALSE);
6136 }
6137 if (satosin6(addr)->sin6_scope_id &&
6138 satosin6(subnet_addr)->sin6_scope_id &&
6139 satosin6(addr)->sin6_scope_id != satosin6(subnet_addr)->sin6_scope_id) {
6140 return (FALSE);
6141 }
6142 return (necp_buffer_compare_with_bit_prefix((u_int8_t *)&satosin6(addr)->sin6_addr, (u_int8_t *)&satosin6(subnet_addr)->sin6_addr, subnet_prefix));
6143 }
6144 default: {
6145 return (FALSE);
6146 }
6147 }
6148
6149 return (FALSE);
6150 }
6151
6152 /*
6153 * Return values:
6154 * -1: sa1 < sa2
6155 * 0: sa1 == sa2
6156 * 1: sa1 > sa2
6157 * 2: Not comparable or error
6158 */
6159 static int
6160 necp_addr_compare(struct sockaddr *sa1, struct sockaddr *sa2, int check_port)
6161 {
6162 int result = 0;
6163 int port_result = 0;
6164
6165 if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len) {
6166 return (2);
6167 }
6168
6169 if (sa1->sa_len == 0) {
6170 return (0);
6171 }
6172
6173 switch (sa1->sa_family) {
6174 case AF_INET: {
6175 if (sa1->sa_len != sizeof(struct sockaddr_in)) {
6176 return (2);
6177 }
6178
6179 result = memcmp(&satosin(sa1)->sin_addr.s_addr, &satosin(sa2)->sin_addr.s_addr, sizeof(satosin(sa1)->sin_addr.s_addr));
6180
6181 if (check_port) {
6182 if (satosin(sa1)->sin_port < satosin(sa2)->sin_port) {
6183 port_result = -1;
6184 } else if (satosin(sa1)->sin_port > satosin(sa2)->sin_port) {
6185 port_result = 1;
6186 }
6187
6188 if (result == 0) {
6189 result = port_result;
6190 } else if ((result > 0 && port_result < 0) || (result < 0 && port_result > 0)) {
6191 return (2);
6192 }
6193 }
6194
6195 break;
6196 }
6197 case AF_INET6: {
6198 if (sa1->sa_len != sizeof(struct sockaddr_in6)) {
6199 return (2);
6200 }
6201
6202 if (satosin6(sa1)->sin6_scope_id != satosin6(sa2)->sin6_scope_id) {
6203 return (2);
6204 }
6205
6206 result = memcmp(&satosin6(sa1)->sin6_addr.s6_addr[0], &satosin6(sa2)->sin6_addr.s6_addr[0], sizeof(struct in6_addr));
6207
6208 if (check_port) {
6209 if (satosin6(sa1)->sin6_port < satosin6(sa2)->sin6_port) {
6210 port_result = -1;
6211 } else if (satosin6(sa1)->sin6_port > satosin6(sa2)->sin6_port) {
6212 port_result = 1;
6213 }
6214
6215 if (result == 0) {
6216 result = port_result;
6217 } else if ((result > 0 && port_result < 0) || (result < 0 && port_result > 0)) {
6218 return (2);
6219 }
6220 }
6221
6222 break;
6223 }
6224 default: {
6225 result = memcmp(sa1, sa2, sa1->sa_len);
6226 break;
6227 }
6228 }
6229
6230 if (result < 0) {
6231 result = (-1);
6232 } else if (result > 0) {
6233 result = (1);
6234 }
6235
6236 return (result);
6237 }
6238
6239 static bool
6240 necp_buffer_compare_with_bit_prefix(u_int8_t *p1, u_int8_t *p2, u_int32_t bits)
6241 {
6242 u_int8_t mask;
6243
6244 /* Handle null pointers */
6245 if (p1 == NULL || p2 == NULL) {
6246 return (p1 == p2);
6247 }
6248
6249 while (bits >= 8) {
6250 if (*p1++ != *p2++) {
6251 return (FALSE);
6252 }
6253 bits -= 8;
6254 }
6255
6256 if (bits > 0) {
6257 mask = ~((1<<(8-bits))-1);
6258 if ((*p1 & mask) != (*p2 & mask)) {
6259 return (FALSE);
6260 }
6261 }
6262 return (TRUE);
6263 }
6264
6265 // Socket operations
6266 #define NECP_MAX_SOCKET_ATTRIBUTE_STRING_LENGTH 253
6267
6268 static bool
6269 necp_set_socket_attribute(u_int8_t *buffer, size_t buffer_length, u_int8_t type, char **buffer_p)
6270 {
6271 int error = 0;
6272 int cursor = 0;
6273 size_t string_size = 0;
6274 char *local_string = NULL;
6275 u_int8_t *value = NULL;
6276
6277 cursor = necp_buffer_find_tlv(buffer, buffer_length, 0, type, 0);
6278 if (cursor < 0) {
6279 // This will clear out the parameter
6280 goto done;
6281 }
6282
6283 string_size = necp_buffer_get_tlv_length(buffer, cursor);
6284 if (string_size == 0 || string_size > NECP_MAX_SOCKET_ATTRIBUTE_STRING_LENGTH) {
6285 // This will clear out the parameter
6286 goto done;
6287 }
6288
6289 MALLOC(local_string, char *, string_size + 1, M_NECP, M_WAITOK);
6290 if (local_string == NULL) {
6291 NECPLOG(LOG_ERR, "Failed to allocate a socket attribute buffer (size %d)", string_size);
6292 goto fail;
6293 }
6294
6295 value = necp_buffer_get_tlv_value(buffer, cursor, NULL);
6296 if (value == NULL) {
6297 NECPLOG0(LOG_ERR, "Failed to get socket attribute");
6298 goto fail;
6299 }
6300
6301 memcpy(local_string, value, string_size);
6302 local_string[string_size] = 0;
6303
6304 done:
6305 if (*buffer_p != NULL) {
6306 FREE(*buffer_p, M_NECP);
6307 *buffer_p = NULL;
6308 }
6309
6310 *buffer_p = local_string;
6311 return (0);
6312 fail:
6313 if (local_string != NULL) {
6314 FREE(local_string, M_NECP);
6315 }
6316 return (error);
6317 }
6318
6319 errno_t
6320 necp_set_socket_attributes(struct socket *so, struct sockopt *sopt)
6321 {
6322 int error = 0;
6323 u_int8_t *buffer = NULL;
6324 struct inpcb *inp = NULL;
6325
6326 if ((SOCK_DOM(so) != PF_INET
6327 #if INET6
6328 && SOCK_DOM(so) != PF_INET6
6329 #endif
6330 )) {
6331 error = EINVAL;
6332 goto done;
6333 }
6334
6335 inp = sotoinpcb(so);
6336
6337 size_t valsize = sopt->sopt_valsize;
6338 if (valsize == 0 ||
6339 valsize > ((sizeof(u_int8_t) + sizeof(u_int32_t) + NECP_MAX_SOCKET_ATTRIBUTE_STRING_LENGTH) * 2)) {
6340 goto done;
6341 }
6342
6343 MALLOC(buffer, u_int8_t *, valsize, M_NECP, M_WAITOK);
6344 if (buffer == NULL) {
6345 goto done;
6346 }
6347
6348 error = sooptcopyin(sopt, buffer, valsize, 0);
6349 if (error) {
6350 goto done;
6351 }
6352
6353 error = necp_set_socket_attribute(buffer, valsize, NECP_TLV_ATTRIBUTE_DOMAIN, &inp->inp_necp_attributes.inp_domain);
6354 if (error) {
6355 NECPLOG0(LOG_ERR, "Could not set domain TLV for socket attributes");
6356 goto done;
6357 }
6358
6359 error = necp_set_socket_attribute(buffer, valsize, NECP_TLV_ATTRIBUTE_ACCOUNT, &inp->inp_necp_attributes.inp_account);
6360 if (error) {
6361 NECPLOG0(LOG_ERR, "Could not set account TLV for socket attributes");
6362 goto done;
6363 }
6364
6365 if (necp_debug) {
6366 NECPLOG(LOG_DEBUG, "Set on socket: Domain %s, Account %s", inp->inp_necp_attributes.inp_domain, inp->inp_necp_attributes.inp_account);
6367 }
6368 done:
6369 if (buffer != NULL) {
6370 FREE(buffer, M_NECP);
6371 }
6372
6373 return (error);
6374 }
6375
6376 errno_t
6377 necp_get_socket_attributes(struct socket *so, struct sockopt *sopt)
6378 {
6379 int error = 0;
6380 u_int8_t *buffer = NULL;
6381 u_int8_t *cursor = NULL;
6382 size_t valsize = 0;
6383 struct inpcb *inp = sotoinpcb(so);
6384
6385 if (inp->inp_necp_attributes.inp_domain != NULL) {
6386 valsize += sizeof(u_int8_t) + sizeof(u_int32_t) + strlen(inp->inp_necp_attributes.inp_domain);
6387 }
6388 if (inp->inp_necp_attributes.inp_account != NULL) {
6389 valsize += sizeof(u_int8_t) + sizeof(u_int32_t) + strlen(inp->inp_necp_attributes.inp_account);
6390 }
6391 if (valsize == 0) {
6392 goto done;
6393 }
6394
6395 MALLOC(buffer, u_int8_t *, valsize, M_NECP, M_WAITOK);
6396 if (buffer == NULL) {
6397 goto done;
6398 }
6399
6400 cursor = buffer;
6401 if (inp->inp_necp_attributes.inp_domain != NULL) {
6402 cursor = necp_buffer_write_tlv(cursor, NECP_TLV_ATTRIBUTE_DOMAIN, strlen(inp->inp_necp_attributes.inp_domain), inp->inp_necp_attributes.inp_domain);
6403 }
6404
6405 if (inp->inp_necp_attributes.inp_account != NULL) {
6406 cursor = necp_buffer_write_tlv(cursor, NECP_TLV_ATTRIBUTE_ACCOUNT, strlen(inp->inp_necp_attributes.inp_account), inp->inp_necp_attributes.inp_account);
6407 }
6408
6409 error = sooptcopyout(sopt, buffer, valsize);
6410 if (error) {
6411 goto done;
6412 }
6413 done:
6414 if (buffer != NULL) {
6415 FREE(buffer, M_NECP);
6416 }
6417
6418 return (error);
6419 }
6420
6421 static bool
6422 necp_route_is_allowed_inner(struct rtentry *route, struct ifnet *ifp, u_int32_t route_rule_id, bool *cellular_denied)
6423 {
6424 bool default_is_allowed = TRUE;
6425 u_int8_t type_aggregate_action = NECP_ROUTE_RULE_NONE;
6426 int exception_index = 0;
6427 struct ifnet *delegated_ifp = NULL;
6428 struct necp_route_rule *route_rule = NULL;
6429
6430 route_rule = necp_lookup_route_rule_locked(&necp_route_rules, route_rule_id);
6431 if (route_rule == NULL) {
6432 return (TRUE);
6433 }
6434
6435 default_is_allowed = (route_rule->default_action == NECP_ROUTE_RULE_DENY_INTERFACE) ? FALSE : TRUE;
6436 if (ifp == NULL) {
6437 ifp = route->rt_ifp;
6438 }
6439 if (ifp == NULL) {
6440 if (necp_debug > 1 && !default_is_allowed) {
6441 NECPLOG(LOG_DEBUG, "Route Allowed: No interface for route, using default for Rule %d Allowed %d", route_rule_id, default_is_allowed);
6442 }
6443 return (default_is_allowed);
6444 }
6445
6446 delegated_ifp = ifp->if_delegated.ifp;
6447 for (exception_index = 0; exception_index < MAX_ROUTE_RULE_INTERFACES; exception_index++) {
6448 if (route_rule->exception_if_indices[exception_index] == 0) {
6449 break;
6450 }
6451 if (route_rule->exception_if_indices[exception_index] == ifp->if_index ||
6452 (delegated_ifp != NULL && route_rule->exception_if_indices[exception_index] == delegated_ifp->if_index)) {
6453 if (necp_debug > 1) {
6454 NECPLOG(LOG_DEBUG, "Route Allowed: Interface match %d for Rule %d Allowed %d", route_rule->exception_if_indices[exception_index], route_rule_id, ((route_rule->exception_if_actions[exception_index] == NECP_ROUTE_RULE_DENY_INTERFACE) ? FALSE : TRUE));
6455 }
6456 return ((route_rule->exception_if_actions[exception_index] == NECP_ROUTE_RULE_DENY_INTERFACE) ? FALSE : TRUE);
6457 }
6458 }
6459
6460 if (route_rule->cellular_action != NECP_ROUTE_RULE_NONE &&
6461 IFNET_IS_CELLULAR(ifp)) {
6462 if (cellular_denied != NULL) {
6463 // Let clients know that cellular was blocked
6464 *cellular_denied = TRUE;
6465 }
6466 if (type_aggregate_action == NECP_ROUTE_RULE_NONE ||
6467 (type_aggregate_action == NECP_ROUTE_RULE_ALLOW_INTERFACE &&
6468 route_rule->cellular_action == NECP_ROUTE_RULE_DENY_INTERFACE)) {
6469 // Deny wins if there is a conflict
6470 type_aggregate_action = route_rule->cellular_action;
6471 }
6472 }
6473
6474 if (route_rule->wifi_action != NECP_ROUTE_RULE_NONE &&
6475 IFNET_IS_WIFI(ifp)) {
6476 if (type_aggregate_action == NECP_ROUTE_RULE_NONE ||
6477 (type_aggregate_action == NECP_ROUTE_RULE_ALLOW_INTERFACE &&
6478 route_rule->wifi_action == NECP_ROUTE_RULE_DENY_INTERFACE)) {
6479 // Deny wins if there is a conflict
6480 type_aggregate_action = route_rule->wifi_action;
6481 }
6482 }
6483
6484 if (route_rule->wired_action != NECP_ROUTE_RULE_NONE &&
6485 IFNET_IS_WIRED(ifp)) {
6486 if (type_aggregate_action == NECP_ROUTE_RULE_NONE ||
6487 (type_aggregate_action == NECP_ROUTE_RULE_ALLOW_INTERFACE &&
6488 route_rule->wired_action == NECP_ROUTE_RULE_DENY_INTERFACE)) {
6489 // Deny wins if there is a conflict
6490 type_aggregate_action = route_rule->wired_action;
6491 }
6492 }
6493
6494 if (route_rule->expensive_action != NECP_ROUTE_RULE_NONE &&
6495 IFNET_IS_EXPENSIVE(ifp)) {
6496 if (type_aggregate_action == NECP_ROUTE_RULE_NONE ||
6497 (type_aggregate_action == NECP_ROUTE_RULE_ALLOW_INTERFACE &&
6498 route_rule->expensive_action == NECP_ROUTE_RULE_DENY_INTERFACE)) {
6499 // Deny wins if there is a conflict
6500 type_aggregate_action = route_rule->expensive_action;
6501 }
6502 }
6503
6504 if (type_aggregate_action != NECP_ROUTE_RULE_NONE) {
6505 if (necp_debug > 1) {
6506 NECPLOG(LOG_DEBUG, "Route Allowed: C:%d WF:%d W:%d E:%d for Rule %d Allowed %d", route_rule->cellular_action, route_rule->wifi_action, route_rule->wired_action, route_rule->expensive_action, route_rule_id, ((type_aggregate_action == NECP_ROUTE_RULE_DENY_INTERFACE) ? FALSE : TRUE));
6507 }
6508 return ((type_aggregate_action == NECP_ROUTE_RULE_DENY_INTERFACE) ? FALSE : TRUE);
6509 }
6510
6511 if (necp_debug > 1 && !default_is_allowed) {
6512 NECPLOG(LOG_DEBUG, "Route Allowed: Using default for Rule %d Allowed %d", route_rule_id, default_is_allowed);
6513 }
6514 return (default_is_allowed);
6515 }
6516
6517 static bool
6518 necp_route_is_allowed(struct rtentry *route, struct ifnet *interface, u_int32_t route_rule_id, bool *cellular_denied)
6519 {
6520 if ((route == NULL && interface == NULL) || route_rule_id == 0) {
6521 if (necp_debug > 1) {
6522 NECPLOG(LOG_DEBUG, "Route Allowed: no route or interface, Rule %d Allowed %d", route_rule_id, TRUE);
6523 }
6524 return (TRUE);
6525 }
6526
6527 if (ROUTE_RULE_IS_AGGREGATE(route_rule_id)) {
6528 struct necp_aggregate_route_rule *aggregate_route_rule = necp_lookup_aggregate_route_rule_locked(route_rule_id);
6529 if (aggregate_route_rule != NULL) {
6530 int index = 0;
6531 for (index = 0; index < MAX_AGGREGATE_ROUTE_RULES; index++) {
6532 u_int32_t sub_route_rule_id = aggregate_route_rule->rule_ids[index];
6533 if (sub_route_rule_id == 0) {
6534 break;
6535 }
6536 if (!necp_route_is_allowed_inner(route, interface, sub_route_rule_id, cellular_denied)) {
6537 return (FALSE);
6538 }
6539 }
6540 }
6541 } else {
6542 return (necp_route_is_allowed_inner(route, interface, route_rule_id, cellular_denied));
6543 }
6544
6545 return (TRUE);
6546 }
6547
6548 bool
6549 necp_packet_is_allowed_over_interface(struct mbuf *packet, struct ifnet *interface)
6550 {
6551 bool is_allowed = TRUE;
6552 u_int32_t route_rule_id = necp_get_route_rule_id_from_packet(packet);
6553 if (route_rule_id != 0 &&
6554 interface != NULL) {
6555 lck_rw_lock_shared(&necp_kernel_policy_lock);
6556 is_allowed = necp_route_is_allowed(NULL, interface, necp_get_route_rule_id_from_packet(packet), NULL);
6557 lck_rw_done(&necp_kernel_policy_lock);
6558 }
6559 return (is_allowed);
6560 }
6561
6562 static bool
6563 necp_netagents_allow_traffic(u_int32_t *netagent_ids, size_t netagent_id_count)
6564 {
6565 size_t netagent_cursor;
6566 for (netagent_cursor = 0; netagent_cursor < netagent_id_count; netagent_cursor++) {
6567 struct necp_uuid_id_mapping *mapping = NULL;
6568 u_int32_t netagent_id = netagent_ids[netagent_cursor];
6569 if (netagent_id == 0) {
6570 break;
6571 }
6572 mapping = necp_uuid_lookup_uuid_with_service_id_locked(netagent_id);
6573 if (mapping != NULL) {
6574 u_int32_t agent_flags = 0;
6575 agent_flags = netagent_get_flags(mapping->uuid);
6576 if (agent_flags & NETAGENT_FLAG_REGISTERED) {
6577 if (agent_flags & NETAGENT_FLAG_ACTIVE) {
6578 continue;
6579 } else if ((agent_flags & NETAGENT_FLAG_VOLUNTARY) == 0) {
6580 return (FALSE);
6581 }
6582 }
6583 }
6584 }
6585 return (TRUE);
6586 }
6587
6588 static bool
6589 necp_socket_is_allowed_to_send_recv_internal(struct inpcb *inp, struct sockaddr *override_local_addr, struct sockaddr *override_remote_addr, ifnet_t interface, necp_kernel_policy_id *return_policy_id, u_int32_t *return_route_rule_id)
6590 {
6591 u_int32_t verifyifindex = interface ? interface->if_index : 0;
6592 bool allowed_to_receive = TRUE;
6593 struct necp_socket_info info;
6594 u_int32_t flowhash = 0;
6595 necp_kernel_policy_result service_action = 0;
6596 necp_kernel_policy_service service = { 0, 0 };
6597 u_int32_t route_rule_id = 0;
6598 struct rtentry *route = NULL;
6599 bool cellular_denied = FALSE;
6600
6601 u_int32_t netagent_ids[NECP_MAX_NETAGENTS];
6602 memset(&netagent_ids, 0, sizeof(netagent_ids));
6603
6604 if (return_policy_id) {
6605 *return_policy_id = NECP_KERNEL_POLICY_ID_NONE;
6606 }
6607 if (return_route_rule_id) {
6608 *return_route_rule_id = 0;
6609 }
6610
6611 if (inp == NULL) {
6612 goto done;
6613 }
6614
6615 route = inp->inp_route.ro_rt;
6616
6617 // Don't lock. Possible race condition, but we don't want the performance hit.
6618 if (necp_kernel_socket_policies_count == 0 ||
6619 (!(inp->inp_flags2 & INP2_WANT_APP_POLICY) && necp_kernel_socket_policies_non_app_count == 0)) {
6620 if (necp_drop_all_order > 0) {
6621 if (necp_pass_loopback > 0 &&
6622 necp_is_loopback(override_local_addr, override_remote_addr, inp, NULL)) {
6623 allowed_to_receive = TRUE;
6624 } else {
6625 allowed_to_receive = FALSE;
6626 }
6627 }
6628 goto done;
6629 }
6630
6631 // If this socket is connected, or we are not taking addresses into account, try to reuse last result
6632 if ((necp_socket_is_connected(inp) || (override_local_addr == NULL && override_remote_addr == NULL)) && inp->inp_policyresult.policy_id != NECP_KERNEL_POLICY_ID_NONE) {
6633 bool policies_have_changed = FALSE;
6634 bool route_allowed = TRUE;
6635 lck_rw_lock_shared(&necp_kernel_policy_lock);
6636 if (inp->inp_policyresult.policy_gencount != necp_kernel_socket_policies_gencount) {
6637 policies_have_changed = TRUE;
6638 } else {
6639 if (inp->inp_policyresult.results.route_rule_id != 0 &&
6640 !necp_route_is_allowed(route, interface, inp->inp_policyresult.results.route_rule_id, &cellular_denied)) {
6641 route_allowed = FALSE;
6642 }
6643 }
6644 lck_rw_done(&necp_kernel_policy_lock);
6645
6646 if (!policies_have_changed) {
6647 if (!route_allowed ||
6648 inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_DROP ||
6649 inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT ||
6650 (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL && interface &&
6651 inp->inp_policyresult.results.result_parameter.tunnel_interface_index != verifyifindex)) {
6652 allowed_to_receive = FALSE;
6653 } else {
6654 if (return_policy_id) {
6655 *return_policy_id = inp->inp_policyresult.policy_id;
6656 }
6657 if (return_route_rule_id) {
6658 *return_route_rule_id = inp->inp_policyresult.results.route_rule_id;
6659 }
6660 }
6661 goto done;
6662 }
6663 }
6664
6665 // Check for loopback exception
6666 if (necp_pass_loopback > 0 &&
6667 necp_is_loopback(override_local_addr, override_remote_addr, inp, NULL)) {
6668 allowed_to_receive = TRUE;
6669 goto done;
6670 }
6671
6672 // Actually calculate policy result
6673 lck_rw_lock_shared(&necp_kernel_policy_lock);
6674 necp_socket_fillout_info_locked(inp, override_local_addr, override_remote_addr, 0, &info);
6675
6676 flowhash = necp_socket_calc_flowhash_locked(&info);
6677 if (inp->inp_policyresult.policy_id != NECP_KERNEL_POLICY_ID_NONE &&
6678 inp->inp_policyresult.policy_gencount == necp_kernel_socket_policies_gencount &&
6679 inp->inp_policyresult.flowhash == flowhash) {
6680 if (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_DROP ||
6681 inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT ||
6682 (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL && interface &&
6683 inp->inp_policyresult.results.result_parameter.tunnel_interface_index != verifyifindex) ||
6684 (inp->inp_policyresult.results.route_rule_id != 0 &&
6685 !necp_route_is_allowed(route, interface, inp->inp_policyresult.results.route_rule_id, &cellular_denied))) {
6686 allowed_to_receive = FALSE;
6687 } else {
6688 if (return_policy_id) {
6689 *return_policy_id = inp->inp_policyresult.policy_id;
6690 }
6691 if (return_route_rule_id) {
6692 *return_route_rule_id = inp->inp_policyresult.results.route_rule_id;
6693 }
6694 }
6695 lck_rw_done(&necp_kernel_policy_lock);
6696 goto done;
6697 }
6698
6699 struct necp_kernel_socket_policy *matched_policy = necp_socket_find_policy_match_with_info_locked(necp_kernel_socket_policies_map[NECP_SOCKET_MAP_APP_ID_TO_BUCKET(info.application_id)], &info, NULL, &route_rule_id, &service_action, &service, netagent_ids, NECP_MAX_NETAGENTS);
6700 if (matched_policy != NULL) {
6701 if (matched_policy->result == NECP_KERNEL_POLICY_RESULT_DROP ||
6702 matched_policy->result == NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT ||
6703 (matched_policy->result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL && interface &&
6704 matched_policy->result_parameter.tunnel_interface_index != verifyifindex) ||
6705 ((service_action == NECP_KERNEL_POLICY_RESULT_TRIGGER_SCOPED ||
6706 service_action == NECP_KERNEL_POLICY_RESULT_NO_TRIGGER_SCOPED) &&
6707 service.identifier != 0 && service.identifier != NECP_NULL_SERVICE_ID) ||
6708 (route_rule_id != 0 &&
6709 !necp_route_is_allowed(route, interface, route_rule_id, &cellular_denied)) ||
6710 !necp_netagents_allow_traffic(netagent_ids, NECP_MAX_NETAGENTS)) {
6711 allowed_to_receive = FALSE;
6712 } else {
6713 if (return_policy_id) {
6714 *return_policy_id = matched_policy->id;
6715 }
6716 if (return_route_rule_id) {
6717 *return_route_rule_id = route_rule_id;
6718 }
6719 }
6720 lck_rw_done(&necp_kernel_policy_lock);
6721
6722 if (necp_debug > 1 && matched_policy->id != inp->inp_policyresult.policy_id) {
6723 NECPLOG(LOG_DEBUG, "Socket Send/Recv Policy: Policy %d Allowed %d", return_policy_id ? *return_policy_id : 0, allowed_to_receive);
6724 }
6725 goto done;
6726 } else if (necp_drop_all_order > 0) {
6727 allowed_to_receive = FALSE;
6728 }
6729
6730 lck_rw_done(&necp_kernel_policy_lock);
6731
6732 done:
6733 if (!allowed_to_receive && cellular_denied) {
6734 soevent(inp->inp_socket, (SO_FILT_HINT_LOCKED | SO_FILT_HINT_IFDENIED));
6735 }
6736
6737 return (allowed_to_receive);
6738 }
6739
6740 bool
6741 necp_socket_is_allowed_to_send_recv_v4(struct inpcb *inp, u_int16_t local_port, u_int16_t remote_port, struct in_addr *local_addr, struct in_addr *remote_addr, ifnet_t interface, necp_kernel_policy_id *return_policy_id, u_int32_t *return_route_rule_id)
6742 {
6743 struct sockaddr_in local;
6744 struct sockaddr_in remote;
6745 local.sin_family = remote.sin_family = AF_INET;
6746 local.sin_len = remote.sin_len = sizeof(struct sockaddr_in);
6747 local.sin_port = local_port;
6748 remote.sin_port = remote_port;
6749 memcpy(&local.sin_addr, local_addr, sizeof(local.sin_addr));
6750 memcpy(&remote.sin_addr, remote_addr, sizeof(remote.sin_addr));
6751
6752 return (necp_socket_is_allowed_to_send_recv_internal(inp, (struct sockaddr *)&local, (struct sockaddr *)&remote, interface, return_policy_id, return_route_rule_id));
6753 }
6754
6755 bool
6756 necp_socket_is_allowed_to_send_recv_v6(struct inpcb *inp, u_int16_t local_port, u_int16_t remote_port, struct in6_addr *local_addr, struct in6_addr *remote_addr, ifnet_t interface, necp_kernel_policy_id *return_policy_id, u_int32_t *return_route_rule_id)
6757 {
6758 struct sockaddr_in6 local;
6759 struct sockaddr_in6 remote;
6760 local.sin6_family = remote.sin6_family = AF_INET6;
6761 local.sin6_len = remote.sin6_len = sizeof(struct sockaddr_in6);
6762 local.sin6_port = local_port;
6763 remote.sin6_port = remote_port;
6764 memcpy(&local.sin6_addr, local_addr, sizeof(local.sin6_addr));
6765 memcpy(&remote.sin6_addr, remote_addr, sizeof(remote.sin6_addr));
6766
6767 return (necp_socket_is_allowed_to_send_recv_internal(inp, (struct sockaddr *)&local, (struct sockaddr *)&remote, interface, return_policy_id, return_route_rule_id));
6768 }
6769
6770 bool
6771 necp_socket_is_allowed_to_send_recv(struct inpcb *inp, necp_kernel_policy_id *return_policy_id, u_int32_t *return_route_rule_id)
6772 {
6773 return (necp_socket_is_allowed_to_send_recv_internal(inp, NULL, NULL, NULL, return_policy_id, return_route_rule_id));
6774 }
6775
6776 int
6777 necp_mark_packet_from_socket(struct mbuf *packet, struct inpcb *inp, necp_kernel_policy_id policy_id, u_int32_t route_rule_id)
6778 {
6779 if (packet == NULL || inp == NULL) {
6780 return (EINVAL);
6781 }
6782
6783 // Mark ID for Pass and IP Tunnel
6784 if (policy_id != NECP_KERNEL_POLICY_ID_NONE) {
6785 packet->m_pkthdr.necp_mtag.necp_policy_id = policy_id;
6786 } else if (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_PASS ||
6787 inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL) {
6788 packet->m_pkthdr.necp_mtag.necp_policy_id = inp->inp_policyresult.policy_id;
6789 } else {
6790 packet->m_pkthdr.necp_mtag.necp_policy_id = NECP_KERNEL_POLICY_ID_NONE;
6791 }
6792 packet->m_pkthdr.necp_mtag.necp_last_interface_index = 0;
6793 if (route_rule_id != 0) {
6794 packet->m_pkthdr.necp_mtag.necp_route_rule_id = route_rule_id;
6795 } else {
6796 packet->m_pkthdr.necp_mtag.necp_route_rule_id = inp->inp_policyresult.results.route_rule_id;
6797 }
6798
6799 return (0);
6800 }
6801
6802 int
6803 necp_mark_packet_from_ip(struct mbuf *packet, necp_kernel_policy_id policy_id)
6804 {
6805 if (packet == NULL) {
6806 return (EINVAL);
6807 }
6808
6809 // Mark ID for Pass and IP Tunnel
6810 if (policy_id != NECP_KERNEL_POLICY_ID_NONE) {
6811 packet->m_pkthdr.necp_mtag.necp_policy_id = policy_id;
6812 } else {
6813 packet->m_pkthdr.necp_mtag.necp_policy_id = NECP_KERNEL_POLICY_ID_NONE;
6814 }
6815
6816 return (0);
6817 }
6818
6819 int
6820 necp_mark_packet_from_interface(struct mbuf *packet, ifnet_t interface)
6821 {
6822 if (packet == NULL) {
6823 return (EINVAL);
6824 }
6825
6826 // Mark ID for Pass and IP Tunnel
6827 if (interface != NULL) {
6828 packet->m_pkthdr.necp_mtag.necp_last_interface_index = interface->if_index;
6829 }
6830
6831 return (0);
6832 }
6833
6834 int
6835 necp_mark_packet_as_keepalive(struct mbuf *packet, bool is_keepalive)
6836 {
6837 if (packet == NULL) {
6838 return (EINVAL);
6839 }
6840
6841 if (is_keepalive) {
6842 packet->m_pkthdr.pkt_flags |= PKTF_KEEPALIVE;
6843 } else {
6844 packet->m_pkthdr.pkt_flags &= ~PKTF_KEEPALIVE;
6845 }
6846
6847 return (0);
6848 }
6849
6850 necp_kernel_policy_id
6851 necp_get_policy_id_from_packet(struct mbuf *packet)
6852 {
6853 if (packet == NULL) {
6854 return (NECP_KERNEL_POLICY_ID_NONE);
6855 }
6856
6857 return (packet->m_pkthdr.necp_mtag.necp_policy_id);
6858 }
6859
6860 u_int32_t
6861 necp_get_last_interface_index_from_packet(struct mbuf *packet)
6862 {
6863 if (packet == NULL) {
6864 return (0);
6865 }
6866
6867 return (packet->m_pkthdr.necp_mtag.necp_last_interface_index);
6868 }
6869
6870 u_int32_t
6871 necp_get_route_rule_id_from_packet(struct mbuf *packet)
6872 {
6873 if (packet == NULL) {
6874 return (0);
6875 }
6876
6877 return (packet->m_pkthdr.necp_mtag.necp_route_rule_id);
6878 }
6879
6880 bool
6881 necp_get_is_keepalive_from_packet(struct mbuf *packet)
6882 {
6883 if (packet == NULL) {
6884 return (FALSE);
6885 }
6886
6887 return (packet->m_pkthdr.pkt_flags & PKTF_KEEPALIVE);
6888 }
6889
6890 u_int32_t
6891 necp_socket_get_content_filter_control_unit(struct socket *so)
6892 {
6893 struct inpcb *inp = sotoinpcb(so);
6894
6895 if (inp == NULL) {
6896 return (0);
6897 }
6898 return (inp->inp_policyresult.results.filter_control_unit);
6899 }
6900
6901 bool
6902 necp_socket_should_use_flow_divert(struct inpcb *inp)
6903 {
6904 if (inp == NULL) {
6905 return (FALSE);
6906 }
6907
6908 return (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT);
6909 }
6910
6911 u_int32_t
6912 necp_socket_get_flow_divert_control_unit(struct inpcb *inp)
6913 {
6914 if (inp == NULL) {
6915 return (0);
6916 }
6917
6918 if (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT) {
6919 return (inp->inp_policyresult.results.result_parameter.flow_divert_control_unit);
6920 }
6921
6922 return (0);
6923 }
6924
6925 bool
6926 necp_socket_should_rescope(struct inpcb *inp)
6927 {
6928 if (inp == NULL) {
6929 return (FALSE);
6930 }
6931
6932 return (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED);
6933 }
6934
6935 u_int
6936 necp_socket_get_rescope_if_index(struct inpcb *inp)
6937 {
6938 if (inp == NULL) {
6939 return (0);
6940 }
6941
6942 if (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED) {
6943 return (inp->inp_policyresult.results.result_parameter.scoped_interface_index);
6944 }
6945
6946 return (0);
6947 }
6948
6949 u_int32_t
6950 necp_socket_get_effective_mtu(struct inpcb *inp, u_int32_t current_mtu)
6951 {
6952 if (inp == NULL) {
6953 return (current_mtu);
6954 }
6955
6956 if (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL &&
6957 (inp->inp_flags & INP_BOUND_IF) &&
6958 inp->inp_boundifp) {
6959
6960 u_int bound_interface_index = inp->inp_boundifp->if_index;
6961 u_int tunnel_interface_index = inp->inp_policyresult.results.result_parameter.tunnel_interface_index;
6962
6963 // The result is IP Tunnel, and is rescoping from one interface to another. Recalculate MTU.
6964 if (bound_interface_index != tunnel_interface_index) {
6965 ifnet_t tunnel_interface = NULL;
6966
6967 ifnet_head_lock_shared();
6968 tunnel_interface = ifindex2ifnet[tunnel_interface_index];
6969 ifnet_head_done();
6970
6971 if (tunnel_interface != NULL) {
6972 u_int32_t direct_tunnel_mtu = tunnel_interface->if_mtu;
6973 u_int32_t delegate_tunnel_mtu = (tunnel_interface->if_delegated.ifp != NULL) ? tunnel_interface->if_delegated.ifp->if_mtu : 0;
6974 if (delegate_tunnel_mtu != 0 &&
6975 strncmp(tunnel_interface->if_name, "ipsec", strlen("ipsec")) == 0) {
6976 // For ipsec interfaces, calculate the overhead from the delegate interface
6977 u_int32_t tunnel_overhead = (u_int32_t)(esp_hdrsiz(NULL) + sizeof(struct ip6_hdr));
6978 if (delegate_tunnel_mtu > tunnel_overhead) {
6979 delegate_tunnel_mtu -= tunnel_overhead;
6980 }
6981
6982 if (delegate_tunnel_mtu < direct_tunnel_mtu) {
6983 // If the (delegate - overhead) < direct, return (delegate - overhead)
6984 return (delegate_tunnel_mtu);
6985 } else {
6986 // Otherwise return direct
6987 return (direct_tunnel_mtu);
6988 }
6989 } else {
6990 // For non-ipsec interfaces, just return the tunnel MTU
6991 return (direct_tunnel_mtu);
6992 }
6993 }
6994 }
6995 }
6996
6997 // By default, just return the MTU passed in
6998 return (current_mtu);
6999 }
7000
7001 ifnet_t
7002 necp_get_ifnet_from_result_parameter(necp_kernel_policy_result_parameter *result_parameter)
7003 {
7004 if (result_parameter == NULL) {
7005 return (NULL);
7006 }
7007
7008 return (ifindex2ifnet[result_parameter->tunnel_interface_index]);
7009 }
7010
7011 bool
7012 necp_packet_can_rebind_to_ifnet(struct mbuf *packet, struct ifnet *interface, struct route *new_route, int family)
7013 {
7014 bool found_match = FALSE;
7015 errno_t result = 0;
7016 ifaddr_t *addresses = NULL;
7017 union necp_sockaddr_union address_storage;
7018 int i;
7019
7020 if (packet == NULL || interface == NULL || new_route == NULL || (family != AF_INET && family != AF_INET6)) {
7021 return (FALSE);
7022 }
7023
7024 result = ifnet_get_address_list_family(interface, &addresses, family);
7025 if (result != 0) {
7026 NECPLOG(LOG_ERR, "Failed to get address list for %s%d", ifnet_name(interface), ifnet_unit(interface));
7027 return (FALSE);
7028 }
7029
7030 for (i = 0; addresses[i] != NULL; i++) {
7031 ROUTE_RELEASE(new_route);
7032 if (ifaddr_address(addresses[i], &address_storage.sa, sizeof(address_storage)) == 0) {
7033 if (family == AF_INET) {
7034 struct ip *ip = mtod(packet, struct ip *);
7035 if (memcmp(&address_storage.sin.sin_addr, &ip->ip_src, sizeof(ip->ip_src)) == 0) {
7036 struct sockaddr_in *dst4 = (struct sockaddr_in *)(void *)&new_route->ro_dst;
7037 dst4->sin_family = AF_INET;
7038 dst4->sin_len = sizeof(struct sockaddr_in);
7039 dst4->sin_addr = ip->ip_dst;
7040 rtalloc_scoped(new_route, interface->if_index);
7041 if (!ROUTE_UNUSABLE(new_route)) {
7042 found_match = TRUE;
7043 goto done;
7044 }
7045 }
7046 } else if (family == AF_INET6) {
7047 struct ip6_hdr *ip6 = mtod(packet, struct ip6_hdr *);
7048 if (memcmp(&address_storage.sin6.sin6_addr, &ip6->ip6_src, sizeof(ip6->ip6_src)) == 0) {
7049 struct sockaddr_in6 *dst6 = (struct sockaddr_in6 *)(void *)&new_route->ro_dst;
7050 dst6->sin6_family = AF_INET6;
7051 dst6->sin6_len = sizeof(struct sockaddr_in6);
7052 dst6->sin6_addr = ip6->ip6_dst;
7053 rtalloc_scoped(new_route, interface->if_index);
7054 if (!ROUTE_UNUSABLE(new_route)) {
7055 found_match = TRUE;
7056 goto done;
7057 }
7058 }
7059 }
7060 }
7061 }
7062
7063 done:
7064 ifnet_free_address_list(addresses);
7065 addresses = NULL;
7066 return (found_match);
7067 }
7068
7069 static bool
7070 necp_addr_is_loopback(struct sockaddr *address)
7071 {
7072 if (address == NULL) {
7073 return (FALSE);
7074 }
7075
7076 if (address->sa_family == AF_INET) {
7077 return (ntohl(((struct sockaddr_in *)(void *)address)->sin_addr.s_addr) == INADDR_LOOPBACK);
7078 } else if (address->sa_family == AF_INET6) {
7079 return IN6_IS_ADDR_LOOPBACK(&((struct sockaddr_in6 *)(void *)address)->sin6_addr);
7080 }
7081
7082 return (FALSE);
7083 }
7084
7085 static bool
7086 necp_is_loopback(struct sockaddr *local_addr, struct sockaddr *remote_addr, struct inpcb *inp, struct mbuf *packet)
7087 {
7088 // Note: This function only checks for the loopback addresses.
7089 // In the future, we may want to expand to also allow any traffic
7090 // going through the loopback interface, but until then, this
7091 // check is cheaper.
7092
7093 if (local_addr != NULL && necp_addr_is_loopback(local_addr)) {
7094 return (TRUE);
7095 }
7096
7097 if (remote_addr != NULL && necp_addr_is_loopback(remote_addr)) {
7098 return (TRUE);
7099 }
7100
7101 if (inp != NULL) {
7102 if ((inp->inp_flags & INP_BOUND_IF) && inp->inp_boundifp && (inp->inp_boundifp->if_flags & IFF_LOOPBACK)) {
7103 return (TRUE);
7104 }
7105 if (inp->inp_vflag & INP_IPV4) {
7106 if (ntohl(inp->inp_laddr.s_addr) == INADDR_LOOPBACK ||
7107 ntohl(inp->inp_faddr.s_addr) == INADDR_LOOPBACK) {
7108 return (TRUE);
7109 }
7110 } else if (inp->inp_vflag & INP_IPV6) {
7111 if (IN6_IS_ADDR_LOOPBACK(&inp->in6p_laddr) ||
7112 IN6_IS_ADDR_LOOPBACK(&inp->in6p_faddr)) {
7113 return (TRUE);
7114 }
7115 }
7116 }
7117
7118 if (packet != NULL) {
7119 struct ip *ip = mtod(packet, struct ip *);
7120 if (ip->ip_v == 4) {
7121 if (ntohl(ip->ip_src.s_addr) == INADDR_LOOPBACK) {
7122 return (TRUE);
7123 }
7124 if (ntohl(ip->ip_dst.s_addr) == INADDR_LOOPBACK) {
7125 return (TRUE);
7126 }
7127 } else if (ip->ip_v == 6) {
7128 struct ip6_hdr *ip6 = mtod(packet, struct ip6_hdr *);
7129 if (IN6_IS_ADDR_LOOPBACK(&ip6->ip6_src)) {
7130 return (TRUE);
7131 }
7132 if (IN6_IS_ADDR_LOOPBACK(&ip6->ip6_dst)) {
7133 return (TRUE);
7134 }
7135 }
7136 }
7137
7138 return (FALSE);
7139 }