necp.c   [plain text]


/*
 * Copyright (c) 2013-2014 Apple Inc. All rights reserved.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. The rights granted to you under the License
 * may not be used to create, or enable the creation or redistribution of,
 * unlawful or unlicensed copies of an Apple operating system, or to
 * circumvent, violate, or enable the circumvention or violation of, any
 * terms of an Apple operating system software license agreement.
 *
 * Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
 */

#include <string.h>
#include <sys/systm.h>
#include <sys/types.h>
#include <sys/syslog.h>
#include <sys/queue.h>
#include <sys/malloc.h>
#include <libkern/OSMalloc.h>
#include <sys/kernel.h>
#include <sys/kern_control.h>
#include <sys/mbuf.h>
#include <sys/kpi_mbuf.h>
#include <sys/proc_uuid_policy.h>
#include <net/if.h>
#include <sys/protosw.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <netinet/ip.h>
#include <netinet/ip6.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <netinet/in_pcb.h>
#include <net/flowhash.h>
#include <net/if_var.h>
#include <sys/kauth.h>
#include <sys/sysctl.h>
#include <sys/sysproto.h>
#include <sys/priv.h>
#include <net/necp.h>

/*
 * NECP - Network Extension Control Policy database
 * ------------------------------------------------
 * The goal of this module is to allow clients connecting via a
 * kernel control socket to create high-level policy sessions, which
 * are ingested into low-level kernel policies that control and tag
 * traffic at the application, socket, and IP layers.
 *
 * ------------------------------------------------
 * Sessions
 * ------------------------------------------------
 * Each session owns a list of session policies, each of which can
 * specify any combination of conditions and a single result. Each
 * session also has a priority level (such as High, Default, or Low)
 * which is requested by the client. Based on the requested level,
 * a session order value is assigned to the session, which will be used
 * to sort kernel policies generated by the session. The session client
 * can specify the sub-order for each policy it creates which will be
 * used to further sort the kernel policies.
 *
 *  Kernel Control Socket --> 1 necp_session --> list of necp_session_policy structs
 *
 * ------------------------------------------------
 * Kernel Policies
 * ------------------------------------------------
 * Whenever a session send the Apply command, its policies are ingested
 * and generate kernel policies. There are two phases of kernel policy
 * ingestion.
 *
 * 1. The session policy is parsed to create kernel policies at the socket
 *	  and IP layers, when applicable. For example, a policy that requires
 *    all traffic from App1 to Pass will generate a socket kernel policy to
 *    match App1 and mark packets with ID1, and also an IP policy to match
 *    ID1 and let the packet pass. This is handled in necp_apply_policy. The
 *    resulting kernel policies are added to the global socket and IP layer
 *    policy lists.
 *  necp_session_policy --> necp_kernel_socket_policy and necp_kernel_ip_output_policy
 *                                      ||                             ||
 *                                      \/                             \/
 *                          necp_kernel_socket_policies   necp_kernel_ip_output_policies
 *
 * 2. Once the global lists of kernel policies have been filled out, each
 *    list is traversed to create optimized sub-lists ("Maps") which are used during
 *    data-path evaluation. IP policies are sent into necp_kernel_ip_output_policies_map,
 *    which hashes incoming packets based on marked socket-layer policies, and removes
 *    duplicate or overlapping polcies. Socket policies are sent into two maps,
 *    necp_kernel_socket_policies_map and necp_kernel_socket_policies_app_layer_map.
 *    The app layer map is used for policy checks coming in from user space, and is one
 *    list with duplicate and overlapping policies removed. The socket map hashes based
 *    on app UUID, and removes duplicate and overlapping policies.
 *  necp_kernel_socket_policy --> necp_kernel_socket_policies_app_layer_map
 *                            |-> necp_kernel_socket_policies_map
 *
 *  necp_kernel_ip_output_policies --> necp_kernel_ip_output_policies_map
 *
 * ------------------------------------------------
 * Drop All Level
 * ------------------------------------------------
 * The Drop All Level is a sysctl that controls the level at which policies are allowed
 * to override a global drop rule. If the value is 0, no drop rule is applied. If the value
 * is 1, all traffic is dropped. If the value is greater than 1, all kernel policies created
 * by a session with a priority level better than (numerically less than) the
 * Drop All Level will allow matching traffic to not be dropped. The Drop All Level is
 * dynamically interpreted into necp_drop_all_order, which specifies the equivalent assigned
 * session orders to be dropped.
 */

u_int32_t necp_drop_all_order = 0;
u_int32_t necp_drop_all_level = 0;

u_int32_t necp_pass_loopback = 1; // 0=Off, 1=On
u_int32_t necp_pass_keepalives = 1; // 0=Off, 1=On

u_int32_t necp_debug = 0; // 0=None, 1=Basic, 2=EveryMatch

static int sysctl_handle_necp_level SYSCTL_HANDLER_ARGS;

SYSCTL_NODE(_net, OID_AUTO, necp, CTLFLAG_RW | CTLFLAG_LOCKED, 0, "NECP");
SYSCTL_INT(_net_necp, NECPCTL_PASS_LOOPBACK, pass_loopback, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_pass_loopback, 0, "");
SYSCTL_INT(_net_necp, NECPCTL_PASS_KEEPALIVES, pass_keepalives, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_pass_keepalives, 0, "");
SYSCTL_INT(_net_necp, NECPCTL_DEBUG, debug, CTLFLAG_LOCKED | CTLFLAG_RW, &necp_debug, 0, "");
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", "");

#define	NECPLOG(level, format, ...) do {											\
	log((level > LOG_NOTICE ? LOG_NOTICE : level), "%s: " format "\n", __FUNCTION__, __VA_ARGS__); 	\
} while (0)

#define	NECPLOG0(level, msg) do {											\
	log((level > LOG_NOTICE ? LOG_NOTICE : level), "%s: %s\n", __FUNCTION__, msg); 	\
} while (0)

#define	LIST_INSERT_SORTED_ASCENDING(head, elm, field, sortfield, tmpelm) do {		\
	if (LIST_EMPTY((head)) || (LIST_FIRST(head)->sortfield >= (elm)->sortfield)) {	\
		LIST_INSERT_HEAD((head), elm, field);										\
	} else {																		\
		LIST_FOREACH(tmpelm, head, field) {											\
			if (LIST_NEXT(tmpelm, field) == NULL || LIST_NEXT(tmpelm, field)->sortfield >= (elm)->sortfield) {	\
				LIST_INSERT_AFTER(tmpelm, elm, field);								\
				break;																\
			}																		\
		}																			\
	}																				\
} while (0)

#define	LIST_INSERT_SORTED_TWICE_ASCENDING(head, elm, field, firstsortfield, secondsortfield, tmpelm) do {	\
	if (LIST_EMPTY((head)) || (LIST_FIRST(head)->firstsortfield > (elm)->firstsortfield) || ((LIST_FIRST(head)->firstsortfield == (elm)->firstsortfield) && (LIST_FIRST(head)->secondsortfield >= (elm)->secondsortfield))) {														\
		LIST_INSERT_HEAD((head), elm, field);										\
	} else {																		\
		LIST_FOREACH(tmpelm, head, field) {											\
			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_INSERT_AFTER(tmpelm, elm, field);								\
				break;																\
			}																		\
		}																			\
	}																				\
} while (0)

#define	LIST_INSERT_SORTED_THRICE_ASCENDING(head, elm, field, firstsortfield, secondsortfield, thirdsortfield, tmpelm) do { \
	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))) {															\
		LIST_INSERT_HEAD((head), elm, field);										\
	} else {																		\
		LIST_FOREACH(tmpelm, head, field) {											\
			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)))	{ \
				LIST_INSERT_AFTER(tmpelm, elm, field);								\
				break;																\
			}																		\
		}																			\
	}																				\
} while (0)

#define	NECP_KERNEL_CONDITION_ALL_INTERFACES	0x00001
#define	NECP_KERNEL_CONDITION_BOUND_INTERFACE	0x00002
#define	NECP_KERNEL_CONDITION_PROTOCOL			0x00004
#define	NECP_KERNEL_CONDITION_LOCAL_START		0x00008
#define	NECP_KERNEL_CONDITION_LOCAL_END			0x00010
#define	NECP_KERNEL_CONDITION_LOCAL_PREFIX		0x00020
#define	NECP_KERNEL_CONDITION_REMOTE_START		0x00040
#define	NECP_KERNEL_CONDITION_REMOTE_END		0x00080
#define	NECP_KERNEL_CONDITION_REMOTE_PREFIX		0x00100
#define	NECP_KERNEL_CONDITION_APP_ID			0x00200
#define	NECP_KERNEL_CONDITION_REAL_APP_ID		0x00400
#define	NECP_KERNEL_CONDITION_DOMAIN			0x00800
#define	NECP_KERNEL_CONDITION_ACCOUNT_ID		0x01000
#define	NECP_KERNEL_CONDITION_POLICY_ID			0x02000
#define	NECP_KERNEL_CONDITION_PID				0x04000
#define	NECP_KERNEL_CONDITION_UID				0x08000
#define	NECP_KERNEL_CONDITION_LAST_INTERFACE	0x10000			// Only set from packets looping between interfaces
#define NECP_KERNEL_CONDITION_TRAFFIC_CLASS		0x20000
#define NECP_KERNEL_CONDITION_ENTITLEMENT		0x40000

struct necp_service_registration {
	LIST_ENTRY(necp_service_registration)	session_chain;
	LIST_ENTRY(necp_service_registration)	kernel_chain;
	u_int32_t								service_id;
};

struct necp_session {
	u_int32_t					control_unit;
	u_int32_t					session_priority; // Descriptive priority rating
	u_int32_t					session_order;

	bool						proc_locked; // Messages must come from proc_uuid
	uuid_t						proc_uuid;

	bool						dirty;
	LIST_HEAD(_policies, necp_session_policy) policies;
	
	LIST_HEAD(_services, necp_service_registration) services;
};

struct necp_socket_info {
	pid_t pid;
	uid_t uid;
	union necp_sockaddr_union local_addr;
	union necp_sockaddr_union remote_addr;
	u_int32_t bound_interface_index;
	u_int32_t traffic_class;
	u_int16_t protocol;
	u_int32_t application_id;
	u_int32_t real_application_id;
	u_int32_t account_id;
	char *domain;
	errno_t cred_result;
};

static kern_ctl_ref	necp_kctlref;
static u_int32_t	necp_family;
static OSMallocTag	necp_malloc_tag;
static	lck_grp_attr_t	*necp_kernel_policy_grp_attr	= NULL;
static	lck_attr_t		*necp_kernel_policy_mtx_attr	= NULL;
static	lck_grp_t		*necp_kernel_policy_mtx_grp		= NULL;
decl_lck_rw_data(static, necp_kernel_policy_lock);

static necp_policy_id necp_last_policy_id = 0;
static necp_kernel_policy_id necp_last_kernel_policy_id = 0;
static u_int32_t necp_last_uuid_id = 0;
static u_int32_t necp_last_string_id = 0;

/*
 * On modification, invalidate cached lookups by bumping the generation count.
 * Other calls will need to take the slowpath of taking
 * the subsystem lock.
 */
static volatile int32_t necp_kernel_socket_policies_gencount;
#define	BUMP_KERNEL_SOCKET_POLICIES_GENERATION_COUNT() do {							\
	if (OSIncrementAtomic(&necp_kernel_socket_policies_gencount) == (INT32_MAX - 1)) {	\
		necp_kernel_socket_policies_gencount = 1;										\
	}																				\
} while (0)

static u_int32_t necp_kernel_application_policies_condition_mask;
static size_t necp_kernel_application_policies_count;
static u_int32_t necp_kernel_socket_policies_condition_mask;
static size_t necp_kernel_socket_policies_count;
static size_t necp_kernel_socket_policies_non_app_count;
static LIST_HEAD(_necpkernelsocketconnectpolicies, necp_kernel_socket_policy) necp_kernel_socket_policies;
#define	NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS 5
#define	NECP_SOCKET_MAP_APP_ID_TO_BUCKET(appid) (appid ? (appid%(NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS - 1) + 1) : 0)
static struct necp_kernel_socket_policy **necp_kernel_socket_policies_map[NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS];
static struct necp_kernel_socket_policy **necp_kernel_socket_policies_app_layer_map;
/*
 * A note on policy 'maps': these are used for boosting efficiency when matching policies. For each dimension of the map,
 * such as an ID, the 0 bucket is reserved for sockets/packets that do not have this parameter, while the other
 * buckets lead to an array of policy pointers that form the list applicable when the (parameter%(NUM_BUCKETS - 1) + 1) == bucket_index.
 *
 * For example, a packet with policy ID of 7, when there are 4 ID buckets, will map to bucket (7%3 + 1) = 2.
 */

static u_int32_t necp_kernel_ip_output_policies_condition_mask;
static size_t necp_kernel_ip_output_policies_count;
static size_t necp_kernel_ip_output_policies_non_id_count;
static LIST_HEAD(_necpkernelipoutputpolicies, necp_kernel_ip_output_policy) necp_kernel_ip_output_policies;
#define	NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS 5
#define	NECP_IP_OUTPUT_MAP_ID_TO_BUCKET(id) (id ? (id%(NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS - 1) + 1) : 0)
static struct necp_kernel_ip_output_policy **necp_kernel_ip_output_policies_map[NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS];

static struct necp_session *necp_create_session(u_int32_t control_unit);
static void necp_delete_session(struct necp_session *session);

static void necp_handle_policy_add(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset);
static void necp_handle_policy_get(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset);
static void necp_handle_policy_delete(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset);
static void necp_handle_policy_apply_all(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset);
static void necp_handle_policy_list_all(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset);
static void necp_handle_policy_delete_all(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset);
static void necp_handle_set_session_priority(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset);
static void necp_handle_lock_session_to_proc(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset);
static void necp_handle_register_service(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset);
static void necp_handle_unregister_service(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset);

static struct necp_session_policy *necp_policy_create(struct necp_session *session, necp_policy_order order, u_int8_t *conditions_array, size_t conditions_array_size, u_int8_t *result, size_t result_size);
static struct necp_session_policy *necp_policy_find(struct necp_session *session, necp_policy_id policy_id);
static bool necp_policy_mark_for_deletion(struct necp_session *session, struct necp_session_policy *policy);
static bool necp_policy_mark_all_for_deletion(struct necp_session *session);
static bool necp_policy_delete(struct necp_session *session, struct necp_session_policy *policy);
static void necp_policy_apply_all(struct necp_session *session);

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, 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);
static bool necp_kernel_socket_policy_delete(necp_kernel_policy_id policy_id);
static bool necp_kernel_socket_policies_reprocess(void);
static bool necp_kernel_socket_policies_update_uuid_table(void);
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, necp_kernel_policy_result *return_service_action, necp_kernel_policy_service *return_service);

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, 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);
static bool necp_kernel_ip_output_policy_delete(necp_kernel_policy_id policy_id);
static bool necp_kernel_ip_output_policies_reprocess(void);

static bool necp_is_addr_in_range(struct sockaddr *addr, struct sockaddr *range_start, struct sockaddr *range_end);
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);
static bool necp_is_addr_in_subnet(struct sockaddr *addr, struct sockaddr *subnet_addr, u_int8_t subnet_prefix);
static int necp_addr_compare(struct sockaddr *sa1, struct sockaddr *sa2, int check_port);
static bool necp_buffer_compare_with_bit_prefix(u_int8_t *p1, u_int8_t *p2, u_int32_t bits);
static bool necp_is_loopback(struct sockaddr *local_addr, struct sockaddr *remote_addr, struct inpcb *inp, struct mbuf *packet);

struct necp_uuid_id_mapping {
	LIST_ENTRY(necp_uuid_id_mapping) chain;
	uuid_t		uuid;
	u_int32_t	id;
	u_int32_t	refcount;
	u_int32_t	table_refcount; // Add to UUID policy table count
};
static size_t necp_num_uuid_app_id_mappings;
static bool necp_uuid_app_id_mappings_dirty;
#define	NECP_UUID_APP_ID_HASH_SIZE 64
static u_long necp_uuid_app_id_hash_mask;
static u_long necp_uuid_app_id_hash_num_buckets;
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
#define	APPUUIDHASH(uuid) (&necp_uuid_app_id_hashtbl[uuid[0] & necp_uuid_app_id_hash_mask]) // Assume first byte of UUIDs are evenly distributed
static u_int32_t necp_create_uuid_app_id_mapping(uuid_t uuid, bool *allocated_mapping, bool uuid_policy_table);
static bool necp_remove_uuid_app_id_mapping(uuid_t uuid, bool *removed_mapping, bool uuid_policy_table);

static struct necp_uuid_id_mapping *necp_uuid_lookup_service_id_locked(uuid_t uuid);
static struct necp_uuid_id_mapping *necp_uuid_lookup_uuid_with_service_id_locked(u_int32_t local_id);
static u_int32_t necp_create_uuid_service_id_mapping(uuid_t uuid);
static bool necp_remove_uuid_service_id_mapping(uuid_t uuid);

struct necp_string_id_mapping {
	LIST_ENTRY(necp_string_id_mapping) chain;
	char		*string;
	necp_app_id	id;
	u_int32_t	refcount;
};
static LIST_HEAD(necp_string_id_mapping_list, necp_string_id_mapping) necp_account_id_list;
static u_int32_t necp_create_string_to_id_mapping(struct necp_string_id_mapping_list *list, char *domain);
static bool necp_remove_string_to_id_mapping(struct necp_string_id_mapping_list *list, char *domain);

static LIST_HEAD(_necp_kernel_service_list, necp_service_registration) necp_registered_service_list;

static char *necp_create_trimmed_domain(char *string, size_t length);
static inline int necp_count_dots(char *string, size_t length);

// Session order allocation
static u_int32_t
necp_allocate_new_session_order(u_int32_t priority, u_int32_t control_unit)
{
	u_int32_t new_order = 0;

	// For now, just allocate 1000 orders for each priority
	if (priority == NECP_SESSION_PRIORITY_UNKNOWN || priority > NECP_SESSION_NUM_PRIORITIES) {
		priority = NECP_SESSION_PRIORITY_DEFAULT;
	}

	// Use the control unit to decide the offset into the priority list
	new_order = (control_unit) + ((priority - 1) * 1000);

	return (new_order);
}

static inline u_int32_t
necp_get_first_order_for_priority(u_int32_t priority)
{
	return (((priority - 1) * 1000) + 1);
}

// Sysctl handler
static int
sysctl_handle_necp_level SYSCTL_HANDLER_ARGS
{
#pragma unused(arg1, arg2)
	int error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
	if (necp_drop_all_level == 0) {
		necp_drop_all_order = 0;
	} else {
		necp_drop_all_order = necp_get_first_order_for_priority(necp_drop_all_level);
	}
	return (error);
}


// Kernel Control functions
static errno_t necp_register_control(void);
static errno_t necp_ctl_connect(kern_ctl_ref kctlref, struct sockaddr_ctl *sac, void **unitinfo);
static errno_t necp_ctl_disconnect(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo);
static errno_t necp_ctl_send(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo, mbuf_t m, int flags);
static void necp_ctl_rcvd(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo, int flags);
static errno_t necp_ctl_getopt(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo, int opt, void *data, size_t *len);
static errno_t necp_ctl_setopt(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo, int opt, void *data, size_t len);

static bool necp_send_ctl_data(struct necp_session *session, u_int8_t *buffer, size_t buffer_size);

errno_t
necp_init(void)
{
	errno_t result = 0;

	result = necp_register_control();
	if (result != 0) {
		goto done;
	}

	necp_kernel_policy_grp_attr = lck_grp_attr_alloc_init();
	if (necp_kernel_policy_grp_attr == NULL) {
		NECPLOG0(LOG_ERR, "lck_grp_attr_alloc_init failed");
		result = ENOMEM;
		goto done;
	}

	necp_kernel_policy_mtx_grp = lck_grp_alloc_init(NECP_CONTROL_NAME, necp_kernel_policy_grp_attr);
	if (necp_kernel_policy_mtx_grp == NULL) {
		NECPLOG0(LOG_ERR, "lck_grp_alloc_init failed");
		result = ENOMEM;
		goto done;
	}

	necp_kernel_policy_mtx_attr = lck_attr_alloc_init();
	if (necp_kernel_policy_mtx_attr == NULL) {
		NECPLOG0(LOG_ERR, "lck_attr_alloc_init failed");
		result = ENOMEM;
		goto done;
	}

	lck_rw_init(&necp_kernel_policy_lock, necp_kernel_policy_mtx_grp, necp_kernel_policy_mtx_attr);

	LIST_INIT(&necp_kernel_socket_policies);
	LIST_INIT(&necp_kernel_ip_output_policies);

	LIST_INIT(&necp_account_id_list);

	LIST_INIT(&necp_uuid_service_id_list);
	
	LIST_INIT(&necp_registered_service_list);

	necp_uuid_app_id_hashtbl = hashinit(NECP_UUID_APP_ID_HASH_SIZE, M_NECP, &necp_uuid_app_id_hash_mask);
	necp_uuid_app_id_hash_num_buckets = necp_uuid_app_id_hash_mask + 1;
	necp_num_uuid_app_id_mappings = 0;
	necp_uuid_app_id_mappings_dirty = FALSE;

	necp_kernel_application_policies_condition_mask = 0;
	necp_kernel_socket_policies_condition_mask = 0;
	necp_kernel_ip_output_policies_condition_mask = 0;

	necp_kernel_application_policies_count = 0;
	necp_kernel_socket_policies_count = 0;
	necp_kernel_socket_policies_non_app_count = 0;
	necp_kernel_ip_output_policies_count = 0;
	necp_kernel_ip_output_policies_non_id_count = 0;

	necp_last_policy_id = 0;
	necp_last_kernel_policy_id = 0;

	necp_kernel_socket_policies_gencount = 1;

	memset(&necp_kernel_socket_policies_map, 0, sizeof(necp_kernel_socket_policies_map));
	memset(&necp_kernel_ip_output_policies_map, 0, sizeof(necp_kernel_ip_output_policies_map));
	necp_kernel_socket_policies_app_layer_map = NULL;

done:
	if (result != 0) {
		if (necp_kernel_policy_mtx_attr != NULL) {
			lck_attr_free(necp_kernel_policy_mtx_attr);
			necp_kernel_policy_mtx_attr = NULL;
		}
		if (necp_kernel_policy_mtx_grp != NULL) {
			lck_grp_free(necp_kernel_policy_mtx_grp);
			necp_kernel_policy_mtx_grp = NULL;
		}
		if (necp_kernel_policy_grp_attr != NULL) {
			lck_grp_attr_free(necp_kernel_policy_grp_attr);
			necp_kernel_policy_grp_attr = NULL;
		}
		if (necp_kctlref != NULL) {
			ctl_deregister(necp_kctlref);
			necp_kctlref = NULL;
		}
	}
	return (result);
}

static errno_t
necp_register_control(void)
{
	struct kern_ctl_reg	kern_ctl;
	errno_t				result = 0;

	// Create a tag to allocate memory
	necp_malloc_tag = OSMalloc_Tagalloc(NECP_CONTROL_NAME, OSMT_DEFAULT);

	// Find a unique value for our interface family
	result = mbuf_tag_id_find(NECP_CONTROL_NAME, &necp_family);
	if (result != 0) {
		NECPLOG(LOG_ERR, "mbuf_tag_id_find_internal failed: %d", result);
		return (result);
	}

	bzero(&kern_ctl, sizeof(kern_ctl));
	strlcpy(kern_ctl.ctl_name, NECP_CONTROL_NAME, sizeof(kern_ctl.ctl_name));
	kern_ctl.ctl_name[sizeof(kern_ctl.ctl_name) - 1] = 0;
	kern_ctl.ctl_flags = CTL_FLAG_PRIVILEGED; // Require root
	kern_ctl.ctl_sendsize = 64 * 1024;
	kern_ctl.ctl_recvsize = 64 * 1024;
	kern_ctl.ctl_connect = necp_ctl_connect;
	kern_ctl.ctl_disconnect = necp_ctl_disconnect;
	kern_ctl.ctl_send = necp_ctl_send;
	kern_ctl.ctl_rcvd = necp_ctl_rcvd;
	kern_ctl.ctl_setopt = necp_ctl_setopt;
	kern_ctl.ctl_getopt = necp_ctl_getopt;

	result = ctl_register(&kern_ctl, &necp_kctlref);
	if (result != 0) {
		NECPLOG(LOG_ERR, "ctl_register failed: %d", result);
		return (result);
	}

	return (0);
}

static errno_t
necp_ctl_connect(kern_ctl_ref kctlref, struct sockaddr_ctl *sac, void **unitinfo)
{
#pragma unused(kctlref)
	*unitinfo = necp_create_session(sac->sc_unit);
	if (*unitinfo == NULL) {
		// Could not allocate session
		return (ENOBUFS);
	}

	return (0);
}

static errno_t
necp_ctl_disconnect(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo)
{
#pragma unused(kctlref, unit)
	struct necp_session *session = (struct necp_session *)unitinfo;
	if (session != NULL) {
		necp_policy_mark_all_for_deletion(session);
		necp_policy_apply_all(session);
		necp_delete_session((struct necp_session *)unitinfo);
	}

	return (0);
}


// Message handling
static int
necp_packet_find_tlv(mbuf_t packet, int offset, u_int8_t type, int *err, int next)
{
	size_t	cursor			= offset;
	int		error			= 0;
	size_t	curr_length;
	u_int8_t	curr_type;

	*err = 0;

	do {
		if (!next) {
			error = mbuf_copydata(packet, cursor, sizeof(curr_type), &curr_type);
			if (error) {
				*err = ENOENT;
				return (-1);
			}
		} else {
			next = 0;
			curr_type = NECP_TLV_NIL;
		}

		if (curr_type != type) {
			cursor += sizeof(curr_type);
			error = mbuf_copydata(packet, cursor, sizeof(curr_length), &curr_length);
			if (error) {
				*err = error;
				return (-1);
			}
			cursor += (sizeof(curr_length) + curr_length);
		}
	} while (curr_type != type);

	return (cursor);
}

