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