xref: /xnu-8792.41.9/security/mac_base.c (revision 5c2921b07a2480ab43ec66f5b9e41cb872bc554f)
1 /*
2  * Copyright (c) 2007-2020 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 /*-
29  * Copyright (c) 1999, 2000, 2001, 2002 Robert N. M. Watson
30  * Copyright (c) 2001 Ilmar S. Habibulin
31  * Copyright (c) 2001, 2002, 2003, 2004 Networks Associates Technology, Inc.
32  * Copyright (c) 2005-2006 SPARTA, Inc.
33  *
34  * This software was developed by Robert Watson and Ilmar Habibulin for the
35  * TrustedBSD Project.
36  *
37  * This software was developed for the FreeBSD Project in part by Network
38  * Associates Laboratories, the Security Research Division of Network
39  * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"),
40  * as part of the DARPA CHATS research program.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
45  * 1. Redistributions of source code must retain the above copyright
46  *    notice, this list of conditions and the following disclaimer.
47  * 2. Redistributions in binary form must reproduce the above copyright
48  *    notice, this list of conditions and the following disclaimer in the
49  *    documentation and/or other materials provided with the distribution.
50  *
51  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
52  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
53  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
54  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
55  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
56  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
57  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
58  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
59  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
60  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
61  * SUCH DAMAGE.
62  *
63  */
64 
65 /*-
66  * Framework for extensible kernel access control.  This file contains
67  * Kernel and userland interface to the framework, policy registration
68  * and composition.  Per-object interfaces, controls, and labeling may be
69  * found in src/sys/mac/.  Sample policies may be found in src/sys/mac*.
70  */
71 
72 #include <stdarg.h>
73 #include <string.h>
74 #include <security/mac_internal.h>
75 #include <security/mac_mach_internal.h>
76 #include <sys/param.h>
77 #include <sys/vnode.h>
78 #include <sys/vnode_internal.h>
79 #include <sys/vfs_context.h>
80 #include <sys/namei.h>
81 #include <bsd/bsm/audit.h>
82 #include <bsd/security/audit/audit.h>
83 #include <bsd/security/audit/audit_private.h>
84 #include <sys/file.h>
85 #include <sys/file_internal.h>
86 #include <sys/filedesc.h>
87 #include <sys/proc.h>
88 #include <sys/proc_internal.h>
89 #include <sys/kauth.h>
90 #include <sys/sysproto.h>
91 
92 #include <mach/exception_types.h>
93 #include <mach/vm_types.h>
94 #include <mach/vm_prot.h>
95 
96 #include <kern/kalloc.h>
97 #include <kern/sched_prim.h>
98 #include <kern/task.h>
99 
100 #if CONFIG_MACF
101 #include <security/mac.h>
102 #include <security/mac_policy.h>
103 #include <security/mac_framework.h>
104 #include <security/mac_internal.h>
105 #include <security/mac_mach_internal.h>
106 #endif
107 
108 #include <libkern/section_keywords.h>
109 
110 /*
111  * define MB_DEBUG to display run-time debugging information
112  * #define MB_DEBUG 1
113  */
114 
115 #ifdef MB_DEBUG
116 #define DPRINTF(x)      printf x
117 #else
118 #define MB_DEBUG
119 #define DPRINTF(x)
120 #endif
121 
122 #if CONFIG_MACF
123 SYSCTL_NODE(, OID_AUTO, security, CTLFLAG_RW | CTLFLAG_LOCKED, 0,
124     "Security Controls");
125 SYSCTL_EXTENSIBLE_NODE(_security, OID_AUTO, mac, CTLFLAG_RW | CTLFLAG_LOCKED, 0,
126     "TrustedBSD MAC policy controls");
127 
128 /*
129  * Declare that the kernel provides MAC support, version 1.  This permits
130  * modules to refuse to be loaded if the necessary support isn't present,
131  * even if it's pre-boot.
132  */
133 #if 0
134 MODULE_VERSION(kernel_mac_support, 1);
135 #endif
136 
137 #if MAC_MAX_SLOTS > 32
138 #error "MAC_MAX_SLOTS too large"
139 #endif
140 
141 static unsigned int mac_max_slots = MAC_MAX_SLOTS;
142 static unsigned int mac_slot_offsets_free = (1 << MAC_MAX_SLOTS) - 1;
143 SYSCTL_UINT(_security_mac, OID_AUTO, max_slots, CTLFLAG_RD | CTLFLAG_LOCKED,
144     &mac_max_slots, 0, "");
145 
146 /*
147  * Has the kernel started generating labeled objects yet?  All read/write
148  * access to this variable is serialized during the boot process.  Following
149  * the end of serialization, we don't update this flag; no locking.
150  */
151 int     mac_late = 0;
152 
153 /*
154  * Flag to indicate whether or not we should allocate label storage for
155  * new vnodes.  Since most dynamic policies we currently work with don't
156  * rely on vnode labeling, try to avoid paying the cost of mtag allocation
157  * unless specifically notified of interest.  One result of this is
158  * that if a dynamically loaded policy requests vnode labels, it must
159  * be able to deal with a NULL label being returned on any vnodes that
160  * were already in flight when the policy was loaded.  Since the policy
161  * already has to deal with uninitialized labels, this probably won't
162  * be a problem.
163  */
164 #if CONFIG_MACF_LAZY_VNODE_LABELS
165 unsigned int    mac_label_vnodes = 1;
166 #else
167 unsigned int    mac_label_vnodes = 0;
168 #endif /* CONFIG_MACF_LAZY_VNODE_LABELS */
169 SYSCTL_UINT(_security_mac, OID_AUTO, labelvnodes, SECURITY_MAC_CTLFLAGS
170 #if CONFIG_MACF_LAZY_VNODE_LABELS
171     | CTLFLAG_RD
172 #endif
173     , &mac_label_vnodes, 0, "Label all vnodes");
174 
175 unsigned int mac_vnode_label_count = 0;
176 SYSCTL_UINT(_security_mac, OID_AUTO, vnode_label_count, SECURITY_MAC_CTLFLAGS | CTLFLAG_RD,
177     &mac_vnode_label_count, 0, "Count of vnode labels");
178 
179 unsigned int mac_device_enforce = 1;
180 SYSCTL_UINT(_security_mac, OID_AUTO, device_enforce, SECURITY_MAC_CTLFLAGS,
181     &mac_device_enforce, 0, "Enforce MAC policy on device operations");
182 
183 unsigned int    mac_pipe_enforce = 1;
184 SYSCTL_UINT(_security_mac, OID_AUTO, pipe_enforce, SECURITY_MAC_CTLFLAGS,
185     &mac_pipe_enforce, 0, "Enforce MAC policy on pipe operations");
186 
187 unsigned int    mac_posixsem_enforce = 1;
188 SYSCTL_UINT(_security_mac, OID_AUTO, posixsem_enforce, SECURITY_MAC_CTLFLAGS,
189     &mac_posixsem_enforce, 0, "Enforce MAC policy on POSIX semaphores");
190 
191 unsigned int mac_posixshm_enforce = 1;
192 SYSCTL_UINT(_security_mac, OID_AUTO, posixshm_enforce, SECURITY_MAC_CTLFLAGS,
193     &mac_posixshm_enforce, 0, "Enforce MAC policy on Posix Shared Memory");
194 
195 unsigned int    mac_proc_enforce = 1;
196 SYSCTL_UINT(_security_mac, OID_AUTO, proc_enforce, SECURITY_MAC_CTLFLAGS,
197     &mac_proc_enforce, 0, "Enforce MAC policy on process operations");
198 
199 unsigned int mac_socket_enforce = 1;
200 SYSCTL_UINT(_security_mac, OID_AUTO, socket_enforce, SECURITY_MAC_CTLFLAGS,
201     &mac_socket_enforce, 0, "Enforce MAC policy on socket operations");
202 
203 unsigned int    mac_system_enforce = 1;
204 SYSCTL_UINT(_security_mac, OID_AUTO, system_enforce, SECURITY_MAC_CTLFLAGS,
205     &mac_system_enforce, 0, "Enforce MAC policy on system-wide interfaces");
206 
207 unsigned int    mac_sysvmsg_enforce = 1;
208 SYSCTL_UINT(_security_mac, OID_AUTO, sysvmsg_enforce, SECURITY_MAC_CTLFLAGS,
209     &mac_sysvmsg_enforce, 0, "Enforce MAC policy on System V IPC message queues");
210 
211 unsigned int    mac_sysvsem_enforce = 1;
212 SYSCTL_UINT(_security_mac, OID_AUTO, sysvsem_enforce, SECURITY_MAC_CTLFLAGS,
213     &mac_sysvsem_enforce, 0, "Enforce MAC policy on System V IPC semaphores");
214 
215 unsigned int    mac_sysvshm_enforce = 1;
216 SYSCTL_INT(_security_mac, OID_AUTO, sysvshm_enforce, SECURITY_MAC_CTLFLAGS,
217     &mac_sysvshm_enforce, 0, "Enforce MAC policy on System V Shared Memory");
218 
219 unsigned int    mac_vm_enforce = 1;
220 SYSCTL_INT(_security_mac, OID_AUTO, vm_enforce, SECURITY_MAC_CTLFLAGS,
221     &mac_vm_enforce, 0, "Enforce MAC policy on VM operations");
222 
223 unsigned int    mac_vnode_enforce = 1;
224 SYSCTL_UINT(_security_mac, OID_AUTO, vnode_enforce, SECURITY_MAC_CTLFLAGS,
225     &mac_vnode_enforce, 0, "Enforce MAC policy on vnode operations");
226 
227 /*
228  * mac_policy_list holds the list of policy modules.  Modules with a
229  * handle lower than staticmax are considered "static" and cannot be
230  * unloaded.  Such policies can be invoked without holding the busy count.
231  *
232  * Modules with a handle at or above the staticmax high water mark
233  * are considered to be "dynamic" policies.  A busy count is maintained
234  * for the list, stored in mac_policy_busy.  The busy count is protected
235  * by mac_policy_mtx; the list may be modified only while the busy
236  * count is 0, requiring that the lock be held to prevent new references
237  * to the list from being acquired.  For almost all operations,
238  * incrementing the busy count is sufficient to guarantee consistency,
239  * as the list cannot be modified while the busy count is elevated.
240  * For a few special operations involving a change to the list of
241  * active policies, the mtx itself must be held.
242  */
243 static LCK_GRP_DECLARE(mac_lck_grp, "MAC lock");
244 static LCK_MTX_DECLARE(mac_policy_mtx, &mac_lck_grp);
245 
246 /*
247  * Policy list array allocation chunk size. Each entry holds a pointer.
248  */
249 #define MAC_POLICY_LIST_CHUNKSIZE 8
250 
251 static int mac_policy_busy;
252 
253 #if !XNU_TARGET_OS_OSX
254 SECURITY_READ_ONLY_LATE(mac_policy_list_t) mac_policy_list;
255 SECURITY_READ_ONLY_LATE(static struct mac_policy_list_element) mac_policy_static_entries[MAC_POLICY_LIST_CHUNKSIZE];
256 #else
257 mac_policy_list_t mac_policy_list;
258 #endif
259 
260 /*
261  * mac_label_element_list holds the master list of label namespaces for
262  * all the policies. When a policy is loaded, each of it's label namespace
263  * elements is added to the master list if not already present. When a
264  * policy is unloaded, the namespace elements are removed if no other
265  * policy is interested in that namespace element.
266  */
267 struct mac_label_element_list_t mac_label_element_list;
268 struct mac_label_element_list_t mac_static_label_element_list;
269 
270 static __inline void
mac_policy_grab_exclusive(void)271 mac_policy_grab_exclusive(void)
272 {
273 	lck_mtx_lock(&mac_policy_mtx);
274 	while (mac_policy_busy != 0) {
275 		lck_mtx_sleep(&mac_policy_mtx, LCK_SLEEP_UNLOCK,
276 		    (event_t)&mac_policy_busy, THREAD_UNINT);
277 		lck_mtx_lock(&mac_policy_mtx);
278 	}
279 }
280 
281 static __inline void
mac_policy_release_exclusive(void)282 mac_policy_release_exclusive(void)
283 {
284 	KASSERT(mac_policy_busy == 0,
285 	    ("mac_policy_release_exclusive(): not exclusive"));
286 	lck_mtx_unlock(&mac_policy_mtx);
287 	thread_wakeup((event_t) &mac_policy_busy);
288 }
289 
290 void
mac_policy_list_busy(void)291 mac_policy_list_busy(void)
292 {
293 	lck_mtx_lock(&mac_policy_mtx);
294 	mac_policy_busy++;
295 	lck_mtx_unlock(&mac_policy_mtx);
296 }
297 
298 int
mac_policy_list_conditional_busy(void)299 mac_policy_list_conditional_busy(void)
300 {
301 	int ret;
302 
303 	if (mac_policy_list.numloaded <= mac_policy_list.staticmax) {
304 		return 0;
305 	}
306 
307 	lck_mtx_lock(&mac_policy_mtx);
308 	if (mac_policy_list.numloaded > mac_policy_list.staticmax) {
309 		mac_policy_busy++;
310 		ret = 1;
311 	} else {
312 		ret = 0;
313 	}
314 	lck_mtx_unlock(&mac_policy_mtx);
315 	return ret;
316 }
317 
318 void
mac_policy_list_unbusy(void)319 mac_policy_list_unbusy(void)
320 {
321 	lck_mtx_lock(&mac_policy_mtx);
322 	mac_policy_busy--;
323 	KASSERT(mac_policy_busy >= 0, ("MAC_POLICY_LIST_LOCK"));
324 	if (mac_policy_busy == 0) {
325 		thread_wakeup(&mac_policy_busy);
326 	}
327 	lck_mtx_unlock(&mac_policy_mtx);
328 }
329 
330 /*
331  * Early pre-malloc MAC initialization, including appropriate SMP locks.
332  */
333 void
mac_policy_init(void)334 mac_policy_init(void)
335 {
336 	mac_policy_list.numloaded = 0;
337 	mac_policy_list.max = MAC_POLICY_LIST_CHUNKSIZE;
338 	mac_policy_list.maxindex = 0;
339 	mac_policy_list.staticmax = 0;
340 	mac_policy_list.freehint = 0;
341 	mac_policy_list.chunks = 1;
342 
343 #if !XNU_TARGET_OS_OSX
344 	mac_policy_list.entries = mac_policy_static_entries;
345 #else
346 	mac_policy_list.entries = kalloc_type(struct mac_policy_list_element,
347 	    MAC_POLICY_LIST_CHUNKSIZE, Z_WAITOK | Z_ZERO);
348 #endif
349 
350 	SLIST_INIT(&mac_label_element_list);
351 	SLIST_INIT(&mac_static_label_element_list);
352 }
353 
354 /* Function pointer set up for loading security extensions.
355  * It is set to an actual function after OSlibkernInit()
356  * has been called, and is set back to 0 by OSKextRemoveKextBootstrap()
357  * after bsd_init().
358  */
359 void (*load_security_extensions_function)(void) = 0;
360 
361 /*
362  * Init after early Mach startup, but before BSD
363  */
364 void
mac_policy_initmach(void)365 mac_policy_initmach(void)
366 {
367 	/*
368 	 * For the purposes of modules that want to know if they were
369 	 * loaded "early", set the mac_late flag once we've processed
370 	 * modules either linked into the kernel, or loaded before the
371 	 * kernel startup.
372 	 */
373 
374 	if (load_security_extensions_function) {
375 		load_security_extensions_function();
376 	}
377 	mac_late = 1;
378 }
379 
380 /*
381  * BSD startup.
382  */
383 void
mac_policy_initbsd(void)384 mac_policy_initbsd(void)
385 {
386 	struct mac_policy_conf *mpc;
387 	u_int i;
388 
389 	printf("MAC Framework successfully initialized\n");
390 
391 	/* Call bsd init functions of already loaded policies */
392 
393 	/*
394 	 * Using the exclusive lock means no other framework entry
395 	 * points can proceed while initializations are running.
396 	 * This may not be necessary.
397 	 */
398 	mac_policy_grab_exclusive();
399 
400 	for (i = 0; i <= mac_policy_list.maxindex; i++) {
401 		mpc = mac_get_mpc(i);
402 		if ((mpc != NULL) && (mpc->mpc_ops->mpo_policy_initbsd != NULL)) {
403 			(*(mpc->mpc_ops->mpo_policy_initbsd))(mpc);
404 		}
405 	}
406 
407 	mac_policy_release_exclusive();
408 }
409 
410 /*
411  * After a policy has been loaded, add the label namespaces managed by the
412  * policy to either the static or non-static label namespace list.
413  * A namespace is added to the the list only if it is not already on one of
414  * the lists.
415  */
416 void
mac_policy_addto_labellist(mac_policy_handle_t handle,int static_entry)417 mac_policy_addto_labellist(mac_policy_handle_t handle, int static_entry)
418 {
419 	struct mac_label_element *mle, *mle_tmp;
420 	struct mac_label_listener *mll, *mll_tmp;
421 	struct mac_label_element_list_t *list;
422 	struct mac_policy_conf *mpc;
423 	const char *name, *name2;
424 	struct mac_label_element_list_t mles = SLIST_HEAD_INITIALIZER(mles);
425 	struct mac_label_listeners_t mlls = SLIST_HEAD_INITIALIZER(mlls);
426 
427 	mpc = mac_get_mpc(handle);
428 
429 	if (mpc->mpc_labelnames == NULL) {
430 		return;
431 	}
432 
433 	if (mpc->mpc_labelname_count == 0) {
434 		return;
435 	}
436 
437 	if (static_entry) {
438 		list = &mac_static_label_element_list;
439 	} else {
440 		list = &mac_label_element_list;
441 	}
442 
443 	/*
444 	 * Before we grab the policy list lock, allocate enough memory
445 	 * to contain the potential new elements so we don't have to
446 	 * give up the lock, or allocate with the lock held.
447 	 */
448 	for (uint32_t idx = 0; idx < mpc->mpc_labelname_count; idx++) {
449 		mle = kalloc_type(struct mac_label_element, Z_WAITOK_ZERO_NOFAIL);
450 		SLIST_INSERT_HEAD(&mles, mle, mle_list);
451 
452 		mll = kalloc_type(struct mac_label_listener, Z_WAITOK);
453 		SLIST_INSERT_HEAD(&mlls, mll, mll_list);
454 	}
455 
456 	if (mac_late) {
457 		mac_policy_grab_exclusive();
458 	}
459 	for (uint32_t idx = 0; idx < mpc->mpc_labelname_count; idx++) {
460 		if (*(name = mpc->mpc_labelnames[idx]) == '?') {
461 			name++;
462 		}
463 		/*
464 		 * Check both label element lists and add to the
465 		 * appropriate list only if not already on a list.
466 		 */
467 		SLIST_FOREACH(mle, &mac_static_label_element_list, mle_list) {
468 			if (*(name2 = mle->mle_name) == '?') {
469 				name2++;
470 			}
471 			if (strcmp(name, name2) == 0) {
472 				break;
473 			}
474 		}
475 		if (mle == NULL) {
476 			SLIST_FOREACH(mle, &mac_label_element_list, mle_list) {
477 				if (*(name2 = mle->mle_name) == '?') {
478 					name2++;
479 				}
480 				if (strcmp(name, name2) == 0) {
481 					break;
482 				}
483 			}
484 		}
485 		if (mle == NULL) {
486 			mle = SLIST_FIRST(&mles);
487 			SLIST_REMOVE_HEAD(&mles, mle_list);
488 			strlcpy(mle->mle_name, mpc->mpc_labelnames[idx],
489 			    MAC_MAX_LABEL_ELEMENT_NAME);
490 			SLIST_INIT(&mle->mle_listeners);
491 			SLIST_INSERT_HEAD(list, mle, mle_list);
492 		}
493 
494 		mll = SLIST_FIRST(&mlls);
495 		SLIST_REMOVE_HEAD(&mlls, mll_list);
496 		/* Add policy handler as a listener. */
497 		mll->mll_handle = handle;
498 		SLIST_INSERT_HEAD(&mle->mle_listeners, mll, mll_list);
499 	}
500 	if (mac_late) {
501 		mac_policy_release_exclusive();
502 	}
503 
504 	SLIST_FOREACH_SAFE(mle, &mles, mle_list, mle_tmp) {
505 		kfree_type(struct mac_label_element, mle);
506 	}
507 	SLIST_FOREACH_SAFE(mll, &mlls, mll_list, mll_tmp) {
508 		kfree_type(struct mac_label_listener, mll);
509 	}
510 }
511 
512 /*
513  * After a policy has been unloaded, remove the label namespaces that the
514  * the policy manages from the non-static list of namespaces.
515  * The removal only takes place when no other policy is interested in the
516  * namespace.
517  *
518  * Must be called with the policy exclusive lock held.
519  */
520 void
mac_policy_removefrom_labellist(mac_policy_handle_t handle)521 mac_policy_removefrom_labellist(mac_policy_handle_t handle)
522 {
523 	struct mac_label_listener *mll, **mllp;
524 	struct mac_label_element *mle, **mlep;
525 	struct mac_policy_conf *mpc;
526 
527 	mpc = mac_get_mpc(handle);
528 
529 	if (mpc->mpc_labelnames == NULL) {
530 		return;
531 	}
532 
533 	if (mpc->mpc_labelname_count == 0) {
534 		return;
535 	}
536 
537 	/*
538 	 * Unregister policy as being interested in any label
539 	 * namespaces.  If no other policy is listening, remove
540 	 * that label element from the list.  Note that we only
541 	 * have to worry about the non-static list.
542 	 */
543 	SLIST_FOREACH_PREVPTR(mle, mlep, &mac_label_element_list, mle_list) {
544 		SLIST_FOREACH_PREVPTR(mll, mllp, &mle->mle_listeners, mll_list) {
545 			if (mll->mll_handle == handle) {
546 				*mllp = SLIST_NEXT(mll, mll_list);
547 				kfree_type(struct mac_label_listener, mll);
548 				if (SLIST_EMPTY(&mle->mle_listeners)) {
549 					*mlep = SLIST_NEXT(mle, mle_list);
550 					kfree_type(struct mac_label_element, mle);
551 				}
552 				return;
553 			}
554 		}
555 	}
556 }
557 
558 /*
559  * After the policy list has changed, walk the list to update any global
560  * flags.
561  */
562 static void
mac_policy_updateflags(void)563 mac_policy_updateflags(void)
564 {
565 }
566 
567 static __inline void
mac_policy_fixup_mmd_list(struct mac_module_data * new)568 mac_policy_fixup_mmd_list(struct mac_module_data *new)
569 {
570 	struct mac_module_data *old;
571 	struct mac_module_data_element *ele, *aele;
572 	struct mac_module_data_list *arr, *dict;
573 	unsigned int i, j, k;
574 
575 	old = new->base_addr;
576 	DPRINTF(("fixup_mmd: old %p new %p\n", old, new));
577 	for (i = 0; i < new->count; i++) {
578 		ele = &(new->data[i]);
579 		DPRINTF(("fixup_mmd: ele %p\n", ele));
580 		DPRINTF(("   key %p value %p\n", ele->key, ele->value));
581 		mmd_fixup_ele(old, new, ele); /* Fix up key/value ptrs.       */
582 		DPRINTF(("   key %p value %p\n", ele->key, ele->value));
583 		if (ele->value_type == MAC_DATA_TYPE_ARRAY) {
584 			arr = (struct mac_module_data_list *)ele->value;
585 			DPRINTF(("fixup_mmd: array @%p\n", arr));
586 			for (j = 0; j < arr->count; j++) {
587 				aele = &(arr->list[j]);
588 				DPRINTF(("fixup_mmd: aele %p\n", aele));
589 				DPRINTF(("   key %p value %p\n", aele->key, aele->value));
590 				mmd_fixup_ele(old, new, aele);
591 				DPRINTF(("   key %p value %p\n", aele->key, aele->value));
592 				if (arr->type == MAC_DATA_TYPE_DICT) {
593 					dict = (struct mac_module_data_list *)aele->value;
594 					DPRINTF(("fixup_mmd: dict @%p\n", dict));
595 					for (k = 0; k < dict->count; k++) {
596 						mmd_fixup_ele(old, new,
597 						    &(dict->list[k]));
598 					}
599 				}
600 			}
601 		}
602 	}
603 	new->base_addr = new;
604 }
605 
606 int
mac_policy_register(struct mac_policy_conf * mpc,mac_policy_handle_t * handlep,void * xd)607 mac_policy_register(struct mac_policy_conf *mpc, mac_policy_handle_t *handlep,
608     void *xd)
609 {
610 #if XNU_TARGET_OS_OSX
611 	struct mac_policy_list_element *tmac_policy_list_element;
612 #endif
613 	int error, slot, static_entry = 0;
614 	u_int i;
615 
616 	/*
617 	 * Some preliminary checks to make sure the policy's conf structure
618 	 * contains the required fields.
619 	 */
620 	if (mpc->mpc_name == NULL) {
621 		panic("policy's name is not set");
622 	}
623 
624 	if (mpc->mpc_fullname == NULL) {
625 		panic("policy's full name is not set");
626 	}
627 
628 	if (mpc->mpc_labelname_count > MAC_MAX_MANAGED_NAMESPACES) {
629 		panic("policy's managed label namespaces exceeds maximum");
630 	}
631 
632 	if (mpc->mpc_ops == NULL) {
633 		panic("policy's OPs field is NULL");
634 	}
635 
636 	error = 0;
637 
638 	if (mac_late) {
639 		if (mpc->mpc_loadtime_flags & MPC_LOADTIME_FLAG_NOTLATE) {
640 			printf("Module %s does not support late loading.\n",
641 			    mpc->mpc_name);
642 			return EPERM;
643 		}
644 		mac_policy_grab_exclusive();
645 	}
646 
647 	if (mac_policy_list.numloaded >= mac_policy_list.max) {
648 #if XNU_TARGET_OS_OSX
649 		/* allocate new policy list array, zero new chunk */
650 		tmac_policy_list_element =
651 		    kalloc_type(struct mac_policy_list_element,
652 		    MAC_POLICY_LIST_CHUNKSIZE * (mac_policy_list.chunks + 1),
653 		    Z_WAITOK | Z_ZERO);
654 
655 		/* copy old entries into new list */
656 		memcpy(tmac_policy_list_element, mac_policy_list.entries,
657 		    sizeof(struct mac_policy_list_element) *
658 		    MAC_POLICY_LIST_CHUNKSIZE * mac_policy_list.chunks);
659 
660 		/* free old array */
661 		kfree_type(struct mac_policy_list_element,
662 		    MAC_POLICY_LIST_CHUNKSIZE * mac_policy_list.chunks,
663 		    mac_policy_list.entries);
664 
665 		mac_policy_list.entries = tmac_policy_list_element;
666 
667 		/* Update maximums, etc */
668 		mac_policy_list.max += MAC_POLICY_LIST_CHUNKSIZE;
669 		mac_policy_list.chunks++;
670 #else
671 		printf("out of space in mac_policy_list.\n");
672 		return ENOMEM;
673 #endif /* XNU_TARGET_OS_OSX */
674 	}
675 
676 	/* Check for policy with same name already loaded */
677 	for (i = 0; i <= mac_policy_list.maxindex; i++) {
678 		if (mac_policy_list.entries[i].mpc == NULL) {
679 			continue;
680 		}
681 
682 		if (strcmp(mac_policy_list.entries[i].mpc->mpc_name,
683 		    mpc->mpc_name) == 0) {
684 			error = EEXIST;
685 			goto out;
686 		}
687 	}
688 
689 	if (mpc->mpc_field_off != NULL) {
690 		slot = ffs(mac_slot_offsets_free);
691 		if (slot == 0) {
692 			error = ENOMEM;
693 			goto out;
694 		}
695 		slot--;
696 		mac_slot_offsets_free &= ~(1 << slot);
697 		*mpc->mpc_field_off = slot;
698 	}
699 	mpc->mpc_runtime_flags |= MPC_RUNTIME_FLAG_REGISTERED;
700 
701 	if (xd) {
702 		struct mac_module_data *mmd = xd; /* module data from plist */
703 
704 		/* Make a copy of the data. */
705 		mpc->mpc_data = (void *)kalloc_data(mmd->size, Z_WAITOK);
706 		if (mpc->mpc_data != NULL) {
707 			memcpy(mpc->mpc_data, mmd, mmd->size);
708 
709 			/* Fix up pointers after copy. */
710 			mac_policy_fixup_mmd_list(mpc->mpc_data);
711 		}
712 	}
713 
714 	/* Find the first free handle in the list (using our hint). */
715 	for (i = mac_policy_list.freehint; i < mac_policy_list.max; i++) {
716 		if (mac_policy_list.entries[i].mpc == NULL) {
717 			*handlep = i;
718 			mac_policy_list.freehint = ++i;
719 			break;
720 		}
721 	}
722 
723 	/*
724 	 * If we are loading a MAC module before the framework has
725 	 * finished initializing or the module is not unloadable and
726 	 * we can place its handle adjacent to the last static entry,
727 	 * bump the static policy high water mark.
728 	 * Static policies can get by with weaker locking requirements.
729 	 */
730 	if (!mac_late ||
731 	    ((mpc->mpc_loadtime_flags & MPC_LOADTIME_FLAG_UNLOADOK) == 0 &&
732 	    *handlep == mac_policy_list.staticmax)) {
733 		static_entry = 1;
734 		mac_policy_list.staticmax++;
735 	}
736 
737 	mac_policy_list.entries[*handlep].mpc = mpc;
738 
739 	/* Update counters, etc */
740 	if (*handlep > mac_policy_list.maxindex) {
741 		mac_policy_list.maxindex = *handlep;
742 	}
743 	mac_policy_list.numloaded++;
744 
745 	/* Per-policy initialization. */
746 	printf("calling mpo_policy_init for %s\n", mpc->mpc_name);
747 	if (mpc->mpc_ops->mpo_policy_init != NULL) {
748 		(*(mpc->mpc_ops->mpo_policy_init))(mpc);
749 	}
750 
751 	if (mac_late && mpc->mpc_ops->mpo_policy_initbsd != NULL) {
752 		printf("calling mpo_policy_initbsd for %s\n", mpc->mpc_name);
753 		(*(mpc->mpc_ops->mpo_policy_initbsd))(mpc);
754 	}
755 
756 	mac_policy_updateflags();
757 
758 	if (mac_late) {
759 		mac_policy_release_exclusive();
760 	}
761 
762 	mac_policy_addto_labellist(*handlep, static_entry);
763 
764 	printf("Security policy loaded: %s (%s)\n", mpc->mpc_fullname,
765 	    mpc->mpc_name);
766 
767 	return 0;
768 
769 out:
770 	if (mac_late) {
771 		mac_policy_release_exclusive();
772 	}
773 
774 	return error;
775 }
776 
777 int
mac_policy_unregister(mac_policy_handle_t handle)778 mac_policy_unregister(mac_policy_handle_t handle)
779 {
780 	struct mac_policy_conf *mpc;
781 
782 	/*
783 	 * If we fail the load, we may get a request to unload.  Check
784 	 * to see if we did the run-time registration, and if not,
785 	 * silently succeed.
786 	 */
787 	mac_policy_grab_exclusive();
788 	mpc = mac_get_mpc(handle);
789 	if ((mpc->mpc_runtime_flags & MPC_RUNTIME_FLAG_REGISTERED) == 0) {
790 		mac_policy_release_exclusive();
791 		return 0;
792 	}
793 
794 #if 0
795 	/*
796 	 * Don't allow unloading modules with private data.
797 	 */
798 	if (mpc->mpc_field_off != NULL) {
799 		MAC_POLICY_LIST_UNLOCK();
800 		return EBUSY;
801 	}
802 #endif
803 	/*
804 	 * Only allow the unload to proceed if the module is unloadable
805 	 * by its own definition.
806 	 */
807 	if ((mpc->mpc_loadtime_flags & MPC_LOADTIME_FLAG_UNLOADOK) == 0) {
808 		mac_policy_release_exclusive();
809 		return EBUSY;
810 	}
811 
812 	mac_policy_removefrom_labellist(handle);
813 
814 	mac_get_mpc(handle) = NULL;
815 	if (handle < mac_policy_list.freehint &&
816 	    handle >= mac_policy_list.staticmax) {
817 		mac_policy_list.freehint = handle;
818 	}
819 
820 	if (handle == mac_policy_list.maxindex) {
821 		mac_policy_list.maxindex--;
822 	}
823 
824 	mac_policy_list.numloaded--;
825 	if (mpc->mpc_field_off != NULL) {
826 		mac_slot_offsets_free |= (1 << *mpc->mpc_field_off);
827 	}
828 
829 	if (mpc->mpc_ops->mpo_policy_destroy != NULL) {
830 		(*(mpc->mpc_ops->mpo_policy_destroy))(mpc);
831 	}
832 
833 	mpc->mpc_runtime_flags &= ~MPC_RUNTIME_FLAG_REGISTERED;
834 	mac_policy_updateflags();
835 
836 	mac_policy_release_exclusive();
837 
838 	if (mpc->mpc_data) {
839 		struct mac_module_data *mmd = mpc->mpc_data;
840 		__typed_allocators_ignore(kfree_data(mmd, mmd->size)); // rdar://87952845
841 		mpc->mpc_data = NULL;
842 	}
843 
844 	printf("Security policy unload: %s (%s)\n", mpc->mpc_fullname,
845 	    mpc->mpc_name);
846 
847 	return 0;
848 }
849 
850 /*
851  * Define an error value precedence, and given two arguments, selects the
852  * value with the higher precedence.
853  */
854 int
mac_error_select(int error1,int error2)855 mac_error_select(int error1, int error2)
856 {
857 	/* Certain decision-making errors take top priority. */
858 	if (error1 == EDEADLK || error2 == EDEADLK) {
859 		return EDEADLK;
860 	}
861 
862 	/* Invalid arguments should be reported where possible. */
863 	if (error1 == EINVAL || error2 == EINVAL) {
864 		return EINVAL;
865 	}
866 
867 	/* Precedence goes to "visibility", with both process and file. */
868 	if (error1 == ESRCH || error2 == ESRCH) {
869 		return ESRCH;
870 	}
871 
872 	if (error1 == ENOENT || error2 == ENOENT) {
873 		return ENOENT;
874 	}
875 
876 	/* Precedence goes to DAC/MAC protections. */
877 	if (error1 == EACCES || error2 == EACCES) {
878 		return EACCES;
879 	}
880 
881 	/* Precedence goes to privilege. */
882 	if (error1 == EPERM || error2 == EPERM) {
883 		return EPERM;
884 	}
885 
886 	/* Precedence goes to error over success; otherwise, arbitrary. */
887 	if (error1 != 0) {
888 		return error1;
889 	}
890 	return error2;
891 }
892 
893 int
mac_check_structmac_consistent(struct user_mac * mac)894 mac_check_structmac_consistent(struct user_mac *mac)
895 {
896 	if (mac->m_buflen > MAC_MAX_LABEL_BUF_LEN || mac->m_buflen == 0) {
897 		return EINVAL;
898 	}
899 
900 	return 0;
901 }
902 
903 /*
904  * Get the external forms of labels from all policies, for a single
905  * label namespace or "*" for all namespaces.  Returns ENOENT if no policy
906  * is registered for the namespace, unless the namespace begins with a '?'.
907  */
908 static int
mac_label_externalize(size_t mpo_externalize_off,struct label * label,const char * element,struct sbuf * sb)909 mac_label_externalize(size_t mpo_externalize_off, struct label *label,
910     const char *element, struct sbuf *sb)
911 {
912 	struct mac_policy_conf *mpc;
913 	struct mac_label_listener *mll;
914 	struct mac_label_element *mle;
915 	struct mac_label_element_list_t *element_list;
916 	const char *name;
917 	int (*mpo_externalize)(struct label *, char *, struct sbuf *);
918 	int all_labels = 0, ignorenotfound = 0, error = 0, busy = FALSE;
919 	int sb_pos;
920 	unsigned int count = 0;
921 
922 	if (element[0] == '?') {
923 		element++;
924 		ignorenotfound = 1;
925 	} else if (element[0] == '*' && element[1] == '\0') {
926 		all_labels = 1;
927 	}
928 
929 	element_list = &mac_static_label_element_list;
930 element_loop:
931 	SLIST_FOREACH(mle, element_list, mle_list) {
932 		name = mle->mle_name;
933 		if (all_labels) {
934 			if (*name == '?') {
935 				continue;
936 			}
937 		} else {
938 			if (*name == '?') {
939 				name++;
940 			}
941 			if (strcmp(name, element) != 0) {
942 				continue;
943 			}
944 		}
945 		SLIST_FOREACH(mll, &mle->mle_listeners, mll_list) {
946 			mpc = mac_policy_list.entries[mll->mll_handle].mpc;
947 			if (mpc == NULL) {
948 				continue;
949 			}
950 			mpo_externalize = *(const typeof(mpo_externalize) *)
951 			    ((const char *)mpc->mpc_ops + mpo_externalize_off);
952 			if (mpo_externalize == NULL) {
953 				continue;
954 			}
955 			sb_pos = sbuf_len(sb);
956 			error = sbuf_printf(sb, "%s/", name);
957 			if (error) {
958 				goto done;
959 			}
960 			error = mpo_externalize(label, mle->mle_name, sb);
961 			if (error) {
962 				if (error != ENOENT) {
963 					goto done;
964 				}
965 				/*
966 				 * If a policy doesn't have a label to
967 				 * externalize it returns ENOENT.  This
968 				 * may occur for policies that support
969 				 * multiple label elements for some
970 				 * (but not all) object types.
971 				 */
972 				sbuf_setpos(sb, sb_pos);
973 				error = 0;
974 				continue;
975 			}
976 			error = sbuf_putc(sb, ',');
977 			if (error) {
978 				goto done;
979 			}
980 			count++;
981 		}
982 	}
983 	/* If there are dynamic policies present, check their elements too. */
984 	if (!busy && mac_policy_list_conditional_busy() == 1) {
985 		element_list = &mac_label_element_list;
986 		busy = TRUE;
987 		goto element_loop;
988 	}
989 done:
990 	if (busy) {
991 		mac_policy_list_unbusy();
992 	}
993 	if (!error && count == 0) {
994 		if (!all_labels && !ignorenotfound) {
995 			error = ENOENT; /* XXX: ENOLABEL? */
996 		}
997 	}
998 	return error;
999 }
1000 
1001 /*
1002  * Get the external forms of labels from all policies, for all label
1003  * namespaces contained in a list.
1004  *
1005  * XXX This may be leaking an sbuf.
1006  */
1007 int
mac_externalize(size_t mpo_externalize_off,struct label * label,const char * elementlist,char * outbuf,size_t outbuflen)1008 mac_externalize(size_t mpo_externalize_off, struct label *label,
1009     const char *elementlist, char *outbuf, size_t outbuflen)
1010 {
1011 	char *element;
1012 	char *scratch_base;
1013 	char *scratch;
1014 	struct sbuf sb;
1015 	int error = 0, len;
1016 	size_t buf_len = strlen(elementlist) + 1;
1017 
1018 	/* allocate a scratch buffer the size of the string */
1019 	scratch_base = kalloc_data(buf_len, Z_WAITOK);
1020 	if (scratch_base == NULL) {
1021 		error = ENOMEM;
1022 		goto out;
1023 	}
1024 
1025 	/* copy the elementlist to the scratch buffer */
1026 	strlcpy(scratch_base, elementlist, buf_len);
1027 
1028 	/*
1029 	 * set up a temporary pointer that can be used to iterate the
1030 	 * scratch buffer without losing the allocation address
1031 	 */
1032 	scratch = scratch_base;
1033 
1034 	/*
1035 	 * initialize an sbuf mapping over the output buffer (or newly-allocated internal buffer, if
1036 	 * outbuf is NULL), up to sbuf's limit of INT_MAX.
1037 	 */
1038 	if (outbuflen > INT_MAX) {
1039 		outbuflen = INT_MAX;
1040 	}
1041 	if (sbuf_new(&sb, outbuf, (int)outbuflen, SBUF_FIXEDLEN) == NULL) {
1042 		/* could not allocate interior buffer */
1043 		error = ENOMEM;
1044 		goto out;
1045 	}
1046 	/* iterate the scratch buffer; NOTE: buffer contents modified! */
1047 	while ((element = strsep(&scratch, ",")) != NULL) {
1048 		error = mac_label_externalize(mpo_externalize_off, label,
1049 		    element, &sb);
1050 		if (error) {
1051 			break;
1052 		}
1053 	}
1054 	if ((len = sbuf_len(&sb)) > 0) {
1055 		sbuf_setpos(&sb, len - 1);      /* trim trailing comma */
1056 	}
1057 	sbuf_finish(&sb);
1058 
1059 out:
1060 	if (scratch_base != NULL) {
1061 		kfree_data(scratch_base, buf_len);
1062 	}
1063 
1064 	return error;
1065 }
1066 
1067 /*
1068  * Have all policies set the internal form of a label, for a single
1069  * label namespace.
1070  */
1071 static int
mac_label_internalize(size_t mpo_internalize_off,struct label * label,char * element_name,char * element_data)1072 mac_label_internalize(size_t mpo_internalize_off, struct label *label,
1073     char *element_name, char *element_data)
1074 {
1075 	struct mac_policy_conf *mpc;
1076 	struct mac_label_listener *mll;
1077 	struct mac_label_element *mle;
1078 	struct mac_label_element_list_t *element_list;
1079 	int (*mpo_internalize)(struct label *, char *, char *);
1080 	int error = 0, busy = FALSE;
1081 	unsigned int count = 0;
1082 	const char *name;
1083 
1084 	element_list = &mac_static_label_element_list;
1085 element_loop:
1086 	SLIST_FOREACH(mle, element_list, mle_list) {
1087 		if (*(name = mle->mle_name) == '?') {
1088 			name++;
1089 		}
1090 		if (strcmp(element_name, name) != 0) {
1091 			continue;
1092 		}
1093 		SLIST_FOREACH(mll, &mle->mle_listeners, mll_list) {
1094 			mpc = mac_policy_list.entries[mll->mll_handle].mpc;
1095 			if (mpc == NULL) {
1096 				continue;
1097 			}
1098 			mpo_internalize = *(const typeof(mpo_internalize) *)
1099 			    ((const char *)mpc->mpc_ops + mpo_internalize_off);
1100 			if (mpo_internalize == NULL) {
1101 				continue;
1102 			}
1103 			error = mpo_internalize(label, element_name,
1104 			    element_data);
1105 			if (error) {
1106 				goto done;
1107 			}
1108 			count++;
1109 		}
1110 	}
1111 	/* If there are dynamic policies present, check their elements too. */
1112 	if (!busy && mac_policy_list_conditional_busy() == 1) {
1113 		element_list = &mac_label_element_list;
1114 		busy = TRUE;
1115 		goto element_loop;
1116 	}
1117 done:
1118 	if (busy) {
1119 		mac_policy_list_unbusy();
1120 	}
1121 	if (!error && count == 0) {
1122 		error = ENOPOLICY;
1123 	}
1124 	return error;
1125 }
1126 
1127 int
mac_internalize(size_t mpo_internalize_off,struct label * label,char * textlabels)1128 mac_internalize(size_t mpo_internalize_off, struct label *label,
1129     char *textlabels)
1130 {
1131 	char *element_name, *element_data;
1132 	int error = 0;
1133 
1134 	while (!error && (element_name = strsep(&textlabels, ",")) != NULL) {
1135 		element_data = strchr(element_name, '/');
1136 		if (element_data == NULL) {
1137 			error = EINVAL;
1138 			break;
1139 		}
1140 		*element_data++ = '\0';
1141 		error = mac_label_internalize(mpo_internalize_off, label,
1142 		    element_name, element_data);
1143 	}
1144 	return error;
1145 }
1146 
1147 static int
user_mac_copyin(struct proc * p,user_addr_t mac_p,struct user_mac * mac)1148 user_mac_copyin(struct proc *p, user_addr_t mac_p, struct user_mac *mac)
1149 {
1150 	int error;
1151 
1152 	if (IS_64BIT_PROCESS(p)) {
1153 		struct user64_mac mac64;
1154 		if ((error = copyin(mac_p, &mac64, sizeof(mac64)))) {
1155 			return error;
1156 		}
1157 
1158 		mac->m_buflen = mac64.m_buflen;
1159 		mac->m_string = mac64.m_string;
1160 	} else {
1161 		struct user32_mac mac32;
1162 		if ((error = copyin(mac_p, &mac32, sizeof(mac32)))) {
1163 			return error;
1164 		}
1165 
1166 		mac->m_buflen = mac32.m_buflen;
1167 		mac->m_string = mac32.m_string;
1168 	}
1169 
1170 	return mac_check_structmac_consistent(mac);
1171 }
1172 
1173 int
mac_do_get(struct proc * p,user_addr_t mac_p,mac_getter_t getter)1174 mac_do_get(struct proc *p, user_addr_t mac_p, mac_getter_t getter)
1175 {
1176 	struct user_mac mac;
1177 	char *input;
1178 	char *output;
1179 	size_t len;
1180 	size_t ulen;
1181 	int error;
1182 
1183 	if ((error = user_mac_copyin(p, mac_p, &mac))) {
1184 		return error;
1185 	}
1186 
1187 	len = mac.m_buflen;
1188 	input = kalloc_data(len, Z_WAITOK);
1189 	if ((error = copyinstr(mac.m_string, input, len, &ulen))) {
1190 		kfree_data(input, len);
1191 		return error;
1192 	}
1193 
1194 	AUDIT_ARG(mac_string, input);
1195 
1196 	output = kalloc_data(len, Z_WAITOK | Z_ZERO);
1197 
1198 	error = getter(input, output, len);
1199 	if (error == 0) {
1200 		/* mac_check_structmac_consistent => len > 0 */
1201 		output[len - 1] = '\0';
1202 		error = copyout(output, mac.m_string, strlen(output) + 1);
1203 	}
1204 
1205 	kfree_data(output, len);
1206 	kfree_data(input, len);
1207 	return error;
1208 }
1209 
1210 int
mac_do_set(struct proc * p,user_addr_t mac_p,mac_setter_t setter)1211 mac_do_set(struct proc *p, user_addr_t mac_p, mac_setter_t setter)
1212 {
1213 	struct user_mac mac;
1214 	char *input;
1215 	size_t len;
1216 	size_t ulen;
1217 	int error;
1218 
1219 	if ((error = user_mac_copyin(p, mac_p, &mac))) {
1220 		return error;
1221 	}
1222 
1223 	len = mac.m_buflen;
1224 	input = kalloc_data(len, Z_WAITOK);
1225 	if ((error = copyinstr(mac.m_string, input, len, &ulen))) {
1226 		kfree_data(input, len);
1227 		return error;
1228 	}
1229 
1230 	AUDIT_ARG(mac_string, input);
1231 
1232 	error = setter(input, len);
1233 
1234 	kfree_data(input, len);
1235 	return error;
1236 }
1237 
1238 /* system calls */
1239 
1240 int
__mac_get_pid(struct proc * p,struct __mac_get_pid_args * uap,int * ret __unused)1241 __mac_get_pid(struct proc *p, struct __mac_get_pid_args *uap, int *ret __unused)
1242 {
1243 	return mac_do_get(p, uap->mac_p,
1244 	           ^(char *input, char *output, size_t len) {
1245 		struct proc *tproc;
1246 		struct ucred *tcred;
1247 		int error;
1248 
1249 		AUDIT_ARG(pid, uap->pid);
1250 
1251 		tproc = proc_find(uap->pid);
1252 		if (tproc == NULL) {
1253 		        return ESRCH;
1254 		}
1255 
1256 		tcred = kauth_cred_proc_ref(tproc);
1257 		proc_rele(tproc);
1258 
1259 		error = mac_cred_label_externalize(mac_cred_label(tcred),
1260 		input, output, len, M_WAITOK);
1261 
1262 		kauth_cred_unref(&tcred);
1263 		return error;
1264 	});
1265 }
1266 
1267 int
__mac_get_proc(proc_t p,struct __mac_get_proc_args * uap,int * ret __unused)1268 __mac_get_proc(proc_t p, struct __mac_get_proc_args *uap, int *ret __unused)
1269 {
1270 	return mac_do_get(p, uap->mac_p,
1271 	           ^(char *input, char *output, size_t len) {
1272 		struct label *label;
1273 
1274 		label = mac_cred_label(kauth_cred_get());
1275 
1276 		return mac_cred_label_externalize(label, input, output, len, M_WAITOK);
1277 	});
1278 }
1279 
1280 int
__mac_set_proc(proc_t p,struct __mac_set_proc_args * uap,int * ret __unused)1281 __mac_set_proc(proc_t p, struct __mac_set_proc_args *uap, int *ret __unused)
1282 {
1283 	return mac_do_set(p, uap->mac_p,
1284 	           ^(char *input, __unused size_t len) {
1285 		struct label *intlabel;
1286 		int error;
1287 
1288 		intlabel = mac_cred_label_alloc();
1289 		if ((error = mac_cred_label_internalize(intlabel, input))) {
1290 		        goto out;
1291 		}
1292 
1293 		if ((error = mac_cred_check_label_update(kauth_cred_get(), intlabel))) {
1294 		        goto out;
1295 		}
1296 
1297 		error = kauth_proc_label_update(p, intlabel);
1298 
1299 		out:
1300 		mac_cred_label_free(intlabel);
1301 		return error;
1302 	});
1303 }
1304 
1305 int
__mac_get_fd(proc_t p,struct __mac_get_fd_args * uap,int * ret __unused)1306 __mac_get_fd(proc_t p, struct __mac_get_fd_args *uap, int *ret __unused)
1307 {
1308 	return mac_do_get(p, uap->mac_p,
1309 	           ^(char *input, char *output, size_t len) {
1310 		struct fileproc *fp;
1311 		struct vnode *vp;
1312 		int error;
1313 		struct label *intlabel;
1314 
1315 		AUDIT_ARG(fd, uap->fd);
1316 
1317 		if ((error = fp_lookup(p, uap->fd, &fp, 0))) {
1318 		        return error;
1319 		}
1320 
1321 		error = mac_file_check_get(kauth_cred_get(), fp->fp_glob, input, len);
1322 		if (error) {
1323 		        fp_drop(p, uap->fd, fp, 0);
1324 		        return error;
1325 		}
1326 
1327 		switch (FILEGLOB_DTYPE(fp->fp_glob)) {
1328 		case DTYPE_VNODE:
1329 			intlabel = mac_vnode_label_alloc(NULL);
1330 			if (intlabel == NULL) {
1331 			        error = ENOMEM;
1332 			        break;
1333 			}
1334 			vp = (struct vnode *)fp_get_data(fp);
1335 			error = vnode_getwithref(vp);
1336 			if (error == 0) {
1337 			        mac_vnode_label_copy(mac_vnode_label(vp), intlabel);
1338 			        error = mac_vnode_label_externalize(intlabel,
1339 			        input, output, len, M_WAITOK);
1340 			        vnode_put(vp);
1341 			}
1342 			mac_vnode_label_free(intlabel);
1343 			break;
1344 		case DTYPE_SOCKET:
1345 		case DTYPE_PSXSHM:
1346 		case DTYPE_PSXSEM:
1347 		case DTYPE_PIPE:
1348 		case DTYPE_KQUEUE:
1349 		case DTYPE_FSEVENTS:
1350 		case DTYPE_ATALK:
1351 		case DTYPE_NETPOLICY:
1352 		case DTYPE_CHANNEL:
1353 		case DTYPE_NEXUS:
1354 		default:
1355 			error = ENOSYS;           // only sockets/vnodes so far
1356 			break;
1357 		}
1358 		fp_drop(p, uap->fd, fp, 0);
1359 		return error;
1360 	});
1361 }
1362 
1363 static int
mac_get_filelink(proc_t p,user_addr_t mac_p,user_addr_t path_p,int follow)1364 mac_get_filelink(proc_t p, user_addr_t mac_p, user_addr_t path_p, int follow)
1365 {
1366 	return mac_do_get(p, mac_p,
1367 	           ^(char *input, char *output, size_t len) {
1368 		struct vnode *vp;
1369 		struct nameidata nd;
1370 		struct label *intlabel;
1371 		int error;
1372 
1373 		NDINIT(&nd, LOOKUP, OP_LOOKUP,
1374 		LOCKLEAF | (follow ? FOLLOW : NOFOLLOW) | AUDITVNPATH1,
1375 		UIO_USERSPACE, path_p,
1376 		vfs_context_current());
1377 		if ((error = namei(&nd))) {
1378 		        return error;
1379 		}
1380 		vp = nd.ni_vp;
1381 
1382 		nameidone(&nd);
1383 
1384 		intlabel = mac_vnode_label_alloc(NULL);
1385 		mac_vnode_label_copy(mac_vnode_label(vp), intlabel);
1386 		error = mac_vnode_label_externalize(intlabel, input, output,
1387 		len, M_WAITOK);
1388 		mac_vnode_label_free(intlabel);
1389 
1390 		vnode_put(vp);
1391 		return error;
1392 	});
1393 }
1394 
1395 int
__mac_get_file(proc_t p,struct __mac_get_file_args * uap,int * ret __unused)1396 __mac_get_file(proc_t p, struct __mac_get_file_args *uap,
1397     int *ret __unused)
1398 {
1399 	return mac_get_filelink(p, uap->mac_p, uap->path_p, 1);
1400 }
1401 
1402 int
__mac_get_link(proc_t p,struct __mac_get_link_args * uap,int * ret __unused)1403 __mac_get_link(proc_t p, struct __mac_get_link_args *uap,
1404     int *ret __unused)
1405 {
1406 	return mac_get_filelink(p, uap->mac_p, uap->path_p, 0);
1407 }
1408 
1409 int
__mac_set_fd(proc_t p,struct __mac_set_fd_args * uap,int * ret __unused)1410 __mac_set_fd(proc_t p, struct __mac_set_fd_args *uap, int *ret __unused)
1411 {
1412 	return mac_do_set(p, uap->mac_p,
1413 	           ^(char *input, size_t len) {
1414 		struct fileproc *fp;
1415 		struct vfs_context *ctx = vfs_context_current();
1416 		int error;
1417 		struct label *intlabel;
1418 		struct vnode *vp;
1419 
1420 		AUDIT_ARG(fd, uap->fd);
1421 
1422 		if ((error = fp_lookup(p, uap->fd, &fp, 0))) {
1423 		        return error;
1424 		}
1425 
1426 		error = mac_file_check_set(vfs_context_ucred(ctx), fp->fp_glob, input, len);
1427 		if (error) {
1428 		        fp_drop(p, uap->fd, fp, 0);
1429 		        return error;
1430 		}
1431 
1432 		switch (FILEGLOB_DTYPE(fp->fp_glob)) {
1433 		case DTYPE_VNODE:
1434 			if (mac_label_vnodes == 0) {
1435 			        error = ENOSYS;
1436 			        break;
1437 			}
1438 
1439 			intlabel = mac_vnode_label_alloc(NULL);
1440 
1441 			error = mac_vnode_label_internalize(intlabel, input);
1442 			if (error) {
1443 			        mac_vnode_label_free(intlabel);
1444 			        break;
1445 			}
1446 
1447 			vp = (struct vnode *)fp_get_data(fp);
1448 
1449 			error = vnode_getwithref(vp);
1450 			if (error == 0) {
1451 			        error = vn_setlabel(vp, intlabel, ctx);
1452 			        vnode_put(vp);
1453 			}
1454 			mac_vnode_label_free(intlabel);
1455 			break;
1456 
1457 		case DTYPE_SOCKET:
1458 		case DTYPE_PSXSHM:
1459 		case DTYPE_PSXSEM:
1460 		case DTYPE_PIPE:
1461 		case DTYPE_KQUEUE:
1462 		case DTYPE_FSEVENTS:
1463 		case DTYPE_ATALK:
1464 		case DTYPE_NETPOLICY:
1465 		case DTYPE_CHANNEL:
1466 		case DTYPE_NEXUS:
1467 		default:
1468 			error = ENOSYS;          // only sockets/vnodes so far
1469 			break;
1470 		}
1471 
1472 		fp_drop(p, uap->fd, fp, 0);
1473 		return error;
1474 	});
1475 }
1476 
1477 static int
mac_set_filelink(proc_t p,user_addr_t mac_p,user_addr_t path_p,int follow)1478 mac_set_filelink(proc_t p, user_addr_t mac_p, user_addr_t path_p,
1479     int follow)
1480 {
1481 	return mac_do_set(p, mac_p,
1482 	           ^(char *input, __unused size_t len) {
1483 		struct vnode *vp;
1484 		struct vfs_context *ctx = vfs_context_current();
1485 		struct label *intlabel;
1486 		struct nameidata nd;
1487 		int error;
1488 
1489 		if (mac_label_vnodes == 0) {
1490 		        return ENOSYS;
1491 		}
1492 
1493 		intlabel = mac_vnode_label_alloc(NULL);
1494 		error = mac_vnode_label_internalize(intlabel, input);
1495 		if (error) {
1496 		        mac_vnode_label_free(intlabel);
1497 		        return error;
1498 		}
1499 
1500 		NDINIT(&nd, LOOKUP, OP_LOOKUP,
1501 		LOCKLEAF | (follow ? FOLLOW : NOFOLLOW) | AUDITVNPATH1,
1502 		UIO_USERSPACE, path_p, ctx);
1503 		error = namei(&nd);
1504 		if (error) {
1505 		        mac_vnode_label_free(intlabel);
1506 		        return error;
1507 		}
1508 		vp = nd.ni_vp;
1509 
1510 		nameidone(&nd);
1511 
1512 		error = vn_setlabel(vp, intlabel, ctx);
1513 		vnode_put(vp);
1514 		mac_vnode_label_free(intlabel);
1515 
1516 		return error;
1517 	});
1518 }
1519 
1520 int
__mac_set_file(proc_t p,struct __mac_set_file_args * uap,int * ret __unused)1521 __mac_set_file(proc_t p, struct __mac_set_file_args *uap,
1522     int *ret __unused)
1523 {
1524 	return mac_set_filelink(p, uap->mac_p, uap->path_p, 1);
1525 }
1526 
1527 int
__mac_set_link(proc_t p,struct __mac_set_link_args * uap,int * ret __unused)1528 __mac_set_link(proc_t p, struct __mac_set_link_args *uap,
1529     int *ret __unused)
1530 {
1531 	return mac_set_filelink(p, uap->mac_p, uap->path_p, 0);
1532 }
1533 
1534 static int
mac_proc_check_mac_syscall(proc_t p,const char * target,int callnum)1535 mac_proc_check_mac_syscall(proc_t p, const char *target, int callnum)
1536 {
1537 	int error;
1538 
1539 #if SECURITY_MAC_CHECK_ENFORCE
1540 	/* 21167099 - only check if we allow write */
1541 	if (!mac_proc_enforce) {
1542 		return 0;
1543 	}
1544 #endif
1545 
1546 	MAC_CHECK(proc_check_syscall_mac, p, target, callnum);
1547 
1548 	return error;
1549 }
1550 
1551 /*
1552  * __mac_syscall: Perform a MAC policy system call
1553  *
1554  * Parameters:    p                       Process calling this routine
1555  *                uap                     User argument descriptor (see below)
1556  *                retv                    (Unused)
1557  *
1558  * Indirect:      uap->policy             Name of target MAC policy
1559  *                uap->call               MAC policy-specific system call to perform
1560  *                uap->arg                MAC policy-specific system call arguments
1561  *
1562  * Returns:        0                      Success
1563  *                !0                      Not success
1564  *
1565  */
1566 int
__mac_syscall(proc_t p,struct __mac_syscall_args * uap,int * retv __unused)1567 __mac_syscall(proc_t p, struct __mac_syscall_args *uap, int *retv __unused)
1568 {
1569 	struct mac_policy_conf *mpc;
1570 	char target[MAC_MAX_POLICY_NAME];
1571 	int error;
1572 	u_int i;
1573 	size_t ulen;
1574 
1575 	error = copyinstr(uap->policy, target, sizeof(target), &ulen);
1576 	if (error) {
1577 		return error;
1578 	}
1579 	AUDIT_ARG(value32, uap->call);
1580 	AUDIT_ARG(mac_string, target);
1581 
1582 	error = mac_proc_check_mac_syscall(p, target, uap->call);
1583 	if (error) {
1584 		return error;
1585 	}
1586 
1587 	error = ENOPOLICY;
1588 
1589 	for (i = 0; i < mac_policy_list.staticmax; i++) {
1590 		mpc = mac_policy_list.entries[i].mpc;
1591 		if (mpc == NULL) {
1592 			continue;
1593 		}
1594 
1595 		if (strcmp(mpc->mpc_name, target) == 0 &&
1596 		    mpc->mpc_ops->mpo_policy_syscall != NULL) {
1597 			error = mpc->mpc_ops->mpo_policy_syscall(p,
1598 			    uap->call, uap->arg);
1599 			goto done;
1600 		}
1601 	}
1602 	if (mac_policy_list_conditional_busy() != 0) {
1603 		for (; i <= mac_policy_list.maxindex; i++) {
1604 			mpc = mac_policy_list.entries[i].mpc;
1605 			if (mpc == NULL) {
1606 				continue;
1607 			}
1608 
1609 			if (strcmp(mpc->mpc_name, target) == 0 &&
1610 			    mpc->mpc_ops->mpo_policy_syscall != NULL) {
1611 				error = mpc->mpc_ops->mpo_policy_syscall(p,
1612 				    uap->call, uap->arg);
1613 				break;
1614 			}
1615 		}
1616 		mac_policy_list_unbusy();
1617 	}
1618 
1619 done:
1620 	return error;
1621 }
1622 
1623 int
mac_mount_label_get(struct mount * mp,user_addr_t mac_p)1624 mac_mount_label_get(struct mount *mp, user_addr_t mac_p)
1625 {
1626 	return mac_do_get(current_proc(), mac_p,
1627 	           ^(char *input, char *output, size_t len) {
1628 		return mac_mount_label_externalize(mac_mount_label(mp), input,
1629 		output, len);
1630 	});
1631 }
1632 
1633 /*
1634  * __mac_get_mount: Get mount point label information for a given pathname
1635  *
1636  * Parameters:    p                        (ignored)
1637  *                uap                      User argument descriptor (see below)
1638  *                ret                      (ignored)
1639  *
1640  * Indirect:      uap->path                Pathname
1641  *                uap->mac_p               MAC info
1642  *
1643  * Returns:        0                       Success
1644  *                !0                       Not success
1645  */
1646 int
__mac_get_mount(proc_t p __unused,struct __mac_get_mount_args * uap,int * ret __unused)1647 __mac_get_mount(proc_t p __unused, struct __mac_get_mount_args *uap,
1648     int *ret __unused)
1649 {
1650 	struct nameidata nd;
1651 	struct vfs_context *ctx = vfs_context_current();
1652 	struct mount *mp;
1653 	int error;
1654 
1655 	NDINIT(&nd, LOOKUP, OP_LOOKUP, FOLLOW | AUDITVNPATH1,
1656 	    UIO_USERSPACE, uap->path, ctx);
1657 	error = namei(&nd);
1658 	if (error) {
1659 		return error;
1660 	}
1661 	mp = nd.ni_vp->v_mount;
1662 	mount_ref(mp, 0);
1663 	vnode_put(nd.ni_vp);
1664 	nameidone(&nd);
1665 
1666 	error = mac_mount_label_get(mp, uap->mac_p);
1667 	mount_drop(mp, 0);
1668 	return error;
1669 }
1670 
1671 /*
1672  * mac_schedule_userret()
1673  *
1674  * Schedule a callback to the mpo_thread_userret hook. The mpo_thread_userret
1675  * hook is called just before the thread exit from the kernel in ast_taken().
1676  *
1677  * Returns:	 0		Success
1678  *              !0		Not successful
1679  */
1680 int
mac_schedule_userret(void)1681 mac_schedule_userret(void)
1682 {
1683 	act_set_astmacf(current_thread());
1684 	return 0;
1685 }
1686 
1687 /*
1688  * mac_do_machexc()
1689  *
1690  * Do a Mach exception.  This should only be done in the mpo_thread_userret
1691  * callback.
1692  *
1693  * params:	code		exception code
1694  *              subcode		exception subcode
1695  *              flags		flags:
1696  *                              MAC_DOEXCF_TRACED  Only do exception if being
1697  *                                                 ptrace()'ed.
1698  *
1699  *
1700  * Returns:	 0		Success
1701  *              !0		Not successful
1702  */
1703 int
mac_do_machexc(int64_t code,int64_t subcode,uint32_t flags)1704 mac_do_machexc(int64_t code, int64_t subcode, uint32_t flags)
1705 {
1706 	mach_exception_data_type_t  codes[EXCEPTION_CODE_MAX];
1707 	proc_t p = current_proc();
1708 
1709 	/* Only allow execption codes in MACF's reserved range. */
1710 	if ((code < EXC_MACF_MIN) || (code > EXC_MACF_MAX)) {
1711 		return 1;
1712 	}
1713 
1714 	if (flags & MAC_DOEXCF_TRACED &&
1715 	    !(p->p_lflag & P_LTRACED && (p->p_lflag & P_LPPWAIT) == 0)) {
1716 		return 0;
1717 	}
1718 
1719 
1720 	/* Send the Mach exception */
1721 	codes[0] = (mach_exception_data_type_t)code;
1722 	codes[1] = (mach_exception_data_type_t)subcode;
1723 
1724 	return bsd_exception(EXC_SOFTWARE, codes, 2) != KERN_SUCCESS;
1725 }
1726 
1727 #else /* MAC */
1728 
1729 void (*load_security_extensions_function)(void) = 0;
1730 
1731 struct sysctl_oid_list sysctl__security_mac_children;
1732 
1733 int
mac_policy_register(struct mac_policy_conf * mpc __unused,mac_policy_handle_t * handlep __unused,void * xd __unused)1734 mac_policy_register(struct mac_policy_conf *mpc __unused,
1735     mac_policy_handle_t *handlep __unused, void *xd __unused)
1736 {
1737 	return 0;
1738 }
1739 
1740 int
mac_policy_unregister(mac_policy_handle_t handle __unused)1741 mac_policy_unregister(mac_policy_handle_t handle __unused)
1742 {
1743 	return 0;
1744 }
1745 
1746 int
mac_audit_text(char * text __unused,mac_policy_handle_t handle __unused)1747 mac_audit_text(char *text __unused, mac_policy_handle_t handle __unused)
1748 {
1749 	return 0;
1750 }
1751 
1752 int
mac_vnop_setxattr(struct vnode * vp __unused,const char * name __unused,char * buf __unused,size_t len __unused)1753 mac_vnop_setxattr(struct vnode *vp __unused, const char *name __unused, char *buf __unused, size_t len __unused)
1754 {
1755 	return ENOENT;
1756 }
1757 
1758 int
mac_vnop_getxattr(struct vnode * vp __unused,const char * name __unused,char * buf __unused,size_t len __unused,size_t * attrlen __unused)1759 mac_vnop_getxattr(struct vnode *vp __unused, const char *name __unused,
1760     char *buf __unused, size_t len __unused, size_t *attrlen __unused)
1761 {
1762 	return ENOENT;
1763 }
1764 
1765 int
mac_vnop_removexattr(struct vnode * vp __unused,const char * name __unused)1766 mac_vnop_removexattr(struct vnode *vp __unused, const char *name __unused)
1767 {
1768 	return ENOENT;
1769 }
1770 
1771 int
mac_file_setxattr(struct fileglob * fg __unused,const char * name __unused,char * buf __unused,size_t len __unused)1772 mac_file_setxattr(struct fileglob *fg __unused, const char *name __unused, char *buf __unused, size_t len __unused)
1773 {
1774 	return ENOENT;
1775 }
1776 
1777 int
mac_file_getxattr(struct fileglob * fg __unused,const char * name __unused,char * buf __unused,size_t len __unused,size_t * attrlen __unused)1778 mac_file_getxattr(struct fileglob *fg __unused, const char *name __unused,
1779     char *buf __unused, size_t len __unused, size_t *attrlen __unused)
1780 {
1781 	return ENOENT;
1782 }
1783 
1784 int
mac_file_removexattr(struct fileglob * fg __unused,const char * name __unused)1785 mac_file_removexattr(struct fileglob *fg __unused, const char *name __unused)
1786 {
1787 	return ENOENT;
1788 }
1789 
1790 intptr_t
mac_label_get(struct label * l __unused,int slot __unused)1791 mac_label_get(struct label *l __unused, int slot __unused)
1792 {
1793 	return 0;
1794 }
1795 
1796 void
mac_label_set(struct label * l __unused,int slot __unused,intptr_t v __unused)1797 mac_label_set(struct label *l __unused, int slot __unused, intptr_t v __unused)
1798 {
1799 	return;
1800 }
1801 
1802 int mac_iokit_check_hid_control(kauth_cred_t cred __unused);
1803 int
mac_iokit_check_hid_control(kauth_cred_t cred __unused)1804 mac_iokit_check_hid_control(kauth_cred_t cred __unused)
1805 {
1806 	return 0;
1807 }
1808 
1809 int mac_vnode_check_open(vfs_context_t ctx, struct vnode *vp, int acc_mode);
1810 int
mac_vnode_check_open(vfs_context_t ctx __unused,struct vnode * vp __unused,int acc_mode __unused)1811 mac_vnode_check_open(vfs_context_t ctx __unused, struct vnode *vp __unused, int acc_mode __unused)
1812 {
1813 	return 0;
1814 }
1815 
1816 int mac_mount_check_snapshot_mount(vfs_context_t ctx, struct vnode *rvp, struct vnode *vp, struct componentname *cnp,
1817     const char *name, const char *vfc_name);
1818 int
mac_mount_check_snapshot_mount(vfs_context_t ctx __unused,struct vnode * rvp __unused,struct vnode * vp __unused,struct componentname * cnp __unused,const char * name __unused,const char * vfc_name __unused)1819 mac_mount_check_snapshot_mount(vfs_context_t ctx __unused, struct vnode *rvp __unused, struct vnode *vp __unused,
1820     struct componentname *cnp __unused, const char *name __unused, const char *vfc_name __unused)
1821 {
1822 	return 0;
1823 }
1824 
1825 int mac_vnode_check_trigger_resolve(vfs_context_t ctx __unused, struct vnode *dvp __unused, struct componentname *cnp __unused);
1826 int
mac_vnode_check_trigger_resolve(vfs_context_t ctx __unused,struct vnode * dvp __unused,struct componentname * cnp __unused)1827 mac_vnode_check_trigger_resolve(vfs_context_t ctx __unused, struct vnode *dvp __unused, struct componentname *cnp __unused)
1828 {
1829 	return 0;
1830 }
1831 
1832 #endif /* !MAC */
1833