static int
necp_packet_get_tlv_at_offset(mbuf_t packet, int tlv_offset, size_t buff_len, void *buff, size_t *value_size)
{
	int		error		= 0;
	size_t	length;

	if (tlv_offset < 0) {
		return (error);
	}

	error = mbuf_copydata(packet, tlv_offset + sizeof(u_int8_t), sizeof(length), &length);
	if (error) {
		return (error);
	}

	if (value_size != NULL) {
		*value_size = length;
	}

	if (buff != NULL && buff_len > 0) {
		size_t to_copy = (length < buff_len) ? length : buff_len;
		error = mbuf_copydata(packet, tlv_offset + sizeof(u_int8_t) + sizeof(length), to_copy, buff);
		if (error) {
			return (error);
		}
	}

	return (0);
}

static int
necp_packet_get_tlv(mbuf_t packet, int offset, u_int8_t type, size_t buff_len, void *buff, size_t *value_size)
{
	int		error		= 0;
	int		tlv_offset;

	tlv_offset = necp_packet_find_tlv(packet, offset, type, &error, 0);
	if (tlv_offset < 0) {
		return (error);
	}

	return (necp_packet_get_tlv_at_offset(packet, tlv_offset, buff_len, buff, value_size));
}

static u_int8_t *
necp_buffer_write_packet_header(u_int8_t *buffer, u_int8_t packet_type, u_int8_t flags, u_int32_t message_id)
{
	((struct necp_packet_header *)(void *)buffer)->packet_type = packet_type;
	((struct necp_packet_header *)(void *)buffer)->flags = flags;
	((struct necp_packet_header *)(void *)buffer)->message_id = message_id;
	return (buffer + sizeof(struct necp_packet_header));
}

static u_int8_t *
necp_buffer_write_tlv(u_int8_t *buffer, u_int8_t type, size_t length, const void *value)
{
	*(u_int8_t *)(buffer) = type;
	*(size_t *)(void *)(buffer + sizeof(type)) = length;
	if (length > 0) {
		memcpy((u_int8_t *)(buffer + sizeof(type) + sizeof(length)), value, length);
	}

	return ((u_int8_t *)(buffer + sizeof(type) + sizeof(length) + length));
}

static u_int8_t
necp_buffer_get_tlv_type(u_int8_t *buffer, int tlv_offset)
{
	u_int8_t *type = NULL;

	if (buffer == NULL) {
		return (0);
	}

	type = (u_int8_t *)((u_int8_t *)buffer + tlv_offset);
	return (type ? *type : 0);
}

static size_t
necp_buffer_get_tlv_length(u_int8_t *buffer, int tlv_offset)
{
	size_t *length = NULL;

	if (buffer == NULL) {
		return (0);
	}

	length = (size_t *)(void *)((u_int8_t *)buffer + tlv_offset + sizeof(u_int8_t));
	return (length ? *length : 0);
}

static u_int8_t *
necp_buffer_get_tlv_value(u_int8_t *buffer, int tlv_offset, size_t *value_size)
{
	u_int8_t *value = NULL;
	size_t length = necp_buffer_get_tlv_length(buffer, tlv_offset);
	if (length == 0) {
		return (value);
	}

	if (value_size) {
		*value_size = length;
	}

	value = (u_int8_t *)((u_int8_t *)buffer + tlv_offset + sizeof(u_int8_t) + sizeof(size_t));
	return (value);
}

static int
necp_buffer_find_tlv(u_int8_t *buffer, size_t buffer_length, int offset, u_int8_t type, int next)
{
	size_t cursor = offset;
	size_t curr_length;
	u_int8_t curr_type;

	do {
		if (cursor >= buffer_length) {
			return (-1);
		}
		if (!next) {
			curr_type = necp_buffer_get_tlv_type(buffer, cursor);
		} else {
			next = 0;
			curr_type = NECP_TLV_NIL;
		}
		if (curr_type != type) {
			curr_length = necp_buffer_get_tlv_length(buffer, cursor);
			cursor += (sizeof(curr_type) + sizeof(curr_length) + curr_length);
		}
	} while (curr_type != type);

	return (cursor);
}

static bool
necp_send_ctl_data(struct necp_session *session, u_int8_t *buffer, size_t buffer_size)
{
	int		error;

	if (necp_kctlref == NULL || session == NULL || buffer == NULL || buffer_size == 0) {
		return (FALSE);
	}

	error = ctl_enqueuedata(necp_kctlref, session->control_unit, buffer, buffer_size, CTL_DATA_EOR);

	return (error == 0);
}

static bool
necp_send_success_response(struct necp_session *session, u_int8_t packet_type, u_int32_t message_id)
{
	bool success = TRUE;
	u_int8_t *response = NULL;
	u_int8_t *cursor = NULL;
	size_t response_size = sizeof(struct necp_packet_header) + sizeof(u_int8_t) + sizeof(size_t);
	MALLOC(response, u_int8_t *, response_size, M_NECP, M_WAITOK);
	if (response == NULL) {
		return (FALSE);
	}
	cursor = response;
	cursor = necp_buffer_write_packet_header(cursor, packet_type, NECP_PACKET_FLAGS_RESPONSE, message_id);
	cursor = necp_buffer_write_tlv(cursor, NECP_TLV_NIL, 0, NULL);

	if (!(success = necp_send_ctl_data(session, (u_int8_t *)response, response_size))) {
		NECPLOG0(LOG_ERR, "Failed to send response");
	}

	FREE(response, M_NECP);
	return (success);
}

static bool
necp_send_error_response(struct necp_session *session, u_int8_t packet_type, u_int32_t message_id, u_int32_t error)
{
	bool success = TRUE;
	u_int8_t *response = NULL;
	u_int8_t *cursor = NULL;
	size_t response_size = sizeof(struct necp_packet_header) + sizeof(u_int8_t) + sizeof(size_t) + sizeof(u_int32_t);
	MALLOC(response, u_int8_t *, response_size, M_NECP, M_WAITOK);
	if (response == NULL) {
		return (FALSE);
	}
	cursor = response;
	cursor = necp_buffer_write_packet_header(cursor, packet_type, NECP_PACKET_FLAGS_RESPONSE, message_id);
	cursor = necp_buffer_write_tlv(cursor, NECP_TLV_ERROR, sizeof(error), &error);

	if (!(success = necp_send_ctl_data(session, (u_int8_t *)response, response_size))) {
		NECPLOG0(LOG_ERR, "Failed to send response");
	}

	FREE(response, M_NECP);
	return (success);
}

static bool
necp_send_policy_id_response(struct necp_session *session, u_int8_t packet_type, u_int32_t message_id, necp_policy_id policy_id)
{
	bool success = TRUE;
	u_int8_t *response = NULL;
	u_int8_t *cursor = NULL;
	size_t response_size = sizeof(struct necp_packet_header) + sizeof(u_int8_t) + sizeof(size_t) + sizeof(u_int32_t);
	MALLOC(response, u_int8_t *, response_size, M_NECP, M_WAITOK);
	if (response == NULL) {
		return (FALSE);
	}
	cursor = response;
	cursor = necp_buffer_write_packet_header(cursor, packet_type, NECP_PACKET_FLAGS_RESPONSE, message_id);
	cursor = necp_buffer_write_tlv(cursor, NECP_TLV_POLICY_ID, sizeof(policy_id), &policy_id);

	if (!(success = necp_send_ctl_data(session, (u_int8_t *)response, response_size))) {
		NECPLOG0(LOG_ERR, "Failed to send response");
	}

	FREE(response, M_NECP);
	return (success);
}

static errno_t
necp_ctl_send(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo, mbuf_t packet, int flags)
{
#pragma unused(kctlref, unit, flags)
	struct necp_session *session = (struct necp_session *)unitinfo;
	struct necp_packet_header header;
	int error = 0;

	if (session == NULL) {
		NECPLOG0(LOG_ERR, "Got a NULL session");
		error = EINVAL;
		goto done;
	}

	if (mbuf_pkthdr_len(packet) < sizeof(header)) {
		NECPLOG(LOG_ERR, "Got a bad packet, length (%lu) < sizeof header (%lu)", mbuf_pkthdr_len(packet), sizeof(header));
		error = EINVAL;
		goto done;
	}

	error = mbuf_copydata(packet, 0, sizeof(header), &header);
	if (error) {
		NECPLOG(LOG_ERR, "mbuf_copydata failed for the header: %d", error);
		error = ENOBUFS;
		goto done;
	}

	if (session->proc_locked) {
		// Verify that the calling process is allowed to send messages
		uuid_t proc_uuid;
		proc_getexecutableuuid(current_proc(), proc_uuid, sizeof(proc_uuid));
		if (uuid_compare(proc_uuid, session->proc_uuid) != 0) {
			necp_send_error_response(session, header.packet_type, header.message_id, NECP_ERROR_INVALID_PROCESS);
			goto done;
		}
	}

	switch (header.packet_type) {
		case NECP_PACKET_TYPE_POLICY_ADD: {
			necp_handle_policy_add(session, header.message_id, packet, sizeof(header));
			break;
		}
		case NECP_PACKET_TYPE_POLICY_GET: {
			necp_handle_policy_get(session, header.message_id, packet, sizeof(header));
			break;
		}
		case NECP_PACKET_TYPE_POLICY_DELETE: {
			necp_handle_policy_delete(session, header.message_id, packet, sizeof(header));
			break;
		}
		case NECP_PACKET_TYPE_POLICY_APPLY_ALL: {
			necp_handle_policy_apply_all(session, header.message_id, packet, sizeof(header));
			break;
		}
		case NECP_PACKET_TYPE_POLICY_LIST_ALL: {
			necp_handle_policy_list_all(session, header.message_id, packet, sizeof(header));
			break;
		}
		case NECP_PACKET_TYPE_POLICY_DELETE_ALL: {
			necp_handle_policy_delete_all(session, header.message_id, packet, sizeof(header));
			break;
		}
		case NECP_PACKET_TYPE_SET_SESSION_PRIORITY: {
			necp_handle_set_session_priority(session, header.message_id, packet, sizeof(header));
			break;
		}
		case NECP_PACKET_TYPE_LOCK_SESSION_TO_PROC: {
			necp_handle_lock_session_to_proc(session, header.message_id, packet, sizeof(header));
			break;
		}
		case NECP_PACKET_TYPE_REGISTER_SERVICE: {
			necp_handle_register_service(session, header.message_id, packet, sizeof(header));
			break;
		}
		case NECP_PACKET_TYPE_UNREGISTER_SERVICE: {
			necp_handle_unregister_service(session, header.message_id, packet, sizeof(header));
			break;
		}
		default: {
			NECPLOG(LOG_ERR, "Received unknown message type %d", header.packet_type);
			necp_send_error_response(session, header.packet_type, header.message_id, NECP_ERROR_UNKNOWN_PACKET_TYPE);
			break;
		}
	}

done:
	mbuf_freem(packet);
	return (error);
}

static void
necp_ctl_rcvd(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo, int flags)
{
#pragma unused(kctlref, unit, unitinfo, flags)
	return;
}

static errno_t
necp_ctl_getopt(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo, int opt, void *data, size_t *len)
{
#pragma unused(kctlref, unit, unitinfo, opt, data, len)
	return (0);
}

static errno_t
necp_ctl_setopt(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo, int opt, void *data, size_t len)
{
#pragma unused(kctlref, unit, unitinfo, opt, data, len)
	return (0);
}

// Session Management
static struct necp_session *
necp_create_session(u_int32_t control_unit)
{
	struct necp_session *new_session = NULL;

	MALLOC(new_session, struct necp_session *, sizeof(*new_session), M_NECP, M_WAITOK);
	if (new_session == NULL) {
		goto done;
	}
	if (necp_debug) {
		NECPLOG(LOG_DEBUG, "Create NECP session, control unit %d", control_unit);
	}
	memset(new_session, 0, sizeof(*new_session));
	new_session->session_priority = NECP_SESSION_PRIORITY_UNKNOWN;
	new_session->session_order = necp_allocate_new_session_order(new_session->session_priority, control_unit);
	new_session->control_unit = control_unit;
	new_session->dirty = FALSE;
	LIST_INIT(&new_session->policies);

done:
	return (new_session);
}

static void
necp_delete_session(struct necp_session *session)
{
	if (session != NULL) {
		struct necp_service_registration *service = NULL;
		struct necp_service_registration *temp_service = NULL;
		LIST_FOREACH_SAFE(service, &session->services, session_chain, temp_service) {
			LIST_REMOVE(service, session_chain);
			lck_rw_lock_exclusive(&necp_kernel_policy_lock);
			LIST_REMOVE(service, kernel_chain);
			lck_rw_done(&necp_kernel_policy_lock);
			FREE(service, M_NECP);
		}
		if (necp_debug) {
			NECPLOG0(LOG_DEBUG, "Deleted NECP session");
		}
		FREE(session, M_NECP);
	}
}

// Session Policy Management
static inline u_int8_t
necp_policy_result_get_type_from_buffer(u_int8_t *buffer, size_t length)
{
	return ((buffer && length >= sizeof(u_int8_t)) ? buffer[0] : 0);
}

static inline size_t
necp_policy_result_get_parameter_length_from_buffer(u_int8_t *buffer, size_t length)
{
	return ((buffer && length > sizeof(u_int8_t)) ? (length - sizeof(u_int8_t)) : 0);
}

static inline u_int8_t *
necp_policy_result_get_parameter_pointer_from_buffer(u_int8_t *buffer, size_t length)
{
	return ((buffer && length > sizeof(u_int8_t)) ? (buffer + sizeof(u_int8_t)) : NULL);
}

static bool
necp_policy_result_is_valid(u_int8_t *buffer, size_t length)
{
	bool validated = FALSE;
	u_int8_t type = necp_policy_result_get_type_from_buffer(buffer, length);
	size_t parameter_length = necp_policy_result_get_parameter_length_from_buffer(buffer, length);
	switch (type) {
		case NECP_POLICY_RESULT_PASS: {
			validated = TRUE;
			break;
		}
		case NECP_POLICY_RESULT_SKIP: {
			if (parameter_length >= sizeof(u_int32_t)) {
				validated = TRUE;
			}
			break;
		}
		case NECP_POLICY_RESULT_DROP: {
			validated = TRUE;
			break;
		}
		case NECP_POLICY_RESULT_SOCKET_DIVERT: {
			if (parameter_length >= sizeof(u_int32_t)) {
				validated = TRUE;
			}
			break;
		}
		case NECP_POLICY_RESULT_SOCKET_SCOPED: {
			if (parameter_length > 0) {
				validated = TRUE;
			}
			break;
		}
		case NECP_POLICY_RESULT_IP_TUNNEL: {
			if (parameter_length > sizeof(u_int32_t)) {
				validated = TRUE;
			}
			break;
		}
		case NECP_POLICY_RESULT_SOCKET_FILTER: {
			if (parameter_length >= sizeof(u_int32_t)) {
				validated = TRUE;
			}
			break;
		}
		case NECP_POLICY_RESULT_TRIGGER:
		case NECP_POLICY_RESULT_TRIGGER_IF_NEEDED:
		case NECP_POLICY_RESULT_TRIGGER_SCOPED:
		case NECP_POLICY_RESULT_NO_TRIGGER_SCOPED: {
			if (parameter_length >= sizeof(uuid_t)) {
				validated = TRUE;
			}
			break;
		}
		default: {
			validated = FALSE;
			break;
		}
	}

	if (necp_debug) {
		NECPLOG(LOG_DEBUG, "Policy result type %d, valid %d", type, validated);
	}

	return (validated);
}

static inline u_int8_t
necp_policy_condition_get_type_from_buffer(u_int8_t *buffer, size_t length)
{
	return ((buffer && length >= sizeof(u_int8_t)) ? buffer[0] : 0);
}

static inline u_int8_t
necp_policy_condition_get_flags_from_buffer(u_int8_t *buffer, size_t length)
{
	return ((buffer && length >= (2 * sizeof(u_int8_t))) ? buffer[1] : 0);
}

static inline size_t
necp_policy_condition_get_value_length_from_buffer(u_int8_t *buffer, size_t length)
{
	return ((buffer && length >= (2 * sizeof(u_int8_t))) ? (length - (2 * sizeof(u_int8_t))) : 0);
}

static inline u_int8_t *
necp_policy_condition_get_value_pointer_from_buffer(u_int8_t *buffer, size_t length)
{
	return ((buffer && length > (2 * sizeof(u_int8_t))) ? (buffer + (2 * sizeof(u_int8_t))) : NULL);
}

static inline bool
necp_policy_condition_is_default(u_int8_t *buffer, size_t length)
{
	return (necp_policy_condition_get_type_from_buffer(buffer, length) == NECP_POLICY_CONDITION_DEFAULT);
}

static inline bool
necp_policy_condition_is_application(u_int8_t *buffer, size_t length)
{
	return (necp_policy_condition_get_type_from_buffer(buffer, length) == NECP_POLICY_CONDITION_APPLICATION);
}

static inline bool
necp_policy_condition_requires_application(u_int8_t *buffer, size_t length)
{
	u_int8_t type = necp_policy_condition_get_type_from_buffer(buffer, length);
	return (type == NECP_POLICY_CONDITION_REAL_APPLICATION ||
			type == NECP_POLICY_CONDITION_ENTITLEMENT);
}

static bool
necp_policy_condition_is_valid(u_int8_t *buffer, size_t length, u_int8_t policy_result_type)
{
	bool validated = FALSE;
	bool result_cannot_have_ip_layer = (policy_result_type == NECP_POLICY_RESULT_SOCKET_DIVERT ||
										policy_result_type == NECP_POLICY_RESULT_SOCKET_FILTER ||
										policy_result_type == NECP_POLICY_RESULT_TRIGGER ||
										policy_result_type == NECP_POLICY_RESULT_TRIGGER_IF_NEEDED ||
										policy_result_type == NECP_POLICY_RESULT_TRIGGER_SCOPED ||
										policy_result_type == NECP_POLICY_RESULT_NO_TRIGGER_SCOPED ||
										policy_result_type == NECP_POLICY_RESULT_SOCKET_SCOPED) ? TRUE : FALSE;
	size_t condition_length = necp_policy_condition_get_value_length_from_buffer(buffer, length);
	u_int8_t *condition_value = necp_policy_condition_get_value_pointer_from_buffer(buffer, length);
	u_int8_t type = necp_policy_condition_get_type_from_buffer(buffer, length);
	u_int8_t flags = necp_policy_condition_get_flags_from_buffer(buffer, length);
	switch (type) {
		case NECP_POLICY_CONDITION_APPLICATION:
		case NECP_POLICY_CONDITION_REAL_APPLICATION: {
			if (!(flags & NECP_POLICY_CONDITION_FLAGS_NEGATIVE) &&
				condition_length >= sizeof(uuid_t) &&
				condition_value != NULL &&
				!uuid_is_null(condition_value)) {
				validated = TRUE;
			}
			break;
		}
		case NECP_POLICY_CONDITION_DOMAIN:
		case NECP_POLICY_CONDITION_ACCOUNT:
		case NECP_POLICY_CONDITION_BOUND_INTERFACE: {
			if (condition_length > 0) {
				validated = TRUE;
			}
			break;
		}
		case NECP_POLICY_CONDITION_TRAFFIC_CLASS: {
			if (condition_length >= sizeof(struct necp_policy_condition_tc_range)) {
				validated = TRUE;
			}
			break;
		}
		case NECP_POLICY_CONDITION_DEFAULT:
		case NECP_POLICY_CONDITION_ALL_INTERFACES:
		case NECP_POLICY_CONDITION_ENTITLEMENT: {
			if (!(flags & NECP_POLICY_CONDITION_FLAGS_NEGATIVE)) {
				validated = TRUE;
			}
			break;
		}
		case NECP_POLICY_CONDITION_IP_PROTOCOL: {
			if (condition_length >= sizeof(u_int16_t)) {
				validated = TRUE;
			}
			break;
		}
		case NECP_POLICY_CONDITION_PID: {
			if (condition_length >= sizeof(pid_t) &&
				condition_value != NULL &&
				*((pid_t *)(void *)condition_value) != 0) {
				validated = TRUE;
			}
			break;
		}
		case NECP_POLICY_CONDITION_UID: {
			if (condition_length >= sizeof(uid_t)) {
				validated = TRUE;
			}
			break;
		}
		case NECP_POLICY_CONDITION_LOCAL_ADDR:
		case NECP_POLICY_CONDITION_REMOTE_ADDR: {
			if (!result_cannot_have_ip_layer && condition_length >= sizeof(struct necp_policy_condition_addr)) {
				validated = TRUE;
			}
			break;
		}
		case NECP_POLICY_CONDITION_LOCAL_ADDR_RANGE:
		case NECP_POLICY_CONDITION_REMOTE_ADDR_RANGE: {
			if (!result_cannot_have_ip_layer && condition_length >= sizeof(struct necp_policy_condition_addr_range)) {
				validated = TRUE;
			}
			break;
		}
		default: {
			validated = FALSE;
			break;
		}
	}

	if (necp_debug) {
		NECPLOG(LOG_DEBUG, "Policy condition type %d, valid %d", type, validated);
	}

	return (validated);
}

static void
necp_handle_set_session_priority(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset)
{
	int error;
	struct necp_session_policy *policy = NULL;
	struct necp_session_policy *temp_policy = NULL;
	u_int32_t response_error = NECP_ERROR_INTERNAL;
	u_int32_t requested_session_priority = NECP_SESSION_PRIORITY_UNKNOWN;

	// Read policy id
	error = necp_packet_get_tlv(packet, offset, NECP_TLV_SESSION_PRIORITY, sizeof(requested_session_priority), &requested_session_priority, NULL);
	if (error) {
		NECPLOG(LOG_ERR, "Failed to get session priority: %d", error);
		response_error = NECP_ERROR_INVALID_TLV;
		goto fail;
	}

	if (session == NULL) {
		NECPLOG0(LOG_ERR, "Failed to find session");
		response_error = NECP_ERROR_INTERNAL;
		goto fail;
	}

	// Enforce special session priorities with entitlements
	if (requested_session_priority == NECP_SESSION_PRIORITY_CONTROL ||
		requested_session_priority == NECP_SESSION_PRIORITY_PRIVILEGED_TUNNEL) {
		errno_t cred_result = priv_check_cred(kauth_cred_get(), PRIV_NET_PRIVILEGED_NECP_POLICIES, 0);
		if (cred_result != 0) {
			NECPLOG(LOG_ERR, "Session does not hold necessary entitlement to claim priority level %d", requested_session_priority);
			goto fail;
		}
	}

	if (session->session_priority != requested_session_priority) {
		session->session_priority = requested_session_priority;
		session->session_order = necp_allocate_new_session_order(session->session_priority, session->control_unit);
		session->dirty = TRUE;

		// Mark all policies as needing updates
		LIST_FOREACH_SAFE(policy, &session->policies, chain, temp_policy) {
			policy->pending_update = TRUE;
		}
	}

	necp_send_success_response(session, NECP_PACKET_TYPE_SET_SESSION_PRIORITY, message_id);
	return;

fail:
	necp_send_error_response(session, NECP_PACKET_TYPE_SET_SESSION_PRIORITY, message_id, response_error);
}

static void
necp_handle_lock_session_to_proc(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset)
{
#pragma unused(packet, offset)
	proc_getexecutableuuid(current_proc(), session->proc_uuid, sizeof(session->proc_uuid));
	session->proc_locked = TRUE;
	necp_send_success_response(session, NECP_PACKET_TYPE_LOCK_SESSION_TO_PROC, message_id);
}

static void
necp_handle_register_service(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset)
{
	int error;
	struct necp_service_registration *new_service = NULL;
	u_int32_t response_error = NECP_ERROR_INTERNAL;
	uuid_t service_uuid;
	uuid_clear(service_uuid);

	if (session == NULL) {
		NECPLOG0(LOG_ERR, "Failed to find session");
		response_error = NECP_ERROR_INTERNAL;
		goto fail;
	}

	// Enforce entitlements
	errno_t cred_result = priv_check_cred(kauth_cred_get(), PRIV_NET_PRIVILEGED_NECP_POLICIES, 0);
	if (cred_result != 0) {
		NECPLOG0(LOG_ERR, "Session does not hold necessary entitlement to register service");
		goto fail;
	}

	// Read service uuid
	error = necp_packet_get_tlv(packet, offset, NECP_TLV_SERVICE_UUID, sizeof(uuid_t), service_uuid, NULL);
	if (error) {
		NECPLOG(LOG_ERR, "Failed to get service UUID: %d", error);
		response_error = NECP_ERROR_INVALID_TLV;
		goto fail;
	}

	MALLOC(new_service, struct necp_service_registration *, sizeof(*new_service), M_NECP, M_WAITOK);
	if (new_service == NULL) {
		NECPLOG0(LOG_ERR, "Failed to allocate service registration");
		response_error = NECP_ERROR_INTERNAL;
		goto fail;
	}
	
	lck_rw_lock_exclusive(&necp_kernel_policy_lock);
	memset(new_service, 0, sizeof(*new_service));
	new_service->service_id = necp_create_uuid_service_id_mapping(service_uuid);
	LIST_INSERT_HEAD(&session->services, new_service, session_chain);
	LIST_INSERT_HEAD(&necp_registered_service_list, new_service, kernel_chain);
	lck_rw_done(&necp_kernel_policy_lock);

	necp_send_success_response(session, NECP_PACKET_TYPE_REGISTER_SERVICE, message_id);
	return;
fail:
	necp_send_error_response(session, NECP_PACKET_TYPE_REGISTER_SERVICE, message_id, response_error);
}

static void
necp_handle_unregister_service(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset)
{
	int error;
	struct necp_service_registration *service = NULL;
	struct necp_service_registration *temp_service = NULL;
	u_int32_t response_error = NECP_ERROR_INTERNAL;
	struct necp_uuid_id_mapping *mapping = NULL;
	uuid_t service_uuid;
	uuid_clear(service_uuid);

	if (session == NULL) {
		NECPLOG0(LOG_ERR, "Failed to find session");
		response_error = NECP_ERROR_INTERNAL;
		goto fail;
	}

	// Read service uuid
	error = necp_packet_get_tlv(packet, offset, NECP_TLV_SERVICE_UUID, sizeof(uuid_t), service_uuid, NULL);
	if (error) {
		NECPLOG(LOG_ERR, "Failed to get service UUID: %d", error);
		response_error = NECP_ERROR_INVALID_TLV;
		goto fail;
	}

	// Mark remove all matching services for this session
	lck_rw_lock_exclusive(&necp_kernel_policy_lock);
	mapping = necp_uuid_lookup_service_id_locked(service_uuid);
	if (mapping != NULL) {
		LIST_FOREACH_SAFE(service, &session->services, session_chain, temp_service) {
			if (service->service_id == mapping->id) {
				LIST_REMOVE(service, session_chain);
				LIST_REMOVE(service, kernel_chain);
				FREE(service, M_NECP);
			}
		}
		necp_remove_uuid_service_id_mapping(service_uuid);
	}
	lck_rw_done(&necp_kernel_policy_lock);

	necp_send_success_response(session, NECP_PACKET_TYPE_REGISTER_SERVICE, message_id);
	return;
fail:
	necp_send_error_response(session, NECP_PACKET_TYPE_REGISTER_SERVICE, message_id, response_error);
}

