xref: /xnu-10002.61.3/security/mac_base.c (revision 0f4c859e951fba394238ab619495c4e1d54d0f34)
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 	/*
618 	 * Some preliminary checks to make sure the policy's conf structure
619 	 * contains the required fields.
620 	 */
621 	if (mpc->mpc_name == NULL) {
622 		panic("policy's name is not set");
623 	}
624 
625 	if (mpc->mpc_fullname == NULL) {
626 		panic("policy's full name is not set");
627 	}
628 
629 	if (mpc->mpc_labelname_count > MAC_MAX_MANAGED_NAMESPACES) {
630 		panic("policy's managed label namespaces exceeds maximum");
631 	}
632 
633 	if (mpc->mpc_ops == NULL) {
634 		panic("policy's OPs field is NULL");
635 	}
636 
637 	error = 0;
638 
639 	if (mac_late) {
640 		if (mpc->mpc_loadtime_flags & MPC_LOADTIME_FLAG_NOTLATE) {
641 			printf("Module %s does not support late loading.\n",
642 			    mpc->mpc_name);
643 			return EPERM;
644 		}
645 		mac_policy_grab_exclusive();
646 	}
647 
648 	if (mac_policy_list.numloaded >= mac_policy_list.max) {
649 #if XNU_TARGET_OS_OSX
650 		/* allocate new policy list array, zero new chunk */
651 		tmac_policy_list_element =
652 		    kalloc_type(struct mac_policy_list_element,
653 		    MAC_POLICY_LIST_CHUNKSIZE * (mac_policy_list.chunks + 1),
654 		    Z_WAITOK | Z_ZERO);
655 
656 		/* copy old entries into new list */
657 		memcpy(tmac_policy_list_element, mac_policy_list.entries,
658 		    sizeof(struct mac_policy_list_element) *
659 		    MAC_POLICY_LIST_CHUNKSIZE * mac_policy_list.chunks);
660 
661 		/* free old array */
662 		kfree_type(struct mac_policy_list_element,
663 		    MAC_POLICY_LIST_CHUNKSIZE * mac_policy_list.chunks,
664 		    mac_policy_list.entries);
665 
666 		mac_policy_list.entries = tmac_policy_list_element;
667 
668 		/* Update maximums, etc */
669 		mac_policy_list.max += MAC_POLICY_LIST_CHUNKSIZE;
670 		mac_policy_list.chunks++;
671 #else
672 		printf("out of space in mac_policy_list.\n");
673 		return ENOMEM;
674 #endif /* XNU_TARGET_OS_OSX */
675 	}
676 
677 	/* Check for policy with same name already loaded */
678 	for (i = 0; i <= mac_policy_list.maxindex; i++) {
679 		if (mac_policy_list.entries[i].mpc == NULL) {
680 			continue;
681 		}
682 
683 		if (strcmp(mac_policy_list.entries[i].mpc->mpc_name,
684 		    mpc->mpc_name) == 0) {
685 			error = EEXIST;
686 			goto out;
687 		}
688 	}
689 
690 	if (mpc->mpc_field_off != NULL) {
691 		slot = ffs(mac_slot_offsets_free);
692 		if (slot == 0) {
693 			error = ENOMEM;
694 			goto out;
695 		}
696 		slot--;
697 		mac_slot_offsets_free &= ~(1 << slot);
698 		*mpc->mpc_field_off = slot;
699 	}
700 	mpc->mpc_runtime_flags |= MPC_RUNTIME_FLAG_REGISTERED;
701 
702 	if (xd) {
703 		struct mac_module_data *mmd = xd; /* module data from plist */
704 
705 		/* Make a copy of the data. */
706 		mpc->mpc_data = (void *)kalloc_data(mmd->size, Z_WAITOK);
707 		if (mpc->mpc_data != NULL) {
708 			memcpy(mpc->mpc_data, mmd, mmd->size);
709 
710 			/* Fix up pointers after copy. */
711 			mac_policy_fixup_mmd_list(mpc->mpc_data);
712 		}
713 	}
714 
715 	/* Find the first free handle in the list (using our hint). */
716 	for (i = mac_policy_list.freehint; i < mac_policy_list.max; i++) {
717 		if (mac_policy_list.entries[i].mpc == NULL) {
718 			*handlep = i;
719 			mac_policy_list.freehint = ++i;
720 			break;
721 		}
722 	}
723 
724 	/*
725 	 * If we are loading a MAC module before the framework has
726 	 * finished initializing or the module is not unloadable and
727 	 * we can place its handle adjacent to the last static entry,
728 	 * bump the static policy high water mark.
729 	 * Static policies can get by with weaker locking requirements.
730 	 */
731 	if (!mac_late ||
732 	    ((mpc->mpc_loadtime_flags & MPC_LOADTIME_FLAG_UNLOADOK) == 0 &&
733 	    *handlep == mac_policy_list.staticmax)) {
734 		static_entry = 1;
735 		mac_policy_list.staticmax++;
736 	}
737 
738 	mac_policy_list.entries[*handlep].mpc = mpc;
739 
740 	/* Update counters, etc */
741 	if (*handlep > mac_policy_list.maxindex) {
742 		mac_policy_list.maxindex = *handlep;
743 	}
744 	mac_policy_list.numloaded++;
745 
746 	/* Per-policy initialization. */
747 	printf("calling mpo_policy_init for %s\n", mpc->mpc_name);
748 	if (mpc->mpc_ops->mpo_policy_init != NULL) {
749 		(*(mpc->mpc_ops->mpo_policy_init))(mpc);
750 	}
751 
752 	if (mac_late && mpc->mpc_ops->mpo_policy_initbsd != NULL) {
753 		printf("calling mpo_policy_initbsd for %s\n", mpc->mpc_name);
754 		(*(mpc->mpc_ops->mpo_policy_initbsd))(mpc);
755 	}
756 
757 	mac_policy_updateflags();
758 
759 	if (mac_late) {
760 		mac_policy_release_exclusive();
761 	}
762 
763 	mac_policy_addto_labellist(*handlep, static_entry);
764 
765 	printf("Security policy loaded: %s (%s)\n", mpc->mpc_fullname,
766 	    mpc->mpc_name);
767 
768 	return 0;
769 
770 out:
771 	if (mac_late) {
772 		mac_policy_release_exclusive();
773 	}
774 
775 	return error;
776 }
777 
778 int
mac_policy_unregister(mac_policy_handle_t handle)779 mac_policy_unregister(mac_policy_handle_t handle)
780 {
781 	struct mac_policy_conf *mpc;
782 
783 	/*
784 	 * If we fail the load, we may get a request to unload.  Check
785 	 * to see if we did the run-time registration, and if not,
786 	 * silently succeed.
787 	 */
788 	mac_policy_grab_exclusive();
789 	mpc = mac_get_mpc(handle);
790 	if ((mpc->mpc_runtime_flags & MPC_RUNTIME_FLAG_REGISTERED) == 0) {
791 		mac_policy_release_exclusive();
792 		return 0;
793 	}
794 
795 #if 0
796 	/*
797 	 * Don't allow unloading modules with private data.
798 	 */
799 	if (mpc->mpc_field_off != NULL) {
800 		MAC_POLICY_LIST_UNLOCK();
801 		return EBUSY;
802 	}
803 #endif
804 	/*
805 	 * Only allow the unload to proceed if the module is unloadable
806 	 * by its own definition.
807 	 */
808 	if ((mpc->mpc_loadtime_flags & MPC_LOADTIME_FLAG_UNLOADOK) == 0) {
809 		mac_policy_release_exclusive();
810 		return EBUSY;
811 	}
812 
813 	mac_policy_removefrom_labellist(handle);
814 
815 	mac_get_mpc(handle) = NULL;
816 	if (handle < mac_policy_list.freehint &&
817 	    handle >= mac_policy_list.staticmax) {
818 		mac_policy_list.freehint = handle;
819 	}
820 
821 	if (handle == mac_policy_list.maxindex) {
822 		mac_policy_list.maxindex--;
823 	}
824 
825 	mac_policy_list.numloaded--;
826 	if (mpc->mpc_field_off != NULL) {
827 		mac_slot_offsets_free |= (1 << *mpc->mpc_field_off);
828 	}
829 
830 	if (mpc->mpc_ops->mpo_policy_destroy != NULL) {
831 		(*(mpc->mpc_ops->mpo_policy_destroy))(mpc);
832 	}
833 
834 	mpc->mpc_runtime_flags &= ~MPC_RUNTIME_FLAG_REGISTERED;
835 	mac_policy_updateflags();
836 
837 	mac_policy_release_exclusive();
838 
839 	if (mpc->mpc_data) {
840 		struct mac_module_data *mmd = mpc->mpc_data;
841 		__typed_allocators_ignore(kfree_data(mmd, mmd->size)); // rdar://87952845
842 		mpc->mpc_data = NULL;
843 	}
844 
845 	printf("Security policy unload: %s (%s)\n", mpc->mpc_fullname,
846 	    mpc->mpc_name);
847 
848 	return 0;
849 }
850 
851 /*
852  * Define an error value precedence, and given two arguments, selects the
853  * value with the higher precedence.
854  */
855 int
mac_error_select(int error1,int error2)856 mac_error_select(int error1, int error2)
857 {
858 	/* Certain decision-making errors take top priority. */
859 	if (error1 == EDEADLK || error2 == EDEADLK) {
860 		return EDEADLK;
861 	}
862 
863 	/* Invalid arguments should be reported where possible. */
864 	if (error1 == EINVAL || error2 == EINVAL) {
865 		return EINVAL;
866 	}
867 
868 	/* Precedence goes to "visibility", with both process and file. */
869 	if (error1 == ESRCH || error2 == ESRCH) {
870 		return ESRCH;
871 	}
872 
873 	if (error1 == ENOENT || error2 == ENOENT) {
874 		return ENOENT;
875 	}
876 
877 	/* Precedence goes to DAC/MAC protections. */
878 	if (error1 == EACCES || error2 == EACCES) {
879 		return EACCES;
880 	}
881 
882 	/* Precedence goes to privilege. */
883 	if (error1 == EPERM || error2 == EPERM) {
884 		return EPERM;
885 	}
886 
887 	/* Precedence goes to error over success; otherwise, arbitrary. */
888 	if (error1 != 0) {
889 		return error1;
890 	}
891 	return error2;
892 }
893 
894 int
mac_check_structmac_consistent(struct user_mac * mac)895 mac_check_structmac_consistent(struct user_mac *mac)
896 {
897 	if (mac->m_buflen > MAC_MAX_LABEL_BUF_LEN || mac->m_buflen == 0) {
898 		return EINVAL;
899 	}
900 
901 	return 0;
902 }
903 
904 /*
905  * Get the external forms of labels from all policies, for a single
906  * label namespace or "*" for all namespaces.  Returns ENOENT if no policy
907  * is registered for the namespace, unless the namespace begins with a '?'.
908  */
909 static int
mac_label_externalize(size_t mpo_externalize_off,struct label * label,const char * element,struct sbuf * sb)910 mac_label_externalize(size_t mpo_externalize_off, struct label *label,
911     const char *element, struct sbuf *sb)
912 {
913 	struct mac_policy_conf *mpc;
914 	struct mac_label_listener *mll;
915 	struct mac_label_element *mle;
916 	struct mac_label_element_list_t *element_list;
917 	const char *name;
918 	int (*mpo_externalize)(struct label *, char *, struct sbuf *);
919 	int all_labels = 0, ignorenotfound = 0, error = 0, busy = FALSE;
920 	int sb_pos;
921 	unsigned int count = 0;
922 
923 	if (element[0] == '?') {
924 		element++;
925 		ignorenotfound = 1;
926 	} else if (element[0] == '*' && element[1] == '\0') {
927 		all_labels = 1;
928 	}
929 
930 	element_list = &mac_static_label_element_list;
931 element_loop:
932 	SLIST_FOREACH(mle, element_list, mle_list) {
933 		name = mle->mle_name;
934 		if (all_labels) {
935 			if (*name == '?') {
936 				continue;
937 			}
938 		} else {
939 			if (*name == '?') {
940 				name++;
941 			}
942 			if (strcmp(name, element) != 0) {
943 				continue;
944 			}
945 		}
946 		SLIST_FOREACH(mll, &mle->mle_listeners, mll_list) {
947 			mpc = mac_policy_list.entries[mll->mll_handle].mpc;
948 			if (mpc == NULL) {
949 				continue;
950 			}
951 			mpo_externalize = *(const typeof(mpo_externalize) *)
952 			    ((const char *)mpc->mpc_ops + mpo_externalize_off);
953 			if (mpo_externalize == NULL) {
954 				continue;
955 			}
956 			sb_pos = sbuf_len(sb);
957 			error = sbuf_printf(sb, "%s/", name);
958 			if (error) {
959 				goto done;
960 			}
961 			error = mpo_externalize(label, mle->mle_name, sb);
962 			if (error) {
963 				if (error != ENOENT) {
964 					goto done;
965 				}
966 				/*
967 				 * If a policy doesn't have a label to
968 				 * externalize it returns ENOENT.  This
969 				 * may occur for policies that support
970 				 * multiple label elements for some
971 				 * (but not all) object types.
972 				 */
973 				sbuf_setpos(sb, sb_pos);
974 				error = 0;
975 				continue;
976 			}
977 			error = sbuf_putc(sb, ',');
978 			if (error) {
979 				goto done;
980 			}
981 			count++;
982 		}
983 	}
984 	/* If there are dynamic policies present, check their elements too. */
985 	if (!busy && mac_policy_list_conditional_busy() == 1) {
986 		element_list = &mac_label_element_list;
987 		busy = TRUE;
988 		goto element_loop;
989 	}
990 done:
991 	if (busy) {
992 		mac_policy_list_unbusy();
993 	}
994 	if (!error && count == 0) {
995 		if (!all_labels && !ignorenotfound) {
996 			error = ENOENT; /* XXX: ENOLABEL? */
997 		}
998 	}
999 	return error;
1000 }
1001 
1002 /*
1003  * Get the external forms of labels from all policies, for all label
1004  * namespaces contained in a list.
1005  *
1006  * XXX This may be leaking an sbuf.
1007  */
1008 int
mac_externalize(size_t mpo_externalize_off,struct label * label,const char * elementlist,char * outbuf,size_t outbuflen)1009 mac_externalize(size_t mpo_externalize_off, struct label *label,
1010     const char *elementlist, char *outbuf, size_t outbuflen)
1011 {
1012 	char *element;
1013 	char *scratch_base;
1014 	char *scratch;
1015 	struct sbuf sb;
1016 	int error = 0, len;
1017 	size_t buf_len = strlen(elementlist) + 1;
1018 
1019 	/* allocate a scratch buffer the size of the string */
1020 	scratch_base = kalloc_data(buf_len, Z_WAITOK);
1021 	if (scratch_base == NULL) {
1022 		error = ENOMEM;
1023 		goto out;
1024 	}
1025 
1026 	/* copy the elementlist to the scratch buffer */
1027 	strlcpy(scratch_base, elementlist, buf_len);
1028 
1029 	/*
1030 	 * set up a temporary pointer that can be used to iterate the
1031 	 * scratch buffer without losing the allocation address
1032 	 */
1033 	scratch = scratch_base;
1034 
1035 	/*
1036 	 * initialize an sbuf mapping over the output buffer (or newly-allocated internal buffer, if
1037 	 * outbuf is NULL), up to sbuf's limit of INT_MAX.
1038 	 */
1039 	if (outbuflen > INT_MAX) {
1040 		outbuflen = INT_MAX;
1041 	}
1042 	if (sbuf_new(&sb, outbuf, (int)outbuflen, SBUF_FIXEDLEN) == NULL) {
1043 		/* could not allocate interior buffer */
1044 		error = ENOMEM;
1045 		goto out;
1046 	}
1047 	/* iterate the scratch buffer; NOTE: buffer contents modified! */
1048 	while ((element = strsep(&scratch, ",")) != NULL) {
1049 		error = mac_label_externalize(mpo_externalize_off, label,
1050 		    element, &sb);
1051 		if (error) {
1052 			break;
1053 		}
1054 	}
1055 	if ((len = sbuf_len(&sb)) > 0) {
1056 		sbuf_setpos(&sb, len - 1);      /* trim trailing comma */
1057 	}
1058 	sbuf_finish(&sb);
1059 
1060 out:
1061 	if (scratch_base != NULL) {
1062 		kfree_data(scratch_base, buf_len);
1063 	}
1064 
1065 	return error;
1066 }
1067 
1068 /*
1069  * Have all policies set the internal form of a label, for a single
1070  * label namespace.
1071  */
1072 static int
mac_label_internalize(size_t mpo_internalize_off,struct label * label,char * element_name,char * element_data)1073 mac_label_internalize(size_t mpo_internalize_off, struct label *label,
1074     char *element_name, char *element_data)
1075 {
1076 	struct mac_policy_conf *mpc;
1077 	struct mac_label_listener *mll;
1078 	struct mac_label_element *mle;
1079 	struct mac_label_element_list_t *element_list;
1080 	int (*mpo_internalize)(struct label *, char *, char *);
1081 	int error = 0, busy = FALSE;
1082 	unsigned int count = 0;
1083 	const char *name;
1084 
1085 	element_list = &mac_static_label_element_list;
1086 element_loop:
1087 	SLIST_FOREACH(mle, element_list, mle_list) {
1088 		if (*(name = mle->mle_name) == '?') {
1089 			name++;
1090 		}
1091 		if (strcmp(element_name, name) != 0) {
1092 			continue;
1093 		}
1094 		SLIST_FOREACH(mll, &mle->mle_listeners, mll_list) {
1095 			mpc = mac_policy_list.entries[mll->mll_handle].mpc;
1096 			if (mpc == NULL) {
1097 				continue;
1098 			}
1099 			mpo_internalize = *(const typeof(mpo_internalize) *)
1100 			    ((const char *)mpc->mpc_ops + mpo_internalize_off);
1101 			if (mpo_internalize == NULL) {
1102 				continue;
1103 			}
1104 			error = mpo_internalize(label, element_name,
1105 			    element_data);
1106 			if (error) {
1107 				goto done;
1108 			}
1109 			count++;
1110 		}
1111 	}
1112 	/* If there are dynamic policies present, check their elements too. */
1113 	if (!busy && mac_policy_list_conditional_busy() == 1) {
1114 		element_list = &mac_label_element_list;
1115 		busy = TRUE;
1116 		goto element_loop;
1117 	}
1118 done:
1119 	if (busy) {
1120 		mac_policy_list_unbusy();
1121 	}
1122 	if (!error && count == 0) {
1123 		error = ENOPOLICY;
1124 	}
1125 	return error;
1126 }
1127 
1128 int
mac_internalize(size_t mpo_internalize_off,struct label * label,char * textlabels)1129 mac_internalize(size_t mpo_internalize_off, struct label *label,
1130     char *textlabels)
1131 {
1132 	char *element_name, *element_data;
1133 	int error = 0;
1134 
1135 	while (!error && (element_name = strsep(&textlabels, ",")) != NULL) {
1136 		element_data = strchr(element_name, '/');
1137 		if (element_data == NULL) {
1138 			error = EINVAL;
1139 			break;
1140 		}
1141 		*element_data++ = '\0';
1142 		error = mac_label_internalize(mpo_internalize_off, label,
1143 		    element_name, element_data);
1144 	}
1145 	return error;
1146 }
1147 
1148 static int
user_mac_copyin(struct proc * p,user_addr_t mac_p,struct user_mac * mac)1149 user_mac_copyin(struct proc *p, user_addr_t mac_p, struct user_mac *mac)
1150 {
1151 	int error;
1152 
1153 	if (IS_64BIT_PROCESS(p)) {
1154 		struct user64_mac mac64;
1155 		if ((error = copyin(mac_p, &mac64, sizeof(mac64)))) {
1156 			return error;
1157 		}
1158 
1159 		mac->m_buflen = mac64.m_buflen;
1160 		mac->m_string = mac64.m_string;
1161 	} else {
1162 		struct user32_mac mac32;
1163 		if ((error = copyin(mac_p, &mac32, sizeof(mac32)))) {
1164 			return error;
1165 		}
1166 
1167 		mac->m_buflen = mac32.m_buflen;
1168 		mac->m_string = mac32.m_string;
1169 	}
1170 
1171 	return mac_check_structmac_consistent(mac);
1172 }
1173 
1174 int
mac_do_get(struct proc * p,user_addr_t mac_p,mac_getter_t getter)1175 mac_do_get(struct proc *p, user_addr_t mac_p, mac_getter_t getter)
1176 {
1177 	struct user_mac mac;
1178 	char *input;
1179 	char *output;
1180 	size_t len;
1181 	size_t ulen;
1182 	int error;
1183 
1184 	if ((error = user_mac_copyin(p, mac_p, &mac))) {
1185 		return error;
1186 	}
1187 
1188 	len = mac.m_buflen;
1189 	input = kalloc_data(len, Z_WAITOK);
1190 	if ((error = copyinstr(mac.m_string, input, len, &ulen))) {
1191 		kfree_data(input, len);
1192 		return error;
1193 	}
1194 
1195 	AUDIT_ARG(mac_string, input);
1196 
1197 	output = kalloc_data(len, Z_WAITOK | Z_ZERO);
1198 
1199 	error = getter(input, output, len);
1200 	if (error == 0) {
1201 		/* mac_check_structmac_consistent => len > 0 */
1202 		output[len - 1] = '\0';
1203 		error = copyout(output, mac.m_string, strlen(output) + 1);
1204 	}
1205 
1206 	kfree_data(output, len);
1207 	kfree_data(input, len);
1208 	return error;
1209 }
1210 
1211 int
mac_do_set(struct proc * p,user_addr_t mac_p,mac_setter_t setter)1212 mac_do_set(struct proc *p, user_addr_t mac_p, mac_setter_t setter)
1213 {
1214 	struct user_mac mac;
1215 	char *input;
1216 	size_t len;
1217 	size_t ulen;
1218 	int error;
1219 
1220 	if ((error = user_mac_copyin(p, mac_p, &mac))) {
1221 		return error;
1222 	}
1223 
1224 	len = mac.m_buflen;
1225 	input = kalloc_data(len, Z_WAITOK);
1226 	if ((error = copyinstr(mac.m_string, input, len, &ulen))) {
1227 		kfree_data(input, len);
1228 		return error;
1229 	}
1230 
1231 	AUDIT_ARG(mac_string, input);
1232 
1233 	error = setter(input, len);
1234 
1235 	kfree_data(input, len);
1236 	return error;
1237 }
1238 
1239 /* system calls */
1240 
1241 int
__mac_get_pid(struct proc * p,struct __mac_get_pid_args * uap,int * ret __unused)1242 __mac_get_pid(struct proc *p, struct __mac_get_pid_args *uap, int *ret __unused)
1243 {
1244 	return mac_do_get(p, uap->mac_p,
1245 	           ^(char *input, char *output, size_t len) {
1246 		struct proc *tproc;
1247 		struct ucred *tcred;
1248 		int error;
1249 
1250 		AUDIT_ARG(pid, uap->pid);
1251 
1252 		tproc = proc_find(uap->pid);
1253 		if (tproc == NULL) {
1254 		        return ESRCH;
1255 		}
1256 
1257 		tcred = kauth_cred_proc_ref(tproc);
1258 		proc_rele(tproc);
1259 
1260 		error = mac_cred_label_externalize(mac_cred_label(tcred),
1261 		input, output, len, M_WAITOK);
1262 
1263 		kauth_cred_unref(&tcred);
1264 		return error;
1265 	});
1266 }
1267 
1268 int
__mac_get_proc(proc_t p,struct __mac_get_proc_args * uap,int * ret __unused)1269 __mac_get_proc(proc_t p, struct __mac_get_proc_args *uap, int *ret __unused)
1270 {
1271 	return mac_do_get(p, uap->mac_p,
1272 	           ^(char *input, char *output, size_t len) {
1273 		struct label *label;
1274 
1275 		label = mac_cred_label(kauth_cred_get());
1276 
1277 		return mac_cred_label_externalize(label, input, output, len, M_WAITOK);
1278 	});
1279 }
1280 
1281 int
__mac_set_proc(proc_t p,struct __mac_set_proc_args * uap,int * ret __unused)1282 __mac_set_proc(proc_t p, struct __mac_set_proc_args *uap, int *ret __unused)
1283 {
1284 	return mac_do_set(p, uap->mac_p,
1285 	           ^(char *input, __unused size_t len) {
1286 		struct label *intlabel;
1287 		int error;
1288 
1289 		intlabel = mac_cred_label_alloc();
1290 		if ((error = mac_cred_label_internalize(intlabel, input))) {
1291 		        goto out;
1292 		}
1293 
1294 		if ((error = mac_cred_check_label_update(kauth_cred_get(), intlabel))) {
1295 		        goto out;
1296 		}
1297 
1298 		error = kauth_proc_label_update(p, intlabel);
1299 
1300 		out:
1301 		mac_cred_label_free(intlabel);
1302 		return error;
1303 	});
1304 }
1305 
1306 int
__mac_get_fd(proc_t p,struct __mac_get_fd_args * uap,int * ret __unused)1307 __mac_get_fd(proc_t p, struct __mac_get_fd_args *uap, int *ret __unused)
1308 {
1309 	return mac_do_get(p, uap->mac_p,
1310 	           ^(char *input, char *output, size_t len) {
1311 		struct fileproc *fp;
1312 		struct vnode *vp;
1313 		int error;
1314 		struct label *intlabel;
1315 
1316 		AUDIT_ARG(fd, uap->fd);
1317 
1318 		if ((error = fp_lookup(p, uap->fd, &fp, 0))) {
1319 		        return error;
1320 		}
1321 
1322 		error = mac_file_check_get(kauth_cred_get(), fp->fp_glob, input, len);
1323 		if (error) {
1324 		        fp_drop(p, uap->fd, fp, 0);
1325 		        return error;
1326 		}
1327 
1328 		switch (FILEGLOB_DTYPE(fp->fp_glob)) {
1329 		case DTYPE_VNODE:
1330 			intlabel = mac_vnode_label_alloc(NULL);
1331 			if (intlabel == NULL) {
1332 			        error = ENOMEM;
1333 			        break;
1334 			}
1335 			vp = (struct vnode *)fp_get_data(fp);
1336 			error = vnode_getwithref(vp);
1337 			if (error == 0) {
1338 			        mac_vnode_label_copy(mac_vnode_label(vp), intlabel);
1339 			        error = mac_vnode_label_externalize(intlabel,
1340 			        input, output, len, M_WAITOK);
1341 			        vnode_put(vp);
1342 			}
1343 			mac_vnode_label_free(intlabel);
1344 			break;
1345 		case DTYPE_SOCKET:
1346 		case DTYPE_PSXSHM:
1347 		case DTYPE_PSXSEM:
1348 		case DTYPE_PIPE:
1349 		case DTYPE_KQUEUE:
1350 		case DTYPE_FSEVENTS:
1351 		case DTYPE_ATALK:
1352 		case DTYPE_NETPOLICY:
1353 		case DTYPE_CHANNEL:
1354 		case DTYPE_NEXUS:
1355 		default:
1356 			error = ENOSYS;           // only sockets/vnodes so far
1357 			break;
1358 		}
1359 		fp_drop(p, uap->fd, fp, 0);
1360 		return error;
1361 	});
1362 }
1363 
1364 static int
mac_get_filelink(proc_t p,user_addr_t mac_p,user_addr_t path_p,int follow)1365 mac_get_filelink(proc_t p, user_addr_t mac_p, user_addr_t path_p, int follow)
1366 {
1367 	return mac_do_get(p, mac_p,
1368 	           ^(char *input, char *output, size_t len) {
1369 		struct vnode *vp;
1370 		struct nameidata nd;
1371 		struct label *intlabel;
1372 		int error;
1373 
1374 		NDINIT(&nd, LOOKUP, OP_LOOKUP,
1375 		LOCKLEAF | (follow ? FOLLOW : NOFOLLOW) | AUDITVNPATH1,
1376 		UIO_USERSPACE, path_p,
1377 		vfs_context_current());
1378 		if ((error = namei(&nd))) {
1379 		        return error;
1380 		}
1381 		vp = nd.ni_vp;
1382 
1383 		nameidone(&nd);
1384 
1385 		intlabel = mac_vnode_label_alloc(NULL);
1386 		mac_vnode_label_copy(mac_vnode_label(vp), intlabel);
1387 		error = mac_vnode_label_externalize(intlabel, input, output,
1388 		len, M_WAITOK);
1389 		mac_vnode_label_free(intlabel);
1390 
1391 		vnode_put(vp);
1392 		return error;
1393 	});
1394 }
1395 
1396 int
__mac_get_file(proc_t p,struct __mac_get_file_args * uap,int * ret __unused)1397 __mac_get_file(proc_t p, struct __mac_get_file_args *uap,
1398     int *ret __unused)
1399 {
1400 	return mac_get_filelink(p, uap->mac_p, uap->path_p, 1);
1401 }
1402 
1403 int
__mac_get_link(proc_t p,struct __mac_get_link_args * uap,int * ret __unused)1404 __mac_get_link(proc_t p, struct __mac_get_link_args *uap,
1405     int *ret __unused)
1406 {
1407 	return mac_get_filelink(p, uap->mac_p, uap->path_p, 0);
1408 }
1409 
1410 int
__mac_set_fd(proc_t p,struct __mac_set_fd_args * uap,int * ret __unused)1411 __mac_set_fd(proc_t p, struct __mac_set_fd_args *uap, int *ret __unused)
1412 {
1413 	return mac_do_set(p, uap->mac_p,
1414 	           ^(char *input, size_t len) {
1415 		struct fileproc *fp;
1416 		struct vfs_context *ctx = vfs_context_current();
1417 		int error;
1418 		struct label *intlabel;
1419 		struct vnode *vp;
1420 
1421 		AUDIT_ARG(fd, uap->fd);
1422 
1423 		if ((error = fp_lookup(p, uap->fd, &fp, 0))) {
1424 		        return error;
1425 		}
1426 
1427 		error = mac_file_check_set(vfs_context_ucred(ctx), fp->fp_glob, input, len);
1428 		if (error) {
1429 		        fp_drop(p, uap->fd, fp, 0);
1430 		        return error;
1431 		}
1432 
1433 		switch (FILEGLOB_DTYPE(fp->fp_glob)) {
1434 		case DTYPE_VNODE:
1435 			if (mac_label_vnodes == 0) {
1436 			        error = ENOSYS;
1437 			        break;
1438 			}
1439 
1440 			intlabel = mac_vnode_label_alloc(NULL);
1441 
1442 			error = mac_vnode_label_internalize(intlabel, input);
1443 			if (error) {
1444 			        mac_vnode_label_free(intlabel);
1445 			        break;
1446 			}
1447 
1448 			vp = (struct vnode *)fp_get_data(fp);
1449 
1450 			error = vnode_getwithref(vp);
1451 			if (error == 0) {
1452 			        error = vn_setlabel(vp, intlabel, ctx);
1453 			        vnode_put(vp);
1454 			}
1455 			mac_vnode_label_free(intlabel);
1456 			break;
1457 
1458 		case DTYPE_SOCKET:
1459 		case DTYPE_PSXSHM:
1460 		case DTYPE_PSXSEM:
1461 		case DTYPE_PIPE:
1462 		case DTYPE_KQUEUE:
1463 		case DTYPE_FSEVENTS:
1464 		case DTYPE_ATALK:
1465 		case DTYPE_NETPOLICY:
1466 		case DTYPE_CHANNEL:
1467 		case DTYPE_NEXUS:
1468 		default:
1469 			error = ENOSYS;          // only sockets/vnodes so far
1470 			break;
1471 		}
1472 
1473 		fp_drop(p, uap->fd, fp, 0);
1474 		return error;
1475 	});
1476 }
1477 
1478 static int
mac_set_filelink(proc_t p,user_addr_t mac_p,user_addr_t path_p,int follow)1479 mac_set_filelink(proc_t p, user_addr_t mac_p, user_addr_t path_p,
1480     int follow)
1481 {
1482 	return mac_do_set(p, mac_p,
1483 	           ^(char *input, __unused size_t len) {
1484 		struct vnode *vp;
1485 		struct vfs_context *ctx = vfs_context_current();
1486 		struct label *intlabel;
1487 		struct nameidata nd;
1488 		int error;
1489 
1490 		if (mac_label_vnodes == 0) {
1491 		        return ENOSYS;
1492 		}
1493 
1494 		intlabel = mac_vnode_label_alloc(NULL);
1495 		error = mac_vnode_label_internalize(intlabel, input);
1496 		if (error) {
1497 		        mac_vnode_label_free(intlabel);
1498 		        return error;
1499 		}
1500 
1501 		NDINIT(&nd, LOOKUP, OP_LOOKUP,
1502 		LOCKLEAF | (follow ? FOLLOW : NOFOLLOW) | AUDITVNPATH1,
1503 		UIO_USERSPACE, path_p, ctx);
1504 		error = namei(&nd);
1505 		if (error) {
1506 		        mac_vnode_label_free(intlabel);
1507 		        return error;
1508 		}
1509 		vp = nd.ni_vp;
1510 
1511 		nameidone(&nd);
1512 
1513 		error = vn_setlabel(vp, intlabel, ctx);
1514 		vnode_put(vp);
1515 		mac_vnode_label_free(intlabel);
1516 
1517 		return error;
1518 	});
1519 }
1520 
1521 int
__mac_set_file(proc_t p,struct __mac_set_file_args * uap,int * ret __unused)1522 __mac_set_file(proc_t p, struct __mac_set_file_args *uap,
1523     int *ret __unused)
1524 {
1525 	return mac_set_filelink(p, uap->mac_p, uap->path_p, 1);
1526 }
1527 
1528 int
__mac_set_link(proc_t p,struct __mac_set_link_args * uap,int * ret __unused)1529 __mac_set_link(proc_t p, struct __mac_set_link_args *uap,
1530     int *ret __unused)
1531 {
1532 	return mac_set_filelink(p, uap->mac_p, uap->path_p, 0);
1533 }
1534 
1535 static int
mac_proc_check_mac_syscall(proc_t p,const char * target,int callnum)1536 mac_proc_check_mac_syscall(proc_t p, const char *target, int callnum)
1537 {
1538 	int error;
1539 
1540 #if SECURITY_MAC_CHECK_ENFORCE
1541 	/* 21167099 - only check if we allow write */
1542 	if (!mac_proc_enforce) {
1543 		return 0;
1544 	}
1545 #endif
1546 
1547 	MAC_CHECK(proc_check_syscall_mac, p, target, callnum);
1548 
1549 	return error;
1550 }
1551 
1552 /*
1553  * __mac_syscall: Perform a MAC policy system call
1554  *
1555  * Parameters:    p                       Process calling this routine
1556  *                uap                     User argument descriptor (see below)
1557  *                retv                    (Unused)
1558  *
1559  * Indirect:      uap->policy             Name of target MAC policy
1560  *                uap->call               MAC policy-specific system call to perform
1561  *                uap->arg                MAC policy-specific system call arguments
1562  *
1563  * Returns:        0                      Success
1564  *                !0                      Not success
1565  *
1566  */
1567 int
__mac_syscall(proc_t p,struct __mac_syscall_args * uap,int * retv __unused)1568 __mac_syscall(proc_t p, struct __mac_syscall_args *uap, int *retv __unused)
1569 {
1570 	struct mac_policy_conf *mpc;
1571 	char target[MAC_MAX_POLICY_NAME];
1572 	int error;
1573 	u_int i;
1574 	size_t ulen;
1575 
1576 	error = copyinstr(uap->policy, target, sizeof(target), &ulen);
1577 	if (error) {
1578 		return error;
1579 	}
1580 	AUDIT_ARG(value32, uap->call);
1581 	AUDIT_ARG(mac_string, target);
1582 
1583 	error = mac_proc_check_mac_syscall(p, target, uap->call);
1584 	if (error) {
1585 		return error;
1586 	}
1587 
1588 	error = ENOPOLICY;
1589 
1590 	for (i = 0; i < mac_policy_list.staticmax; i++) {
1591 		mpc = mac_policy_list.entries[i].mpc;
1592 		if (mpc == NULL) {
1593 			continue;
1594 		}
1595 
1596 		if (strcmp(mpc->mpc_name, target) == 0 &&
1597 		    mpc->mpc_ops->mpo_policy_syscall != NULL) {
1598 			error = mpc->mpc_ops->mpo_policy_syscall(p,
1599 			    uap->call, uap->arg);
1600 			goto done;
1601 		}
1602 	}
1603 	if (mac_policy_list_conditional_busy() != 0) {
1604 		for (; i <= mac_policy_list.maxindex; i++) {
1605 			mpc = mac_policy_list.entries[i].mpc;
1606 			if (mpc == NULL) {
1607 				continue;
1608 			}
1609 
1610 			if (strcmp(mpc->mpc_name, target) == 0 &&
1611 			    mpc->mpc_ops->mpo_policy_syscall != NULL) {
1612 				error = mpc->mpc_ops->mpo_policy_syscall(p,
1613 				    uap->call, uap->arg);
1614 				break;
1615 			}
1616 		}
1617 		mac_policy_list_unbusy();
1618 	}
1619 
1620 done:
1621 	return error;
1622 }
1623 
1624 int
mac_mount_label_get(struct mount * mp,user_addr_t mac_p)1625 mac_mount_label_get(struct mount *mp, user_addr_t mac_p)
1626 {
1627 	return mac_do_get(current_proc(), mac_p,
1628 	           ^(char *input, char *output, size_t len) {
1629 		return mac_mount_label_externalize(mac_mount_label(mp), input,
1630 		output, len);
1631 	});
1632 }
1633 
1634 /*
1635  * __mac_get_mount: Get mount point label information for a given pathname
1636  *
1637  * Parameters:    p                        (ignored)
1638  *                uap                      User argument descriptor (see below)
1639  *                ret                      (ignored)
1640  *
1641  * Indirect:      uap->path                Pathname
1642  *                uap->mac_p               MAC info
1643  *
1644  * Returns:        0                       Success
1645  *                !0                       Not success
1646  */
1647 int
__mac_get_mount(proc_t p __unused,struct __mac_get_mount_args * uap,int * ret __unused)1648 __mac_get_mount(proc_t p __unused, struct __mac_get_mount_args *uap,
1649     int *ret __unused)
1650 {
1651 	struct nameidata nd;
1652 	struct vfs_context *ctx = vfs_context_current();
1653 	struct mount *mp;
1654 	int error;
1655 
1656 	NDINIT(&nd, LOOKUP, OP_LOOKUP, FOLLOW | AUDITVNPATH1,
1657 	    UIO_USERSPACE, uap->path, ctx);
1658 	error = namei(&nd);
1659 	if (error) {
1660 		return error;
1661 	}
1662 	mp = nd.ni_vp->v_mount;
1663 	mount_ref(mp, 0);
1664 	vnode_put(nd.ni_vp);
1665 	nameidone(&nd);
1666 
1667 	error = mac_mount_label_get(mp, uap->mac_p);
1668 	mount_drop(mp, 0);
1669 	return error;
1670 }
1671 
1672 /*
1673  * mac_schedule_userret()
1674  *
1675  * Schedule a callback to the mpo_thread_userret hook. The mpo_thread_userret
1676  * hook is called just before the thread exit from the kernel in ast_taken().
1677  *
1678  * Returns:	 0		Success
1679  *              !0		Not successful
1680  */
1681 int
mac_schedule_userret(void)1682 mac_schedule_userret(void)
1683 {
1684 	act_set_astmacf(current_thread());
1685 	return 0;
1686 }
1687 
1688 /*
1689  * mac_do_machexc()
1690  *
1691  * Do a Mach exception.  This should only be done in the mpo_thread_userret
1692  * callback.
1693  *
1694  * params:	code		exception code
1695  *              subcode		exception subcode
1696  *              flags		flags:
1697  *                              MAC_DOEXCF_TRACED  Only do exception if being
1698  *                                                 ptrace()'ed.
1699  *
1700  *
1701  * Returns:	 0		Success
1702  *              !0		Not successful
1703  */
1704 int
mac_do_machexc(int64_t code,int64_t subcode,uint32_t flags)1705 mac_do_machexc(int64_t code, int64_t subcode, uint32_t flags)
1706 {
1707 	mach_exception_data_type_t  codes[EXCEPTION_CODE_MAX];
1708 	proc_t p = current_proc();
1709 
1710 	/* Only allow execption codes in MACF's reserved range. */
1711 	if ((code < EXC_MACF_MIN) || (code > EXC_MACF_MAX)) {
1712 		return 1;
1713 	}
1714 
1715 	if (flags & MAC_DOEXCF_TRACED &&
1716 	    !(p->p_lflag & P_LTRACED && (p->p_lflag & P_LPPWAIT) == 0)) {
1717 		return 0;
1718 	}
1719 
1720 
1721 	/* Send the Mach exception */
1722 	codes[0] = (mach_exception_data_type_t)code;
1723 	codes[1] = (mach_exception_data_type_t)subcode;
1724 
1725 	return bsd_exception(EXC_SOFTWARE, codes, 2) != KERN_SUCCESS;
1726 }
1727 
1728 #else /* MAC */
1729 
1730 void (*load_security_extensions_function)(void) = 0;
1731 
1732 struct sysctl_oid_list sysctl__security_mac_children;
1733 
1734 int
mac_policy_register(struct mac_policy_conf * mpc __unused,mac_policy_handle_t * handlep __unused,void * xd __unused)1735 mac_policy_register(struct mac_policy_conf *mpc __unused,
1736     mac_policy_handle_t *handlep __unused, void *xd __unused)
1737 {
1738 	return 0;
1739 }
1740 
1741 int
mac_policy_unregister(mac_policy_handle_t handle __unused)1742 mac_policy_unregister(mac_policy_handle_t handle __unused)
1743 {
1744 	return 0;
1745 }
1746 
1747 int
mac_audit_text(char * text __unused,mac_policy_handle_t handle __unused)1748 mac_audit_text(char *text __unused, mac_policy_handle_t handle __unused)
1749 {
1750 	return 0;
1751 }
1752 
1753 int
mac_vnop_setxattr(struct vnode * vp __unused,const char * name __unused,char * buf __unused,size_t len __unused)1754 mac_vnop_setxattr(struct vnode *vp __unused, const char *name __unused, char *buf __unused, size_t len __unused)
1755 {
1756 	return ENOENT;
1757 }
1758 
1759 int
mac_vnop_getxattr(struct vnode * vp __unused,const char * name __unused,char * buf __unused,size_t len __unused,size_t * attrlen __unused)1760 mac_vnop_getxattr(struct vnode *vp __unused, const char *name __unused,
1761     char *buf __unused, size_t len __unused, size_t *attrlen __unused)
1762 {
1763 	return ENOENT;
1764 }
1765 
1766 int
mac_vnop_removexattr(struct vnode * vp __unused,const char * name __unused)1767 mac_vnop_removexattr(struct vnode *vp __unused, const char *name __unused)
1768 {
1769 	return ENOENT;
1770 }
1771 
1772 int
mac_file_setxattr(struct fileglob * fg __unused,const char * name __unused,char * buf __unused,size_t len __unused)1773 mac_file_setxattr(struct fileglob *fg __unused, const char *name __unused, char *buf __unused, size_t len __unused)
1774 {
1775 	return ENOENT;
1776 }
1777 
1778 int
mac_file_getxattr(struct fileglob * fg __unused,const char * name __unused,char * buf __unused,size_t len __unused,size_t * attrlen __unused)1779 mac_file_getxattr(struct fileglob *fg __unused, const char *name __unused,
1780     char *buf __unused, size_t len __unused, size_t *attrlen __unused)
1781 {
1782 	return ENOENT;
1783 }
1784 
1785 int
mac_file_removexattr(struct fileglob * fg __unused,const char * name __unused)1786 mac_file_removexattr(struct fileglob *fg __unused, const char *name __unused)
1787 {
1788 	return ENOENT;
1789 }
1790 
1791 intptr_t
mac_label_get(struct label * l __unused,int slot __unused)1792 mac_label_get(struct label *l __unused, int slot __unused)
1793 {
1794 	return 0;
1795 }
1796 
1797 void
mac_label_set(struct label * l __unused,int slot __unused,intptr_t v __unused)1798 mac_label_set(struct label *l __unused, int slot __unused, intptr_t v __unused)
1799 {
1800 	return;
1801 }
1802 
1803 int mac_iokit_check_hid_control(kauth_cred_t cred __unused);
1804 int
mac_iokit_check_hid_control(kauth_cred_t cred __unused)1805 mac_iokit_check_hid_control(kauth_cred_t cred __unused)
1806 {
1807 	return 0;
1808 }
1809 
1810 int mac_vnode_check_open(vfs_context_t ctx, struct vnode *vp, int acc_mode);
1811 int
mac_vnode_check_open(vfs_context_t ctx __unused,struct vnode * vp __unused,int acc_mode __unused)1812 mac_vnode_check_open(vfs_context_t ctx __unused, struct vnode *vp __unused, int acc_mode __unused)
1813 {
1814 	return 0;
1815 }
1816 
1817 int mac_mount_check_snapshot_mount(vfs_context_t ctx, struct vnode *rvp, struct vnode *vp, struct componentname *cnp,
1818     const char *name, const char *vfc_name);
1819 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)1820 mac_mount_check_snapshot_mount(vfs_context_t ctx __unused, struct vnode *rvp __unused, struct vnode *vp __unused,
1821     struct componentname *cnp __unused, const char *name __unused, const char *vfc_name __unused)
1822 {
1823 	return 0;
1824 }
1825 
1826 int mac_vnode_check_trigger_resolve(vfs_context_t ctx __unused, struct vnode *dvp __unused, struct componentname *cnp __unused);
1827 int
mac_vnode_check_trigger_resolve(vfs_context_t ctx __unused,struct vnode * dvp __unused,struct componentname * cnp __unused)1828 mac_vnode_check_trigger_resolve(vfs_context_t ctx __unused, struct vnode *dvp __unused, struct componentname *cnp __unused)
1829 {
1830 	return 0;
1831 }
1832 
1833 #endif /* !MAC */
1834