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