static void
necp_handle_policy_add(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset)
{
	bool has_default_condition = FALSE;
	bool has_non_default_condition = FALSE;
	bool has_application_condition = FALSE;
	bool requires_application_condition = FALSE;
	u_int8_t *conditions_array = NULL;
	size_t conditions_array_size = 0;
	int conditions_array_cursor;

	int cursor;
	int error = 0;
	u_int32_t response_error = NECP_ERROR_INTERNAL;

	necp_policy_order order = 0;
	struct necp_session_policy *policy = NULL;
	u_int8_t *policy_result = NULL;
	size_t policy_result_size = 0;

	// Read policy order
	error = necp_packet_get_tlv(packet, offset, NECP_TLV_POLICY_ORDER, sizeof(order), &order, NULL);
	if (error) {
		NECPLOG(LOG_ERR, "Failed to get policy order: %d", error);
		response_error = NECP_ERROR_INVALID_TLV;
		goto fail;
	}

	// Read policy result
	cursor = necp_packet_find_tlv(packet, offset, NECP_TLV_POLICY_RESULT, &error, 0);
	error = necp_packet_get_tlv_at_offset(packet, cursor, 0, NULL, &policy_result_size);
	if (error || policy_result_size == 0) {
		NECPLOG(LOG_ERR, "Failed to get policy result length: %d", error);
		response_error = NECP_ERROR_INVALID_TLV;
		goto fail;
	}
	MALLOC(policy_result, u_int8_t *, policy_result_size, M_NECP, M_WAITOK);
	if (policy_result == NULL) {
		NECPLOG(LOG_ERR, "Failed to allocate a policy result buffer (size %d)", policy_result_size);
		response_error = NECP_ERROR_INTERNAL;
		goto fail;
	}
	error = necp_packet_get_tlv_at_offset(packet, cursor, policy_result_size, policy_result, NULL);
	if (error) {
		NECPLOG(LOG_ERR, "Failed to get policy result: %d", error);
		response_error = NECP_ERROR_POLICY_RESULT_INVALID;
		goto fail;
	}
	if (!necp_policy_result_is_valid(policy_result, policy_result_size)) {
		NECPLOG0(LOG_ERR, "Failed to validate policy result");
		response_error = NECP_ERROR_POLICY_RESULT_INVALID;
		goto fail;
	}

	// Read policy conditions
	for (cursor = necp_packet_find_tlv(packet, offset, NECP_TLV_POLICY_CONDITION, &error, 0);
		cursor >= 0;
		cursor = necp_packet_find_tlv(packet, cursor, NECP_TLV_POLICY_CONDITION, &error, 1)) {
		size_t condition_size = 0;
		necp_packet_get_tlv_at_offset(packet, cursor, 0, NULL, &condition_size);

		if (condition_size > 0) {
			conditions_array_size += (sizeof(u_int8_t) + sizeof(size_t) + condition_size);
		}
	}

	if (conditions_array_size == 0) {
		NECPLOG0(LOG_ERR, "Failed to get policy conditions");
		response_error = NECP_ERROR_INVALID_TLV;
		goto fail;
	}
	MALLOC(conditions_array, u_int8_t *, conditions_array_size, M_NECP, M_WAITOK);
	if (conditions_array == NULL) {
		NECPLOG(LOG_ERR, "Failed to allocate a policy conditions array (size %d)", conditions_array_size);
		response_error = NECP_ERROR_INTERNAL;
		goto fail;
	}

	conditions_array_cursor = 0;
	for (cursor = necp_packet_find_tlv(packet, offset, NECP_TLV_POLICY_CONDITION, &error, 0);
		cursor >= 0;
		cursor = necp_packet_find_tlv(packet, cursor, NECP_TLV_POLICY_CONDITION, &error, 1)) {
		u_int8_t condition_type = NECP_TLV_POLICY_CONDITION;
		size_t condition_size = 0;
		necp_packet_get_tlv_at_offset(packet, cursor, 0, NULL, &condition_size);
		if (condition_size > 0 && condition_size <= (conditions_array_size - conditions_array_cursor)) {
			// Add type
			memcpy((conditions_array + conditions_array_cursor), &condition_type, sizeof(condition_type));
			conditions_array_cursor += sizeof(condition_type);

			// Add length
			memcpy((conditions_array + conditions_array_cursor), &condition_size, sizeof(condition_size));
			conditions_array_cursor += sizeof(condition_size);

			// Add value
			necp_packet_get_tlv_at_offset(packet, cursor, condition_size, (conditions_array + conditions_array_cursor), NULL);
			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))) {
				NECPLOG0(LOG_ERR, "Failed to validate policy condition");
				response_error = NECP_ERROR_POLICY_CONDITIONS_INVALID;
				goto fail;
			}

			if (necp_policy_condition_is_default((conditions_array + conditions_array_cursor), condition_size)) {
				has_default_condition = TRUE;
			} else {
				has_non_default_condition = TRUE;
			}
			if (has_default_condition && has_non_default_condition) {
				NECPLOG0(LOG_ERR, "Failed to validate conditions; contained default and non-default conditions");
				response_error = NECP_ERROR_POLICY_CONDITIONS_INVALID;
				goto fail;
			}
			
			if (necp_policy_condition_is_application((conditions_array + conditions_array_cursor), condition_size)) {
				has_application_condition = TRUE;
			}
			
			if (necp_policy_condition_requires_application((conditions_array + conditions_array_cursor), condition_size)) {
				requires_application_condition = TRUE;
			}

			conditions_array_cursor += condition_size;
		}
	}
	
	if (requires_application_condition && !has_application_condition) {
		NECPLOG0(LOG_ERR, "Failed to validate conditions; did not contain application condition");
		response_error = NECP_ERROR_POLICY_CONDITIONS_INVALID;
		goto fail;
	}

	if ((policy = necp_policy_create(session, order, conditions_array, conditions_array_size, policy_result, policy_result_size)) == NULL) {
		response_error = NECP_ERROR_INTERNAL;
		goto fail;
	}

	necp_send_policy_id_response(session, NECP_PACKET_TYPE_POLICY_ADD, message_id, policy->id);
	return;

fail:
	if (policy_result != NULL) {
		FREE(policy_result, M_NECP);
	}
	if (conditions_array != NULL) {
		FREE(conditions_array, M_NECP);
	}

	necp_send_error_response(session, NECP_PACKET_TYPE_POLICY_ADD, message_id, response_error);
}

static void
necp_handle_policy_get(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset)
{
#pragma unused(offset)
	int error;
	u_int8_t *response = NULL;
	u_int8_t *cursor = NULL;
	u_int32_t response_error = NECP_ERROR_INTERNAL;
	necp_policy_id policy_id = 0;
	size_t order_tlv_size = 0;
	size_t result_tlv_size = 0;
	size_t response_size = 0;

	struct necp_session_policy *policy = NULL;

	// Read policy id
	error = necp_packet_get_tlv(packet, offset, NECP_TLV_POLICY_ID, sizeof(policy_id), &policy_id, NULL);
	if (error) {
		NECPLOG(LOG_ERR, "Failed to get policy id: %d", error);
		response_error = NECP_ERROR_INVALID_TLV;
		goto fail;
	}

	policy = necp_policy_find(session, policy_id);
	if (policy == NULL || policy->pending_deletion) {
		NECPLOG(LOG_ERR, "Failed to find policy with id %d", policy_id);
		response_error = NECP_ERROR_POLICY_ID_NOT_FOUND;
		goto fail;
	}

	order_tlv_size = sizeof(u_int8_t) + sizeof(size_t) + sizeof(necp_policy_order);
	result_tlv_size = (policy->result_size ? (sizeof(u_int8_t) + sizeof(size_t) + policy->result_size) : 0);
	response_size = sizeof(struct necp_packet_header) + order_tlv_size + result_tlv_size + policy->conditions_size;
	MALLOC(response, u_int8_t *, response_size, M_NECP, M_WAITOK);
	if (response == NULL) {
		necp_send_error_response(session, NECP_PACKET_TYPE_POLICY_LIST_ALL, message_id, NECP_ERROR_INTERNAL);
		return;
	}

	cursor = response;
	cursor = necp_buffer_write_packet_header(cursor, NECP_PACKET_TYPE_POLICY_GET, NECP_PACKET_FLAGS_RESPONSE, message_id);
	cursor = necp_buffer_write_tlv(cursor, NECP_TLV_POLICY_ORDER, sizeof(necp_policy_order), &policy->order);

	if (result_tlv_size) {
		cursor = necp_buffer_write_tlv(cursor, NECP_TLV_POLICY_RESULT, policy->result_size, &policy->result);
	}
	if (policy->conditions_size) {
		memcpy(((u_int8_t *)(void *)(cursor)), policy->conditions, policy->conditions_size);
	}

	if (!necp_send_ctl_data(session, (u_int8_t *)response, response_size)) {
		NECPLOG0(LOG_ERR, "Failed to send response");
	}

	FREE(response, M_NECP);
	return;

fail:
	necp_send_error_response(session, NECP_PACKET_TYPE_POLICY_GET, message_id, response_error);
}

static void
necp_handle_policy_delete(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset)
{
	int error;
	u_int32_t response_error = NECP_ERROR_INTERNAL;
	necp_policy_id policy_id = 0;

	struct necp_session_policy *policy = NULL;

	// Read policy id
	error = necp_packet_get_tlv(packet, offset, NECP_TLV_POLICY_ID, sizeof(policy_id), &policy_id, NULL);
	if (error) {
		NECPLOG(LOG_ERR, "Failed to get policy id: %d", error);
		response_error = NECP_ERROR_INVALID_TLV;
		goto fail;
	}

	policy = necp_policy_find(session, policy_id);
	if (policy == NULL || policy->pending_deletion) {
		NECPLOG(LOG_ERR, "Failed to find policy with id %d", policy_id);
		response_error = NECP_ERROR_POLICY_ID_NOT_FOUND;
		goto fail;
	}

	necp_policy_mark_for_deletion(session, policy);

	necp_send_success_response(session, NECP_PACKET_TYPE_POLICY_DELETE, message_id);
	return;

fail:
	necp_send_error_response(session, NECP_PACKET_TYPE_POLICY_DELETE, message_id, response_error);
}

static void
necp_handle_policy_apply_all(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset)
{
#pragma unused(packet, offset)
	necp_policy_apply_all(session);
	necp_send_success_response(session, NECP_PACKET_TYPE_POLICY_APPLY_ALL, message_id);
}

static void
necp_handle_policy_list_all(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset)
{
#pragma unused(packet, offset)
	size_t tlv_size = (sizeof(u_int8_t) + sizeof(size_t) + sizeof(u_int32_t));
	size_t response_size = 0;
	u_int8_t *response = NULL;
	u_int8_t *cursor = NULL;
	int num_policies = 0;
	int cur_policy_index = 0;
	struct necp_session_policy *policy;

	LIST_FOREACH(policy, &session->policies, chain) {
		if (!policy->pending_deletion) {
			num_policies++;
		}
	}

	// Create a response with one Policy ID TLV for each policy
	response_size = sizeof(struct necp_packet_header) + num_policies * tlv_size;
	MALLOC(response, u_int8_t *, response_size, M_NECP, M_WAITOK);
	if (response == NULL) {
		necp_send_error_response(session, NECP_PACKET_TYPE_POLICY_LIST_ALL, message_id, NECP_ERROR_INTERNAL);
		return;
	}

	cursor = response;
	cursor = necp_buffer_write_packet_header(cursor, NECP_PACKET_TYPE_POLICY_LIST_ALL, NECP_PACKET_FLAGS_RESPONSE, message_id);

	LIST_FOREACH(policy, &session->policies, chain) {
		if (!policy->pending_deletion && cur_policy_index < num_policies) {
			cursor = necp_buffer_write_tlv(cursor, NECP_TLV_POLICY_ID, sizeof(u_int32_t), &policy->id);
			cur_policy_index++;
		}
	}

	if (!necp_send_ctl_data(session, (u_int8_t *)response, response_size)) {
		NECPLOG0(LOG_ERR, "Failed to send response");
	}

	FREE(response, M_NECP);
}

static void
necp_handle_policy_delete_all(struct necp_session *session, u_int32_t message_id, mbuf_t packet, int offset)
{
#pragma unused(packet, offset)
	necp_policy_mark_all_for_deletion(session);
	necp_send_success_response(session, NECP_PACKET_TYPE_POLICY_DELETE_ALL, message_id);
}

static necp_policy_id
necp_policy_get_new_id(void)
{
	necp_policy_id newid = 0;

	lck_rw_lock_exclusive(&necp_kernel_policy_lock);

	necp_last_policy_id++;
	if (necp_last_policy_id < 1) {
		necp_last_policy_id = 1;
	}

	newid = necp_last_policy_id;
	lck_rw_done(&necp_kernel_policy_lock);

	if (newid == 0) {
		NECPLOG0(LOG_DEBUG, "Allocate policy id failed.\n");
		return (0);
	}

	return (newid);
}

static struct necp_session_policy *
necp_policy_create(struct necp_session *session, necp_policy_order order, u_int8_t *conditions_array, size_t conditions_array_size, u_int8_t *result, size_t result_size)
{
	struct necp_session_policy *new_policy = NULL;
	struct necp_session_policy *tmp_policy = NULL;

	if (session == NULL || conditions_array == NULL || result == NULL || result_size == 0) {
		goto done;
	}

	MALLOC_ZONE(new_policy, struct necp_session_policy *, sizeof(*new_policy), M_NECP_SESSION_POLICY, M_WAITOK);
	if (new_policy == NULL) {
		goto done;
	}

	memset(new_policy, 0, sizeof(*new_policy));
	new_policy->applied = FALSE;
	new_policy->pending_deletion = FALSE;
	new_policy->pending_update = FALSE;
	new_policy->order = order;
	new_policy->conditions = conditions_array;
	new_policy->conditions_size = conditions_array_size;
	new_policy->result = result;
	new_policy->result_size = result_size;
	new_policy->id = necp_policy_get_new_id();

	LIST_INSERT_SORTED_ASCENDING(&session->policies, new_policy, chain, order, tmp_policy);

	session->dirty = TRUE;

	if (necp_debug) {
		NECPLOG(LOG_DEBUG, "Created NECP policy, order %d", order);
	}
done:
	return (new_policy);
}

static struct necp_session_policy *
necp_policy_find(struct necp_session *session, necp_policy_id policy_id)
{
	struct necp_session_policy *policy = NULL;
	if (policy_id == 0) {
		return (NULL);
	}

	LIST_FOREACH(policy, &session->policies, chain) {
		if (policy->id == policy_id) {
			return (policy);
		}
	}

	return (NULL);
}

static inline u_int8_t
necp_policy_get_result_type(struct necp_session_policy *policy)
{
	return (policy ? necp_policy_result_get_type_from_buffer(policy->result, policy->result_size) : 0);
}

static inline size_t
necp_policy_get_result_parameter_length(struct necp_session_policy *policy)
{
	return (policy ? necp_policy_result_get_parameter_length_from_buffer(policy->result, policy->result_size) : 0);
}

static bool
necp_policy_get_result_parameter(struct necp_session_policy *policy, u_int8_t *parameter_buffer, size_t parameter_buffer_length)
{
	if (policy) {
		size_t parameter_length = necp_policy_result_get_parameter_length_from_buffer(policy->result, policy->result_size);
		if (parameter_buffer_length >= parameter_length) {
			u_int8_t *parameter = necp_policy_result_get_parameter_pointer_from_buffer(policy->result, policy->result_size);
			if (parameter && parameter_buffer) {
				memcpy(parameter_buffer, parameter, parameter_length);
				return (TRUE);
			}
		}
	}

	return (FALSE);
}

static bool
necp_policy_mark_for_deletion(struct necp_session *session, struct necp_session_policy *policy)
{
	if (session == NULL || policy == NULL) {
		return (FALSE);
	}

	policy->pending_deletion = TRUE;
	session->dirty = TRUE;

	if (necp_debug) {
		NECPLOG0(LOG_DEBUG, "Marked NECP policy for removal");
	}
	return (TRUE);
}

static bool
necp_policy_mark_all_for_deletion(struct necp_session *session)
{
	struct necp_session_policy *policy = NULL;
	struct necp_session_policy *temp_policy = NULL;

	LIST_FOREACH_SAFE(policy, &session->policies, chain, temp_policy) {
		necp_policy_mark_for_deletion(session, policy);
	}

	return (TRUE);
}

static bool
necp_policy_delete(struct necp_session *session, struct necp_session_policy *policy)
{
	if (session == NULL || policy == NULL) {
		return (FALSE);
	}

	LIST_REMOVE(policy, chain);

	if (policy->result) {
		FREE(policy->result, M_NECP);
		policy->result = NULL;
	}

	if (policy->conditions) {
		FREE(policy->conditions, M_NECP);
		policy->conditions = NULL;
	}

	FREE_ZONE(policy, sizeof(*policy), M_NECP_SESSION_POLICY);

	if (necp_debug) {
		NECPLOG0(LOG_DEBUG, "Removed NECP policy");
	}
	return (TRUE);
}

static bool
necp_policy_unapply(struct necp_session_policy *policy)
{
	int i = 0;
	if (policy == NULL) {
		return (FALSE);
	}

	lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	// Release local uuid mappings
	if (!uuid_is_null(policy->applied_app_uuid)) {
		bool removed_mapping = FALSE;
		if (necp_remove_uuid_app_id_mapping(policy->applied_app_uuid, &removed_mapping, TRUE) && removed_mapping) {
			necp_uuid_app_id_mappings_dirty = TRUE;
			necp_num_uuid_app_id_mappings--;
		}
		uuid_clear(policy->applied_app_uuid);
	}
	if (!uuid_is_null(policy->applied_real_app_uuid)) {
		necp_remove_uuid_app_id_mapping(policy->applied_real_app_uuid, NULL, FALSE);
		uuid_clear(policy->applied_real_app_uuid);
	}
	if (!uuid_is_null(policy->applied_service_uuid)) {
		necp_remove_uuid_service_id_mapping(policy->applied_service_uuid);
		uuid_clear(policy->applied_service_uuid);
	}

	// Release string mappings
	if (policy->applied_account != NULL) {
		necp_remove_string_to_id_mapping(&necp_account_id_list, policy->applied_account);
		FREE(policy->applied_account, M_NECP);
		policy->applied_account = NULL;
	}

	// Remove socket policies
	for (i = 0; i < MAX_KERNEL_SOCKET_POLICIES; i++) {
		if (policy->kernel_socket_policies[i] != 0) {
			necp_kernel_socket_policy_delete(policy->kernel_socket_policies[i]);
			policy->kernel_socket_policies[i] = 0;
		}
	}

	// Remove IP output policies
	for (i = 0; i < MAX_KERNEL_IP_OUTPUT_POLICIES; i++) {
		if (policy->kernel_ip_output_policies[i] != 0) {
			necp_kernel_ip_output_policy_delete(policy->kernel_ip_output_policies[i]);
			policy->kernel_ip_output_policies[i] = 0;
		}
	}

	policy->applied = FALSE;

	return (TRUE);
}

#define	NECP_KERNEL_POLICY_SUBORDER_ID_TUNNEL_CONDITION			0
#define	NECP_KERNEL_POLICY_SUBORDER_NON_ID_TUNNEL_CONDITION		1
#define	NECP_KERNEL_POLICY_SUBORDER_ID_CONDITION				2
#define	NECP_KERNEL_POLICY_SUBORDER_NON_ID_CONDITIONS			3
struct necp_policy_result_ip_tunnel {
	u_int32_t secondary_result;
	char interface_name[IFXNAMSIZ];
} __attribute__((__packed__));

struct necp_policy_result_service {
	uuid_t identifier;
	u_int32_t data;
} __attribute__((__packed__));

