xref: /linux/security/apparmor/policy.c (revision 9208c05f9fdfd927ea160b97dfef3c379049fff2)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * AppArmor security module
4  *
5  * This file contains AppArmor policy manipulation functions
6  *
7  * Copyright (C) 1998-2008 Novell/SUSE
8  * Copyright 2009-2010 Canonical Ltd.
9  *
10  * AppArmor policy is based around profiles, which contain the rules a
11  * task is confined by.  Every task in the system has a profile attached
12  * to it determined either by matching "unconfined" tasks against the
13  * visible set of profiles or by following a profiles attachment rules.
14  *
15  * Each profile exists in a profile namespace which is a container of
16  * visible profiles.  Each namespace contains a special "unconfined" profile,
17  * which doesn't enforce any confinement on a task beyond DAC.
18  *
19  * Namespace and profile names can be written together in either
20  * of two syntaxes.
21  *	:namespace:profile - used by kernel interfaces for easy detection
22  *	namespace://profile - used by policy
23  *
24  * Profile names can not start with : or @ or ^ and may not contain \0
25  *
26  * Reserved profile names
27  *	unconfined - special automatically generated unconfined profile
28  *	inherit - special name to indicate profile inheritance
29  *	null-XXXX-YYYY - special automatically generated learning profiles
30  *
31  * Namespace names may not start with / or @ and may not contain \0 or :
32  * Reserved namespace names
33  *	user-XXXX - user defined profiles
34  *
35  * a // in a profile or namespace name indicates a hierarchical name with the
36  * name before the // being the parent and the name after the child.
37  *
38  * Profile and namespace hierarchies serve two different but similar purposes.
39  * The namespace contains the set of visible profiles that are considered
40  * for attachment.  The hierarchy of namespaces allows for virtualizing
41  * the namespace so that for example a chroot can have its own set of profiles
42  * which may define some local user namespaces.
43  * The profile hierarchy severs two distinct purposes,
44  * -  it allows for sub profiles or hats, which allows an application to run
45  *    subprograms under its own profile with different restriction than it
46  *    self, and not have it use the system profile.
47  *    eg. if a mail program starts an editor, the policy might make the
48  *        restrictions tighter on the editor tighter than the mail program,
49  *        and definitely different than general editor restrictions
50  * - it allows for binary hierarchy of profiles, so that execution history
51  *   is preserved.  This feature isn't exploited by AppArmor reference policy
52  *   but is allowed.  NOTE: this is currently suboptimal because profile
53  *   aliasing is not currently implemented so that a profile for each
54  *   level must be defined.
55  *   eg. /bin/bash///bin/ls as a name would indicate /bin/ls was started
56  *       from /bin/bash
57  *
58  *   A profile or namespace name that can contain one or more // separators
59  *   is referred to as an hname (hierarchical).
60  *   eg.  /bin/bash//bin/ls
61  *
62  *   An fqname is a name that may contain both namespace and profile hnames.
63  *   eg. :ns:/bin/bash//bin/ls
64  *
65  * NOTES:
66  *   - locking of profile lists is currently fairly coarse.  All profile
67  *     lists within a namespace use the namespace lock.
68  * FIXME: move profile lists to using rcu_lists
69  */
70 
71 #include <linux/slab.h>
72 #include <linux/spinlock.h>
73 #include <linux/string.h>
74 #include <linux/cred.h>
75 #include <linux/rculist.h>
76 #include <linux/user_namespace.h>
77 
78 #include "include/apparmor.h"
79 #include "include/capability.h"
80 #include "include/cred.h"
81 #include "include/file.h"
82 #include "include/ipc.h"
83 #include "include/match.h"
84 #include "include/path.h"
85 #include "include/policy.h"
86 #include "include/policy_ns.h"
87 #include "include/policy_unpack.h"
88 #include "include/resource.h"
89 
90 int unprivileged_userns_apparmor_policy = 1;
91 int aa_unprivileged_unconfined_restricted;
92 
93 const char *const aa_profile_mode_names[] = {
94 	"enforce",
95 	"complain",
96 	"kill",
97 	"unconfined",
98 	"user",
99 };
100 
101 
102 static void aa_free_pdb(struct aa_policydb *pdb)
103 {
104 	if (pdb) {
105 		aa_put_dfa(pdb->dfa);
106 		if (pdb->perms)
107 			kvfree(pdb->perms);
108 		aa_free_str_table(&pdb->trans);
109 		kfree(pdb);
110 	}
111 }
112 
113 /**
114  * aa_pdb_free_kref - free aa_policydb by kref (called by aa_put_pdb)
115  * @kref: kref callback for freeing of a dfa  (NOT NULL)
116  */
117 void aa_pdb_free_kref(struct kref *kref)
118 {
119 	struct aa_policydb *pdb = container_of(kref, struct aa_policydb, count);
120 
121 	aa_free_pdb(pdb);
122 }
123 
124 
125 struct aa_policydb *aa_alloc_pdb(gfp_t gfp)
126 {
127 	struct aa_policydb *pdb = kzalloc(sizeof(struct aa_policydb), gfp);
128 
129 	if (!pdb)
130 		return NULL;
131 
132 	kref_init(&pdb->count);
133 
134 	return pdb;
135 }
136 
137 
138 /**
139  * __add_profile - add a profiles to list and label tree
140  * @list: list to add it to  (NOT NULL)
141  * @profile: the profile to add  (NOT NULL)
142  *
143  * refcount @profile, should be put by __list_remove_profile
144  *
145  * Requires: namespace lock be held, or list not be shared
146  */
147 static void __add_profile(struct list_head *list, struct aa_profile *profile)
148 {
149 	struct aa_label *l;
150 
151 	AA_BUG(!list);
152 	AA_BUG(!profile);
153 	AA_BUG(!profile->ns);
154 	AA_BUG(!mutex_is_locked(&profile->ns->lock));
155 
156 	list_add_rcu(&profile->base.list, list);
157 	/* get list reference */
158 	aa_get_profile(profile);
159 	l = aa_label_insert(&profile->ns->labels, &profile->label);
160 	AA_BUG(l != &profile->label);
161 	aa_put_label(l);
162 }
163 
164 /**
165  * __list_remove_profile - remove a profile from the list it is on
166  * @profile: the profile to remove  (NOT NULL)
167  *
168  * remove a profile from the list, warning generally removal should
169  * be done with __replace_profile as most profile removals are
170  * replacements to the unconfined profile.
171  *
172  * put @profile list refcount
173  *
174  * Requires: namespace lock be held, or list not have been live
175  */
176 static void __list_remove_profile(struct aa_profile *profile)
177 {
178 	AA_BUG(!profile);
179 	AA_BUG(!profile->ns);
180 	AA_BUG(!mutex_is_locked(&profile->ns->lock));
181 
182 	list_del_rcu(&profile->base.list);
183 	aa_put_profile(profile);
184 }
185 
186 /**
187  * __remove_profile - remove old profile, and children
188  * @profile: profile to be replaced  (NOT NULL)
189  *
190  * Requires: namespace list lock be held, or list not be shared
191  */
192 static void __remove_profile(struct aa_profile *profile)
193 {
194 	AA_BUG(!profile);
195 	AA_BUG(!profile->ns);
196 	AA_BUG(!mutex_is_locked(&profile->ns->lock));
197 
198 	/* release any children lists first */
199 	__aa_profile_list_release(&profile->base.profiles);
200 	/* released by free_profile */
201 	aa_label_remove(&profile->label);
202 	__aafs_profile_rmdir(profile);
203 	__list_remove_profile(profile);
204 }
205 
206 /**
207  * __aa_profile_list_release - remove all profiles on the list and put refs
208  * @head: list of profiles  (NOT NULL)
209  *
210  * Requires: namespace lock be held
211  */
212 void __aa_profile_list_release(struct list_head *head)
213 {
214 	struct aa_profile *profile, *tmp;
215 	list_for_each_entry_safe(profile, tmp, head, base.list)
216 		__remove_profile(profile);
217 }
218 
219 /**
220  * aa_free_data - free a data blob
221  * @ptr: data to free
222  * @arg: unused
223  */
224 static void aa_free_data(void *ptr, void *arg)
225 {
226 	struct aa_data *data = ptr;
227 
228 	kvfree_sensitive(data->data, data->size);
229 	kfree_sensitive(data->key);
230 	kfree_sensitive(data);
231 }
232 
233 static void free_attachment(struct aa_attachment *attach)
234 {
235 	int i;
236 
237 	for (i = 0; i < attach->xattr_count; i++)
238 		kfree_sensitive(attach->xattrs[i]);
239 	kfree_sensitive(attach->xattrs);
240 	aa_put_pdb(attach->xmatch);
241 }
242 
243 static void free_ruleset(struct aa_ruleset *rules)
244 {
245 	int i;
246 
247 	aa_put_pdb(rules->file);
248 	aa_put_pdb(rules->policy);
249 	aa_free_cap_rules(&rules->caps);
250 	aa_free_rlimit_rules(&rules->rlimits);
251 
252 	for (i = 0; i < rules->secmark_count; i++)
253 		kfree_sensitive(rules->secmark[i].label);
254 	kfree_sensitive(rules->secmark);
255 	kfree_sensitive(rules);
256 }
257 
258 struct aa_ruleset *aa_alloc_ruleset(gfp_t gfp)
259 {
260 	struct aa_ruleset *rules;
261 
262 	rules = kzalloc(sizeof(*rules), gfp);
263 	if (rules)
264 		INIT_LIST_HEAD(&rules->list);
265 
266 	return rules;
267 }
268 
269 /**
270  * aa_free_profile - free a profile
271  * @profile: the profile to free  (MAYBE NULL)
272  *
273  * Free a profile, its hats and null_profile. All references to the profile,
274  * its hats and null_profile must have been put.
275  *
276  * If the profile was referenced from a task context, free_profile() will
277  * be called from an rcu callback routine, so we must not sleep here.
278  */
279 void aa_free_profile(struct aa_profile *profile)
280 {
281 	struct aa_ruleset *rule, *tmp;
282 	struct rhashtable *rht;
283 
284 	AA_DEBUG("%s(%p)\n", __func__, profile);
285 
286 	if (!profile)
287 		return;
288 
289 	/* free children profiles */
290 	aa_policy_destroy(&profile->base);
291 	aa_put_profile(rcu_access_pointer(profile->parent));
292 
293 	aa_put_ns(profile->ns);
294 	kfree_sensitive(profile->rename);
295 	kfree_sensitive(profile->disconnected);
296 
297 	free_attachment(&profile->attach);
298 
299 	/*
300 	 * at this point there are no tasks that can have a reference
301 	 * to rules
302 	 */
303 	list_for_each_entry_safe(rule, tmp, &profile->rules, list) {
304 		list_del_init(&rule->list);
305 		free_ruleset(rule);
306 	}
307 	kfree_sensitive(profile->dirname);
308 
309 	if (profile->data) {
310 		rht = profile->data;
311 		profile->data = NULL;
312 		rhashtable_free_and_destroy(rht, aa_free_data, NULL);
313 		kfree_sensitive(rht);
314 	}
315 
316 	kfree_sensitive(profile->hash);
317 	aa_put_loaddata(profile->rawdata);
318 	aa_label_destroy(&profile->label);
319 
320 	kfree_sensitive(profile);
321 }
322 
323 /**
324  * aa_alloc_profile - allocate, initialize and return a new profile
325  * @hname: name of the profile  (NOT NULL)
326  * @proxy: proxy to use OR null if to allocate a new one
327  * @gfp: allocation type
328  *
329  * Returns: refcount profile or NULL on failure
330  */
331 struct aa_profile *aa_alloc_profile(const char *hname, struct aa_proxy *proxy,
332 				    gfp_t gfp)
333 {
334 	struct aa_profile *profile;
335 	struct aa_ruleset *rules;
336 
337 	/* freed by free_profile - usually through aa_put_profile */
338 	profile = kzalloc(struct_size(profile, label.vec, 2), gfp);
339 	if (!profile)
340 		return NULL;
341 
342 	if (!aa_policy_init(&profile->base, NULL, hname, gfp))
343 		goto fail;
344 	if (!aa_label_init(&profile->label, 1, gfp))
345 		goto fail;
346 
347 	INIT_LIST_HEAD(&profile->rules);
348 
349 	/* allocate the first ruleset, but leave it empty */
350 	rules = aa_alloc_ruleset(gfp);
351 	if (!rules)
352 		goto fail;
353 	list_add(&rules->list, &profile->rules);
354 
355 	/* update being set needed by fs interface */
356 	if (!proxy) {
357 		proxy = aa_alloc_proxy(&profile->label, gfp);
358 		if (!proxy)
359 			goto fail;
360 	} else
361 		aa_get_proxy(proxy);
362 	profile->label.proxy = proxy;
363 
364 	profile->label.hname = profile->base.hname;
365 	profile->label.flags |= FLAG_PROFILE;
366 	profile->label.vec[0] = profile;
367 
368 	/* refcount released by caller */
369 	return profile;
370 
371 fail:
372 	aa_free_profile(profile);
373 
374 	return NULL;
375 }
376 
377 /* TODO: profile accounting - setup in remove */
378 
379 /**
380  * __strn_find_child - find a profile on @head list using substring of @name
381  * @head: list to search  (NOT NULL)
382  * @name: name of profile (NOT NULL)
383  * @len: length of @name substring to match
384  *
385  * Requires: rcu_read_lock be held
386  *
387  * Returns: unrefcounted profile ptr, or NULL if not found
388  */
389 static struct aa_profile *__strn_find_child(struct list_head *head,
390 					    const char *name, int len)
391 {
392 	return (struct aa_profile *)__policy_strn_find(head, name, len);
393 }
394 
395 /**
396  * __find_child - find a profile on @head list with a name matching @name
397  * @head: list to search  (NOT NULL)
398  * @name: name of profile (NOT NULL)
399  *
400  * Requires: rcu_read_lock be held
401  *
402  * Returns: unrefcounted profile ptr, or NULL if not found
403  */
404 static struct aa_profile *__find_child(struct list_head *head, const char *name)
405 {
406 	return __strn_find_child(head, name, strlen(name));
407 }
408 
409 /**
410  * aa_find_child - find a profile by @name in @parent
411  * @parent: profile to search  (NOT NULL)
412  * @name: profile name to search for  (NOT NULL)
413  *
414  * Returns: a refcounted profile or NULL if not found
415  */
416 struct aa_profile *aa_find_child(struct aa_profile *parent, const char *name)
417 {
418 	struct aa_profile *profile;
419 
420 	rcu_read_lock();
421 	do {
422 		profile = __find_child(&parent->base.profiles, name);
423 	} while (profile && !aa_get_profile_not0(profile));
424 	rcu_read_unlock();
425 
426 	/* refcount released by caller */
427 	return profile;
428 }
429 
430 /**
431  * __lookup_parent - lookup the parent of a profile of name @hname
432  * @ns: namespace to lookup profile in  (NOT NULL)
433  * @hname: hierarchical profile name to find parent of  (NOT NULL)
434  *
435  * Lookups up the parent of a fully qualified profile name, the profile
436  * that matches hname does not need to exist, in general this
437  * is used to load a new profile.
438  *
439  * Requires: rcu_read_lock be held
440  *
441  * Returns: unrefcounted policy or NULL if not found
442  */
443 static struct aa_policy *__lookup_parent(struct aa_ns *ns,
444 					 const char *hname)
445 {
446 	struct aa_policy *policy;
447 	struct aa_profile *profile = NULL;
448 	char *split;
449 
450 	policy = &ns->base;
451 
452 	for (split = strstr(hname, "//"); split;) {
453 		profile = __strn_find_child(&policy->profiles, hname,
454 					    split - hname);
455 		if (!profile)
456 			return NULL;
457 		policy = &profile->base;
458 		hname = split + 2;
459 		split = strstr(hname, "//");
460 	}
461 	if (!profile)
462 		return &ns->base;
463 	return &profile->base;
464 }
465 
466 /**
467  * __create_missing_ancestors - create place holders for missing ancestores
468  * @ns: namespace to lookup profile in (NOT NULL)
469  * @hname: hierarchical profile name to find parent of (NOT NULL)
470  * @gfp: type of allocation.
471  *
472  * Requires: ns mutex lock held
473  *
474  * Return: unrefcounted parent policy on success or %NULL if error creating
475  *          place holder profiles.
476  */
477 static struct aa_policy *__create_missing_ancestors(struct aa_ns *ns,
478 						    const char *hname,
479 						    gfp_t gfp)
480 {
481 	struct aa_policy *policy;
482 	struct aa_profile *parent, *profile = NULL;
483 	char *split;
484 
485 	AA_BUG(!ns);
486 	AA_BUG(!hname);
487 
488 	policy = &ns->base;
489 
490 	for (split = strstr(hname, "//"); split;) {
491 		parent = profile;
492 		profile = __strn_find_child(&policy->profiles, hname,
493 					    split - hname);
494 		if (!profile) {
495 			const char *name = kstrndup(hname, split - hname,
496 						    gfp);
497 			if (!name)
498 				return NULL;
499 			profile = aa_alloc_null(parent, name, gfp);
500 			kfree(name);
501 			if (!profile)
502 				return NULL;
503 			if (!parent)
504 				profile->ns = aa_get_ns(ns);
505 		}
506 		policy = &profile->base;
507 		hname = split + 2;
508 		split = strstr(hname, "//");
509 	}
510 	if (!profile)
511 		return &ns->base;
512 	return &profile->base;
513 }
514 
515 /**
516  * __lookupn_profile - lookup the profile matching @hname
517  * @base: base list to start looking up profile name from  (NOT NULL)
518  * @hname: hierarchical profile name  (NOT NULL)
519  * @n: length of @hname
520  *
521  * Requires: rcu_read_lock be held
522  *
523  * Returns: unrefcounted profile pointer or NULL if not found
524  *
525  * Do a relative name lookup, recursing through profile tree.
526  */
527 static struct aa_profile *__lookupn_profile(struct aa_policy *base,
528 					    const char *hname, size_t n)
529 {
530 	struct aa_profile *profile = NULL;
531 	const char *split;
532 
533 	for (split = strnstr(hname, "//", n); split;
534 	     split = strnstr(hname, "//", n)) {
535 		profile = __strn_find_child(&base->profiles, hname,
536 					    split - hname);
537 		if (!profile)
538 			return NULL;
539 
540 		base = &profile->base;
541 		n -= split + 2 - hname;
542 		hname = split + 2;
543 	}
544 
545 	if (n)
546 		return __strn_find_child(&base->profiles, hname, n);
547 	return NULL;
548 }
549 
550 static struct aa_profile *__lookup_profile(struct aa_policy *base,
551 					   const char *hname)
552 {
553 	return __lookupn_profile(base, hname, strlen(hname));
554 }
555 
556 /**
557  * aa_lookupn_profile - find a profile by its full or partial name
558  * @ns: the namespace to start from (NOT NULL)
559  * @hname: name to do lookup on.  Does not contain namespace prefix (NOT NULL)
560  * @n: size of @hname
561  *
562  * Returns: refcounted profile or NULL if not found
563  */
564 struct aa_profile *aa_lookupn_profile(struct aa_ns *ns, const char *hname,
565 				      size_t n)
566 {
567 	struct aa_profile *profile;
568 
569 	rcu_read_lock();
570 	do {
571 		profile = __lookupn_profile(&ns->base, hname, n);
572 	} while (profile && !aa_get_profile_not0(profile));
573 	rcu_read_unlock();
574 
575 	/* the unconfined profile is not in the regular profile list */
576 	if (!profile && strncmp(hname, "unconfined", n) == 0)
577 		profile = aa_get_newest_profile(ns->unconfined);
578 
579 	/* refcount released by caller */
580 	return profile;
581 }
582 
583 struct aa_profile *aa_lookup_profile(struct aa_ns *ns, const char *hname)
584 {
585 	return aa_lookupn_profile(ns, hname, strlen(hname));
586 }
587 
588 struct aa_profile *aa_fqlookupn_profile(struct aa_label *base,
589 					const char *fqname, size_t n)
590 {
591 	struct aa_profile *profile;
592 	struct aa_ns *ns;
593 	const char *name, *ns_name;
594 	size_t ns_len;
595 
596 	name = aa_splitn_fqname(fqname, n, &ns_name, &ns_len);
597 	if (ns_name) {
598 		ns = aa_lookupn_ns(labels_ns(base), ns_name, ns_len);
599 		if (!ns)
600 			return NULL;
601 	} else
602 		ns = aa_get_ns(labels_ns(base));
603 
604 	if (name)
605 		profile = aa_lookupn_profile(ns, name, n - (name - fqname));
606 	else if (ns)
607 		/* default profile for ns, currently unconfined */
608 		profile = aa_get_newest_profile(ns->unconfined);
609 	else
610 		profile = NULL;
611 	aa_put_ns(ns);
612 
613 	return profile;
614 }
615 
616 
617 struct aa_profile *aa_alloc_null(struct aa_profile *parent, const char *name,
618 				 gfp_t gfp)
619 {
620 	struct aa_profile *profile;
621 	struct aa_ruleset *rules;
622 
623 	profile = aa_alloc_profile(name, NULL, gfp);
624 	if (!profile)
625 		return NULL;
626 
627 	/* TODO: ideally we should inherit abi from parent */
628 	profile->label.flags |= FLAG_NULL;
629 	profile->attach.xmatch = aa_get_pdb(nullpdb);
630 	rules = list_first_entry(&profile->rules, typeof(*rules), list);
631 	rules->file = aa_get_pdb(nullpdb);
632 	rules->policy = aa_get_pdb(nullpdb);
633 
634 	if (parent) {
635 		profile->path_flags = parent->path_flags;
636 
637 		/* released on free_profile */
638 		rcu_assign_pointer(profile->parent, aa_get_profile(parent));
639 		profile->ns = aa_get_ns(parent->ns);
640 	}
641 
642 	return profile;
643 }
644 
645 /**
646  * aa_new_learning_profile - create or find a null-X learning profile
647  * @parent: profile that caused this profile to be created (NOT NULL)
648  * @hat: true if the null- learning profile is a hat
649  * @base: name to base the null profile off of
650  * @gfp: type of allocation
651  *
652  * Find/Create a null- complain mode profile used in learning mode.  The
653  * name of the profile is unique and follows the format of parent//null-XXX.
654  * where XXX is based on the @name or if that fails or is not supplied
655  * a unique number
656  *
657  * null profiles are added to the profile list but the list does not
658  * hold a count on them so that they are automatically released when
659  * not in use.
660  *
661  * Returns: new refcounted profile else NULL on failure
662  */
663 struct aa_profile *aa_new_learning_profile(struct aa_profile *parent, bool hat,
664 					   const char *base, gfp_t gfp)
665 {
666 	struct aa_profile *p, *profile;
667 	const char *bname;
668 	char *name = NULL;
669 
670 	AA_BUG(!parent);
671 
672 	if (base) {
673 		name = kmalloc(strlen(parent->base.hname) + 8 + strlen(base),
674 			       gfp);
675 		if (name) {
676 			sprintf(name, "%s//null-%s", parent->base.hname, base);
677 			goto name;
678 		}
679 		/* fall through to try shorter uniq */
680 	}
681 
682 	name = kmalloc(strlen(parent->base.hname) + 2 + 7 + 8, gfp);
683 	if (!name)
684 		return NULL;
685 	sprintf(name, "%s//null-%x", parent->base.hname,
686 		atomic_inc_return(&parent->ns->uniq_null));
687 
688 name:
689 	/* lookup to see if this is a dup creation */
690 	bname = basename(name);
691 	profile = aa_find_child(parent, bname);
692 	if (profile)
693 		goto out;
694 
695 	profile = aa_alloc_null(parent, name, gfp);
696 	if (!profile)
697 		goto fail;
698 	profile->mode = APPARMOR_COMPLAIN;
699 	if (hat)
700 		profile->label.flags |= FLAG_HAT;
701 
702 	mutex_lock_nested(&profile->ns->lock, profile->ns->level);
703 	p = __find_child(&parent->base.profiles, bname);
704 	if (p) {
705 		aa_free_profile(profile);
706 		profile = aa_get_profile(p);
707 	} else {
708 		__add_profile(&parent->base.profiles, profile);
709 	}
710 	mutex_unlock(&profile->ns->lock);
711 
712 	/* refcount released by caller */
713 out:
714 	kfree(name);
715 
716 	return profile;
717 
718 fail:
719 	kfree(name);
720 	aa_free_profile(profile);
721 	return NULL;
722 }
723 
724 /**
725  * replacement_allowed - test to see if replacement is allowed
726  * @profile: profile to test if it can be replaced  (MAYBE NULL)
727  * @noreplace: true if replacement shouldn't be allowed but addition is okay
728  * @info: Returns - info about why replacement failed (NOT NULL)
729  *
730  * Returns: %0 if replacement allowed else error code
731  */
732 static int replacement_allowed(struct aa_profile *profile, int noreplace,
733 			       const char **info)
734 {
735 	if (profile) {
736 		if (profile->label.flags & FLAG_IMMUTIBLE) {
737 			*info = "cannot replace immutable profile";
738 			return -EPERM;
739 		} else if (noreplace) {
740 			*info = "profile already exists";
741 			return -EEXIST;
742 		}
743 	}
744 	return 0;
745 }
746 
747 /* audit callback for net specific fields */
748 static void audit_cb(struct audit_buffer *ab, void *va)
749 {
750 	struct common_audit_data *sa = va;
751 	struct apparmor_audit_data *ad = aad(sa);
752 
753 	if (ad->iface.ns) {
754 		audit_log_format(ab, " ns=");
755 		audit_log_untrustedstring(ab, ad->iface.ns);
756 	}
757 }
758 
759 /**
760  * audit_policy - Do auditing of policy changes
761  * @subj_label: label to check if it can manage policy
762  * @op: policy operation being performed
763  * @ns_name: name of namespace being manipulated
764  * @name: name of profile being manipulated (NOT NULL)
765  * @info: any extra information to be audited (MAYBE NULL)
766  * @error: error code
767  *
768  * Returns: the error to be returned after audit is done
769  */
770 static int audit_policy(struct aa_label *subj_label, const char *op,
771 			const char *ns_name, const char *name,
772 			const char *info, int error)
773 {
774 	DEFINE_AUDIT_DATA(ad, LSM_AUDIT_DATA_NONE, AA_CLASS_NONE, op);
775 
776 	ad.iface.ns = ns_name;
777 	ad.name = name;
778 	ad.info = info;
779 	ad.error = error;
780 	ad.subj_label = subj_label;
781 
782 	aa_audit_msg(AUDIT_APPARMOR_STATUS, &ad, audit_cb);
783 
784 	return error;
785 }
786 
787 /* don't call out to other LSMs in the stack for apparmor policy admin
788  * permissions
789  */
790 static int policy_ns_capable(const struct cred *subj_cred,
791 			     struct aa_label *label,
792 			     struct user_namespace *userns, int cap)
793 {
794 	int err;
795 
796 	/* check for MAC_ADMIN cap in cred */
797 	err = cap_capable(subj_cred, userns, cap, CAP_OPT_NONE);
798 	if (!err)
799 		err = aa_capable(subj_cred, label, cap, CAP_OPT_NONE);
800 
801 	return err;
802 }
803 
804 /**
805  * aa_policy_view_capable - check if viewing policy in at @ns is allowed
806  * @subj_cred: cred of subject
807  * @label: label that is trying to view policy in ns
808  * @ns: namespace being viewed by @label (may be NULL if @label's ns)
809  *
810  * Returns: true if viewing policy is allowed
811  *
812  * If @ns is NULL then the namespace being viewed is assumed to be the
813  * tasks current namespace.
814  */
815 bool aa_policy_view_capable(const struct cred *subj_cred,
816 			     struct aa_label *label, struct aa_ns *ns)
817 {
818 	struct user_namespace *user_ns = subj_cred->user_ns;
819 	struct aa_ns *view_ns = labels_view(label);
820 	bool root_in_user_ns = uid_eq(current_euid(), make_kuid(user_ns, 0)) ||
821 			       in_egroup_p(make_kgid(user_ns, 0));
822 	bool response = false;
823 	if (!ns)
824 		ns = view_ns;
825 
826 	if (root_in_user_ns && aa_ns_visible(view_ns, ns, true) &&
827 	    (user_ns == &init_user_ns ||
828 	     (unprivileged_userns_apparmor_policy != 0 &&
829 	      user_ns->level == view_ns->level)))
830 		response = true;
831 
832 	return response;
833 }
834 
835 bool aa_policy_admin_capable(const struct cred *subj_cred,
836 			     struct aa_label *label, struct aa_ns *ns)
837 {
838 	struct user_namespace *user_ns = subj_cred->user_ns;
839 	bool capable = policy_ns_capable(subj_cred, label, user_ns,
840 					 CAP_MAC_ADMIN) == 0;
841 
842 	AA_DEBUG("cap_mac_admin? %d\n", capable);
843 	AA_DEBUG("policy locked? %d\n", aa_g_lock_policy);
844 
845 	return aa_policy_view_capable(subj_cred, label, ns) && capable &&
846 		!aa_g_lock_policy;
847 }
848 
849 bool aa_current_policy_view_capable(struct aa_ns *ns)
850 {
851 	struct aa_label *label;
852 	bool res;
853 
854 	label = __begin_current_label_crit_section();
855 	res = aa_policy_view_capable(current_cred(), label, ns);
856 	__end_current_label_crit_section(label);
857 
858 	return res;
859 }
860 
861 bool aa_current_policy_admin_capable(struct aa_ns *ns)
862 {
863 	struct aa_label *label;
864 	bool res;
865 
866 	label = __begin_current_label_crit_section();
867 	res = aa_policy_admin_capable(current_cred(), label, ns);
868 	__end_current_label_crit_section(label);
869 
870 	return res;
871 }
872 
873 /**
874  * aa_may_manage_policy - can the current task manage policy
875  * @subj_cred: subjects cred
876  * @label: label to check if it can manage policy
877  * @ns: namespace being managed by @label (may be NULL if @label's ns)
878  * @mask: contains the policy manipulation operation being done
879  *
880  * Returns: 0 if the task is allowed to manipulate policy else error
881  */
882 int aa_may_manage_policy(const struct cred *subj_cred, struct aa_label *label,
883 			 struct aa_ns *ns, u32 mask)
884 {
885 	const char *op;
886 
887 	if (mask & AA_MAY_REMOVE_POLICY)
888 		op = OP_PROF_RM;
889 	else if (mask & AA_MAY_REPLACE_POLICY)
890 		op = OP_PROF_REPL;
891 	else
892 		op = OP_PROF_LOAD;
893 
894 	/* check if loading policy is locked out */
895 	if (aa_g_lock_policy)
896 		return audit_policy(label, op, NULL, NULL, "policy_locked",
897 				    -EACCES);
898 
899 	if (!aa_policy_admin_capable(subj_cred, label, ns))
900 		return audit_policy(label, op, NULL, NULL, "not policy admin",
901 				    -EACCES);
902 
903 	/* TODO: add fine grained mediation of policy loads */
904 	return 0;
905 }
906 
907 static struct aa_profile *__list_lookup_parent(struct list_head *lh,
908 					       struct aa_profile *profile)
909 {
910 	const char *base = basename(profile->base.hname);
911 	long len = base - profile->base.hname;
912 	struct aa_load_ent *ent;
913 
914 	/* parent won't have trailing // so remove from len */
915 	if (len <= 2)
916 		return NULL;
917 	len -= 2;
918 
919 	list_for_each_entry(ent, lh, list) {
920 		if (ent->new == profile)
921 			continue;
922 		if (strncmp(ent->new->base.hname, profile->base.hname, len) ==
923 		    0 && ent->new->base.hname[len] == 0)
924 			return ent->new;
925 	}
926 
927 	return NULL;
928 }
929 
930 /**
931  * __replace_profile - replace @old with @new on a list
932  * @old: profile to be replaced  (NOT NULL)
933  * @new: profile to replace @old with  (NOT NULL)
934  *
935  * Will duplicate and refcount elements that @new inherits from @old
936  * and will inherit @old children.
937  *
938  * refcount @new for list, put @old list refcount
939  *
940  * Requires: namespace list lock be held, or list not be shared
941  */
942 static void __replace_profile(struct aa_profile *old, struct aa_profile *new)
943 {
944 	struct aa_profile *child, *tmp;
945 
946 	if (!list_empty(&old->base.profiles)) {
947 		LIST_HEAD(lh);
948 		list_splice_init_rcu(&old->base.profiles, &lh, synchronize_rcu);
949 
950 		list_for_each_entry_safe(child, tmp, &lh, base.list) {
951 			struct aa_profile *p;
952 
953 			list_del_init(&child->base.list);
954 			p = __find_child(&new->base.profiles, child->base.name);
955 			if (p) {
956 				/* @p replaces @child  */
957 				__replace_profile(child, p);
958 				continue;
959 			}
960 
961 			/* inherit @child and its children */
962 			/* TODO: update hname of inherited children */
963 			/* list refcount transferred to @new */
964 			p = aa_deref_parent(child);
965 			rcu_assign_pointer(child->parent, aa_get_profile(new));
966 			list_add_rcu(&child->base.list, &new->base.profiles);
967 			aa_put_profile(p);
968 		}
969 	}
970 
971 	if (!rcu_access_pointer(new->parent)) {
972 		struct aa_profile *parent = aa_deref_parent(old);
973 		rcu_assign_pointer(new->parent, aa_get_profile(parent));
974 	}
975 	aa_label_replace(&old->label, &new->label);
976 	/* migrate dents must come after label replacement b/c update */
977 	__aafs_profile_migrate_dents(old, new);
978 
979 	if (list_empty(&new->base.list)) {
980 		/* new is not on a list already */
981 		list_replace_rcu(&old->base.list, &new->base.list);
982 		aa_get_profile(new);
983 		aa_put_profile(old);
984 	} else
985 		__list_remove_profile(old);
986 }
987 
988 /**
989  * __lookup_replace - lookup replacement information for a profile
990  * @ns: namespace the lookup occurs in
991  * @hname: name of profile to lookup
992  * @noreplace: true if not replacing an existing profile
993  * @p: Returns - profile to be replaced
994  * @info: Returns - info string on why lookup failed
995  *
996  * Returns: profile to replace (no ref) on success else ptr error
997  */
998 static int __lookup_replace(struct aa_ns *ns, const char *hname,
999 			    bool noreplace, struct aa_profile **p,
1000 			    const char **info)
1001 {
1002 	*p = aa_get_profile(__lookup_profile(&ns->base, hname));
1003 	if (*p) {
1004 		int error = replacement_allowed(*p, noreplace, info);
1005 		if (error) {
1006 			*info = "profile can not be replaced";
1007 			return error;
1008 		}
1009 	}
1010 
1011 	return 0;
1012 }
1013 
1014 static void share_name(struct aa_profile *old, struct aa_profile *new)
1015 {
1016 	aa_put_str(new->base.hname);
1017 	aa_get_str(old->base.hname);
1018 	new->base.hname = old->base.hname;
1019 	new->base.name = old->base.name;
1020 	new->label.hname = old->label.hname;
1021 }
1022 
1023 /* Update to newest version of parent after previous replacements
1024  * Returns: unrefcount newest version of parent
1025  */
1026 static struct aa_profile *update_to_newest_parent(struct aa_profile *new)
1027 {
1028 	struct aa_profile *parent, *newest;
1029 
1030 	parent = rcu_dereference_protected(new->parent,
1031 					   mutex_is_locked(&new->ns->lock));
1032 	newest = aa_get_newest_profile(parent);
1033 
1034 	/* parent replaced in this atomic set? */
1035 	if (newest != parent) {
1036 		aa_put_profile(parent);
1037 		rcu_assign_pointer(new->parent, newest);
1038 	} else
1039 		aa_put_profile(newest);
1040 
1041 	return newest;
1042 }
1043 
1044 /**
1045  * aa_replace_profiles - replace profile(s) on the profile list
1046  * @policy_ns: namespace load is occurring on
1047  * @label: label that is attempting to load/replace policy
1048  * @mask: permission mask
1049  * @udata: serialized data stream  (NOT NULL)
1050  *
1051  * unpack and replace a profile on the profile list and uses of that profile
1052  * by any task creds via invalidating the old version of the profile, which
1053  * tasks will notice to update their own cred.  If the profile does not exist
1054  * on the profile list it is added.
1055  *
1056  * Returns: size of data consumed else error code on failure.
1057  */
1058 ssize_t aa_replace_profiles(struct aa_ns *policy_ns, struct aa_label *label,
1059 			    u32 mask, struct aa_loaddata *udata)
1060 {
1061 	const char *ns_name = NULL, *info = NULL;
1062 	struct aa_ns *ns = NULL;
1063 	struct aa_load_ent *ent, *tmp;
1064 	struct aa_loaddata *rawdata_ent;
1065 	const char *op;
1066 	ssize_t count, error;
1067 	LIST_HEAD(lh);
1068 
1069 	op = mask & AA_MAY_REPLACE_POLICY ? OP_PROF_REPL : OP_PROF_LOAD;
1070 	aa_get_loaddata(udata);
1071 	/* released below */
1072 	error = aa_unpack(udata, &lh, &ns_name);
1073 	if (error)
1074 		goto out;
1075 
1076 	/* ensure that profiles are all for the same ns
1077 	 * TODO: update locking to remove this constaint. All profiles in
1078 	 *       the load set must succeed as a set or the load will
1079 	 *       fail. Sort ent list and take ns locks in hierarchy order
1080 	 */
1081 	count = 0;
1082 	list_for_each_entry(ent, &lh, list) {
1083 		if (ns_name) {
1084 			if (ent->ns_name &&
1085 			    strcmp(ent->ns_name, ns_name) != 0) {
1086 				info = "policy load has mixed namespaces";
1087 				error = -EACCES;
1088 				goto fail;
1089 			}
1090 		} else if (ent->ns_name) {
1091 			if (count) {
1092 				info = "policy load has mixed namespaces";
1093 				error = -EACCES;
1094 				goto fail;
1095 			}
1096 			ns_name = ent->ns_name;
1097 		} else
1098 			count++;
1099 	}
1100 	if (ns_name) {
1101 		ns = aa_prepare_ns(policy_ns ? policy_ns : labels_ns(label),
1102 				   ns_name);
1103 		if (IS_ERR(ns)) {
1104 			op = OP_PROF_LOAD;
1105 			info = "failed to prepare namespace";
1106 			error = PTR_ERR(ns);
1107 			ns = NULL;
1108 			ent = NULL;
1109 			goto fail;
1110 		}
1111 	} else
1112 		ns = aa_get_ns(policy_ns ? policy_ns : labels_ns(label));
1113 
1114 	mutex_lock_nested(&ns->lock, ns->level);
1115 	/* check for duplicate rawdata blobs: space and file dedup */
1116 	if (!list_empty(&ns->rawdata_list)) {
1117 		list_for_each_entry(rawdata_ent, &ns->rawdata_list, list) {
1118 			if (aa_rawdata_eq(rawdata_ent, udata)) {
1119 				struct aa_loaddata *tmp;
1120 
1121 				tmp = __aa_get_loaddata(rawdata_ent);
1122 				/* check we didn't fail the race */
1123 				if (tmp) {
1124 					aa_put_loaddata(udata);
1125 					udata = tmp;
1126 					break;
1127 				}
1128 			}
1129 		}
1130 	}
1131 	/* setup parent and ns info */
1132 	list_for_each_entry(ent, &lh, list) {
1133 		struct aa_policy *policy;
1134 		struct aa_profile *p;
1135 
1136 		if (aa_g_export_binary)
1137 			ent->new->rawdata = aa_get_loaddata(udata);
1138 		error = __lookup_replace(ns, ent->new->base.hname,
1139 					 !(mask & AA_MAY_REPLACE_POLICY),
1140 					 &ent->old, &info);
1141 		if (error)
1142 			goto fail_lock;
1143 
1144 		if (ent->new->rename) {
1145 			error = __lookup_replace(ns, ent->new->rename,
1146 						!(mask & AA_MAY_REPLACE_POLICY),
1147 						&ent->rename, &info);
1148 			if (error)
1149 				goto fail_lock;
1150 		}
1151 
1152 		/* released when @new is freed */
1153 		ent->new->ns = aa_get_ns(ns);
1154 
1155 		if (ent->old || ent->rename)
1156 			continue;
1157 
1158 		/* no ref on policy only use inside lock */
1159 		p = NULL;
1160 		policy = __lookup_parent(ns, ent->new->base.hname);
1161 		if (!policy) {
1162 			/* first check for parent in the load set */
1163 			p = __list_lookup_parent(&lh, ent->new);
1164 			if (!p) {
1165 				/*
1166 				 * fill in missing parent with null
1167 				 * profile that doesn't have
1168 				 * permissions. This allows for
1169 				 * individual profile loading where
1170 				 * the child is loaded before the
1171 				 * parent, and outside of the current
1172 				 * atomic set. This unfortunately can
1173 				 * happen with some userspaces.  The
1174 				 * null profile will be replaced once
1175 				 * the parent is loaded.
1176 				 */
1177 				policy = __create_missing_ancestors(ns,
1178 							ent->new->base.hname,
1179 							GFP_KERNEL);
1180 				if (!policy) {
1181 					error = -ENOENT;
1182 					info = "parent does not exist";
1183 					goto fail_lock;
1184 				}
1185 			}
1186 		}
1187 		if (!p && policy != &ns->base)
1188 			/* released on profile replacement or free_profile */
1189 			p = (struct aa_profile *) policy;
1190 		rcu_assign_pointer(ent->new->parent, aa_get_profile(p));
1191 	}
1192 
1193 	/* create new fs entries for introspection if needed */
1194 	if (!udata->dents[AAFS_LOADDATA_DIR] && aa_g_export_binary) {
1195 		error = __aa_fs_create_rawdata(ns, udata);
1196 		if (error) {
1197 			info = "failed to create raw_data dir and files";
1198 			ent = NULL;
1199 			goto fail_lock;
1200 		}
1201 	}
1202 	list_for_each_entry(ent, &lh, list) {
1203 		if (!ent->old) {
1204 			struct dentry *parent;
1205 			if (rcu_access_pointer(ent->new->parent)) {
1206 				struct aa_profile *p;
1207 				p = aa_deref_parent(ent->new);
1208 				parent = prof_child_dir(p);
1209 			} else
1210 				parent = ns_subprofs_dir(ent->new->ns);
1211 			error = __aafs_profile_mkdir(ent->new, parent);
1212 		}
1213 
1214 		if (error) {
1215 			info = "failed to create";
1216 			goto fail_lock;
1217 		}
1218 	}
1219 
1220 	/* Done with checks that may fail - do actual replacement */
1221 	__aa_bump_ns_revision(ns);
1222 	if (aa_g_export_binary)
1223 		__aa_loaddata_update(udata, ns->revision);
1224 	list_for_each_entry_safe(ent, tmp, &lh, list) {
1225 		list_del_init(&ent->list);
1226 		op = (!ent->old && !ent->rename) ? OP_PROF_LOAD : OP_PROF_REPL;
1227 
1228 		if (ent->old && ent->old->rawdata == ent->new->rawdata &&
1229 		    ent->new->rawdata) {
1230 			/* dedup actual profile replacement */
1231 			audit_policy(label, op, ns_name, ent->new->base.hname,
1232 				     "same as current profile, skipping",
1233 				     error);
1234 			/* break refcount cycle with proxy. */
1235 			aa_put_proxy(ent->new->label.proxy);
1236 			ent->new->label.proxy = NULL;
1237 			goto skip;
1238 		}
1239 
1240 		/*
1241 		 * TODO: finer dedup based on profile range in data. Load set
1242 		 * can differ but profile may remain unchanged
1243 		 */
1244 		audit_policy(label, op, ns_name, ent->new->base.hname, NULL,
1245 			     error);
1246 
1247 		if (ent->old) {
1248 			share_name(ent->old, ent->new);
1249 			__replace_profile(ent->old, ent->new);
1250 		} else {
1251 			struct list_head *lh;
1252 
1253 			if (rcu_access_pointer(ent->new->parent)) {
1254 				struct aa_profile *parent;
1255 
1256 				parent = update_to_newest_parent(ent->new);
1257 				lh = &parent->base.profiles;
1258 			} else
1259 				lh = &ns->base.profiles;
1260 			__add_profile(lh, ent->new);
1261 		}
1262 	skip:
1263 		aa_load_ent_free(ent);
1264 	}
1265 	__aa_labelset_update_subtree(ns);
1266 	mutex_unlock(&ns->lock);
1267 
1268 out:
1269 	aa_put_ns(ns);
1270 	aa_put_loaddata(udata);
1271 	kfree(ns_name);
1272 
1273 	if (error)
1274 		return error;
1275 	return udata->size;
1276 
1277 fail_lock:
1278 	mutex_unlock(&ns->lock);
1279 
1280 	/* audit cause of failure */
1281 	op = (ent && !ent->old) ? OP_PROF_LOAD : OP_PROF_REPL;
1282 fail:
1283 	  audit_policy(label, op, ns_name, ent ? ent->new->base.hname : NULL,
1284 		       info, error);
1285 	/* audit status that rest of profiles in the atomic set failed too */
1286 	info = "valid profile in failed atomic policy load";
1287 	list_for_each_entry(tmp, &lh, list) {
1288 		if (tmp == ent) {
1289 			info = "unchecked profile in failed atomic policy load";
1290 			/* skip entry that caused failure */
1291 			continue;
1292 		}
1293 		op = (!tmp->old) ? OP_PROF_LOAD : OP_PROF_REPL;
1294 		audit_policy(label, op, ns_name, tmp->new->base.hname, info,
1295 			     error);
1296 	}
1297 	list_for_each_entry_safe(ent, tmp, &lh, list) {
1298 		list_del_init(&ent->list);
1299 		aa_load_ent_free(ent);
1300 	}
1301 
1302 	goto out;
1303 }
1304 
1305 /**
1306  * aa_remove_profiles - remove profile(s) from the system
1307  * @policy_ns: namespace the remove is being done from
1308  * @subj: label attempting to remove policy
1309  * @fqname: name of the profile or namespace to remove  (NOT NULL)
1310  * @size: size of the name
1311  *
1312  * Remove a profile or sub namespace from the current namespace, so that
1313  * they can not be found anymore and mark them as replaced by unconfined
1314  *
1315  * NOTE: removing confinement does not restore rlimits to preconfinement values
1316  *
1317  * Returns: size of data consume else error code if fails
1318  */
1319 ssize_t aa_remove_profiles(struct aa_ns *policy_ns, struct aa_label *subj,
1320 			   char *fqname, size_t size)
1321 {
1322 	struct aa_ns *ns = NULL;
1323 	struct aa_profile *profile = NULL;
1324 	const char *name = fqname, *info = NULL;
1325 	const char *ns_name = NULL;
1326 	ssize_t error = 0;
1327 
1328 	if (*fqname == 0) {
1329 		info = "no profile specified";
1330 		error = -ENOENT;
1331 		goto fail;
1332 	}
1333 
1334 	if (fqname[0] == ':') {
1335 		size_t ns_len;
1336 
1337 		name = aa_splitn_fqname(fqname, size, &ns_name, &ns_len);
1338 		/* released below */
1339 		ns = aa_lookupn_ns(policy_ns ? policy_ns : labels_ns(subj),
1340 				   ns_name, ns_len);
1341 		if (!ns) {
1342 			info = "namespace does not exist";
1343 			error = -ENOENT;
1344 			goto fail;
1345 		}
1346 	} else
1347 		/* released below */
1348 		ns = aa_get_ns(policy_ns ? policy_ns : labels_ns(subj));
1349 
1350 	if (!name) {
1351 		/* remove namespace - can only happen if fqname[0] == ':' */
1352 		mutex_lock_nested(&ns->parent->lock, ns->parent->level);
1353 		__aa_bump_ns_revision(ns);
1354 		__aa_remove_ns(ns);
1355 		mutex_unlock(&ns->parent->lock);
1356 	} else {
1357 		/* remove profile */
1358 		mutex_lock_nested(&ns->lock, ns->level);
1359 		profile = aa_get_profile(__lookup_profile(&ns->base, name));
1360 		if (!profile) {
1361 			error = -ENOENT;
1362 			info = "profile does not exist";
1363 			goto fail_ns_lock;
1364 		}
1365 		name = profile->base.hname;
1366 		__aa_bump_ns_revision(ns);
1367 		__remove_profile(profile);
1368 		__aa_labelset_update_subtree(ns);
1369 		mutex_unlock(&ns->lock);
1370 	}
1371 
1372 	/* don't fail removal if audit fails */
1373 	(void) audit_policy(subj, OP_PROF_RM, ns_name, name, info,
1374 			    error);
1375 	aa_put_ns(ns);
1376 	aa_put_profile(profile);
1377 	return size;
1378 
1379 fail_ns_lock:
1380 	mutex_unlock(&ns->lock);
1381 	aa_put_ns(ns);
1382 
1383 fail:
1384 	(void) audit_policy(subj, OP_PROF_RM, ns_name, name, info,
1385 			    error);
1386 	return error;
1387 }
1388