1 /*-
2  * Copyright (c) 1999-2002, 2006 Robert N. M. Watson
3  * Copyright (c) 2001 Ilmar S. Habibulin
4  * Copyright (c) 2001-2005 Networks Associates Technology, Inc.
5  * Copyright (c) 2005-2006 SPARTA, Inc.
6  * Copyright (c) 2008-2009 Apple Inc.
7  * All rights reserved.
8  *
9  * This software was developed by Robert Watson and Ilmar Habibulin for the
10  * TrustedBSD Project.
11  *
12  * This software was developed for the FreeBSD Project in part by Network
13  * Associates Laboratories, the Security Research Division of Network
14  * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"),
15  * as part of the DARPA CHATS research program.
16  *
17  * This software was enhanced by SPARTA ISSO under SPAWAR contract
18  * N66001-04-C-6019 ("SEFOS").
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  * 1. Redistributions of source code must retain the above copyright
24  *    notice, this list of conditions and the following disclaimer.
25  * 2. Redistributions in binary form must reproduce the above copyright
26  *    notice, this list of conditions and the following disclaimer in the
27  *    documentation and/or other materials provided with the distribution.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
30  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
33  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
35  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
37  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
38  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39  * SUCH DAMAGE.
40  */
41 
42 /*-
43  * Framework for extensible kernel access control.  This file contains core
44  * kernel infrastructure for the TrustedBSD MAC Framework, including policy
45  * registration, versioning, locking, error composition operator, and system
46  * calls.
47  *
48  * The MAC Framework implements three programming interfaces:
49  *
50  * - The kernel MAC interface, defined in mac_framework.h, and invoked
51  *   throughout the kernel to request security decisions, notify of security
52  *   related events, etc.
53  *
54  * - The MAC policy module interface, defined in mac_policy.h, which is
55  *   implemented by MAC policy modules and invoked by the MAC Framework to
56  *   forward kernel security requests and notifications to policy modules.
57  *
58  * - The user MAC API, defined in mac.h, which allows user programs to query
59  *   and set label state on objects.
60  *
61  * The majority of the MAC Framework implementation may be found in
62  * src/sys/security/mac.  Sample policy modules may be found in
63  * src/sys/security/mac_*.
64  */
65 
66 #include "opt_mac.h"
67 
68 #include <sys/cdefs.h>
69 __FBSDID("$FreeBSD$");
70 
71 #include <sys/param.h>
72 #include <sys/condvar.h>
73 #include <sys/kernel.h>
74 #include <sys/lock.h>
75 #include <sys/mutex.h>
76 #include <sys/mac.h>
77 #include <sys/module.h>
78 #include <sys/systm.h>
79 #include <sys/sysctl.h>
80 
81 #include <security/mac/mac_framework.h>
82 #include <security/mac/mac_internal.h>
83 #include <security/mac/mac_policy.h>
84 
85 /*
86  * Root sysctl node for all MAC and MAC policy controls.
87  */
88 SYSCTL_NODE(_security, OID_AUTO, mac, CTLFLAG_RW, 0,
89     "TrustedBSD MAC policy controls");
90 
91 /*
92  * Declare that the kernel provides MAC support, version 3 (FreeBSD 7.x).
93  * This permits modules to refuse to be loaded if the necessary support isn't
94  * present, even if it's pre-boot.
95  */
96 MODULE_VERSION(kernel_mac_support, MAC_VERSION);
97 
98 static unsigned int	mac_version = MAC_VERSION;
99 SYSCTL_UINT(_security_mac, OID_AUTO, version, CTLFLAG_RD, &mac_version, 0,
100     "");
101 
102 /*
103  * Labels consist of a indexed set of "slots", which are allocated policies
104  * as required.  The MAC Framework maintains a bitmask of slots allocated so
105  * far to prevent reuse.  Slots cannot be reused, as the MAC Framework
106  * guarantees that newly allocated slots in labels will be NULL unless
107  * otherwise initialized, and because we do not have a mechanism to garbage
108  * collect slots on policy unload.  As labeled policies tend to be statically
109  * loaded during boot, and not frequently unloaded and reloaded, this is not
110  * generally an issue.
111  */
112 #if MAC_MAX_SLOTS > 32
113 #error "MAC_MAX_SLOTS too large"
114 #endif
115 
116 static unsigned int mac_max_slots = MAC_MAX_SLOTS;
117 static unsigned int mac_slot_offsets_free = (1 << MAC_MAX_SLOTS) - 1;
118 SYSCTL_UINT(_security_mac, OID_AUTO, max_slots, CTLFLAG_RD, &mac_max_slots,
119     0, "");
120 
121 /*
122  * Has the kernel started generating labeled objects yet?  All read/write
123  * access to this variable is serialized during the boot process.  Following
124  * the end of serialization, we don't update this flag; no locking.
125  */
126 static int	mac_late = 0;
127 
128 /*
129  * Each policy declares a mask of object types requiring labels to be
130  * allocated for them.  For convenience, we combine and cache the bitwise or
131  * of the per-policy object flags to track whether we will allocate a label
132  * for an object type at run-time.
133  */
134 uint64_t	mac_labeled;
135 SYSCTL_QUAD(_security_mac, OID_AUTO, labeled, CTLFLAG_RD, &mac_labeled, 0,
136     "Mask of object types being labeled");
137 
138 MALLOC_DEFINE(M_MACTEMP, "mactemp", "MAC temporary label storage");
139 
140 /*
141  * mac_static_policy_list holds a list of policy modules that are not loaded
142  * while the system is "live", and cannot be unloaded.  These policies can be
143  * invoked without holding the busy count.
144  *
145  * mac_policy_list stores the list of dynamic policies.  A busy count is
146  * maintained for the list, stored in mac_policy_busy.  The busy count is
147  * protected by mac_policy_mtx; the list may be modified only while the busy
148  * count is 0, requiring that the lock be held to prevent new references to
149  * the list from being acquired.  For almost all operations, incrementing the
150  * busy count is sufficient to guarantee consistency, as the list cannot be
151  * modified while the busy count is elevated.  For a few special operations
152  * involving a change to the list of active policies, the mtx itself must be
153  * held.  A condition variable, mac_policy_cv, is used to signal potential
154  * exclusive consumers that they should try to acquire the lock if a first
155  * attempt at exclusive access fails.
156  *
157  * This design intentionally avoids fairness, and may starve attempts to
158  * acquire an exclusive lock on a busy system.  This is required because we
159  * do not ever want acquiring a read reference to perform an unbounded length
160  * sleep.  Read references are acquired in ithreads, network isrs, etc, and
161  * any unbounded blocking could lead quickly to deadlock.
162  *
163  * Another reason for never blocking on read references is that the MAC
164  * Framework may recurse: if a policy calls a VOP, for example, this might
165  * lead to vnode life cycle operations (such as init/destroy).
166  *
167  * If the kernel option MAC_STATIC has been compiled in, all locking becomes
168  * a no-op, and the global list of policies is not allowed to change after
169  * early boot.
170  *
171  * XXXRW: Currently, we signal mac_policy_cv every time the framework becomes
172  * unbusy and there is a thread waiting to enter it exclusively.  Since it
173  * may take some time before the thread runs, we may issue a lot of signals.
174  * We should instead keep track of the fact that we've signalled, taking into
175  * account that the framework may be busy again by the time the thread runs,
176  * requiring us to re-signal.
177  */
178 #ifndef MAC_STATIC
179 static struct mtx mac_policy_mtx;
180 static struct cv mac_policy_cv;
181 static int mac_policy_count;
182 static int mac_policy_wait;
183 #endif
184 struct mac_policy_list_head mac_policy_list;
185 struct mac_policy_list_head mac_static_policy_list;
186 
187 /*
188  * We manually invoke WITNESS_WARN() to allow Witness to generate warnings
189  * even if we don't end up ever triggering the wait at run-time.  The
190  * consumer of the exclusive interface must not hold any locks (other than
191  * potentially Giant) since we may sleep for long (potentially indefinite)
192  * periods of time waiting for the framework to become quiescent so that a
193  * policy list change may be made.
194  */
195 void
196 mac_policy_grab_exclusive(void)
197 {
198 
199 #ifndef MAC_STATIC
200 	if (!mac_late)
201 		return;
202 
203 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
204  	    "mac_policy_grab_exclusive() at %s:%d", __FILE__, __LINE__);
205 	mtx_lock(&mac_policy_mtx);
206 	while (mac_policy_count != 0) {
207 		mac_policy_wait++;
208 		cv_wait(&mac_policy_cv, &mac_policy_mtx);
209 		mac_policy_wait--;
210 	}
211 #endif
212 }
213 
214 void
215 mac_policy_assert_exclusive(void)
216 {
217 
218 #ifndef MAC_STATIC
219 	if (!mac_late)
220 		return;
221 
222 	mtx_assert(&mac_policy_mtx, MA_OWNED);
223 	KASSERT(mac_policy_count == 0,
224 	    ("mac_policy_assert_exclusive(): not exclusive"));
225 #endif
226 }
227 
228 void
229 mac_policy_release_exclusive(void)
230 {
231 #ifndef MAC_STATIC
232 	int dowakeup;
233 
234 	if (!mac_late)
235 		return;
236 
237 	KASSERT(mac_policy_count == 0,
238 	    ("mac_policy_release_exclusive(): not exclusive"));
239 	dowakeup = (mac_policy_wait != 0);
240 	mtx_unlock(&mac_policy_mtx);
241 	if (dowakeup)
242 		cv_signal(&mac_policy_cv);
243 #endif
244 }
245 
246 void
247 mac_policy_list_busy(void)
248 {
249 
250 #ifndef MAC_STATIC
251 	if (!mac_late)
252 		return;
253 
254 	mtx_lock(&mac_policy_mtx);
255 	mac_policy_count++;
256 	mtx_unlock(&mac_policy_mtx);
257 #endif
258 }
259 
260 int
261 mac_policy_list_conditional_busy(void)
262 {
263 #ifndef MAC_STATIC
264 	int ret;
265 
266 	if (!mac_late)
267 		return (1);
268 
269 	mtx_lock(&mac_policy_mtx);
270 	if (!LIST_EMPTY(&mac_policy_list)) {
271 		mac_policy_count++;
272 		ret = 1;
273 	} else
274 		ret = 0;
275 	mtx_unlock(&mac_policy_mtx);
276 	return (ret);
277 #else
278 	return (1);
279 #endif
280 }
281 
282 void
283 mac_policy_list_unbusy(void)
284 {
285 #ifndef MAC_STATIC
286 	int dowakeup;
287 
288 	if (!mac_late)
289 		return;
290 
291 	mtx_lock(&mac_policy_mtx);
292 	mac_policy_count--;
293 	KASSERT(mac_policy_count >= 0, ("MAC_POLICY_LIST_LOCK"));
294 	dowakeup = (mac_policy_count == 0 && mac_policy_wait != 0);
295 	mtx_unlock(&mac_policy_mtx);
296 
297 	if (dowakeup)
298 		cv_signal(&mac_policy_cv);
299 #endif
300 }
301 
302 /*
303  * Initialize the MAC subsystem, including appropriate SMP locks.
304  */
305 static void
306 mac_init(void)
307 {
308 
309 	LIST_INIT(&mac_static_policy_list);
310 	LIST_INIT(&mac_policy_list);
311 	mac_labelzone_init();
312 
313 #ifndef MAC_STATIC
314 	mtx_init(&mac_policy_mtx, "mac_policy_mtx", NULL, MTX_DEF);
315 	cv_init(&mac_policy_cv, "mac_policy_cv");
316 #endif
317 }
318 
319 /*
320  * For the purposes of modules that want to know if they were loaded "early",
321  * set the mac_late flag once we've processed modules either linked into the
322  * kernel, or loaded before the kernel startup.
323  */
324 static void
325 mac_late_init(void)
326 {
327 
328 	mac_late = 1;
329 }
330 
331 /*
332  * Given a policy, derive from its set of non-NULL label init methods what
333  * object types the policy is interested in.
334  */
335 static uint64_t
336 mac_policy_getlabeled(struct mac_policy_conf *mpc)
337 {
338 	uint64_t labeled;
339 
340 #define	MPC_FLAG(method, flag)					\
341 	if (mpc->mpc_ops->mpo_ ## method != NULL)			\
342 		labeled |= (flag);					\
343 
344 	labeled = 0;
345 	MPC_FLAG(cred_init_label, MPC_OBJECT_CRED);
346 	MPC_FLAG(proc_init_label, MPC_OBJECT_PROC);
347 	MPC_FLAG(vnode_init_label, MPC_OBJECT_VNODE);
348 	MPC_FLAG(inpcb_init_label, MPC_OBJECT_INPCB);
349 	MPC_FLAG(socket_init_label, MPC_OBJECT_SOCKET);
350 	MPC_FLAG(devfs_init_label, MPC_OBJECT_DEVFS);
351 	MPC_FLAG(mbuf_init_label, MPC_OBJECT_MBUF);
352 	MPC_FLAG(ipq_init_label, MPC_OBJECT_IPQ);
353 	MPC_FLAG(ifnet_init_label, MPC_OBJECT_IFNET);
354 	MPC_FLAG(bpfdesc_init_label, MPC_OBJECT_BPFDESC);
355 	MPC_FLAG(pipe_init_label, MPC_OBJECT_PIPE);
356 	MPC_FLAG(mount_init_label, MPC_OBJECT_MOUNT);
357 	MPC_FLAG(posixsem_init_label, MPC_OBJECT_POSIXSEM);
358 	MPC_FLAG(posixshm_init_label, MPC_OBJECT_POSIXSHM);
359 	MPC_FLAG(sysvmsg_init_label, MPC_OBJECT_SYSVMSG);
360 	MPC_FLAG(sysvmsq_init_label, MPC_OBJECT_SYSVMSQ);
361 	MPC_FLAG(sysvsem_init_label, MPC_OBJECT_SYSVSEM);
362 	MPC_FLAG(sysvshm_init_label, MPC_OBJECT_SYSVSHM);
363 	MPC_FLAG(syncache_init_label, MPC_OBJECT_SYNCACHE);
364 	MPC_FLAG(ip6q_init_label, MPC_OBJECT_IP6Q);
365 
366 #undef MPC_FLAG
367 	return (labeled);
368 }
369 
370 /*
371  * When policies are loaded or unloaded, walk the list of registered policies
372  * and built mac_labeled, a bitmask representing the union of all objects
373  * requiring labels across all policies.
374  */
375 static void
376 mac_policy_updateflags(void)
377 {
378 	struct mac_policy_conf *mpc;
379 
380 	mac_policy_assert_exclusive();
381 
382 	mac_labeled = 0;
383 	LIST_FOREACH(mpc, &mac_static_policy_list, mpc_list)
384 		mac_labeled |= mac_policy_getlabeled(mpc);
385 	LIST_FOREACH(mpc, &mac_policy_list, mpc_list)
386 		mac_labeled |= mac_policy_getlabeled(mpc);
387 }
388 
389 static int
390 mac_policy_register(struct mac_policy_conf *mpc)
391 {
392 	struct mac_policy_conf *tmpc;
393 	int error, slot, static_entry;
394 
395 	error = 0;
396 
397 	/*
398 	 * We don't technically need exclusive access while !mac_late, but
399 	 * hold it for assertion consistency.
400 	 */
401 	mac_policy_grab_exclusive();
402 
403 	/*
404 	 * If the module can potentially be unloaded, or we're loading late,
405 	 * we have to stick it in the non-static list and pay an extra
406 	 * performance overhead.  Otherwise, we can pay a light locking cost
407 	 * and stick it in the static list.
408 	 */
409 	static_entry = (!mac_late &&
410 	    !(mpc->mpc_loadtime_flags & MPC_LOADTIME_FLAG_UNLOADOK));
411 
412 	if (static_entry) {
413 		LIST_FOREACH(tmpc, &mac_static_policy_list, mpc_list) {
414 			if (strcmp(tmpc->mpc_name, mpc->mpc_name) == 0) {
415 				error = EEXIST;
416 				goto out;
417 			}
418 		}
419 	} else {
420 		LIST_FOREACH(tmpc, &mac_policy_list, mpc_list) {
421 			if (strcmp(tmpc->mpc_name, mpc->mpc_name) == 0) {
422 				error = EEXIST;
423 				goto out;
424 			}
425 		}
426 	}
427 	if (mpc->mpc_field_off != NULL) {
428 		slot = ffs(mac_slot_offsets_free);
429 		if (slot == 0) {
430 			error = ENOMEM;
431 			goto out;
432 		}
433 		slot--;
434 		mac_slot_offsets_free &= ~(1 << slot);
435 		*mpc->mpc_field_off = slot;
436 	}
437 	mpc->mpc_runtime_flags |= MPC_RUNTIME_FLAG_REGISTERED;
438 
439 	/*
440 	 * If we're loading a MAC module after the framework has initialized,
441 	 * it has to go into the dynamic list.  If we're loading it before
442 	 * we've finished initializing, it can go into the static list with
443 	 * weaker locker requirements.
444 	 */
445 	if (static_entry)
446 		LIST_INSERT_HEAD(&mac_static_policy_list, mpc, mpc_list);
447 	else
448 		LIST_INSERT_HEAD(&mac_policy_list, mpc, mpc_list);
449 
450 	/*
451 	 * Per-policy initialization.  Currently, this takes place under the
452 	 * exclusive lock, so policies must not sleep in their init method.
453 	 * In the future, we may want to separate "init" from "start", with
454 	 * "init" occuring without the lock held.  Likewise, on tear-down,
455 	 * breaking out "stop" from "destroy".
456 	 */
457 	if (mpc->mpc_ops->mpo_init != NULL)
458 		(*(mpc->mpc_ops->mpo_init))(mpc);
459 	mac_policy_updateflags();
460 
461 	printf("Security policy loaded: %s (%s)\n", mpc->mpc_fullname,
462 	    mpc->mpc_name);
463 
464 out:
465 	mac_policy_release_exclusive();
466 	return (error);
467 }
468 
469 static int
470 mac_policy_unregister(struct mac_policy_conf *mpc)
471 {
472 
473 	/*
474 	 * If we fail the load, we may get a request to unload.  Check to see
475 	 * if we did the run-time registration, and if not, silently succeed.
476 	 */
477 	mac_policy_grab_exclusive();
478 	if ((mpc->mpc_runtime_flags & MPC_RUNTIME_FLAG_REGISTERED) == 0) {
479 		mac_policy_release_exclusive();
480 		return (0);
481 	}
482 #if 0
483 	/*
484 	 * Don't allow unloading modules with private data.
485 	 */
486 	if (mpc->mpc_field_off != NULL) {
487 		MAC_POLICY_LIST_UNLOCK();
488 		return (EBUSY);
489 	}
490 #endif
491 	/*
492 	 * Only allow the unload to proceed if the module is unloadable by
493 	 * its own definition.
494 	 */
495 	if ((mpc->mpc_loadtime_flags & MPC_LOADTIME_FLAG_UNLOADOK) == 0) {
496 		mac_policy_release_exclusive();
497 		return (EBUSY);
498 	}
499 	if (mpc->mpc_ops->mpo_destroy != NULL)
500 		(*(mpc->mpc_ops->mpo_destroy))(mpc);
501 
502 	LIST_REMOVE(mpc, mpc_list);
503 	mpc->mpc_runtime_flags &= ~MPC_RUNTIME_FLAG_REGISTERED;
504 	mac_policy_updateflags();
505 
506 	mac_policy_release_exclusive();
507 
508 	printf("Security policy unload: %s (%s)\n", mpc->mpc_fullname,
509 	    mpc->mpc_name);
510 
511 	return (0);
512 }
513 
514 /*
515  * Allow MAC policy modules to register during boot, etc.
516  */
517 int
518 mac_policy_modevent(module_t mod, int type, void *data)
519 {
520 	struct mac_policy_conf *mpc;
521 	int error;
522 
523 	error = 0;
524 	mpc = (struct mac_policy_conf *) data;
525 
526 #ifdef MAC_STATIC
527 	if (mac_late) {
528 		printf("mac_policy_modevent: MAC_STATIC and late\n");
529 		return (EBUSY);
530 	}
531 #endif
532 
533 	switch (type) {
534 	case MOD_LOAD:
535 		if (mpc->mpc_loadtime_flags & MPC_LOADTIME_FLAG_NOTLATE &&
536 		    mac_late) {
537 			printf("mac_policy_modevent: can't load %s policy "
538 			    "after booting\n", mpc->mpc_name);
539 			error = EBUSY;
540 			break;
541 		}
542 		error = mac_policy_register(mpc);
543 		break;
544 	case MOD_UNLOAD:
545 		/* Don't unregister the module if it was never registered. */
546 		if ((mpc->mpc_runtime_flags & MPC_RUNTIME_FLAG_REGISTERED)
547 		    != 0)
548 			error = mac_policy_unregister(mpc);
549 		else
550 			error = 0;
551 		break;
552 	default:
553 		error = EOPNOTSUPP;
554 		break;
555 	}
556 
557 	return (error);
558 }
559 
560 /*
561  * Define an error value precedence, and given two arguments, selects the
562  * value with the higher precedence.
563  */
564 int
565 mac_error_select(int error1, int error2)
566 {
567 
568 	/* Certain decision-making errors take top priority. */
569 	if (error1 == EDEADLK || error2 == EDEADLK)
570 		return (EDEADLK);
571 
572 	/* Invalid arguments should be reported where possible. */
573 	if (error1 == EINVAL || error2 == EINVAL)
574 		return (EINVAL);
575 
576 	/* Precedence goes to "visibility", with both process and file. */
577 	if (error1 == ESRCH || error2 == ESRCH)
578 		return (ESRCH);
579 
580 	if (error1 == ENOENT || error2 == ENOENT)
581 		return (ENOENT);
582 
583 	/* Precedence goes to DAC/MAC protections. */
584 	if (error1 == EACCES || error2 == EACCES)
585 		return (EACCES);
586 
587 	/* Precedence goes to privilege. */
588 	if (error1 == EPERM || error2 == EPERM)
589 		return (EPERM);
590 
591 	/* Precedence goes to error over success; otherwise, arbitrary. */
592 	if (error1 != 0)
593 		return (error1);
594 	return (error2);
595 }
596 
597 int
598 mac_check_structmac_consistent(struct mac *mac)
599 {
600 
601 	if (mac->m_buflen < 0 ||
602 	    mac->m_buflen > MAC_MAX_LABEL_BUF_LEN)
603 		return (EINVAL);
604 
605 	return (0);
606 }
607 
608 SYSINIT(mac, SI_SUB_MAC, SI_ORDER_FIRST, mac_init, NULL);
609 SYSINIT(mac_late, SI_SUB_MAC_LATE, SI_ORDER_FIRST, mac_late_init, NULL);
610