static bool
necp_policy_apply(struct necp_session *session, struct necp_session_policy *policy)
{
	bool socket_only_conditions = FALSE;
	bool socket_ip_conditions = FALSE;

	bool socket_layer_non_id_conditions = FALSE;
	bool ip_output_layer_non_id_conditions = FALSE;
	bool ip_output_layer_id_condition = FALSE;
	bool ip_output_layer_tunnel_condition_from_id = FALSE;
	bool ip_output_layer_tunnel_condition_from_non_id = FALSE;
	necp_kernel_policy_id cond_ip_output_layer_id = NECP_KERNEL_POLICY_ID_NONE;

	u_int32_t master_condition_mask = 0;
	u_int32_t master_condition_negated_mask = 0;
	ifnet_t cond_bound_interface = NULL;
	u_int32_t cond_account_id = 0;
	char *cond_domain = NULL;
	pid_t cond_pid = 0;
	uid_t cond_uid = 0;
	necp_app_id cond_app_id = 0;
	necp_app_id cond_real_app_id = 0;
	struct necp_policy_condition_tc_range cond_traffic_class;
	cond_traffic_class.start_tc = 0;
	cond_traffic_class.end_tc = 0;
	u_int16_t cond_protocol = 0;
	union necp_sockaddr_union cond_local_start;
	union necp_sockaddr_union cond_local_end;
	u_int8_t cond_local_prefix = 0;
	union necp_sockaddr_union cond_remote_start;
	union necp_sockaddr_union cond_remote_end;
	u_int8_t cond_remote_prefix = 0;
	size_t offset = 0;
	u_int8_t ultimate_result = 0;
	u_int32_t secondary_result = 0;
	necp_kernel_policy_result_parameter secondary_result_parameter;
	memset(&secondary_result_parameter, 0, sizeof(secondary_result_parameter));
	u_int32_t cond_last_interface_index = 0;
	necp_kernel_policy_result_parameter ultimate_result_parameter;
	memset(&ultimate_result_parameter, 0, sizeof(ultimate_result_parameter));

	if (policy == NULL) {
		return (FALSE);
	}

	lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	// Process conditions
	while (offset < policy->conditions_size) {
		size_t length = 0;
		u_int8_t *value = necp_buffer_get_tlv_value(policy->conditions, offset, &length);

		u_int8_t condition_type = necp_policy_condition_get_type_from_buffer(value, length);
		u_int8_t condition_flags = necp_policy_condition_get_flags_from_buffer(value, length);
		bool condition_is_negative = condition_flags & NECP_POLICY_CONDITION_FLAGS_NEGATIVE;
		size_t condition_length = necp_policy_condition_get_value_length_from_buffer(value, length);
		u_int8_t *condition_value = necp_policy_condition_get_value_pointer_from_buffer(value, length);
		switch (condition_type) {
			case NECP_POLICY_CONDITION_DEFAULT: {
				socket_ip_conditions = TRUE;
				break;
			}
			case NECP_POLICY_CONDITION_ALL_INTERFACES: {
				master_condition_mask |= NECP_KERNEL_CONDITION_ALL_INTERFACES;
				socket_ip_conditions = TRUE;
				break;
			}
			case NECP_POLICY_CONDITION_ENTITLEMENT: {
				master_condition_mask |= NECP_KERNEL_CONDITION_ENTITLEMENT;
				socket_only_conditions = TRUE;
				break;
			}
			case NECP_POLICY_CONDITION_DOMAIN: {
				// Make sure there is only one such rule
				if (condition_length > 0 && cond_domain == NULL) {
					cond_domain = necp_create_trimmed_domain((char *)condition_value, condition_length);
					if (cond_domain != NULL) {
						master_condition_mask |= NECP_KERNEL_CONDITION_DOMAIN;
						if (condition_is_negative) {
							master_condition_negated_mask |= NECP_KERNEL_CONDITION_DOMAIN;
						}
						socket_only_conditions = TRUE;
					}
				}
				break;
			}
			case NECP_POLICY_CONDITION_ACCOUNT: {
				// Make sure there is only one such rule
				if (condition_length > 0 && cond_account_id == 0 && policy->applied_account == NULL) {
					char *string = NULL;
					MALLOC(string, char *, condition_length + 1, M_NECP, M_WAITOK);
					if (string != NULL) {
						memcpy(string, condition_value, condition_length);
						string[condition_length] = 0;
						cond_account_id = necp_create_string_to_id_mapping(&necp_account_id_list, string);
						if (cond_account_id != 0) {
							policy->applied_account = string; // Save the string in parent policy
							master_condition_mask |= NECP_KERNEL_CONDITION_ACCOUNT_ID;
							if (condition_is_negative) {
								master_condition_negated_mask |= NECP_KERNEL_CONDITION_ACCOUNT_ID;
							}
							socket_only_conditions = TRUE;
						} else {
							FREE(string, M_NECP);
						}
					}
				}
				break;
			}
			case NECP_POLICY_CONDITION_APPLICATION: {
				// Make sure there is only one such rule, because we save the uuid in the policy
				if (condition_length >= sizeof(uuid_t) && cond_app_id == 0) {
					bool allocated_mapping = FALSE;
					uuid_t application_uuid;
					memcpy(application_uuid, condition_value, sizeof(uuid_t));
					cond_app_id = necp_create_uuid_app_id_mapping(application_uuid, &allocated_mapping, TRUE);
					if (cond_app_id != 0) {
						if (allocated_mapping) {
							necp_uuid_app_id_mappings_dirty = TRUE;
							necp_num_uuid_app_id_mappings++;
						}
						uuid_copy(policy->applied_app_uuid, application_uuid);
						master_condition_mask |= NECP_KERNEL_CONDITION_APP_ID;
						if (condition_is_negative) {
							master_condition_negated_mask |= NECP_KERNEL_CONDITION_APP_ID;
						}
						socket_only_conditions = TRUE;
					}
				}
				break;
			}
			case NECP_POLICY_CONDITION_REAL_APPLICATION: {
				// Make sure there is only one such rule, because we save the uuid in the policy
				if (condition_length >= sizeof(uuid_t) && cond_real_app_id == 0) {
					uuid_t real_application_uuid;
					memcpy(real_application_uuid, condition_value, sizeof(uuid_t));
					cond_real_app_id = necp_create_uuid_app_id_mapping(real_application_uuid, NULL, FALSE);
					if (cond_real_app_id != 0) {
						uuid_copy(policy->applied_real_app_uuid, real_application_uuid);
						master_condition_mask |= NECP_KERNEL_CONDITION_REAL_APP_ID;
						if (condition_is_negative) {
							master_condition_negated_mask |= NECP_KERNEL_CONDITION_REAL_APP_ID;
						}
						socket_only_conditions = TRUE;
					}
				}
				break;
			}
			case NECP_POLICY_CONDITION_PID: {
				if (condition_length >= sizeof(pid_t)) {
					master_condition_mask |= NECP_KERNEL_CONDITION_PID;
					if (condition_is_negative) {
						master_condition_negated_mask |= NECP_KERNEL_CONDITION_PID;
					}
					memcpy(&cond_pid, condition_value, sizeof(cond_pid));
					socket_only_conditions = TRUE;
				}
				break;
			}
			case NECP_POLICY_CONDITION_UID: {
				if (condition_length >= sizeof(uid_t)) {
					master_condition_mask |= NECP_KERNEL_CONDITION_UID;
					if (condition_is_negative) {
						master_condition_negated_mask |= NECP_KERNEL_CONDITION_UID;
					}
					memcpy(&cond_uid, condition_value, sizeof(cond_uid));
					socket_only_conditions = TRUE;
				}
				break;
			}
			case NECP_POLICY_CONDITION_TRAFFIC_CLASS: {
				if (condition_length >= sizeof(struct necp_policy_condition_tc_range)) {
					master_condition_mask |= NECP_KERNEL_CONDITION_TRAFFIC_CLASS;
					if (condition_is_negative) {
						master_condition_negated_mask |= NECP_KERNEL_CONDITION_TRAFFIC_CLASS;
					}
					memcpy(&cond_traffic_class, condition_value, sizeof(cond_traffic_class));
					socket_only_conditions = TRUE;
				}
				break;
			}
			case NECP_POLICY_CONDITION_BOUND_INTERFACE: {
				if (condition_length <= IFXNAMSIZ && condition_length > 0) {
					char interface_name[IFXNAMSIZ];
					memcpy(interface_name, condition_value, condition_length);
					interface_name[condition_length - 1] = 0; // Make sure the string is NULL terminated
					if (ifnet_find_by_name(interface_name, &cond_bound_interface) == 0) {
						master_condition_mask |= NECP_KERNEL_CONDITION_BOUND_INTERFACE;
						if (condition_is_negative) {
							master_condition_negated_mask |= NECP_KERNEL_CONDITION_BOUND_INTERFACE;
						}
					}
					socket_ip_conditions = TRUE;
				}
				break;
			}
			case NECP_POLICY_CONDITION_IP_PROTOCOL: {
				if (condition_length >= sizeof(u_int16_t)) {
					master_condition_mask |= NECP_KERNEL_CONDITION_PROTOCOL;
					if (condition_is_negative) {
						master_condition_negated_mask |= NECP_KERNEL_CONDITION_PROTOCOL;
					}
					memcpy(&cond_protocol, condition_value, sizeof(cond_protocol));
					socket_ip_conditions = TRUE;
				}
				break;
			}
			case NECP_POLICY_CONDITION_LOCAL_ADDR: {
				struct necp_policy_condition_addr *address_struct = (struct necp_policy_condition_addr *)(void *)condition_value;
				cond_local_prefix = address_struct->prefix;
				memcpy(&cond_local_start, &address_struct->address, sizeof(address_struct->address));
				master_condition_mask |= NECP_KERNEL_CONDITION_LOCAL_START;
				master_condition_mask |= NECP_KERNEL_CONDITION_LOCAL_PREFIX;
				if (condition_is_negative) {
					master_condition_negated_mask |= NECP_KERNEL_CONDITION_LOCAL_START;
					master_condition_negated_mask |= NECP_KERNEL_CONDITION_LOCAL_PREFIX;
				}
				socket_ip_conditions = TRUE;
				break;
			}
			case NECP_POLICY_CONDITION_REMOTE_ADDR: {
				struct necp_policy_condition_addr *address_struct = (struct necp_policy_condition_addr *)(void *)condition_value;
				cond_remote_prefix = address_struct->prefix;
				memcpy(&cond_remote_start, &address_struct->address, sizeof(address_struct->address));
				master_condition_mask |= NECP_KERNEL_CONDITION_REMOTE_START;
				master_condition_mask |= NECP_KERNEL_CONDITION_REMOTE_PREFIX;
				if (condition_is_negative) {
					master_condition_negated_mask |= NECP_KERNEL_CONDITION_REMOTE_START;
					master_condition_negated_mask |= NECP_KERNEL_CONDITION_REMOTE_PREFIX;
				}
				socket_ip_conditions = TRUE;
				break;
			}
			case NECP_POLICY_CONDITION_LOCAL_ADDR_RANGE: {
				struct necp_policy_condition_addr_range *address_struct = (struct necp_policy_condition_addr_range *)(void *)condition_value;
				memcpy(&cond_local_start, &address_struct->start_address, sizeof(address_struct->start_address));
				memcpy(&cond_local_end, &address_struct->end_address, sizeof(address_struct->end_address));
				master_condition_mask |= NECP_KERNEL_CONDITION_LOCAL_START;
				master_condition_mask |= NECP_KERNEL_CONDITION_LOCAL_END;
				if (condition_is_negative) {
					master_condition_negated_mask |= NECP_KERNEL_CONDITION_LOCAL_START;
					master_condition_negated_mask |= NECP_KERNEL_CONDITION_LOCAL_END;
				}
				socket_ip_conditions = TRUE;
				break;
			}
			case NECP_POLICY_CONDITION_REMOTE_ADDR_RANGE: {
				struct necp_policy_condition_addr_range *address_struct = (struct necp_policy_condition_addr_range *)(void *)condition_value;
				memcpy(&cond_remote_start, &address_struct->start_address, sizeof(address_struct->start_address));
				memcpy(&cond_remote_end, &address_struct->end_address, sizeof(address_struct->end_address));
				master_condition_mask |= NECP_KERNEL_CONDITION_REMOTE_START;
				master_condition_mask |= NECP_KERNEL_CONDITION_REMOTE_END;
				if (condition_is_negative) {
					master_condition_negated_mask |= NECP_KERNEL_CONDITION_REMOTE_START;
					master_condition_negated_mask |= NECP_KERNEL_CONDITION_REMOTE_END;
				}
				socket_ip_conditions = TRUE;
				break;
			}
			default: {
				break;
			}
		}

		offset += sizeof(u_int8_t) + sizeof(size_t) + length;
	}

	// Process result
	ultimate_result = necp_policy_get_result_type(policy);
	switch (ultimate_result) {
		case NECP_POLICY_RESULT_PASS: {
			if (socket_only_conditions) { // socket_ip_conditions can be TRUE or FALSE
				socket_layer_non_id_conditions = TRUE;
				ip_output_layer_id_condition = TRUE;
			} else if (socket_ip_conditions) {
				socket_layer_non_id_conditions = TRUE;
				ip_output_layer_id_condition = TRUE;
				ip_output_layer_non_id_conditions = TRUE;
			}
			break;
		}
		case NECP_POLICY_RESULT_DROP: {
			if (socket_only_conditions) { // socket_ip_conditions can be TRUE or FALSE
				socket_layer_non_id_conditions = TRUE;
			} else if (socket_ip_conditions) {
				socket_layer_non_id_conditions = TRUE;
				ip_output_layer_non_id_conditions = TRUE;
			}
			break;
		}
		case NECP_POLICY_RESULT_SKIP: {
			u_int32_t skip_policy_order = 0;
			if (necp_policy_get_result_parameter(policy, (u_int8_t *)&skip_policy_order, sizeof(skip_policy_order))) {
				ultimate_result_parameter.skip_policy_order = skip_policy_order;
			}

			if (socket_only_conditions) { // socket_ip_conditions can be TRUE or FALSE
				socket_layer_non_id_conditions = TRUE;
				ip_output_layer_id_condition = TRUE;
			} else if (socket_ip_conditions) {
				socket_layer_non_id_conditions = TRUE;
				ip_output_layer_non_id_conditions = TRUE;
			}
			break;
		}
		case NECP_POLICY_RESULT_SOCKET_DIVERT:
		case NECP_POLICY_RESULT_SOCKET_FILTER: {
			u_int32_t control_unit = 0;
			if (necp_policy_get_result_parameter(policy, (u_int8_t *)&control_unit, sizeof(control_unit))) {
				ultimate_result_parameter.flow_divert_control_unit = control_unit;
			}
			socket_layer_non_id_conditions = TRUE;
			break;
		}
		case NECP_POLICY_RESULT_IP_TUNNEL: {
			struct necp_policy_result_ip_tunnel tunnel_parameters;
			size_t tunnel_parameters_length = necp_policy_get_result_parameter_length(policy);
			if (tunnel_parameters_length > sizeof(u_int32_t) &&
				tunnel_parameters_length <= sizeof(struct necp_policy_result_ip_tunnel) &&
				necp_policy_get_result_parameter(policy, (u_int8_t *)&tunnel_parameters, sizeof(tunnel_parameters))) {
				ifnet_t tunnel_interface = NULL;
				tunnel_parameters.interface_name[tunnel_parameters_length - sizeof(u_int32_t) - 1] = 0; // Make sure the string is NULL terminated
				if (ifnet_find_by_name(tunnel_parameters.interface_name, &tunnel_interface) == 0) {
					ultimate_result_parameter.tunnel_interface_index = tunnel_interface->if_index;
				}

				secondary_result = tunnel_parameters.secondary_result;
				if (secondary_result) {
					cond_last_interface_index = ultimate_result_parameter.tunnel_interface_index;
				}
			}

			if (socket_only_conditions) { // socket_ip_conditions can be TRUE or FALSE
				socket_layer_non_id_conditions = TRUE;
				ip_output_layer_id_condition = TRUE;
				if (secondary_result) {
					ip_output_layer_tunnel_condition_from_id = TRUE;
				}
			} else if (socket_ip_conditions) {
				socket_layer_non_id_conditions = TRUE;
				ip_output_layer_id_condition = TRUE;
				ip_output_layer_non_id_conditions = TRUE;
				if (secondary_result) {
					ip_output_layer_tunnel_condition_from_id = TRUE;
					ip_output_layer_tunnel_condition_from_non_id = TRUE;
				}
			}
			break;
		}
		case NECP_POLICY_RESULT_TRIGGER:
		case NECP_POLICY_RESULT_TRIGGER_IF_NEEDED:
		case NECP_POLICY_RESULT_TRIGGER_SCOPED:
		case NECP_POLICY_RESULT_NO_TRIGGER_SCOPED: {
			struct necp_policy_result_service service_parameters;
			size_t service_result_length = necp_policy_get_result_parameter_length(policy);
			bool has_extra_service_data = FALSE;
			if (service_result_length >= (sizeof(service_parameters))) {
				has_extra_service_data = TRUE;
			}
			if (necp_policy_get_result_parameter(policy, (u_int8_t *)&service_parameters, sizeof(service_parameters))) {
				ultimate_result_parameter.service.identifier = necp_create_uuid_service_id_mapping(service_parameters.identifier);
				if (ultimate_result_parameter.service.identifier != 0) {
					uuid_copy(policy->applied_service_uuid, service_parameters.identifier);
					socket_layer_non_id_conditions = TRUE;
					if (has_extra_service_data) {
						ultimate_result_parameter.service.data = service_parameters.data;
					} else {
						ultimate_result_parameter.service.data = 0;
					}
				}
			}
			break;
		}
		case NECP_POLICY_RESULT_SOCKET_SCOPED: {
			size_t interface_name_length = necp_policy_get_result_parameter_length(policy);
			if (interface_name_length <= IFXNAMSIZ && interface_name_length > 0) {
				char interface_name[IFXNAMSIZ];
				ifnet_t scope_interface = NULL;
				necp_policy_get_result_parameter(policy, (u_int8_t *)interface_name, interface_name_length);
				interface_name[interface_name_length - 1] = 0; // Make sure the string is NULL terminated
				if (ifnet_find_by_name(interface_name, &scope_interface) == 0) {
					ultimate_result_parameter.scoped_interface_index = scope_interface->if_index;
					socket_layer_non_id_conditions = TRUE;
				}
			}
		}
		default: {
			break;
		}
	}

	if (socket_layer_non_id_conditions) {
		necp_kernel_policy_id policy_id = necp_kernel_socket_policy_add(policy->id, policy->order, session->session_order, 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);

		if (policy_id == 0) {
			NECPLOG0(LOG_DEBUG, "Error applying socket kernel policy");
			goto fail;
		}

		cond_ip_output_layer_id = policy_id;
		policy->kernel_socket_policies[0] = policy_id;
	}

	if (ip_output_layer_non_id_conditions) {
		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, 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);

		if (policy_id == 0) {
			NECPLOG0(LOG_DEBUG, "Error applying IP output kernel policy");
			goto fail;
		}

		policy->kernel_ip_output_policies[NECP_KERNEL_POLICY_SUBORDER_NON_ID_CONDITIONS] = policy_id;
	}

	if (ip_output_layer_id_condition) {
		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, 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);

		if (policy_id == 0) {
			NECPLOG0(LOG_DEBUG, "Error applying IP output kernel policy");
			goto fail;
		}

		policy->kernel_ip_output_policies[NECP_KERNEL_POLICY_SUBORDER_ID_CONDITION] = policy_id;
	}

	// Extra policies for IP Output tunnels for when packets loop back
	if (ip_output_layer_tunnel_condition_from_id) {
		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, 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);

		if (policy_id == 0) {
			NECPLOG0(LOG_DEBUG, "Error applying IP output kernel policy");
			goto fail;
		}

		policy->kernel_ip_output_policies[NECP_KERNEL_POLICY_SUBORDER_NON_ID_TUNNEL_CONDITION] = policy_id;
	}

	if (ip_output_layer_tunnel_condition_from_id) {
		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, 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);

		if (policy_id == 0) {
			NECPLOG0(LOG_DEBUG, "Error applying IP output kernel policy");
			goto fail;
		}

		policy->kernel_ip_output_policies[NECP_KERNEL_POLICY_SUBORDER_ID_TUNNEL_CONDITION] = policy_id;
	}

	policy->applied = TRUE;
	policy->pending_update = FALSE;
	return (TRUE);

fail:
	return (FALSE);
}

static void
necp_policy_apply_all(struct necp_session *session)
{
	struct necp_session_policy *policy = NULL;
	struct necp_session_policy *temp_policy = NULL;

	lck_rw_lock_exclusive(&necp_kernel_policy_lock);

	// Remove exisiting applied policies
	if (session->dirty) {
		LIST_FOREACH_SAFE(policy, &session->policies, chain, temp_policy) {
			if (policy->pending_deletion) {
				if (policy->applied) {
					necp_policy_unapply(policy);
				}
				// Delete the policy
				necp_policy_delete(session, policy);
			} else if (!policy->applied) {
				necp_policy_apply(session, policy);
			} else if (policy->pending_update) {
				// Must have been applied, but needs an update. Remove and re-add.
				necp_policy_unapply(policy);
				necp_policy_apply(session, policy);
			}
		}

		necp_kernel_socket_policies_update_uuid_table();
		necp_kernel_socket_policies_reprocess();
		necp_kernel_ip_output_policies_reprocess();

		// Clear dirty bit flags
		session->dirty = FALSE;
	}

	lck_rw_done(&necp_kernel_policy_lock);

	if (necp_debug) {
		NECPLOG0(LOG_DEBUG, "Applied NECP policies");
	}
}

// Kernel Policy Management
// ---------------------
// Kernel policies are derived from session policies
static necp_kernel_policy_id
necp_kernel_policy_get_new_id(void)
{
	necp_kernel_policy_id newid = NECP_KERNEL_POLICY_ID_NONE;

	lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	necp_last_kernel_policy_id++;
	if (necp_last_kernel_policy_id < NECP_KERNEL_POLICY_ID_FIRST_VALID) {
		necp_last_kernel_policy_id = NECP_KERNEL_POLICY_ID_FIRST_VALID;
	}

	newid = necp_last_kernel_policy_id;
	if (newid == NECP_KERNEL_POLICY_ID_NONE) {
		NECPLOG0(LOG_DEBUG, "Allocate kernel policy id failed.\n");
		return (0);
	}

	return (newid);
}

#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)
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, 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)
{
	struct necp_kernel_socket_policy *new_kernel_policy = NULL;
	struct necp_kernel_socket_policy *tmp_kernel_policy = NULL;

	MALLOC_ZONE(new_kernel_policy, struct necp_kernel_socket_policy *, sizeof(*new_kernel_policy), M_NECP_SOCKET_POLICY, M_WAITOK);
	if (new_kernel_policy == NULL) {
		goto done;
	}

	memset(new_kernel_policy, 0, sizeof(*new_kernel_policy));
	new_kernel_policy->parent_policy_id = parent_policy_id;
	new_kernel_policy->id = necp_kernel_policy_get_new_id();
	new_kernel_policy->order = order;
	new_kernel_policy->session_order = session_order;

	// Sanitize condition mask
	new_kernel_policy->condition_mask = (condition_mask & NECP_KERNEL_VALID_SOCKET_CONDITIONS);
	if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES) && (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE)) {
		new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_BOUND_INTERFACE;
	}
	if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REAL_APP_ID) && !(new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_APP_ID)) {
		new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_REAL_APP_ID;
	}
	if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ENTITLEMENT) && !(new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_APP_ID)) {
		new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_ENTITLEMENT;
	}
	if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) && (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX)) {
		new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_LOCAL_PREFIX;
	}
	if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) && (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX)) {
		new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_REMOTE_PREFIX;
	}
	new_kernel_policy->condition_negated_mask = condition_negated_mask & new_kernel_policy->condition_mask;

	// Set condition values
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_APP_ID) {
		new_kernel_policy->cond_app_id = cond_app_id;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REAL_APP_ID) {
		new_kernel_policy->cond_real_app_id = cond_real_app_id;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ACCOUNT_ID) {
		new_kernel_policy->cond_account_id = cond_account_id;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_DOMAIN) {
		new_kernel_policy->cond_domain = cond_domain;
		new_kernel_policy->cond_domain_dot_count = necp_count_dots(cond_domain, strlen(cond_domain));
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_PID) {
		new_kernel_policy->cond_pid = cond_pid;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_UID) {
		new_kernel_policy->cond_uid = cond_uid;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE) {
		if (cond_bound_interface) {
			ifnet_reference(cond_bound_interface);
		}
		new_kernel_policy->cond_bound_interface = cond_bound_interface;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_TRAFFIC_CLASS) {
		new_kernel_policy->cond_traffic_class = cond_traffic_class;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_PROTOCOL) {
		new_kernel_policy->cond_protocol = cond_protocol;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_START) {
		memcpy(&new_kernel_policy->cond_local_start, cond_local_start, cond_local_start->sa.sa_len);
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
		memcpy(&new_kernel_policy->cond_local_end, cond_local_end, cond_local_end->sa.sa_len);
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX) {
		new_kernel_policy->cond_local_prefix = cond_local_prefix;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_START) {
		memcpy(&new_kernel_policy->cond_remote_start, cond_remote_start, cond_remote_start->sa.sa_len);
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
		memcpy(&new_kernel_policy->cond_remote_end, cond_remote_end, cond_remote_end->sa.sa_len);
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX) {
		new_kernel_policy->cond_remote_prefix = cond_remote_prefix;
	}

	new_kernel_policy->result = result;
	memcpy(&new_kernel_policy->result_parameter, &result_parameter, sizeof(result_parameter));

	if (necp_debug) {
		NECPLOG(LOG_DEBUG, "Added kernel policy: socket, id=%d, mask=%x\n", new_kernel_policy->id, new_kernel_policy->condition_mask);
	}
	LIST_INSERT_SORTED_TWICE_ASCENDING(&necp_kernel_socket_policies, new_kernel_policy, chain, session_order, order, tmp_kernel_policy);
done:
	return (new_kernel_policy ? new_kernel_policy->id : 0);
}

static struct necp_kernel_socket_policy *
necp_kernel_socket_policy_find(necp_kernel_policy_id policy_id)
{
	struct necp_kernel_socket_policy *kernel_policy = NULL;
	struct necp_kernel_socket_policy *tmp_kernel_policy = NULL;

	if (policy_id == 0) {
		return (NULL);
	}

	LIST_FOREACH_SAFE(kernel_policy, &necp_kernel_socket_policies, chain, tmp_kernel_policy) {
		if (kernel_policy->id == policy_id) {
			return (kernel_policy);
		}
	}

	return (NULL);
}

static bool
necp_kernel_socket_policy_delete(necp_kernel_policy_id policy_id)
{
	struct necp_kernel_socket_policy *policy = NULL;

	lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	policy = necp_kernel_socket_policy_find(policy_id);
	if (policy) {
		LIST_REMOVE(policy, chain);

		if (policy->cond_bound_interface) {
			ifnet_release(policy->cond_bound_interface);
			policy->cond_bound_interface = NULL;
		}
		
		if (policy->cond_domain) {
			FREE(policy->cond_domain, M_NECP);
			policy->cond_domain = NULL;
		}

		FREE_ZONE(policy, sizeof(*policy), M_NECP_SOCKET_POLICY);
		return (TRUE);
	}

	return (FALSE);
}

static void
necp_kernel_socket_policies_dump_all(void)
{
	struct necp_kernel_socket_policy *policy = NULL;
	int policy_i;
	int app_i;

	if (necp_debug) {
		NECPLOG0(LOG_DEBUG, "NECP Application Policies:\n");
		NECPLOG0(LOG_DEBUG, "-----------\n");
		for (policy_i = 0; necp_kernel_socket_policies_app_layer_map != NULL && necp_kernel_socket_policies_app_layer_map[policy_i] != NULL; policy_i++) {
			policy = necp_kernel_socket_policies_app_layer_map[policy_i];
			NECPLOG(LOG_DEBUG, "\t%d. Policy ID: %d, Order: %d.%d, Mask: %x, Result: %d, Parameter: %d\n", policy_i, policy->id, policy->session_order, policy->order, policy->condition_mask, policy->result, policy->result_parameter);
		}
		if (necp_kernel_socket_policies_app_layer_map[0] != NULL) {
			NECPLOG0(LOG_DEBUG, "-----------\n");
		}

		NECPLOG0(LOG_DEBUG, "NECP Socket Policies:\n");
		NECPLOG0(LOG_DEBUG, "-----------\n");
		for (app_i = 0; app_i < NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS; app_i++) {
			NECPLOG(LOG_DEBUG, "\tApp Bucket: %d\n", app_i);
			for (policy_i = 0; necp_kernel_socket_policies_map[app_i] != NULL && (necp_kernel_socket_policies_map[app_i])[policy_i] != NULL; policy_i++) {
				policy = (necp_kernel_socket_policies_map[app_i])[policy_i];
				NECPLOG(LOG_DEBUG, "\t%d. Policy ID: %d, Order: %d.%d, Mask: %x, Result: %d, Parameter: %d\n", policy_i, policy->id, policy->session_order, policy->order, policy->condition_mask, policy->result, policy->result_parameter);
			}
			NECPLOG0(LOG_DEBUG, "-----------\n");
		}
	}
}

static inline bool
necp_kernel_socket_result_is_service_type(struct necp_kernel_socket_policy *kernel_policy)
{
	return (kernel_policy->result >= NECP_KERNEL_POLICY_RESULT_TRIGGER && kernel_policy->result <= NECP_KERNEL_POLICY_RESULT_NO_TRIGGER_SCOPED);
}

static inline bool
necp_kernel_socket_policy_results_overlap(struct necp_kernel_socket_policy *upper_policy, struct necp_kernel_socket_policy *lower_policy)
{
	if (upper_policy->result == NECP_KERNEL_POLICY_RESULT_DROP) {
		// Drop always cancels out lower policies
		return (TRUE);
	} else if (upper_policy->result == NECP_KERNEL_POLICY_RESULT_SOCKET_FILTER) {
		// Filters never cancel out lower policies
		return (FALSE);
	} else if (necp_kernel_socket_result_is_service_type(upper_policy)) {
		// Trigger/Scoping policies can overlap one another, but not other results
		return (necp_kernel_socket_result_is_service_type(lower_policy));
	} else if (upper_policy->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
		if (upper_policy->session_order != lower_policy->session_order) {
			// A skip cannot override a policy of a different session
			return (FALSE);
		} else {
			if (upper_policy->result_parameter.skip_policy_order == 0 ||
				lower_policy->order >= upper_policy->result_parameter.skip_policy_order) {
				// This policy is beyond the skip
				return (FALSE);
			} else {
				// This policy is inside the skip
				return (TRUE);
			}
		}
	}

	// A hard pass, flow divert, or tunnel will currently block out lower policies
	return (TRUE);
}

static bool
necp_kernel_socket_policy_is_unnecessary(struct necp_kernel_socket_policy *policy, struct necp_kernel_socket_policy **policy_array, int valid_indices)
{
	bool can_skip = FALSE;
	u_int32_t highest_skip_session_order = 0;
	u_int32_t highest_skip_order = 0;
	int i;
	for (i = 0; i < valid_indices; i++) {
		struct necp_kernel_socket_policy *compared_policy = policy_array[i];

		// For policies in a skip window, we can't mark conflicting policies as unnecessary
		if (can_skip) {
			if (highest_skip_session_order != compared_policy->session_order ||
				(highest_skip_order != 0 && compared_policy->order >= highest_skip_order)) {
				// If we've moved on to the next session, or passed the skip window
				highest_skip_session_order = 0;
				highest_skip_order = 0;
				can_skip = FALSE;
			} else {
				// If this policy is also a skip, in can increase the skip window
				if (compared_policy->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
					if (compared_policy->result_parameter.skip_policy_order > highest_skip_order) {
						highest_skip_order = compared_policy->result_parameter.skip_policy_order;
					}
				}
				continue;
			}
		}

		if (compared_policy->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
			// This policy is a skip. Set the skip window accordingly
			can_skip = TRUE;
			highest_skip_session_order = compared_policy->session_order;
			highest_skip_order = compared_policy->result_parameter.skip_policy_order;
		}

		// The result of the compared policy must be able to block out this policy result
		if (!necp_kernel_socket_policy_results_overlap(compared_policy, policy)) {
			continue;
		}

		// If new policy matches All Interfaces, compared policy must also
		if ((policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES) && !(compared_policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES)) {
			continue;
		}

		// Default makes lower policies unecessary always
		if (compared_policy->condition_mask == 0) {
			return (TRUE);
		}

		// Compared must be more general than policy, and include only conditions within policy
		if ((policy->condition_mask & compared_policy->condition_mask) != compared_policy->condition_mask) {
			continue;
		}

		// Negative conditions must match for the overlapping conditions
		if ((policy->condition_negated_mask & compared_policy->condition_mask) != (compared_policy->condition_negated_mask & compared_policy->condition_mask)) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_DOMAIN &&
			strcmp(compared_policy->cond_domain, policy->cond_domain) != 0) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_ACCOUNT_ID &&
			compared_policy->cond_account_id != policy->cond_account_id) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_POLICY_ID &&
			compared_policy->cond_policy_id != policy->cond_policy_id) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_APP_ID &&
			compared_policy->cond_app_id != policy->cond_app_id) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_REAL_APP_ID &&
			compared_policy->cond_real_app_id != policy->cond_real_app_id) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_PID &&
			compared_policy->cond_pid != policy->cond_pid) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_UID &&
			compared_policy->cond_uid != policy->cond_uid) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE &&
			compared_policy->cond_bound_interface != policy->cond_bound_interface) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_PROTOCOL &&
			compared_policy->cond_protocol != policy->cond_protocol) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_TRAFFIC_CLASS &&
			!(compared_policy->cond_traffic_class.start_tc <= policy->cond_traffic_class.start_tc &&
			  compared_policy->cond_traffic_class.end_tc >= policy->cond_traffic_class.end_tc)) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_START) {
			if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
				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)) {
					continue;
				}
			} else if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX) {
				if (compared_policy->cond_local_prefix > policy->cond_local_prefix ||
					!necp_is_addr_in_subnet((struct sockaddr *)&policy->cond_local_start, (struct sockaddr *)&compared_policy->cond_local_start, compared_policy->cond_local_prefix)) {
					continue;
				}
			}
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_START) {
			if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
				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)) {
					continue;
				}
			} else if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX) {
				if (compared_policy->cond_remote_prefix > policy->cond_remote_prefix ||
					!necp_is_addr_in_subnet((struct sockaddr *)&policy->cond_remote_start, (struct sockaddr *)&compared_policy->cond_remote_start, compared_policy->cond_remote_prefix)) {
					continue;
				}
			}
		}

		return (TRUE);
	}

	return (FALSE);
}

static bool
necp_kernel_socket_policies_reprocess(void)
{
	int app_i;
	int bucket_allocation_counts[NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS];
	int bucket_current_free_index[NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS];
	int app_layer_allocation_count = 0;
	int app_layer_current_free_index = 0;
	struct necp_kernel_socket_policy *kernel_policy = NULL;

	lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	// Reset mask to 0
	necp_kernel_application_policies_condition_mask = 0;
	necp_kernel_socket_policies_condition_mask = 0;
	necp_kernel_application_policies_count = 0;
	necp_kernel_socket_policies_count = 0;
	necp_kernel_socket_policies_non_app_count = 0;

	// Reset all maps to NULL
	for (app_i = 0; app_i < NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS; app_i++) {
		if (necp_kernel_socket_policies_map[app_i] != NULL) {
			FREE(necp_kernel_socket_policies_map[app_i], M_NECP);
			necp_kernel_socket_policies_map[app_i] = NULL;
		}

		// Init counts
		bucket_allocation_counts[app_i] = 0;
	}
	if (necp_kernel_socket_policies_app_layer_map != NULL) {
		FREE(necp_kernel_socket_policies_app_layer_map, M_NECP);
		necp_kernel_socket_policies_app_layer_map = NULL;
	}

	// Create masks and counts
	LIST_FOREACH(kernel_policy, &necp_kernel_socket_policies, chain) {
		// App layer mask/count
		necp_kernel_application_policies_condition_mask |= kernel_policy->condition_mask;
		necp_kernel_application_policies_count++;
		app_layer_allocation_count++;

		// Update socket layer bucket mask/counts
		necp_kernel_socket_policies_condition_mask |= kernel_policy->condition_mask;
		necp_kernel_socket_policies_count++;

		if (!(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_APP_ID) ||
			kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_APP_ID) {
			necp_kernel_socket_policies_non_app_count++;
			for (app_i = 0; app_i < NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS; app_i++) {
				bucket_allocation_counts[app_i]++;
			}
		} else {
			bucket_allocation_counts[NECP_SOCKET_MAP_APP_ID_TO_BUCKET(kernel_policy->cond_app_id)]++;
		}
	}

	// Allocate maps
	for (app_i = 0; app_i < NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS; app_i++) {
		if (bucket_allocation_counts[app_i] > 0) {
			// Allocate a NULL-terminated array of policy pointers for each bucket
			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);
			if (necp_kernel_socket_policies_map[app_i] == NULL) {
				goto fail;
			}

			// Initialize the first entry to NULL
			(necp_kernel_socket_policies_map[app_i])[0] = NULL;
		}
		bucket_current_free_index[app_i] = 0;
	}
	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);
	if (necp_kernel_socket_policies_app_layer_map == NULL) {
		goto fail;
	}
	necp_kernel_socket_policies_app_layer_map[0] = NULL;

	// Fill out maps
	LIST_FOREACH(kernel_policy, &necp_kernel_socket_policies, chain) {
		// Insert pointers into map
		if (!(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_APP_ID) ||
			kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_APP_ID) {
			for (app_i = 0; app_i < NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS; app_i++) {
				if (!necp_kernel_socket_policy_is_unnecessary(kernel_policy, necp_kernel_socket_policies_map[app_i], bucket_current_free_index[app_i])) {
					(necp_kernel_socket_policies_map[app_i])[(bucket_current_free_index[app_i])] = kernel_policy;
					bucket_current_free_index[app_i]++;
					(necp_kernel_socket_policies_map[app_i])[(bucket_current_free_index[app_i])] = NULL;
				}
			}
		} else {
			app_i = NECP_SOCKET_MAP_APP_ID_TO_BUCKET(kernel_policy->cond_app_id);
			if (!necp_kernel_socket_policy_is_unnecessary(kernel_policy, necp_kernel_socket_policies_map[app_i], bucket_current_free_index[app_i])) {
				(necp_kernel_socket_policies_map[app_i])[(bucket_current_free_index[app_i])] = kernel_policy;
				bucket_current_free_index[app_i]++;
				(necp_kernel_socket_policies_map[app_i])[(bucket_current_free_index[app_i])] = NULL;
			}
		}

		if (!necp_kernel_socket_policy_is_unnecessary(kernel_policy, necp_kernel_socket_policies_app_layer_map, app_layer_current_free_index)) {
			necp_kernel_socket_policies_app_layer_map[app_layer_current_free_index] = kernel_policy;
			app_layer_current_free_index++;
			necp_kernel_socket_policies_app_layer_map[app_layer_current_free_index] = NULL;
		}
	}
	necp_kernel_socket_policies_dump_all();
	BUMP_KERNEL_SOCKET_POLICIES_GENERATION_COUNT();
	return (TRUE);

fail:
	// Free memory, reset masks to 0
	necp_kernel_application_policies_condition_mask = 0;
	necp_kernel_socket_policies_condition_mask = 0;
	necp_kernel_application_policies_count = 0;
	necp_kernel_socket_policies_count = 0;
	necp_kernel_socket_policies_non_app_count = 0;
	for (app_i = 0; app_i < NECP_KERNEL_SOCKET_POLICIES_MAP_NUM_APP_ID_BUCKETS; app_i++) {
		if (necp_kernel_socket_policies_map[app_i] != NULL) {
			FREE(necp_kernel_socket_policies_map[app_i], M_NECP);
			necp_kernel_socket_policies_map[app_i] = NULL;
		}
	}
	if (necp_kernel_socket_policies_app_layer_map != NULL) {
		FREE(necp_kernel_socket_policies_app_layer_map, M_NECP);
		necp_kernel_socket_policies_app_layer_map = NULL;
	}
	return (FALSE);
}

static u_int32_t
necp_get_new_string_id(void)
{
	u_int32_t newid = 0;

	lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	necp_last_string_id++;
	if (necp_last_string_id < 1) {
		necp_last_string_id = 1;
	}

	newid = necp_last_string_id;
	if (newid == 0) {
		NECPLOG0(LOG_DEBUG, "Allocate string id failed.\n");
		return (0);
	}

	return (newid);
}

static struct necp_string_id_mapping *
necp_lookup_string_to_id_locked(struct necp_string_id_mapping_list *list, char *string)
{
	struct necp_string_id_mapping *searchentry = NULL;
	struct necp_string_id_mapping *foundentry = NULL;

	LIST_FOREACH(searchentry, list, chain) {
		if (strcmp(searchentry->string, string) == 0) {
			foundentry = searchentry;
			break;
		}
	}

	return (foundentry);
}

static u_int32_t
necp_create_string_to_id_mapping(struct necp_string_id_mapping_list *list, char *string)
{
	u_int32_t string_id = 0;
	struct necp_string_id_mapping *existing_mapping = NULL;

	lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	existing_mapping = necp_lookup_string_to_id_locked(list, string);
	if (existing_mapping != NULL) {
		string_id = existing_mapping->id;
		existing_mapping->refcount++;
	} else {
		struct necp_string_id_mapping *new_mapping = NULL;
		MALLOC(new_mapping, struct necp_string_id_mapping *, sizeof(struct necp_string_id_mapping), M_NECP, M_WAITOK);
		if (new_mapping != NULL) {
			memset(new_mapping, 0, sizeof(struct necp_string_id_mapping));

			size_t length = strlen(string) + 1;
			MALLOC(new_mapping->string, char *, length, M_NECP, M_WAITOK);
			if (new_mapping->string != NULL) {
				memcpy(new_mapping->string, string, length);
				new_mapping->id = necp_get_new_string_id();
				new_mapping->refcount = 1;
				LIST_INSERT_HEAD(list, new_mapping, chain);
				string_id = new_mapping->id;
			} else {
				FREE(new_mapping, M_NECP);
				new_mapping = NULL;
			}
		}
	}
	return (string_id);
}

static bool
necp_remove_string_to_id_mapping(struct necp_string_id_mapping_list *list, char *string)
{
	struct necp_string_id_mapping *existing_mapping = NULL;

	lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	existing_mapping = necp_lookup_string_to_id_locked(list, string);
	if (existing_mapping != NULL) {
		if (--existing_mapping->refcount == 0) {
			LIST_REMOVE(existing_mapping, chain);
			FREE(existing_mapping->string, M_NECP);
			FREE(existing_mapping, M_NECP);
		}
		return (TRUE);
	}

	return (FALSE);
}

#define NECP_NULL_SERVICE_ID 1
static u_int32_t
necp_get_new_uuid_id(void)
{
	u_int32_t newid = 0;

	lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	necp_last_uuid_id++;
	if (necp_last_uuid_id < (NECP_NULL_SERVICE_ID + 1)) {
		necp_last_uuid_id = (NECP_NULL_SERVICE_ID + 1);
	}

	newid = necp_last_uuid_id;
	if (newid == 0) {
		NECPLOG0(LOG_DEBUG, "Allocate uuid id failed.\n");
		return (0);
	}

	return (newid);
}

static struct necp_uuid_id_mapping *
necp_uuid_lookup_app_id_locked(uuid_t uuid)
{
	struct necp_uuid_id_mapping *searchentry = NULL;
	struct necp_uuid_id_mapping *foundentry = NULL;

	LIST_FOREACH(searchentry, APPUUIDHASH(uuid), chain) {
		if (uuid_compare(searchentry->uuid, uuid) == 0) {
			foundentry = searchentry;
			break;
		}
	}

	return (foundentry);
}

static u_int32_t
necp_create_uuid_app_id_mapping(uuid_t uuid, bool *allocated_mapping, bool uuid_policy_table)
{
	u_int32_t local_id = 0;
	struct necp_uuid_id_mapping *existing_mapping = NULL;

	lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	if (allocated_mapping) {
		*allocated_mapping = FALSE;
	}

	existing_mapping = necp_uuid_lookup_app_id_locked(uuid);
	if (existing_mapping != NULL) {
		local_id = existing_mapping->id;
		existing_mapping->refcount++;
		if (uuid_policy_table) {
			existing_mapping->table_refcount++;
		}
	} else {
		struct necp_uuid_id_mapping *new_mapping = NULL;
		MALLOC(new_mapping, struct necp_uuid_id_mapping *, sizeof(*new_mapping), M_NECP, M_WAITOK);
		if (new_mapping != NULL) {
			uuid_copy(new_mapping->uuid, uuid);
			new_mapping->id = necp_get_new_uuid_id();
			new_mapping->refcount = 1;
			if (uuid_policy_table) {
				new_mapping->table_refcount = 1;
			} else {
				new_mapping->table_refcount = 0;
			}

			LIST_INSERT_HEAD(APPUUIDHASH(uuid), new_mapping, chain);

			if (allocated_mapping) {
				*allocated_mapping = TRUE;
			}

			local_id = new_mapping->id;
		}
	}

	return (local_id);
}

static bool
necp_remove_uuid_app_id_mapping(uuid_t uuid, bool *removed_mapping, bool uuid_policy_table)
{
	struct necp_uuid_id_mapping *existing_mapping = NULL;

	lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	if (removed_mapping) {
		*removed_mapping = FALSE;
	}

	existing_mapping = necp_uuid_lookup_app_id_locked(uuid);
	if (existing_mapping != NULL) {
		if (uuid_policy_table) {
			existing_mapping->table_refcount--;
		}
		if (--existing_mapping->refcount == 0) {
			LIST_REMOVE(existing_mapping, chain);
			FREE(existing_mapping, M_NECP);
			if (removed_mapping) {
				*removed_mapping = TRUE;
			}
		}
		return (TRUE);
	}

	return (FALSE);
}

static struct necp_uuid_id_mapping *
necp_uuid_get_null_service_id_mapping(void)
{
	static struct necp_uuid_id_mapping null_mapping;
	uuid_clear(null_mapping.uuid);
	null_mapping.id = NECP_NULL_SERVICE_ID;
	
	return (&null_mapping);
}

static struct necp_uuid_id_mapping *
necp_uuid_lookup_service_id_locked(uuid_t uuid)
{
	struct necp_uuid_id_mapping *searchentry = NULL;
	struct necp_uuid_id_mapping *foundentry = NULL;
	
	if (uuid_is_null(uuid)) {
		return necp_uuid_get_null_service_id_mapping();
	}
	
	LIST_FOREACH(searchentry, &necp_uuid_service_id_list, chain) {
		if (uuid_compare(searchentry->uuid, uuid) == 0) {
			foundentry = searchentry;
			break;
		}
	}

	return (foundentry);
}

static struct necp_uuid_id_mapping *
necp_uuid_lookup_uuid_with_service_id_locked(u_int32_t local_id)
{
	struct necp_uuid_id_mapping *searchentry = NULL;
	struct necp_uuid_id_mapping *foundentry = NULL;
	
	if (local_id == NECP_NULL_SERVICE_ID) {
		return necp_uuid_get_null_service_id_mapping();
	}
	
	LIST_FOREACH(searchentry, &necp_uuid_service_id_list, chain) {
		if (searchentry->id == local_id) {
			foundentry = searchentry;
			break;
		}
	}

	return (foundentry);
}

static u_int32_t
necp_create_uuid_service_id_mapping(uuid_t uuid)
{
	u_int32_t local_id = 0;
	struct necp_uuid_id_mapping *existing_mapping = NULL;
	
	if (uuid_is_null(uuid)) {
		return (NECP_NULL_SERVICE_ID);
	}
	
	lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	existing_mapping = necp_uuid_lookup_service_id_locked(uuid);
	if (existing_mapping != NULL) {
		local_id = existing_mapping->id;
		existing_mapping->refcount++;
	} else {
		struct necp_uuid_id_mapping *new_mapping = NULL;
		MALLOC(new_mapping, struct necp_uuid_id_mapping *, sizeof(*new_mapping), M_NECP, M_WAITOK);
		if (new_mapping != NULL) {
			uuid_copy(new_mapping->uuid, uuid);
			new_mapping->id = necp_get_new_uuid_id();
			new_mapping->refcount = 1;

			LIST_INSERT_HEAD(&necp_uuid_service_id_list, new_mapping, chain);

			local_id = new_mapping->id;
		}
	}

	return (local_id);
}

static bool
necp_remove_uuid_service_id_mapping(uuid_t uuid)
{
	struct necp_uuid_id_mapping *existing_mapping = NULL;
	
	if (uuid_is_null(uuid)) {
		return (TRUE);
	}
	
	lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	existing_mapping = necp_uuid_lookup_app_id_locked(uuid);
	if (existing_mapping != NULL) {
		if (--existing_mapping->refcount == 0) {
			LIST_REMOVE(existing_mapping, chain);
			FREE(existing_mapping, M_NECP);
		}
		return (TRUE);
	}

	return (FALSE);
}


static bool
necp_kernel_socket_policies_update_uuid_table(void)
{
	lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	if (necp_uuid_app_id_mappings_dirty) {
		if (proc_uuid_policy_kernel(PROC_UUID_POLICY_OPERATION_CLEAR, NULL, PROC_UUID_NECP_APP_POLICY) < 0) {
			NECPLOG0(LOG_DEBUG, "Error clearing uuids from policy table\n");
			return (FALSE);
		}

		if (necp_num_uuid_app_id_mappings > 0) {
			struct necp_uuid_id_mapping_head *uuid_list_head = NULL;
			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--) {
				struct necp_uuid_id_mapping *mapping = NULL;
				LIST_FOREACH(mapping, uuid_list_head, chain) {
					if (mapping->table_refcount > 0 &&
						proc_uuid_policy_kernel(PROC_UUID_POLICY_OPERATION_ADD, mapping->uuid, PROC_UUID_NECP_APP_POLICY) < 0) {
						NECPLOG0(LOG_DEBUG, "Error adding uuid to policy table\n");
					}
				}
			}
		}

		necp_uuid_app_id_mappings_dirty = FALSE;
	}

	return (TRUE);
}

#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)
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, 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)
{
	struct necp_kernel_ip_output_policy *new_kernel_policy = NULL;
	struct necp_kernel_ip_output_policy *tmp_kernel_policy = NULL;

	MALLOC_ZONE(new_kernel_policy, struct necp_kernel_ip_output_policy *, sizeof(*new_kernel_policy), M_NECP_IP_POLICY, M_WAITOK);
	if (new_kernel_policy == NULL) {
		goto done;
	}

	memset(new_kernel_policy, 0, sizeof(*new_kernel_policy));
	new_kernel_policy->parent_policy_id = parent_policy_id;
	new_kernel_policy->id = necp_kernel_policy_get_new_id();
	new_kernel_policy->suborder = suborder;
	new_kernel_policy->order = order;
	new_kernel_policy->session_order = session_order;

	// Sanitize condition mask
	new_kernel_policy->condition_mask = (condition_mask & NECP_KERNEL_VALID_IP_OUTPUT_CONDITIONS);
	if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES) && (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE)) {
		new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_BOUND_INTERFACE;
	}
	if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) && (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX)) {
		new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_LOCAL_PREFIX;
	}
	if ((new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) && (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX)) {
		new_kernel_policy->condition_mask &= ~NECP_KERNEL_CONDITION_REMOTE_PREFIX;
	}
	new_kernel_policy->condition_negated_mask = condition_negated_mask & new_kernel_policy->condition_mask;

	// Set condition values
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_POLICY_ID) {
		new_kernel_policy->cond_policy_id = cond_policy_id;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE) {
		if (cond_bound_interface) {
			ifnet_reference(cond_bound_interface);
		}
		new_kernel_policy->cond_bound_interface = cond_bound_interface;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LAST_INTERFACE) {
		new_kernel_policy->cond_last_interface_index = cond_last_interface_index;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_PROTOCOL) {
		new_kernel_policy->cond_protocol = cond_protocol;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_START) {
		memcpy(&new_kernel_policy->cond_local_start, cond_local_start, cond_local_start->sa.sa_len);
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
		memcpy(&new_kernel_policy->cond_local_end, cond_local_end, cond_local_end->sa.sa_len);
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX) {
		new_kernel_policy->cond_local_prefix = cond_local_prefix;
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_START) {
		memcpy(&new_kernel_policy->cond_remote_start, cond_remote_start, cond_remote_start->sa.sa_len);
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
		memcpy(&new_kernel_policy->cond_remote_end, cond_remote_end, cond_remote_end->sa.sa_len);
	}
	if (new_kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX) {
		new_kernel_policy->cond_remote_prefix = cond_remote_prefix;
	}

	new_kernel_policy->result = result;
	memcpy(&new_kernel_policy->result_parameter, &result_parameter, sizeof(result_parameter));

	if (necp_debug) {
		NECPLOG(LOG_DEBUG, "Added kernel policy: ip output, id=%d, mask=%x\n", new_kernel_policy->id, new_kernel_policy->condition_mask);
	}
	LIST_INSERT_SORTED_THRICE_ASCENDING(&necp_kernel_ip_output_policies, new_kernel_policy, chain, session_order, order, suborder, tmp_kernel_policy);
done:
	return (new_kernel_policy ? new_kernel_policy->id : 0);
}

static struct necp_kernel_ip_output_policy *
necp_kernel_ip_output_policy_find(necp_kernel_policy_id policy_id)
{
	struct necp_kernel_ip_output_policy *kernel_policy = NULL;
	struct necp_kernel_ip_output_policy *tmp_kernel_policy = NULL;

	if (policy_id == 0) {
		return (NULL);
	}

	LIST_FOREACH_SAFE(kernel_policy, &necp_kernel_ip_output_policies, chain, tmp_kernel_policy) {
		if (kernel_policy->id == policy_id) {
			return (kernel_policy);
		}
	}

	return (NULL);
}

static bool
necp_kernel_ip_output_policy_delete(necp_kernel_policy_id policy_id)
{
	struct necp_kernel_ip_output_policy *policy = NULL;

	lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	policy = necp_kernel_ip_output_policy_find(policy_id);
	if (policy) {
		LIST_REMOVE(policy, chain);

		if (policy->cond_bound_interface) {
			ifnet_release(policy->cond_bound_interface);
			policy->cond_bound_interface = NULL;
		}

		FREE_ZONE(policy, sizeof(*policy), M_NECP_IP_POLICY);
		return (TRUE);
	}

	return (FALSE);
}

static void
necp_kernel_ip_output_policies_dump_all(void)
{
	struct necp_kernel_ip_output_policy *policy = NULL;
	int policy_i;
	int id_i;

	if (necp_debug) {
		NECPLOG0(LOG_DEBUG, "NECP IP Output Policies:\n");
		NECPLOG0(LOG_DEBUG, "-----------\n");
		for (id_i = 0; id_i < NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS; id_i++) {
			NECPLOG(LOG_DEBUG, " ID Bucket: %d\n", id_i);
			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++) {
				policy = (necp_kernel_ip_output_policies_map[id_i])[policy_i];
				NECPLOG(LOG_DEBUG, "\t%d. Policy ID: %d, Order: %d.%d.%d, Mask: %x, Result: %d, Parameter: %d\n", policy_i, policy->id, policy->session_order, policy->order, policy->suborder, policy->condition_mask, policy->result, policy->result_parameter);
			}
			NECPLOG0(LOG_DEBUG, "-----------\n");
		}
	}
}

static inline bool
necp_kernel_ip_output_policy_results_overlap(struct necp_kernel_ip_output_policy *upper_policy, struct necp_kernel_ip_output_policy *lower_policy)
{
	if (upper_policy->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
		if (upper_policy->session_order != lower_policy->session_order) {
			// A skip cannot override a policy of a different session
			return (FALSE);
		} else {
			if (upper_policy->result_parameter.skip_policy_order == 0 ||
				lower_policy->order >= upper_policy->result_parameter.skip_policy_order) {
				// This policy is beyond the skip
				return (FALSE);
			} else {
				// This policy is inside the skip
				return (TRUE);
			}
		}
	}

	// All other IP Output policy results (drop, tunnel, hard pass) currently overlap
	return (TRUE);
}

static bool
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)
{
	bool can_skip = FALSE;
	u_int32_t highest_skip_session_order = 0;
	u_int32_t highest_skip_order = 0;
	int i;
	for (i = 0; i < valid_indices; i++) {
		struct necp_kernel_ip_output_policy *compared_policy = policy_array[i];

		// For policies in a skip window, we can't mark conflicting policies as unnecessary
		if (can_skip) {
			if (highest_skip_session_order != compared_policy->session_order ||
				(highest_skip_order != 0 && compared_policy->order >= highest_skip_order)) {
				// If we've moved on to the next session, or passed the skip window
				highest_skip_session_order = 0;
				highest_skip_order = 0;
				can_skip = FALSE;
			} else {
				// If this policy is also a skip, in can increase the skip window
				if (compared_policy->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
					if (compared_policy->result_parameter.skip_policy_order > highest_skip_order) {
						highest_skip_order = compared_policy->result_parameter.skip_policy_order;
					}
				}
				continue;
			}
		}

		if (compared_policy->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
			// This policy is a skip. Set the skip window accordingly
			can_skip = TRUE;
			highest_skip_session_order = compared_policy->session_order;
			highest_skip_order = compared_policy->result_parameter.skip_policy_order;
		}

		// The result of the compared policy must be able to block out this policy result
		if (!necp_kernel_ip_output_policy_results_overlap(compared_policy, policy)) {
			continue;
		}

		// If new policy matches All Interfaces, compared policy must also
		if ((policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES) && !(compared_policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES)) {
			continue;
		}

		// Default makes lower policies unecessary always
		if (compared_policy->condition_mask == 0) {
			return (TRUE);
		}

		// Compared must be more general than policy, and include only conditions within policy
		if ((policy->condition_mask & compared_policy->condition_mask) != compared_policy->condition_mask) {
			continue;
		}

		// Negative conditions must match for the overlapping conditions
		if ((policy->condition_negated_mask & compared_policy->condition_mask) != (compared_policy->condition_negated_mask & compared_policy->condition_mask)) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_POLICY_ID &&
			compared_policy->cond_policy_id != policy->cond_policy_id) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE &&
			compared_policy->cond_bound_interface != policy->cond_bound_interface) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_PROTOCOL &&
			compared_policy->cond_protocol != policy->cond_protocol) {
			continue;
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_START) {
			if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
				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)) {
					continue;
				}
			} else if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX) {
				if (compared_policy->cond_local_prefix > policy->cond_local_prefix ||
					!necp_is_addr_in_subnet((struct sockaddr *)&policy->cond_local_start, (struct sockaddr *)&compared_policy->cond_local_start, compared_policy->cond_local_prefix)) {
					continue;
				}
			}
		}

		if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_START) {
			if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
				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)) {
					continue;
				}
			} else if (compared_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX) {
				if (compared_policy->cond_remote_prefix > policy->cond_remote_prefix ||
					!necp_is_addr_in_subnet((struct sockaddr *)&policy->cond_remote_start, (struct sockaddr *)&compared_policy->cond_remote_start, compared_policy->cond_remote_prefix)) {
					continue;
				}
			}
		}

		return (TRUE);
	}

	return (FALSE);
}

static bool
necp_kernel_ip_output_policies_reprocess(void)
{
	int i;
	int bucket_allocation_counts[NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS];
	int bucket_current_free_index[NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS];
	struct necp_kernel_ip_output_policy *kernel_policy = NULL;

	lck_rw_assert(&necp_kernel_policy_lock, LCK_RW_ASSERT_EXCLUSIVE);

	// Reset mask to 0
	necp_kernel_ip_output_policies_condition_mask = 0;
	necp_kernel_ip_output_policies_count = 0;
	necp_kernel_ip_output_policies_non_id_count = 0;

	for (i = 0; i < NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS; i++) {
		if (necp_kernel_ip_output_policies_map[i] != NULL) {
			FREE(necp_kernel_ip_output_policies_map[i], M_NECP);
			necp_kernel_ip_output_policies_map[i] = NULL;
		}

		// Init counts
		bucket_allocation_counts[i] = 0;
	}

	LIST_FOREACH(kernel_policy, &necp_kernel_ip_output_policies, chain) {
		// Update mask
		necp_kernel_ip_output_policies_condition_mask |= kernel_policy->condition_mask;
		necp_kernel_ip_output_policies_count++;

		// Update bucket counts
		if (!(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_POLICY_ID)) {
			necp_kernel_ip_output_policies_non_id_count++;
			for (i = 0; i < NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS; i++) {
				bucket_allocation_counts[i]++;
			}
		} else {
			bucket_allocation_counts[NECP_IP_OUTPUT_MAP_ID_TO_BUCKET(kernel_policy->cond_policy_id)]++;
		}
	}

	for (i = 0; i < NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS; i++) {
		if (bucket_allocation_counts[i] > 0) {
			// Allocate a NULL-terminated array of policy pointers for each bucket
			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);
			if (necp_kernel_ip_output_policies_map[i] == NULL) {
				goto fail;
			}

			// Initialize the first entry to NULL
			(necp_kernel_ip_output_policies_map[i])[0] = NULL;
		}
		bucket_current_free_index[i] = 0;
	}

	LIST_FOREACH(kernel_policy, &necp_kernel_ip_output_policies, chain) {
		// Insert pointers into map
		if (!(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_POLICY_ID)) {
			for (i = 0; i < NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS; i++) {
				if (!necp_kernel_ip_output_policy_is_unnecessary(kernel_policy, necp_kernel_ip_output_policies_map[i], bucket_current_free_index[i])) {
					(necp_kernel_ip_output_policies_map[i])[(bucket_current_free_index[i])] = kernel_policy;
					bucket_current_free_index[i]++;
					(necp_kernel_ip_output_policies_map[i])[(bucket_current_free_index[i])] = NULL;
				}
			}
		} else {
			i = NECP_IP_OUTPUT_MAP_ID_TO_BUCKET(kernel_policy->cond_policy_id);
			if (!necp_kernel_ip_output_policy_is_unnecessary(kernel_policy, necp_kernel_ip_output_policies_map[i], bucket_current_free_index[i])) {
				(necp_kernel_ip_output_policies_map[i])[(bucket_current_free_index[i])] = kernel_policy;
				bucket_current_free_index[i]++;
				(necp_kernel_ip_output_policies_map[i])[(bucket_current_free_index[i])] = NULL;
			}
		}
	}
	necp_kernel_ip_output_policies_dump_all();
	return (TRUE);

fail:
	// Free memory, reset mask to 0
	necp_kernel_ip_output_policies_condition_mask = 0;
	necp_kernel_ip_output_policies_count = 0;
	necp_kernel_ip_output_policies_non_id_count = 0;
	for (i = 0; i < NECP_KERNEL_IP_OUTPUT_POLICIES_MAP_NUM_ID_BUCKETS; i++) {
		if (necp_kernel_ip_output_policies_map[i] != NULL) {
			FREE(necp_kernel_ip_output_policies_map[i], M_NECP);
			necp_kernel_ip_output_policies_map[i] = NULL;
		}
	}
	return (FALSE);
}

// Outbound Policy Matching
// ---------------------
struct substring {
	char *string;
	size_t length;
};

static struct substring
necp_trim_dots_and_stars(char *string, size_t length)
{
	struct substring sub;
	sub.string = string;
	sub.length = string ? length : 0;

	while (sub.length && (sub.string[0] == '.' || sub.string[0] == '*')) {
		sub.string++;
		sub.length--;
	}

	while (sub.length && (sub.string[sub.length - 1] == '.' || sub.string[sub.length - 1] == '*')) {
		sub.length--;
	}

	return (sub);
}

static char *
necp_create_trimmed_domain(char *string, size_t length)
{
	char *trimmed_domain = NULL;
	struct substring sub = necp_trim_dots_and_stars(string, length);

	MALLOC(trimmed_domain, char *, sub.length + 1, M_NECP, M_WAITOK);
	if (trimmed_domain == NULL) {
		return (NULL);
	}

	memcpy(trimmed_domain, sub.string, sub.length);
	trimmed_domain[sub.length] = 0;

	return (trimmed_domain);
}

static inline int
necp_count_dots(char *string, size_t length)
{
	int dot_count = 0;
	size_t i = 0;

	for (i = 0; i < length; i++) {
		if (string[i] == '.') {
			dot_count++;
		}
	}

	return (dot_count);
}

static bool
necp_check_suffix(struct substring parent, struct substring suffix, bool require_dot_before_suffix)
{
	if (parent.length <= suffix.length) {
		return (FALSE);
	}

	size_t length_difference = (parent.length - suffix.length);

	if (require_dot_before_suffix) {
		if (((char *)(parent.string + length_difference - 1))[0] != '.') {
			return (FALSE);
		}
	}

	return (memcmp(parent.string + length_difference, suffix.string, suffix.length) == 0);
}

static bool
necp_hostname_matches_domain(struct substring hostname_substring, u_int8_t hostname_dot_count, char *domain, u_int8_t domain_dot_count)
{
	if (hostname_substring.string == NULL || domain == NULL) {
		return (hostname_substring.string == domain);
	}

	struct substring domain_substring;
	domain_substring.string = domain;
	domain_substring.length = strlen(domain);

	if (hostname_dot_count == domain_dot_count) {
		if (hostname_substring.length == domain_substring.length &&
			memcmp(hostname_substring.string, domain_substring.string, hostname_substring.length) == 0) {
			return (TRUE);
		}
	} else if (domain_dot_count > 0 && domain_dot_count < hostname_dot_count) {
		if (necp_check_suffix(hostname_substring, domain_substring, TRUE)) {
			return (TRUE);
		}
	}

	return (FALSE);
}

static void
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, struct necp_socket_info *info)
{
	memset(info, 0, sizeof(struct necp_socket_info));

	info->pid = pid;
	info->uid = uid;
	info->protocol = protocol;
	info->bound_interface_index = bound_interface_index;
	info->traffic_class = traffic_class;
	info->cred_result = 0; // Don't check the entitlement here, only in the socket layer

	if (necp_kernel_application_policies_condition_mask & NECP_KERNEL_CONDITION_APP_ID && !uuid_is_null(application_uuid)) {
		struct necp_uuid_id_mapping *existing_mapping = necp_uuid_lookup_app_id_locked(application_uuid);
		if (existing_mapping) {
			info->application_id = existing_mapping->id;
		}
	}

	if (necp_kernel_application_policies_condition_mask & NECP_KERNEL_CONDITION_REAL_APP_ID && !uuid_is_null(real_application_uuid)) {
		if (uuid_compare(application_uuid, real_application_uuid) == 0) {
			info->real_application_id = info->application_id;
		} else {
			struct necp_uuid_id_mapping *existing_mapping = necp_uuid_lookup_app_id_locked(real_application_uuid);
			if (existing_mapping) {
				info->real_application_id = existing_mapping->id;
			}
		}
	}

	if (necp_kernel_application_policies_condition_mask & NECP_KERNEL_CONDITION_ACCOUNT_ID && account != NULL) {
		struct necp_string_id_mapping *existing_mapping = necp_lookup_string_to_id_locked(&necp_account_id_list, account);
		if (existing_mapping) {
			info->account_id = existing_mapping->id;
		}
	}

	if (necp_kernel_application_policies_condition_mask & NECP_KERNEL_CONDITION_DOMAIN) {
		info->domain = domain;
	}
}

static int
necp_application_find_policy_match_internal(u_int8_t *parameters, size_t parameters_size, struct necp_aggregate_result *returned_result)
{
	int error = 0;
	size_t offset = 0;

	struct necp_kernel_socket_policy *matched_policy = NULL;
	struct necp_socket_info info;
	necp_kernel_policy_filter filter_control_unit = 0;
	necp_kernel_policy_result service_action = 0;
	necp_kernel_policy_service service = { 0, 0 };

	pid_t pid = 0;
	uid_t uid = 0;
	u_int16_t protocol = 0;
	u_int32_t bound_interface_index = 0;
	u_int32_t traffic_class = 0;

	uuid_t application_uuid;
	uuid_clear(application_uuid);
	uuid_t real_application_uuid;
	uuid_clear(real_application_uuid);
	char *domain = NULL;
	char *account = NULL;

	if (returned_result == NULL) {
		return (EINVAL);
	}

	memset(returned_result, 0, sizeof(struct necp_aggregate_result));

	lck_rw_lock_shared(&necp_kernel_policy_lock);
	if (necp_kernel_application_policies_count == 0) {
		if (necp_drop_all_order > 0) {
			returned_result->routing_result = NECP_KERNEL_POLICY_RESULT_DROP;
			lck_rw_done(&necp_kernel_policy_lock);
			return (0);
		}
	}
	lck_rw_done(&necp_kernel_policy_lock);

	while (offset < parameters_size) {
		u_int8_t type = necp_buffer_get_tlv_type(parameters, offset);
		size_t length = necp_buffer_get_tlv_length(parameters, offset);

		if (length > 0 && (offset + sizeof(u_int8_t) + sizeof(size_t) + length) <= parameters_size) {
			u_int8_t *value = necp_buffer_get_tlv_value(parameters, offset, NULL);
			if (value != NULL) {
				switch (type) {
					case NECP_POLICY_CONDITION_APPLICATION: {
						if (length >= sizeof(uuid_t)) {
							uuid_copy(application_uuid, value);
						}
						break;
					}
					case NECP_POLICY_CONDITION_REAL_APPLICATION: {
						if (length >= sizeof(uuid_t)) {
							uuid_copy(real_application_uuid, value);
						}
						break;
					}
					case NECP_POLICY_CONDITION_DOMAIN: {
						domain = (char *)value;
						domain[length - 1] = 0;
						break;
					}
					case NECP_POLICY_CONDITION_ACCOUNT: {
						account = (char *)value;
						account[length - 1] = 0;
						break;
					}
					case NECP_POLICY_CONDITION_TRAFFIC_CLASS: {
						if (length >= sizeof(u_int32_t)) {
							memcpy(&traffic_class, value, sizeof(u_int32_t));
						}
						break;
					}
					case NECP_POLICY_CONDITION_PID: {
						if (length >= sizeof(pid_t)) {
							memcpy(&pid, value, sizeof(pid_t));
						}
						break;
					}
					case NECP_POLICY_CONDITION_UID: {
						if (length >= sizeof(uid_t)) {
							memcpy(&uid, value, sizeof(uid_t));
						}
						break;
					}
					case NECP_POLICY_CONDITION_IP_PROTOCOL: {
						if (length >= sizeof(u_int16_t)) {
							memcpy(&protocol, value, sizeof(u_int16_t));
						}
						break;
					}
					case NECP_POLICY_CONDITION_BOUND_INTERFACE: {
						if (length <= IFXNAMSIZ && length > 0) {
							ifnet_t bound_interface = NULL;
							char interface_name[IFXNAMSIZ];
							memcpy(interface_name, value, length);
							interface_name[length - 1] = 0; // Make sure the string is NULL terminated
							if (ifnet_find_by_name(interface_name, &bound_interface) == 0) {
								bound_interface_index = bound_interface->if_index;
							}
						}
						break;
					}
					default: {
						break;
					}
				}
			}
		}

		offset += sizeof(u_int8_t) + sizeof(size_t) + length;
	}

	// Lock
	lck_rw_lock_shared(&necp_kernel_policy_lock);

	necp_application_fillout_info_locked(application_uuid, real_application_uuid, account, domain, pid, uid, protocol, bound_interface_index, traffic_class, &info);
	matched_policy = necp_socket_find_policy_match_with_info_locked(necp_kernel_socket_policies_app_layer_map, &info, &filter_control_unit, &service_action, &service);
	if (matched_policy) {
		returned_result->routing_result = matched_policy->result;
		memcpy(&returned_result->routing_result_parameter, &matched_policy->result_parameter, sizeof(returned_result->routing_result_parameter));
	} else {
		returned_result->routing_result = NECP_KERNEL_POLICY_RESULT_NONE;
	}
	returned_result->filter_control_unit = filter_control_unit;
	returned_result->service_action = service_action;

	if (service.identifier != 0) {
		struct necp_uuid_id_mapping *mapping = necp_uuid_lookup_uuid_with_service_id_locked(service.identifier);
		if (mapping != NULL) {
			struct necp_service_registration *service_registration = NULL;
			uuid_copy(returned_result->service_uuid, mapping->uuid);
			returned_result->service_data = service.data;
			if (service.identifier == NECP_NULL_SERVICE_ID) {
				// NULL service is always 'registered'
				returned_result->service_flags |= NECP_SERVICE_FLAGS_REGISTERED;
			} else {
				LIST_FOREACH(service_registration, &necp_registered_service_list, kernel_chain) {
					if (service.identifier == service_registration->service_id) {
						returned_result->service_flags |= NECP_SERVICE_FLAGS_REGISTERED;
						break;
					}
				}
			}
		}
	}

	// Unlock
	lck_rw_done(&necp_kernel_policy_lock);

	return (error);
}

#define NECP_MAX_MATCH_POLICY_PARAMETER_SIZE 1024

int
necp_match_policy(struct proc *p, struct necp_match_policy_args *uap, int32_t *retval)
{
#pragma unused(p, retval)
	u_int8_t *parameters = NULL;
	struct necp_aggregate_result returned_result;
	int error = 0;

	if (uap == NULL) {
		error = EINVAL;
		goto done;
	}

	if (uap->parameters == 0 || uap->parameters_size == 0 || uap->parameters_size > NECP_MAX_MATCH_POLICY_PARAMETER_SIZE || uap->returned_result == 0) {
		error = EINVAL;
		goto done;
	}

	MALLOC(parameters, u_int8_t *, uap->parameters_size, M_NECP, M_WAITOK);
	if (parameters == NULL) {
		error = ENOMEM;
		goto done;
	}
	// Copy parameters in
	copyin(uap->parameters, parameters, uap->parameters_size);

	error = necp_application_find_policy_match_internal(parameters, uap->parameters_size, &returned_result);
	if (error) {
		goto done;
	}

	// Copy return value back
	copyout(&returned_result, uap->returned_result, sizeof(struct necp_aggregate_result));
done:
	if (parameters != NULL) {
		FREE(parameters, M_NECP);
	}
	return (error);
}

static bool
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)
{
	if (!(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES)) {
		if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE) {
			u_int32_t cond_bound_interface_index = kernel_policy->cond_bound_interface ? kernel_policy->cond_bound_interface->if_index : 0;
			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE) {
				if (bound_interface_index == cond_bound_interface_index) {
					// No match, matches forbidden interface
					return (FALSE);
				}
			} else {
				if (bound_interface_index != cond_bound_interface_index) {
					// No match, does not match required interface
					return (FALSE);
				}
			}
		} else {
			if (bound_interface_index != 0) {
				// No match, requires a non-bound packet
				return (FALSE);
			}
		}
	}

	if (kernel_policy->condition_mask == 0) {
		return (TRUE);
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_APP_ID) {
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_APP_ID) {
			if (app_id == kernel_policy->cond_app_id) {
				// No match, matches forbidden application
				return (FALSE);
			}
		} else {
			if (app_id != kernel_policy->cond_app_id) {
				// No match, does not match required application
				return (FALSE);
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REAL_APP_ID) {
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_REAL_APP_ID) {
			if (real_app_id == kernel_policy->cond_real_app_id) {
				// No match, matches forbidden application
				return (FALSE);
			}
		} else {
			if (real_app_id != kernel_policy->cond_real_app_id) {
				// No match, does not match required application
				return (FALSE);
			}
		}
	}
	
	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ENTITLEMENT) {
		if (cred_result != 0) {
			// Process is missing entitlement
			return (FALSE);
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_DOMAIN) {
		bool domain_matches = necp_hostname_matches_domain(domain, domain_dot_count, kernel_policy->cond_domain, kernel_policy->cond_domain_dot_count);
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_DOMAIN) {
			if (domain_matches) {
				// No match, matches forbidden domain
				return (FALSE);
			}
		} else {
			if (!domain_matches) {
				// No match, does not match required domain
				return (FALSE);
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ACCOUNT_ID) {
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_ACCOUNT_ID) {
			if (account_id == kernel_policy->cond_account_id) {
				// No match, matches forbidden account
				return (FALSE);
			}
		} else {
			if (account_id != kernel_policy->cond_account_id) {
				// No match, does not match required account
				return (FALSE);
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_PID) {
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_PID) {
			if (pid == kernel_policy->cond_pid) {
				// No match, matches forbidden pid
				return (FALSE);
			}
		} else {
			if (pid != kernel_policy->cond_pid) {
				// No match, does not match required pid
				return (FALSE);
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_UID) {
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_UID) {
			if (uid == kernel_policy->cond_uid) {
				// No match, matches forbidden uid
				return (FALSE);
			}
		} else {
			if (uid != kernel_policy->cond_uid) {
				// No match, does not match required uid
				return (FALSE);
			}
		}
	}
	
	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_TRAFFIC_CLASS) {
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_TRAFFIC_CLASS) {
			if (traffic_class >= kernel_policy->cond_traffic_class.start_tc &&
				traffic_class <= kernel_policy->cond_traffic_class.end_tc) {
				// No match, matches forbidden traffic class
				return (FALSE);
			}
		} else {
			if (traffic_class < kernel_policy->cond_traffic_class.start_tc ||
				traffic_class > kernel_policy->cond_traffic_class.end_tc) {
				// No match, does not match required traffic class
				return (FALSE);
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_PROTOCOL) {
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_PROTOCOL) {
			if (protocol == kernel_policy->cond_protocol) {
				// No match, matches forbidden protocol
				return (FALSE);
			}
		} else {
			if (protocol != kernel_policy->cond_protocol) {
				// No match, does not match required protocol
				return (FALSE);
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_START) {
		if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
			bool inRange = necp_is_addr_in_range((struct sockaddr *)local, (struct sockaddr *)&kernel_policy->cond_local_start, (struct sockaddr *)&kernel_policy->cond_local_end);
			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
				if (inRange) {
					return (FALSE);
				}
			} else {
				if (!inRange) {
					return (FALSE);
				}
			}
		} else if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX) {
			bool inSubnet = necp_is_addr_in_subnet((struct sockaddr *)local, (struct sockaddr *)&kernel_policy->cond_local_start, kernel_policy->cond_local_prefix);
			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX) {
				if (inSubnet) {
					return (FALSE);
				}
			} else {
				if (!inSubnet) {
					return (FALSE);
				}
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_START) {
		if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
			bool inRange = necp_is_addr_in_range((struct sockaddr *)remote, (struct sockaddr *)&kernel_policy->cond_remote_start, (struct sockaddr *)&kernel_policy->cond_remote_end);
			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
				if (inRange) {
					return (FALSE);
				}
			} else {
				if (!inRange) {
					return (FALSE);
				}
			}
		} else if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX) {
			bool inSubnet = necp_is_addr_in_subnet((struct sockaddr *)remote, (struct sockaddr *)&kernel_policy->cond_remote_start, kernel_policy->cond_remote_prefix);
			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX) {
				if (inSubnet) {
					return (FALSE);
				}
			} else {
				if (!inSubnet) {
					return (FALSE);
				}
			}
		}
	}

	return (TRUE);
}

static inline u_int32_t
necp_socket_calc_flowhash_locked(struct necp_socket_info *info)
{
	return (net_flowhash(info, sizeof(*info), necp_kernel_socket_policies_gencount));
}

#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)
static void
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)
{
	struct socket *so = NULL;

	memset(info, 0, sizeof(struct necp_socket_info));

	so = inp->inp_socket;

	if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_PID) {
		info->pid = ((so->so_flags & SOF_DELEGATED) ? so->e_pid : so->last_pid);
	}

	if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_UID) {
		info->uid = kauth_cred_getuid(so->so_cred);
	}
	
	if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_TRAFFIC_CLASS) {
		info->traffic_class = so->so_traffic_class;
	}

	if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_PROTOCOL) {
		if (inp->inp_ip_p) {
			info->protocol = inp->inp_ip_p;
		} else {
			info->protocol = SOCK_PROTO(so);
		}
	}

	if (inp->inp_flags2 & INP2_WANT_APP_POLICY && necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_APP_ID) {
		struct necp_uuid_id_mapping *existing_mapping = necp_uuid_lookup_app_id_locked(((so->so_flags & SOF_DELEGATED) ? so->e_uuid : so->last_uuid));
		if (existing_mapping) {
			info->application_id = existing_mapping->id;
		}

		if (!(so->so_flags & SOF_DELEGATED)) {
			info->real_application_id = info->application_id;
		} else if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_REAL_APP_ID) {
			struct necp_uuid_id_mapping *real_existing_mapping = necp_uuid_lookup_app_id_locked(so->last_uuid);
			if (real_existing_mapping) {
				info->real_application_id = real_existing_mapping->id;
			}
		}
		
		if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_ENTITLEMENT) {
			info->cred_result = priv_check_cred(so->so_cred, PRIV_NET_PRIVILEGED_NECP_MATCH, 0);
		}
	}

	if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_ACCOUNT_ID && inp->inp_necp_attributes.inp_account != NULL) {
		struct necp_string_id_mapping *existing_mapping = necp_lookup_string_to_id_locked(&necp_account_id_list, inp->inp_necp_attributes.inp_account);
		if (existing_mapping) {
			info->account_id = existing_mapping->id;
		}
	}

	if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_CONDITION_DOMAIN) {
		info->domain = inp->inp_necp_attributes.inp_domain;
	}

	if (override_bound_interface) {
		info->bound_interface_index = override_bound_interface;
	} else {
		if ((inp->inp_flags & INP_BOUND_IF) && inp->inp_boundifp) {
			info->bound_interface_index = inp->inp_boundifp->if_index;
		}
	}

	if (necp_kernel_socket_policies_condition_mask & NECP_KERNEL_ADDRESS_TYPE_CONDITIONS) {
		if (inp->inp_vflag & INP_IPV4) {
			if (override_local_addr) {
				memcpy(&info->local_addr, override_local_addr, override_local_addr->sa_len);
			} else {
				((struct sockaddr_in *)&info->local_addr)->sin_family = AF_INET;
				((struct sockaddr_in *)&info->local_addr)->sin_len = sizeof(struct sockaddr_in);
				((struct sockaddr_in *)&info->local_addr)->sin_port = inp->inp_lport;
				memcpy(&((struct sockaddr_in *)&info->local_addr)->sin_addr, &inp->inp_laddr, sizeof(struct in_addr));
			}

			if (override_remote_addr) {
				memcpy(&info->remote_addr, override_remote_addr, override_remote_addr->sa_len);
			} else {
				((struct sockaddr_in *)&info->remote_addr)->sin_family = AF_INET;
				((struct sockaddr_in *)&info->remote_addr)->sin_len = sizeof(struct sockaddr_in);
				((struct sockaddr_in *)&info->remote_addr)->sin_port = inp->inp_fport;
				memcpy(&((struct sockaddr_in *)&info->remote_addr)->sin_addr, &inp->inp_faddr, sizeof(struct in_addr));
			}
		} else if (inp->inp_vflag & INP_IPV6) {
			if (override_local_addr) {
				memcpy(&info->local_addr, override_local_addr, override_local_addr->sa_len);
			} else {
				((struct sockaddr_in6 *)&info->local_addr)->sin6_family = AF_INET6;
				((struct sockaddr_in6 *)&info->local_addr)->sin6_len = sizeof(struct sockaddr_in6);
				((struct sockaddr_in6 *)&info->local_addr)->sin6_port = inp->inp_lport;
				memcpy(&((struct sockaddr_in6 *)&info->local_addr)->sin6_addr, &inp->in6p_laddr, sizeof(struct in6_addr));
			}

			if (override_remote_addr) {
				memcpy(&info->remote_addr, override_remote_addr, override_remote_addr->sa_len);
			} else {
				((struct sockaddr_in6 *)&info->remote_addr)->sin6_family = AF_INET6;
				((struct sockaddr_in6 *)&info->remote_addr)->sin6_len = sizeof(struct sockaddr_in6);
				((struct sockaddr_in6 *)&info->remote_addr)->sin6_port = inp->inp_fport;
				memcpy(&((struct sockaddr_in6 *)&info->remote_addr)->sin6_addr, &inp->in6p_faddr, sizeof(struct in6_addr));
			}
		}
	}
}

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, necp_kernel_policy_result *return_service_action, necp_kernel_policy_service *return_service)
{
	struct necp_kernel_socket_policy *matched_policy = NULL;
	u_int32_t skip_order = 0;
	u_int32_t skip_session_order = 0;
	int i;
	
	// Pre-process domain for quick matching
	struct substring domain_substring = necp_trim_dots_and_stars(info->domain, info->domain ? strlen(info->domain) : 0);
	u_int8_t domain_dot_count = necp_count_dots(domain_substring.string, domain_substring.length);

	if (return_filter) {
		*return_filter = 0;
	}

	if (return_service_action) {
		*return_service_action = 0;
	}

	if (return_service) {
		return_service->identifier = 0;
		return_service->data = 0;
	}

	if (policy_search_array != NULL) {
		for (i = 0; policy_search_array[i] != NULL; i++) {
			if (necp_drop_all_order != 0 && policy_search_array[i]->session_order >= necp_drop_all_order) {
				// We've hit a drop all rule
				break;
			}
			if (skip_session_order && policy_search_array[i]->session_order >= skip_session_order) {
				// Done skipping
				skip_order = 0;
				skip_session_order = 0;
			}
			if (skip_order) {
				if (policy_search_array[i]->order < skip_order) {
					// Skip this policy
					continue;
				} else {
					// Done skipping
					skip_order = 0;
					skip_session_order = 0;
				}
			} else if (skip_session_order) {
				// Skip this policy
				continue;
			}
			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)) {
				if (policy_search_array[i]->result == NECP_KERNEL_POLICY_RESULT_SOCKET_FILTER) {
					if (return_filter && *return_filter == 0) {
						*return_filter = policy_search_array[i]->result_parameter.filter_control_unit;
						if (necp_debug > 1) {
							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);
						}
					}
					continue;
				} else if (necp_kernel_socket_result_is_service_type(policy_search_array[i])) {
					if (return_service_action && *return_service_action == 0) {
						*return_service_action = policy_search_array[i]->result;
						if (necp_debug > 1) {
							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);
						}
					}
					if (return_service && return_service->identifier == 0) {
						return_service->identifier = policy_search_array[i]->result_parameter.service.identifier;
						return_service->data = policy_search_array[i]->result_parameter.service.data;
						if (necp_debug > 1) {
							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);
						}
					}
					continue;
				}

				// Passed all tests, found a match
				matched_policy = policy_search_array[i];
				if (policy_search_array[i]->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
					skip_order = policy_search_array[i]->result_parameter.skip_policy_order;
					skip_session_order = policy_search_array[i]->session_order + 1;
					continue;
				}
				break;
			}
		}
	}

	return (matched_policy);
}

static bool
necp_socket_uses_interface(struct inpcb *inp, u_int32_t interface_index)
{
	bool found_match = FALSE;
	errno_t result = 0;
	ifaddr_t *addresses = NULL;
	union necp_sockaddr_union address_storage;
	int i;
	int family = AF_INET;
	ifnet_t interface = ifindex2ifnet[interface_index];
	
	if (inp == NULL || interface == NULL) {
		return (FALSE);
	}
	
	if (inp->inp_vflag & INP_IPV4) {
		family = AF_INET;
	} else if (inp->inp_vflag & INP_IPV6) {
		family = AF_INET6;
	}
	
	result = ifnet_get_address_list_family(interface, &addresses, family);
	if (result != 0) {
		NECPLOG(LOG_ERR, "Failed to get address list for %s%d", ifnet_name(interface), ifnet_unit(interface));
		return (FALSE);
	}
	
	for (i = 0; addresses[i] != NULL; i++) {
		if (ifaddr_address(addresses[i], &address_storage.sa, sizeof(address_storage)) == 0) {
			if (family == AF_INET) {
				if (memcmp(&address_storage.sin.sin_addr, &inp->inp_laddr, sizeof(inp->inp_laddr)) == 0) {
					found_match = TRUE;
					goto done;
				}
			} else if (family == AF_INET6) {
				if (memcmp(&address_storage.sin6.sin6_addr, &inp->in6p_laddr, sizeof(inp->in6p_laddr)) == 0) {
					found_match = TRUE;
					goto done;
				}
			}
		}
	}
	
done:
	ifnet_free_address_list(addresses);
	addresses = NULL;
	return (found_match);
}

static inline bool
necp_socket_is_connected(struct inpcb *inp)
{
	return (inp->inp_socket->so_state & (SS_ISCONNECTING | SS_ISCONNECTED | SS_ISDISCONNECTING));
}

necp_kernel_policy_id
necp_socket_find_policy_match(struct inpcb *inp, struct sockaddr *override_local_addr, struct sockaddr *override_remote_addr, u_int32_t override_bound_interface)
{
	struct socket *so = NULL;
	necp_kernel_policy_filter filter_control_unit = 0;
	struct necp_kernel_socket_policy *matched_policy = NULL;
	necp_kernel_policy_id matched_policy_id = NECP_KERNEL_POLICY_ID_NONE;
	necp_kernel_policy_result service_action = 0;
	necp_kernel_policy_service service = { 0, 0 };

	struct necp_socket_info info;

	if (inp == NULL) {
		return (NECP_KERNEL_POLICY_ID_NONE);
	}

	so = inp->inp_socket;

	// Don't lock. Possible race condition, but we don't want the performance hit.
	if (necp_kernel_socket_policies_count == 0 ||
		(!(inp->inp_flags2 & INP2_WANT_APP_POLICY) && necp_kernel_socket_policies_non_app_count == 0)) {
		if (necp_drop_all_order > 0) {
			inp->inp_policyresult.policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
			inp->inp_policyresult.policy_gencount = 0;
			inp->inp_policyresult.flowhash = 0;
			inp->inp_policyresult.results.filter_control_unit = 0;
			if (necp_pass_loopback > 0 &&
				necp_is_loopback(override_local_addr, override_remote_addr, inp, NULL)) {
				inp->inp_policyresult.results.result = NECP_KERNEL_POLICY_RESULT_PASS;
			} else {
				inp->inp_policyresult.results.result = NECP_KERNEL_POLICY_RESULT_DROP;
			}
		}
		return (NECP_KERNEL_POLICY_ID_NONE);
	}
	
	// Check for loopback exception
	if (necp_pass_loopback > 0 &&
		necp_is_loopback(override_local_addr, override_remote_addr, inp, NULL)) {
		// Mark socket as a pass
		inp->inp_policyresult.policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		inp->inp_policyresult.policy_gencount = 0;
		inp->inp_policyresult.flowhash = 0;
		inp->inp_policyresult.results.filter_control_unit = 0;
		inp->inp_policyresult.results.result = NECP_KERNEL_POLICY_RESULT_PASS;
		return (NECP_KERNEL_POLICY_ID_NONE);
	}

	// Lock
	lck_rw_lock_shared(&necp_kernel_policy_lock);
	
	necp_socket_fillout_info_locked(inp, override_local_addr, override_remote_addr, override_bound_interface, &info);

	// Check info
	u_int32_t flowhash = necp_socket_calc_flowhash_locked(&info);
	if (inp->inp_policyresult.policy_id != NECP_KERNEL_POLICY_ID_NONE &&
		inp->inp_policyresult.policy_gencount == necp_kernel_socket_policies_gencount &&
		inp->inp_policyresult.flowhash == flowhash) {
		// If already matched this socket on this generation of table, skip

		// Unlock
		lck_rw_done(&necp_kernel_policy_lock);

		return (inp->inp_policyresult.policy_id);
	}

	// Match socket to 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, &filter_control_unit, &service_action, &service);
	// If the socket matched a scoped service policy, mark as Drop if not registered.
	// This covers the cases in which a service is required (on demand) but hasn't started yet.
	if ((service_action == NECP_KERNEL_POLICY_RESULT_TRIGGER_SCOPED ||
		 service_action == NECP_KERNEL_POLICY_RESULT_NO_TRIGGER_SCOPED) &&
		service.identifier != 0 &&
		service.identifier != NECP_NULL_SERVICE_ID) {
		bool service_is_registered = FALSE;
		struct necp_service_registration *service_registration = NULL;
		LIST_FOREACH(service_registration, &necp_registered_service_list, kernel_chain) {
			if (service.identifier == service_registration->service_id) {
				service_is_registered = TRUE;
				break;
			}
		}
		if (!service_is_registered) {
			// Mark socket as a drop if service is not registered
			inp->inp_policyresult.policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
			inp->inp_policyresult.policy_gencount = necp_kernel_socket_policies_gencount;
			inp->inp_policyresult.flowhash = flowhash;
			inp->inp_policyresult.results.filter_control_unit = 0;
			inp->inp_policyresult.results.result = NECP_KERNEL_POLICY_RESULT_DROP;
			
			if (necp_debug > 1) {
				NECPLOG(LOG_DEBUG, "Socket Policy: (BoundInterface %d Proto %d) Dropping packet because service is not registered", info.bound_interface_index, info.protocol);
			}
			
			// Unlock
			lck_rw_done(&necp_kernel_policy_lock);
			return (NECP_KERNEL_POLICY_ID_NONE);
		}
	}
	if (matched_policy) {
		matched_policy_id = matched_policy->id;
		inp->inp_policyresult.policy_id = matched_policy->id;
		inp->inp_policyresult.policy_gencount = necp_kernel_socket_policies_gencount;
		inp->inp_policyresult.flowhash = flowhash;
		inp->inp_policyresult.results.filter_control_unit = filter_control_unit;
		inp->inp_policyresult.results.result = matched_policy->result;
		memcpy(&inp->inp_policyresult.results.result_parameter, &matched_policy->result_parameter, sizeof(matched_policy->result_parameter));

		if (necp_socket_is_connected(inp) &&
			(matched_policy->result == NECP_KERNEL_POLICY_RESULT_DROP ||
			(matched_policy->result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL && !necp_socket_uses_interface(inp, matched_policy->result_parameter.tunnel_interface_index)))) {
			if (necp_debug) {
				NECPLOG(LOG_DEBUG, "Marking socket in state %d as defunct", so->so_state);
			}
			sosetdefunct(current_proc(), so, SHUTDOWN_SOCKET_LEVEL_DISCONNECT_ALL, TRUE);
		}

		if (necp_debug > 1) {
			NECPLOG(LOG_DEBUG, "Socket Policy: (BoundInterface %d Proto %d) Policy %d Result %d Parameter %d", info.bound_interface_index, info.protocol, matched_policy->id, matched_policy->result, matched_policy->result_parameter.tunnel_interface_index);
		}
	} else if (necp_drop_all_order > 0) {
		// Mark socket as a drop if set
		inp->inp_policyresult.policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		inp->inp_policyresult.policy_gencount = necp_kernel_socket_policies_gencount;
		inp->inp_policyresult.flowhash = flowhash;
		inp->inp_policyresult.results.filter_control_unit = 0;
		inp->inp_policyresult.results.result = NECP_KERNEL_POLICY_RESULT_DROP;
	} else {
		// Mark non-matching socket so we don't re-check it
		inp->inp_policyresult.policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		inp->inp_policyresult.policy_gencount = necp_kernel_socket_policies_gencount;
		inp->inp_policyresult.flowhash = flowhash;
		inp->inp_policyresult.results.filter_control_unit = filter_control_unit; // We may have matched a filter, so mark it!
		inp->inp_policyresult.results.result = NECP_KERNEL_POLICY_RESULT_NONE;
	}

	// Unlock
	lck_rw_done(&necp_kernel_policy_lock);

	return (matched_policy_id);
}

static bool
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)
{
	if (!(kernel_policy->condition_mask & NECP_KERNEL_CONDITION_ALL_INTERFACES)) {
		if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE) {
			u_int32_t cond_bound_interface_index = kernel_policy->cond_bound_interface ? kernel_policy->cond_bound_interface->if_index : 0;
			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_BOUND_INTERFACE) {
				if (bound_interface_index == cond_bound_interface_index) {
					// No match, matches forbidden interface
					return (FALSE);
				}
			} else {
				if (bound_interface_index != cond_bound_interface_index) {
					// No match, does not match required interface
					return (FALSE);
				}
			}
		} else {
			if (bound_interface_index != 0) {
				// No match, requires a non-bound packet
				return (FALSE);
			}
		}
	}

	if (kernel_policy->condition_mask == 0) {
		return (TRUE);
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_POLICY_ID) {
		if (socket_policy_id != kernel_policy->cond_policy_id) {
			// No match, does not match required id
			return (FALSE);
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LAST_INTERFACE) {
		if (last_interface_index != kernel_policy->cond_last_interface_index) {
			return (FALSE);
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_PROTOCOL) {
		if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_PROTOCOL) {
			if (protocol == kernel_policy->cond_protocol) {
				// No match, matches forbidden protocol
				return (FALSE);
			}
		} else {
			if (protocol != kernel_policy->cond_protocol) {
				// No match, does not match required protocol
				return (FALSE);
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_START) {
		if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
			bool inRange = necp_is_addr_in_range((struct sockaddr *)local, (struct sockaddr *)&kernel_policy->cond_local_start, (struct sockaddr *)&kernel_policy->cond_local_end);
			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_END) {
				if (inRange) {
					return (FALSE);
				}
			} else {
				if (!inRange) {
					return (FALSE);
				}
			}
		} else if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX) {
			bool inSubnet = necp_is_addr_in_subnet((struct sockaddr *)local, (struct sockaddr *)&kernel_policy->cond_local_start, kernel_policy->cond_local_prefix);
			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_LOCAL_PREFIX) {
				if (inSubnet) {
					return (FALSE);
				}
			} else {
				if (!inSubnet) {
					return (FALSE);
				}
			}
		}
	}

	if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_START) {
		if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
			bool inRange = necp_is_addr_in_range((struct sockaddr *)remote, (struct sockaddr *)&kernel_policy->cond_remote_start, (struct sockaddr *)&kernel_policy->cond_remote_end);
			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_REMOTE_END) {
				if (inRange) {
					return (FALSE);
				}
			} else {
				if (!inRange) {
					return (FALSE);
				}
			}
		} else if (kernel_policy->condition_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX) {
			bool inSubnet = necp_is_addr_in_subnet((struct sockaddr *)remote, (struct sockaddr *)&kernel_policy->cond_remote_start, kernel_policy->cond_remote_prefix);
			if (kernel_policy->condition_negated_mask & NECP_KERNEL_CONDITION_REMOTE_PREFIX) {
				if (inSubnet) {
					return (FALSE);
				}
			} else {
				if (!inSubnet) {
					return (FALSE);
				}
			}
		}
	}

	return (TRUE);
}

static inline struct necp_kernel_ip_output_policy *
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)
{
	u_int32_t skip_order = 0;
	u_int32_t skip_session_order = 0;
	int i;
	struct necp_kernel_ip_output_policy *matched_policy = NULL;
	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)];
	if (policy_search_array != NULL) {
		for (i = 0; policy_search_array[i] != NULL; i++) {
			if (necp_drop_all_order != 0 && policy_search_array[i]->session_order >= necp_drop_all_order) {
				// We've hit a drop all rule
				break;
			}
			if (skip_session_order && policy_search_array[i]->session_order >= skip_session_order) {
				// Done skipping
				skip_order = 0;
				skip_session_order = 0;
			}
			if (skip_order) {
				if (policy_search_array[i]->order < skip_order) {
					// Skip this policy
					continue;
				} else {
					// Done skipping
					skip_order = 0;
					skip_session_order = 0;
				}
			} else if (skip_session_order) {
				// Skip this policy
				continue;
			}
			if (necp_ip_output_check_policy(policy_search_array[i], socket_policy_id, bound_interface_index, last_interface_index, protocol, local_addr, remote_addr)) {
				// Passed all tests, found a match
				matched_policy = policy_search_array[i];

				if (policy_search_array[i]->result == NECP_KERNEL_POLICY_RESULT_SKIP) {
					skip_order = policy_search_array[i]->result_parameter.skip_policy_order;
					skip_session_order = policy_search_array[i]->session_order + 1;
					continue;
				}

				break;
			}
		}
	}

	return (matched_policy);
}

necp_kernel_policy_id
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)
{
	struct ip *ip = NULL;
	int hlen = sizeof(struct ip);
	necp_kernel_policy_id socket_policy_id = NECP_KERNEL_POLICY_ID_NONE;
	necp_kernel_policy_id matched_policy_id = NECP_KERNEL_POLICY_ID_NONE;
	struct necp_kernel_ip_output_policy *matched_policy = NULL;
	u_int16_t protocol = 0;
	u_int32_t bound_interface_index = 0;
	u_int32_t last_interface_index = 0;
	union necp_sockaddr_union local_addr;
	union necp_sockaddr_union remote_addr;

	if (result) {
		*result = 0;
	}

	if (result_parameter) {
		memset(result_parameter, 0, sizeof(*result_parameter));
	}

	if (packet == NULL) {
		return (NECP_KERNEL_POLICY_ID_NONE);
	}
	
	socket_policy_id = necp_get_policy_id_from_packet(packet);

	// Exit early for an empty list
	// Don't lock. Possible race condition, but we don't want the performance hit.
	if (necp_kernel_ip_output_policies_count == 0 ||
		((socket_policy_id == NECP_KERNEL_POLICY_ID_NONE) && necp_kernel_ip_output_policies_non_id_count == 0)) {
		if (necp_drop_all_order > 0) {
			matched_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
			if (result) {
				if ((necp_pass_loopback > 0 &&
					 necp_is_loopback(NULL, NULL, NULL, packet)) ||
					(necp_pass_keepalives > 0 &&
					 necp_get_is_keepalive_from_packet(packet))) {
					*result = NECP_KERNEL_POLICY_RESULT_PASS;
				} else {
					*result = NECP_KERNEL_POLICY_RESULT_DROP;
				}
			}
		}

		return (matched_policy_id);
	}
	
	// Check for loopback exception
	if ((necp_pass_loopback > 0 &&
		 necp_is_loopback(NULL, NULL, NULL, packet)) ||
		(necp_pass_keepalives > 0 &&
		 necp_get_is_keepalive_from_packet(packet))) {
		matched_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		if (result) {
			*result = NECP_KERNEL_POLICY_RESULT_PASS;
		}
		return (matched_policy_id);
	}
	
	last_interface_index = necp_get_last_interface_index_from_packet(packet);

	// Process packet to get relevant fields
	ip = mtod(packet, struct ip *);
#ifdef _IP_VHL
	hlen = _IP_VHL_HL(ip->ip_vhl) << 2;
#else
	hlen = ip->ip_hl << 2;
#endif

	protocol = ip->ip_p;

	if ((flags & IP_OUTARGS) && (ipoa != NULL) &&
		(ipoa->ipoa_flags & IPOAF_BOUND_IF) &&
		ipoa->ipoa_boundif != IFSCOPE_NONE) {
		bound_interface_index = ipoa->ipoa_boundif;
	}

	local_addr.sin.sin_family = AF_INET;
	local_addr.sin.sin_len = sizeof(struct sockaddr_in);
	memcpy(&local_addr.sin.sin_addr, &ip->ip_src, sizeof(ip->ip_src));

	remote_addr.sin.sin_family = AF_INET;
	remote_addr.sin.sin_len = sizeof(struct sockaddr_in);
	memcpy(&((struct sockaddr_in *)&remote_addr)->sin_addr, &ip->ip_dst, sizeof(ip->ip_dst));

	switch (protocol) {
		case IPPROTO_TCP: {
			struct tcphdr th;
			if ((int)(hlen + sizeof(th)) <= packet->m_pkthdr.len) {
				m_copydata(packet, hlen, sizeof(th), (u_int8_t *)&th);
				((struct sockaddr_in *)&local_addr)->sin_port = th.th_sport;
				((struct sockaddr_in *)&remote_addr)->sin_port = th.th_dport;
			}
			break;
		}
		case IPPROTO_UDP: {
			struct udphdr uh;
			if ((int)(hlen + sizeof(uh)) <= packet->m_pkthdr.len) {
				m_copydata(packet, hlen, sizeof(uh), (u_int8_t *)&uh);
				((struct sockaddr_in *)&local_addr)->sin_port = uh.uh_sport;
				((struct sockaddr_in *)&remote_addr)->sin_port = uh.uh_dport;
			}
			break;
		}
		default: {
			((struct sockaddr_in *)&local_addr)->sin_port = 0;
			((struct sockaddr_in *)&remote_addr)->sin_port = 0;
			break;
		}
	}

	// Match packet to policy
	lck_rw_lock_shared(&necp_kernel_policy_lock);
	matched_policy = necp_ip_output_find_policy_match_locked(socket_policy_id, bound_interface_index, last_interface_index, protocol, &local_addr, &remote_addr);
	if (matched_policy) {
		matched_policy_id = matched_policy->id;
		if (result) {
			*result = matched_policy->result;
		}

		if (result_parameter) {
			memcpy(result_parameter, &matched_policy->result_parameter, sizeof(matched_policy->result_parameter));
		}

		if (necp_debug > 1) {
			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);
		}
	} else if (necp_drop_all_order > 0) {
		matched_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		if (result) {
			*result = NECP_KERNEL_POLICY_RESULT_DROP;
		}
	}

	lck_rw_done(&necp_kernel_policy_lock);

	return (matched_policy_id);
}

necp_kernel_policy_id
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)
{
	struct ip6_hdr *ip6 = NULL;
	int next = -1;
	int offset = 0;
	necp_kernel_policy_id socket_policy_id = NECP_KERNEL_POLICY_ID_NONE;
	necp_kernel_policy_id matched_policy_id = NECP_KERNEL_POLICY_ID_NONE;
	struct necp_kernel_ip_output_policy *matched_policy = NULL;
	u_int16_t protocol = 0;
	u_int32_t bound_interface_index = 0;
	u_int32_t last_interface_index = 0;
	union necp_sockaddr_union local_addr;
	union necp_sockaddr_union remote_addr;

	if (result) {
		*result = 0;
	}

	if (result_parameter) {
		memset(result_parameter, 0, sizeof(*result_parameter));
	}

	if (packet == NULL) {
		return (NECP_KERNEL_POLICY_ID_NONE);
	}

	socket_policy_id = necp_get_policy_id_from_packet(packet);
	
	// Exit early for an empty list
	// Don't lock. Possible race condition, but we don't want the performance hit.
	if (necp_kernel_ip_output_policies_count == 0 ||
		((socket_policy_id == NECP_KERNEL_POLICY_ID_NONE) && necp_kernel_ip_output_policies_non_id_count == 0)) {
		if (necp_drop_all_order > 0) {
			matched_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
			if (result) {
				if ((necp_pass_loopback > 0 &&
					 necp_is_loopback(NULL, NULL, NULL, packet)) ||
					(necp_pass_keepalives > 0 &&
					 necp_get_is_keepalive_from_packet(packet))) {
					*result = NECP_KERNEL_POLICY_RESULT_PASS;
				} else {
					*result = NECP_KERNEL_POLICY_RESULT_DROP;
				}
			}
		}

		return (matched_policy_id);
	}
	
	// Check for loopback exception
	if ((necp_pass_loopback > 0 &&
		 necp_is_loopback(NULL, NULL, NULL, packet)) ||
		(necp_pass_keepalives > 0 &&
		 necp_get_is_keepalive_from_packet(packet))) {
		matched_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		if (result) {
			*result = NECP_KERNEL_POLICY_RESULT_PASS;
		}
		return (matched_policy_id);
	}
	
	last_interface_index = necp_get_last_interface_index_from_packet(packet);

	// Process packet to get relevant fields
	ip6 = mtod(packet, struct ip6_hdr *);

	if ((flags & IPV6_OUTARGS) && (ip6oa != NULL) &&
		(ip6oa->ip6oa_flags & IP6OAF_BOUND_IF) &&
		ip6oa->ip6oa_boundif != IFSCOPE_NONE) {
		bound_interface_index = ip6oa->ip6oa_boundif;
	}

	((struct sockaddr_in6 *)&local_addr)->sin6_family = AF_INET6;
	((struct sockaddr_in6 *)&local_addr)->sin6_len = sizeof(struct sockaddr_in6);
	memcpy(&((struct sockaddr_in6 *)&local_addr)->sin6_addr, &ip6->ip6_src, sizeof(ip6->ip6_src));

	((struct sockaddr_in6 *)&remote_addr)->sin6_family = AF_INET6;
	((struct sockaddr_in6 *)&remote_addr)->sin6_len = sizeof(struct sockaddr_in6);
	memcpy(&((struct sockaddr_in6 *)&remote_addr)->sin6_addr, &ip6->ip6_dst, sizeof(ip6->ip6_dst));

	offset = ip6_lasthdr(packet, 0, IPPROTO_IPV6, &next);
	if (offset >= 0 && packet->m_pkthdr.len >= offset) {
		protocol = next;
		switch (protocol) {
			case IPPROTO_TCP: {
				struct tcphdr th;
				if ((int)(offset + sizeof(th)) <= packet->m_pkthdr.len) {
					m_copydata(packet, offset, sizeof(th), (u_int8_t *)&th);
					((struct sockaddr_in6 *)&local_addr)->sin6_port = th.th_sport;
					((struct sockaddr_in6 *)&remote_addr)->sin6_port = th.th_dport;
				}
				break;
			}
			case IPPROTO_UDP: {
				struct udphdr uh;
				if ((int)(offset + sizeof(uh)) <= packet->m_pkthdr.len) {
					m_copydata(packet, offset, sizeof(uh), (u_int8_t *)&uh);
					((struct sockaddr_in6 *)&local_addr)->sin6_port = uh.uh_sport;
					((struct sockaddr_in6 *)&remote_addr)->sin6_port = uh.uh_dport;
				}
				break;
			}
			default: {
				((struct sockaddr_in6 *)&local_addr)->sin6_port = 0;
				((struct sockaddr_in6 *)&remote_addr)->sin6_port = 0;
				break;
			}
		}
	}

	// Match packet to policy
	lck_rw_lock_shared(&necp_kernel_policy_lock);
	matched_policy = necp_ip_output_find_policy_match_locked(socket_policy_id, bound_interface_index, last_interface_index, protocol, &local_addr, &remote_addr);
	if (matched_policy) {
		matched_policy_id = matched_policy->id;
		if (result) {
			*result = matched_policy->result;
		}

		if (result_parameter) {
			memcpy(result_parameter, &matched_policy->result_parameter, sizeof(matched_policy->result_parameter));
		}

		if (necp_debug > 1) {
			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);
		}
	} else if (necp_drop_all_order > 0) {
		matched_policy_id = NECP_KERNEL_POLICY_ID_NO_MATCH;
		if (result) {
			*result = NECP_KERNEL_POLICY_RESULT_DROP;
		}
	}

	lck_rw_done(&necp_kernel_policy_lock);

	return (matched_policy_id);
}

// Utilities
static bool
necp_is_addr_in_range(struct sockaddr *addr, struct sockaddr *range_start, struct sockaddr *range_end)
{
	int cmp = 0;

	if (addr == NULL || range_start == NULL || range_end == NULL) {
		return (FALSE);
	}

	/* Must be greater than or equal to start */
	cmp = necp_addr_compare(addr, range_start, 1);
	if (cmp != 0 && cmp != 1) {
		return (FALSE);
	}

	/* Must be less than or equal to end */
	cmp = necp_addr_compare(addr, range_end, 1);
	if (cmp != 0 && cmp != -1) {
		return (FALSE);
	}

	return (TRUE);
}

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)
{
	int cmp = 0;

	if (inner_range_start == NULL || inner_range_end == NULL || range_start == NULL || range_end == NULL) {
		return (FALSE);
	}

	/* Must be greater than or equal to start */
	cmp = necp_addr_compare(inner_range_start, range_start, 1);
	if (cmp != 0 && cmp != 1) {
		return (FALSE);
	}

	/* Must be less than or equal to end */
	cmp = necp_addr_compare(inner_range_end, range_end, 1);
	if (cmp != 0 && cmp != -1) {
		return (FALSE);
	}

	return (TRUE);
}

static bool
necp_is_addr_in_subnet(struct sockaddr *addr, struct sockaddr *subnet_addr, u_int8_t subnet_prefix)
{
	if (addr == NULL || subnet_addr == NULL) {
		return (FALSE);
	}

	if (addr->sa_family != subnet_addr->sa_family || addr->sa_len != subnet_addr->sa_len) {
		return (FALSE);
	}

	switch (addr->sa_family) {
		case AF_INET: {
			if (satosin(subnet_addr)->sin_port != 0 &&
				satosin(addr)->sin_port != satosin(subnet_addr)->sin_port) {
				return (FALSE);
			}
			return (necp_buffer_compare_with_bit_prefix((u_int8_t *)&satosin(addr)->sin_addr, (u_int8_t *)&satosin(subnet_addr)->sin_addr, subnet_prefix));
		}
		case AF_INET6: {
			if (satosin6(subnet_addr)->sin6_port != 0 &&
				satosin6(addr)->sin6_port != satosin6(subnet_addr)->sin6_port) {
				return (FALSE);
			}
			if (satosin6(addr)->sin6_scope_id &&
				satosin6(subnet_addr)->sin6_scope_id &&
				satosin6(addr)->sin6_scope_id != satosin6(subnet_addr)->sin6_scope_id) {
				return (FALSE);
			}
			return (necp_buffer_compare_with_bit_prefix((u_int8_t *)&satosin6(addr)->sin6_addr, (u_int8_t *)&satosin6(subnet_addr)->sin6_addr, subnet_prefix));
		}
		default: {
			return (FALSE);
		}
	}

	return (FALSE);
}

/*
 * Return values:
 * -1: sa1 < sa2
 * 0: sa1 == sa2
 * 1: sa1 > sa2
 * 2: Not comparable or error
 */
static int
necp_addr_compare(struct sockaddr *sa1, struct sockaddr *sa2, int check_port)
{
	int result = 0;
	int port_result = 0;

	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len) {
		return (2);
	}

	if (sa1->sa_len == 0) {
		return (0);
	}

	switch (sa1->sa_family) {
		case AF_INET: {
			if (sa1->sa_len != sizeof(struct sockaddr_in)) {
				return (2);
			}

			result = memcmp(&satosin(sa1)->sin_addr.s_addr, &satosin(sa2)->sin_addr.s_addr, sizeof(satosin(sa1)->sin_addr.s_addr));

			if (check_port) {
				if (satosin(sa1)->sin_port < satosin(sa2)->sin_port) {
					port_result = -1;
				} else if (satosin(sa1)->sin_port > satosin(sa2)->sin_port) {
					port_result = 1;
				}

				if (result == 0) {
					result = port_result;
				} else if ((result > 0 && port_result < 0) || (result < 0 && port_result > 0)) {
					return (2);
				}
			}

			break;
		}
		case AF_INET6: {
			if (sa1->sa_len != sizeof(struct sockaddr_in6)) {
				return (2);
			}

			if (satosin6(sa1)->sin6_scope_id != satosin6(sa2)->sin6_scope_id) {
				return (2);
			}

			result = memcmp(&satosin6(sa1)->sin6_addr.s6_addr[0], &satosin6(sa2)->sin6_addr.s6_addr[0], sizeof(struct in6_addr));

			if (check_port) {
				if (satosin6(sa1)->sin6_port < satosin6(sa2)->sin6_port) {
					port_result = -1;
				} else if (satosin6(sa1)->sin6_port > satosin6(sa2)->sin6_port) {
					port_result = 1;
				}

				if (result == 0) {
					result = port_result;
				} else if ((result > 0 && port_result < 0) || (result < 0 && port_result > 0)) {
					return (2);
				}
			}

			break;
		}
		default: {
			result = memcmp(sa1, sa2, sa1->sa_len);
			break;
		}
	}

	if (result < 0) {
		result = (-1);
	} else if (result > 0) {
		result = (1);
	}

	return (result);
}

static bool
necp_buffer_compare_with_bit_prefix(u_int8_t *p1, u_int8_t *p2, u_int32_t bits)
{
	u_int8_t mask;

	/* Handle null pointers */
	if (p1 == NULL || p2 == NULL) {
		return (p1 == p2);
	}

	while (bits >= 8) {
		if (*p1++ != *p2++) {
			return (FALSE);
		}
		bits -= 8;
	}

	if (bits > 0) {
		mask = ~((1<<(8-bits))-1);
		if ((*p1 & mask) != (*p2 & mask)) {
			return (FALSE);
		}
	}
	return (TRUE);
}

// Socket operations
#define NECP_MAX_SOCKET_ATTRIBUTE_STRING_LENGTH 253

static bool
necp_set_socket_attribute(u_int8_t *buffer, size_t buffer_length, u_int8_t type, char **buffer_p)
{
	int error = 0;
	int cursor = 0;
	size_t string_size = 0;
	char *local_string = NULL;
	u_int8_t *value = NULL;

	cursor = necp_buffer_find_tlv(buffer, buffer_length, 0, type, 0);
	if (cursor < 0) {
		// This will clear out the parameter
		goto done;
	}

	string_size = necp_buffer_get_tlv_length(buffer, cursor);
	if (string_size == 0 || string_size > NECP_MAX_SOCKET_ATTRIBUTE_STRING_LENGTH) {
		// This will clear out the parameter
		goto done;
	}

	MALLOC(local_string, char *, string_size + 1, M_NECP, M_WAITOK);
	if (local_string == NULL) {
		NECPLOG(LOG_ERR, "Failed to allocate a socket attribute buffer (size %d)", string_size);
		goto fail;
	}

	value = necp_buffer_get_tlv_value(buffer, cursor, NULL);
	if (value == NULL) {
		NECPLOG0(LOG_ERR, "Failed to get socket attribute");
		goto fail;
	}

	memcpy(local_string, value, string_size);
	local_string[string_size] = 0;

done:
	if (*buffer_p != NULL) {
		FREE(*buffer_p, M_NECP);
		*buffer_p = NULL;
	}

	*buffer_p = local_string;
	return (0);
fail:
	if (local_string != NULL) {
		FREE(local_string, M_NECP);
	}
	return (error);
}

errno_t
necp_set_socket_attributes(struct socket *so, struct sockopt *sopt)
{
	int error = 0;
	u_int8_t *buffer = NULL;
	struct inpcb *inp = sotoinpcb(so);

	size_t valsize = sopt->sopt_valsize;
	if (valsize == 0 ||
		valsize > ((sizeof(u_int8_t) + sizeof(size_t) + NECP_MAX_SOCKET_ATTRIBUTE_STRING_LENGTH) * 2)) {
		goto done;
	}

	MALLOC(buffer, u_int8_t *, valsize, M_NECP, M_WAITOK);
	if (buffer == NULL) {
		goto done;
	}

	error = sooptcopyin(sopt, buffer, valsize, 0);
	if (error) {
		goto done;
	}

	error = necp_set_socket_attribute(buffer, valsize, NECP_TLV_ATTRIBUTE_DOMAIN, &inp->inp_necp_attributes.inp_domain);
	if (error) {
		NECPLOG0(LOG_ERR, "Could not set domain TLV for socket attributes");
		goto done;
	}

	error = necp_set_socket_attribute(buffer, valsize, NECP_TLV_ATTRIBUTE_ACCOUNT, &inp->inp_necp_attributes.inp_account);
	if (error) {
		NECPLOG0(LOG_ERR, "Could not set account TLV for socket attributes");
		goto done;
	}

	if (necp_debug) {
		NECPLOG(LOG_DEBUG, "Set on socket: Domain %s, Account %s", inp->inp_necp_attributes.inp_domain, inp->inp_necp_attributes.inp_account);
	}
done:
	if (buffer != NULL) {
		FREE(buffer, M_NECP);
	}

	return (error);
}

errno_t
necp_get_socket_attributes(struct socket *so, struct sockopt *sopt)
{
	int error = 0;
	u_int8_t *buffer = NULL;
	u_int8_t *cursor = NULL;
	size_t valsize = 0;
	struct inpcb *inp = sotoinpcb(so);
	
	if (inp->inp_necp_attributes.inp_domain != NULL) {
		valsize += sizeof(u_int8_t) + sizeof(size_t) + strlen(inp->inp_necp_attributes.inp_domain);
	}
	if (inp->inp_necp_attributes.inp_account != NULL) {
		valsize += sizeof(u_int8_t) + sizeof(size_t) + strlen(inp->inp_necp_attributes.inp_account);
	}
	if (valsize == 0) {
		goto done;
	}

	MALLOC(buffer, u_int8_t *, valsize, M_NECP, M_WAITOK);
	if (buffer == NULL) {
		goto done;
	}

	cursor = buffer;
	if (inp->inp_necp_attributes.inp_domain != NULL) {
		cursor = necp_buffer_write_tlv(cursor, NECP_TLV_ATTRIBUTE_DOMAIN, strlen(inp->inp_necp_attributes.inp_domain), inp->inp_necp_attributes.inp_domain);
	}

	if (inp->inp_necp_attributes.inp_account != NULL) {
		cursor = necp_buffer_write_tlv(cursor, NECP_TLV_ATTRIBUTE_ACCOUNT, strlen(inp->inp_necp_attributes.inp_account), inp->inp_necp_attributes.inp_account);
	}

	error = sooptcopyout(sopt, buffer, valsize);
	if (error) {
		goto done;
	}
done:
	if (buffer != NULL) {
		FREE(buffer, M_NECP);
	}

	return (error);
}

static bool
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 verifyifindex = interface ? interface->if_index : 0;
	bool allowed_to_receive = TRUE;
	struct necp_socket_info info;
	u_int32_t flowhash = 0;
	necp_kernel_policy_result service_action = 0;
	necp_kernel_policy_service service = { 0, 0 };

	if (return_policy_id) {
		*return_policy_id = NECP_KERNEL_POLICY_ID_NONE;
	}

	if (inp == NULL) {
		goto done;
	}

	// Don't lock. Possible race condition, but we don't want the performance hit.
	if (necp_kernel_socket_policies_count == 0 ||
		(!(inp->inp_flags2 & INP2_WANT_APP_POLICY) && necp_kernel_socket_policies_non_app_count == 0)) {
		if (necp_drop_all_order > 0) {
			if (necp_pass_loopback > 0 &&
				necp_is_loopback(override_local_addr, override_remote_addr, inp, NULL)) {
				allowed_to_receive = TRUE;
			} else {
				allowed_to_receive = FALSE;
			}
		}
		goto done;
	}

	// If this socket is connected, or we are not taking addresses into account, try to reuse last result
	if ((necp_socket_is_connected(inp) || (override_local_addr == NULL && override_remote_addr == NULL)) && inp->inp_policyresult.policy_id != NECP_KERNEL_POLICY_ID_NONE) {
		bool policies_have_changed = FALSE;
		lck_rw_lock_shared(&necp_kernel_policy_lock);
		if (inp->inp_policyresult.policy_gencount != necp_kernel_socket_policies_gencount) {
			policies_have_changed = TRUE;
		}
		lck_rw_done(&necp_kernel_policy_lock);

		if (!policies_have_changed) {
			if (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_DROP ||
				inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT ||
				(inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL && interface &&
				inp->inp_policyresult.results.result_parameter.tunnel_interface_index != verifyifindex)) {
				allowed_to_receive = FALSE;
			} else if (return_policy_id) {
				*return_policy_id = inp->inp_policyresult.policy_id;
			}
			goto done;
		}
	}
	
	// Check for loopback exception
	if (necp_pass_loopback > 0 &&
		necp_is_loopback(override_local_addr, override_remote_addr, inp, NULL)) {
		allowed_to_receive = TRUE;
		goto done;
	}

	// Actually calculate policy result
	lck_rw_lock_shared(&necp_kernel_policy_lock);
	necp_socket_fillout_info_locked(inp, override_local_addr, override_remote_addr, 0, &info);

	flowhash = necp_socket_calc_flowhash_locked(&info);
	if (inp->inp_policyresult.policy_id != NECP_KERNEL_POLICY_ID_NONE &&
		inp->inp_policyresult.policy_gencount == necp_kernel_socket_policies_gencount &&
		inp->inp_policyresult.flowhash == flowhash) {
		if (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_DROP ||
			inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT ||
			(inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL && interface &&
			inp->inp_policyresult.results.result_parameter.tunnel_interface_index != verifyifindex)) {
			allowed_to_receive = FALSE;
		} else if (return_policy_id) {
			*return_policy_id = inp->inp_policyresult.policy_id;
		}
		lck_rw_done(&necp_kernel_policy_lock);
		goto done;
	}

	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, &service_action, &service);
	if (matched_policy != NULL) {
		if (matched_policy->result == NECP_KERNEL_POLICY_RESULT_DROP ||
			matched_policy->result == NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT ||
			(matched_policy->result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL && interface &&
			matched_policy->result_parameter.tunnel_interface_index != verifyifindex) ||
			((service_action == NECP_KERNEL_POLICY_RESULT_TRIGGER_SCOPED ||
			  service_action == NECP_KERNEL_POLICY_RESULT_NO_TRIGGER_SCOPED) &&
			 service.identifier != 0 && service.identifier != NECP_NULL_SERVICE_ID)) {
			allowed_to_receive = FALSE;
		} else if (return_policy_id) {
			*return_policy_id = matched_policy->id;
		}
		lck_rw_done(&necp_kernel_policy_lock);

		if (necp_debug > 1 && matched_policy->id != inp->inp_policyresult.policy_id) {
			NECPLOG(LOG_DEBUG, "Socket Send/Recv Policy: Policy %d Allowed %d", return_policy_id ? *return_policy_id : 0, allowed_to_receive);
		}
		goto done;
	} else if (necp_drop_all_order > 0) {
		allowed_to_receive = FALSE;
	}

	lck_rw_done(&necp_kernel_policy_lock);

done:
	return (allowed_to_receive);
}

bool
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)
{
	struct sockaddr_in local;
	struct sockaddr_in remote;
	local.sin_family = remote.sin_family = AF_INET;
	local.sin_len = remote.sin_len = sizeof(struct sockaddr_in);
	local.sin_port = local_port;
	remote.sin_port = remote_port;
	memcpy(&local.sin_addr, local_addr, sizeof(local.sin_addr));
	memcpy(&remote.sin_addr, remote_addr, sizeof(remote.sin_addr));

	return (necp_socket_is_allowed_to_send_recv_internal(inp, (struct sockaddr *)&local, (struct sockaddr *)&remote, interface, return_policy_id));
}

bool
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)
{
	struct sockaddr_in6 local;
	struct sockaddr_in6 remote;
	local.sin6_family = remote.sin6_family = AF_INET6;
	local.sin6_len = remote.sin6_len = sizeof(struct sockaddr_in6);
	local.sin6_port = local_port;
	remote.sin6_port = remote_port;
	memcpy(&local.sin6_addr, local_addr, sizeof(local.sin6_addr));
	memcpy(&remote.sin6_addr, remote_addr, sizeof(remote.sin6_addr));

	return (necp_socket_is_allowed_to_send_recv_internal(inp, (struct sockaddr *)&local, (struct sockaddr *)&remote, interface, return_policy_id));
}

bool
necp_socket_is_allowed_to_send_recv(struct inpcb *inp, necp_kernel_policy_id *return_policy_id)
{
	return (necp_socket_is_allowed_to_send_recv_internal(inp, NULL, NULL, NULL, return_policy_id));
}

int
necp_mark_packet_from_socket(struct mbuf *packet, struct inpcb *inp, necp_kernel_policy_id policy_id)
{
	if (packet == NULL || inp == NULL) {
		return (EINVAL);
	}

	// Mark ID for Pass and IP Tunnel
	if (policy_id != NECP_KERNEL_POLICY_ID_NONE) {
		packet->m_pkthdr.necp_mtag.necp_policy_id = policy_id;
	} else if (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_PASS ||
		inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL) {
		packet->m_pkthdr.necp_mtag.necp_policy_id = inp->inp_policyresult.policy_id;
	} else {
		packet->m_pkthdr.necp_mtag.necp_policy_id = NECP_KERNEL_POLICY_ID_NONE;
	}
	packet->m_pkthdr.necp_mtag.necp_last_interface_index = 0;

	return (0);
}

int
necp_mark_packet_from_ip(struct mbuf *packet, necp_kernel_policy_id policy_id)
{
	if (packet == NULL) {
		return (EINVAL);
	}

	// Mark ID for Pass and IP Tunnel
	if (policy_id != NECP_KERNEL_POLICY_ID_NONE) {
		packet->m_pkthdr.necp_mtag.necp_policy_id = policy_id;
	} else {
		packet->m_pkthdr.necp_mtag.necp_policy_id = NECP_KERNEL_POLICY_ID_NONE;
	}

	return (0);
}

int
necp_mark_packet_from_interface(struct mbuf *packet, ifnet_t interface)
{
	if (packet == NULL) {
		return (EINVAL);
	}

	// Mark ID for Pass and IP Tunnel
	if (interface != NULL) {
		packet->m_pkthdr.necp_mtag.necp_last_interface_index = interface->if_index;
	}

	return (0);
}

int
necp_mark_packet_as_keepalive(struct mbuf *packet, bool is_keepalive)
{
	if (packet == NULL) {
		return (EINVAL);
	}
	
	if (is_keepalive) {
		packet->m_pkthdr.pkt_flags |= PKTF_KEEPALIVE;
	} else {
		packet->m_pkthdr.pkt_flags &= ~PKTF_KEEPALIVE;
	}
	
	return (0);
}

necp_kernel_policy_id
necp_get_policy_id_from_packet(struct mbuf *packet)
{
	if (packet == NULL) {
		return (NECP_KERNEL_POLICY_ID_NONE);
	}
	
	return (packet->m_pkthdr.necp_mtag.necp_policy_id);
}

u_int32_t
necp_get_last_interface_index_from_packet(struct mbuf *packet)
{
	if (packet == NULL) {
		return (0);
	}
	
	return (packet->m_pkthdr.necp_mtag.necp_last_interface_index);
}

bool
necp_get_is_keepalive_from_packet(struct mbuf *packet)
{
	if (packet == NULL) {
		return (FALSE);
	}
	
	return (packet->m_pkthdr.pkt_flags & PKTF_KEEPALIVE);
}

u_int32_t
necp_socket_get_content_filter_control_unit(struct socket *so)
{
	struct inpcb *inp = sotoinpcb(so);
	
	if (inp == NULL) {
		return (0);
	}
	return (inp->inp_policyresult.results.filter_control_unit);
}

bool
necp_socket_should_use_flow_divert(struct inpcb *inp)
{
	if (inp == NULL) {
		return (FALSE);
	}

	return (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT);
}

u_int32_t
necp_socket_get_flow_divert_control_unit(struct inpcb *inp)
{
	if (inp == NULL) {
		return (0);
	}

	if (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_SOCKET_DIVERT) {
		return (inp->inp_policyresult.results.result_parameter.flow_divert_control_unit);
	}

	return (0);
}

bool
necp_socket_should_rescope(struct inpcb *inp)
{
	if (inp == NULL) {
		return (FALSE);
	}
	
	return (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED);
}

u_int
necp_socket_get_rescope_if_index(struct inpcb *inp)
{
	if (inp == NULL) {
		return (0);
	}
	
	if (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_SOCKET_SCOPED) {
		return (inp->inp_policyresult.results.result_parameter.scoped_interface_index);
	}
	
	return (0);
}

ifnet_t
necp_get_ifnet_from_result_parameter(necp_kernel_policy_result_parameter *result_parameter)
{
	if (result_parameter == NULL) {
		return (NULL);
	}

	return (ifindex2ifnet[result_parameter->tunnel_interface_index]);
}

bool
necp_packet_can_rebind_to_ifnet(struct mbuf *packet, struct ifnet *interface, struct route *new_route, int family)
{
	bool found_match = FALSE;
	errno_t result = 0;
	ifaddr_t *addresses = NULL;
	union necp_sockaddr_union address_storage;
	int i;

	if (packet == NULL || interface == NULL || new_route == NULL || (family != AF_INET && family != AF_INET6)) {
		return (FALSE);
	}

	result = ifnet_get_address_list_family(interface, &addresses, family);
	if (result != 0) {
		NECPLOG(LOG_ERR, "Failed to get address list for %s%d", ifnet_name(interface), ifnet_unit(interface));
		return (FALSE);
	}

	for (i = 0; addresses[i] != NULL; i++) {
		ROUTE_RELEASE(new_route);
		if (ifaddr_address(addresses[i], &address_storage.sa, sizeof(address_storage)) == 0) {
			if (family == AF_INET) {
				struct ip *ip = mtod(packet, struct ip *);
				if (memcmp(&address_storage.sin.sin_addr, &ip->ip_src, sizeof(ip->ip_src)) == 0) {
					struct sockaddr_in *dst4 = (struct sockaddr_in *)(void *)&new_route->ro_dst;
					dst4->sin_family = AF_INET;
					dst4->sin_len = sizeof(struct sockaddr_in);
					dst4->sin_addr = ip->ip_dst;
					rtalloc_scoped(new_route, interface->if_index);
					if (!ROUTE_UNUSABLE(new_route)) {
						found_match = TRUE;
						goto done;
					}
				}
			} else if (family == AF_INET6) {
				struct ip6_hdr *ip6 = mtod(packet, struct ip6_hdr *);
				if (memcmp(&address_storage.sin6.sin6_addr, &ip6->ip6_src, sizeof(ip6->ip6_src)) == 0) {
					struct sockaddr_in6 *dst6 = (struct sockaddr_in6 *)(void *)&new_route->ro_dst;
					dst6->sin6_family = AF_INET6;
					dst6->sin6_len = sizeof(struct sockaddr_in6);
					dst6->sin6_addr = ip6->ip6_dst;
					rtalloc_scoped(new_route, interface->if_index);
					if (!ROUTE_UNUSABLE(new_route)) {
						found_match = TRUE;
						goto done;
					}
				}
			}
		}
	}

done:
	ifnet_free_address_list(addresses);
	addresses = NULL;
	return (found_match);
}

static bool
necp_addr_is_loopback(struct sockaddr *address)
{
	if (address == NULL) {
		return (FALSE);
	}
	
	if (address->sa_family == AF_INET) {
		return (ntohl(((struct sockaddr_in *)(void *)address)->sin_addr.s_addr) == INADDR_LOOPBACK);
	} else if (address->sa_family == AF_INET6) {
		return IN6_IS_ADDR_LOOPBACK(&((struct sockaddr_in6 *)(void *)address)->sin6_addr);
	}
	
	return (FALSE);
}

static bool
necp_is_loopback(struct sockaddr *local_addr, struct sockaddr *remote_addr, struct inpcb *inp, struct mbuf *packet)
{
	// Note: This function only checks for the loopback addresses.
	// In the future, we may want to expand to also allow any traffic
	// going through the loopback interface, but until then, this
	// check is cheaper.

	if (local_addr != NULL && necp_addr_is_loopback(local_addr)) {
		return (TRUE);
	}
	
	if (remote_addr != NULL && necp_addr_is_loopback(remote_addr)) {
		return (TRUE);
	}
	
	if (inp != NULL) {
		if ((inp->inp_flags & INP_BOUND_IF) && inp->inp_boundifp && (inp->inp_boundifp->if_flags & IFF_LOOPBACK)) {
			return (TRUE);
		}
		if (inp->inp_vflag & INP_IPV4) {
			if (ntohl(inp->inp_laddr.s_addr) == INADDR_LOOPBACK ||
				ntohl(inp->inp_faddr.s_addr) == INADDR_LOOPBACK) {
				return (TRUE);
			}
		} else if (inp->inp_vflag & INP_IPV6) {
			if (IN6_IS_ADDR_LOOPBACK(&inp->in6p_laddr) ||
				IN6_IS_ADDR_LOOPBACK(&inp->in6p_faddr)) {
				return (TRUE);
			}
		}
	}
	
	if (packet != NULL) {
		struct ip *ip = mtod(packet, struct ip *);
		if (ip->ip_v == 4) {
			if (ntohl(ip->ip_src.s_addr) == INADDR_LOOPBACK) {
				return (TRUE);
			}
			if (ntohl(ip->ip_dst.s_addr) == INADDR_LOOPBACK) {
				return (TRUE);
			}
		} else if (ip->ip_v == 6) {
			struct ip6_hdr *ip6 = mtod(packet, struct ip6_hdr *);
			if (IN6_IS_ADDR_LOOPBACK(&ip6->ip6_src)) {
				return (TRUE);
			}
			if (IN6_IS_ADDR_LOOPBACK(&ip6->ip6_dst)) {
				return (TRUE);
			}
		}
	}
	
	return (FALSE);
}