xref: /openbmc/linux/security/apparmor/domain.c (revision 4eb7ae7a)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * AppArmor security module
4  *
5  * This file contains AppArmor policy attachment and domain transitions
6  *
7  * Copyright (C) 2002-2008 Novell/SUSE
8  * Copyright 2009-2010 Canonical Ltd.
9  */
10 
11 #include <linux/errno.h>
12 #include <linux/fdtable.h>
13 #include <linux/file.h>
14 #include <linux/mount.h>
15 #include <linux/syscalls.h>
16 #include <linux/tracehook.h>
17 #include <linux/personality.h>
18 #include <linux/xattr.h>
19 
20 #include "include/audit.h"
21 #include "include/apparmorfs.h"
22 #include "include/cred.h"
23 #include "include/domain.h"
24 #include "include/file.h"
25 #include "include/ipc.h"
26 #include "include/match.h"
27 #include "include/path.h"
28 #include "include/policy.h"
29 #include "include/policy_ns.h"
30 
31 /**
32  * aa_free_domain_entries - free entries in a domain table
33  * @domain: the domain table to free  (MAYBE NULL)
34  */
35 void aa_free_domain_entries(struct aa_domain *domain)
36 {
37 	int i;
38 	if (domain) {
39 		if (!domain->table)
40 			return;
41 
42 		for (i = 0; i < domain->size; i++)
43 			kzfree(domain->table[i]);
44 		kzfree(domain->table);
45 		domain->table = NULL;
46 	}
47 }
48 
49 /**
50  * may_change_ptraced_domain - check if can change profile on ptraced task
51  * @to_label: profile to change to  (NOT NULL)
52  * @info: message if there is an error
53  *
54  * Check if current is ptraced and if so if the tracing task is allowed
55  * to trace the new domain
56  *
57  * Returns: %0 or error if change not allowed
58  */
59 static int may_change_ptraced_domain(struct aa_label *to_label,
60 				     const char **info)
61 {
62 	struct task_struct *tracer;
63 	struct aa_label *tracerl = NULL;
64 	int error = 0;
65 
66 	rcu_read_lock();
67 	tracer = ptrace_parent(current);
68 	if (tracer)
69 		/* released below */
70 		tracerl = aa_get_task_label(tracer);
71 
72 	/* not ptraced */
73 	if (!tracer || unconfined(tracerl))
74 		goto out;
75 
76 	error = aa_may_ptrace(tracerl, to_label, PTRACE_MODE_ATTACH);
77 
78 out:
79 	rcu_read_unlock();
80 	aa_put_label(tracerl);
81 
82 	if (error)
83 		*info = "ptrace prevents transition";
84 	return error;
85 }
86 
87 /**** TODO: dedup to aa_label_match - needs perm and dfa, merging
88  * specifically this is an exact copy of aa_label_match except
89  * aa_compute_perms is replaced with aa_compute_fperms
90  * and policy.dfa with file.dfa
91  ****/
92 /* match a profile and its associated ns component if needed
93  * Assumes visibility test has already been done.
94  * If a subns profile is not to be matched should be prescreened with
95  * visibility test.
96  */
97 static inline unsigned int match_component(struct aa_profile *profile,
98 					   struct aa_profile *tp,
99 					   bool stack, unsigned int state)
100 {
101 	const char *ns_name;
102 
103 	if (stack)
104 		state = aa_dfa_match(profile->file.dfa, state, "&");
105 	if (profile->ns == tp->ns)
106 		return aa_dfa_match(profile->file.dfa, state, tp->base.hname);
107 
108 	/* try matching with namespace name and then profile */
109 	ns_name = aa_ns_name(profile->ns, tp->ns, true);
110 	state = aa_dfa_match_len(profile->file.dfa, state, ":", 1);
111 	state = aa_dfa_match(profile->file.dfa, state, ns_name);
112 	state = aa_dfa_match_len(profile->file.dfa, state, ":", 1);
113 	return aa_dfa_match(profile->file.dfa, state, tp->base.hname);
114 }
115 
116 /**
117  * label_compound_match - find perms for full compound label
118  * @profile: profile to find perms for
119  * @label: label to check access permissions for
120  * @stack: whether this is a stacking request
121  * @start: state to start match in
122  * @subns: whether to do permission checks on components in a subns
123  * @request: permissions to request
124  * @perms: perms struct to set
125  *
126  * Returns: 0 on success else ERROR
127  *
128  * For the label A//&B//&C this does the perm match for A//&B//&C
129  * @perms should be preinitialized with allperms OR a previous permission
130  *        check to be stacked.
131  */
132 static int label_compound_match(struct aa_profile *profile,
133 				struct aa_label *label, bool stack,
134 				unsigned int state, bool subns, u32 request,
135 				struct aa_perms *perms)
136 {
137 	struct aa_profile *tp;
138 	struct label_it i;
139 	struct path_cond cond = { };
140 
141 	/* find first subcomponent that is visible */
142 	label_for_each(i, label, tp) {
143 		if (!aa_ns_visible(profile->ns, tp->ns, subns))
144 			continue;
145 		state = match_component(profile, tp, stack, state);
146 		if (!state)
147 			goto fail;
148 		goto next;
149 	}
150 
151 	/* no component visible */
152 	*perms = allperms;
153 	return 0;
154 
155 next:
156 	label_for_each_cont(i, label, tp) {
157 		if (!aa_ns_visible(profile->ns, tp->ns, subns))
158 			continue;
159 		state = aa_dfa_match(profile->file.dfa, state, "//&");
160 		state = match_component(profile, tp, false, state);
161 		if (!state)
162 			goto fail;
163 	}
164 	*perms = aa_compute_fperms(profile->file.dfa, state, &cond);
165 	aa_apply_modes_to_perms(profile, perms);
166 	if ((perms->allow & request) != request)
167 		return -EACCES;
168 
169 	return 0;
170 
171 fail:
172 	*perms = nullperms;
173 	return -EACCES;
174 }
175 
176 /**
177  * label_components_match - find perms for all subcomponents of a label
178  * @profile: profile to find perms for
179  * @label: label to check access permissions for
180  * @stack: whether this is a stacking request
181  * @start: state to start match in
182  * @subns: whether to do permission checks on components in a subns
183  * @request: permissions to request
184  * @perms: an initialized perms struct to add accumulation to
185  *
186  * Returns: 0 on success else ERROR
187  *
188  * For the label A//&B//&C this does the perm match for each of A and B and C
189  * @perms should be preinitialized with allperms OR a previous permission
190  *        check to be stacked.
191  */
192 static int label_components_match(struct aa_profile *profile,
193 				  struct aa_label *label, bool stack,
194 				  unsigned int start, bool subns, u32 request,
195 				  struct aa_perms *perms)
196 {
197 	struct aa_profile *tp;
198 	struct label_it i;
199 	struct aa_perms tmp;
200 	struct path_cond cond = { };
201 	unsigned int state = 0;
202 
203 	/* find first subcomponent to test */
204 	label_for_each(i, label, tp) {
205 		if (!aa_ns_visible(profile->ns, tp->ns, subns))
206 			continue;
207 		state = match_component(profile, tp, stack, start);
208 		if (!state)
209 			goto fail;
210 		goto next;
211 	}
212 
213 	/* no subcomponents visible - no change in perms */
214 	return 0;
215 
216 next:
217 	tmp = aa_compute_fperms(profile->file.dfa, state, &cond);
218 	aa_apply_modes_to_perms(profile, &tmp);
219 	aa_perms_accum(perms, &tmp);
220 	label_for_each_cont(i, label, tp) {
221 		if (!aa_ns_visible(profile->ns, tp->ns, subns))
222 			continue;
223 		state = match_component(profile, tp, stack, start);
224 		if (!state)
225 			goto fail;
226 		tmp = aa_compute_fperms(profile->file.dfa, state, &cond);
227 		aa_apply_modes_to_perms(profile, &tmp);
228 		aa_perms_accum(perms, &tmp);
229 	}
230 
231 	if ((perms->allow & request) != request)
232 		return -EACCES;
233 
234 	return 0;
235 
236 fail:
237 	*perms = nullperms;
238 	return -EACCES;
239 }
240 
241 /**
242  * label_match - do a multi-component label match
243  * @profile: profile to match against (NOT NULL)
244  * @label: label to match (NOT NULL)
245  * @stack: whether this is a stacking request
246  * @state: state to start in
247  * @subns: whether to match subns components
248  * @request: permission request
249  * @perms: Returns computed perms (NOT NULL)
250  *
251  * Returns: the state the match finished in, may be the none matching state
252  */
253 static int label_match(struct aa_profile *profile, struct aa_label *label,
254 		       bool stack, unsigned int state, bool subns, u32 request,
255 		       struct aa_perms *perms)
256 {
257 	int error;
258 
259 	*perms = nullperms;
260 	error = label_compound_match(profile, label, stack, state, subns,
261 				     request, perms);
262 	if (!error)
263 		return error;
264 
265 	*perms = allperms;
266 	return label_components_match(profile, label, stack, state, subns,
267 				      request, perms);
268 }
269 
270 /******* end TODO: dedup *****/
271 
272 /**
273  * change_profile_perms - find permissions for change_profile
274  * @profile: the current profile  (NOT NULL)
275  * @target: label to transition to (NOT NULL)
276  * @stack: whether this is a stacking request
277  * @request: requested perms
278  * @start: state to start matching in
279  *
280  *
281  * Returns: permission set
282  *
283  * currently only matches full label A//&B//&C or individual components A, B, C
284  * not arbitrary combinations. Eg. A//&B, C
285  */
286 static int change_profile_perms(struct aa_profile *profile,
287 				struct aa_label *target, bool stack,
288 				u32 request, unsigned int start,
289 				struct aa_perms *perms)
290 {
291 	if (profile_unconfined(profile)) {
292 		perms->allow = AA_MAY_CHANGE_PROFILE | AA_MAY_ONEXEC;
293 		perms->audit = perms->quiet = perms->kill = 0;
294 		return 0;
295 	}
296 
297 	/* TODO: add profile in ns screening */
298 	return label_match(profile, target, stack, start, true, request, perms);
299 }
300 
301 /**
302  * aa_xattrs_match - check whether a file matches the xattrs defined in profile
303  * @bprm: binprm struct for the process to validate
304  * @profile: profile to match against (NOT NULL)
305  * @state: state to start match in
306  *
307  * Returns: number of extended attributes that matched, or < 0 on error
308  */
309 static int aa_xattrs_match(const struct linux_binprm *bprm,
310 			   struct aa_profile *profile, unsigned int state)
311 {
312 	int i;
313 	ssize_t size;
314 	struct dentry *d;
315 	char *value = NULL;
316 	int value_size = 0, ret = profile->xattr_count;
317 
318 	if (!bprm || !profile->xattr_count)
319 		return 0;
320 
321 	/* transition from exec match to xattr set */
322 	state = aa_dfa_null_transition(profile->xmatch, state);
323 
324 	d = bprm->file->f_path.dentry;
325 
326 	for (i = 0; i < profile->xattr_count; i++) {
327 		size = vfs_getxattr_alloc(d, profile->xattrs[i], &value,
328 					  value_size, GFP_KERNEL);
329 		if (size >= 0) {
330 			u32 perm;
331 
332 			/* Check the xattr value, not just presence */
333 			state = aa_dfa_match_len(profile->xmatch, state, value,
334 						 size);
335 			perm = dfa_user_allow(profile->xmatch, state);
336 			if (!(perm & MAY_EXEC)) {
337 				ret = -EINVAL;
338 				goto out;
339 			}
340 		}
341 		/* transition to next element */
342 		state = aa_dfa_null_transition(profile->xmatch, state);
343 		if (size < 0) {
344 			/*
345 			 * No xattr match, so verify if transition to
346 			 * next element was valid. IFF so the xattr
347 			 * was optional.
348 			 */
349 			if (!state) {
350 				ret = -EINVAL;
351 				goto out;
352 			}
353 			/* don't count missing optional xattr as matched */
354 			ret--;
355 		}
356 	}
357 
358 out:
359 	kfree(value);
360 	return ret;
361 }
362 
363 /**
364  * __attach_match_ - find an attachment match
365  * @bprm - binprm structure of transitioning task
366  * @name - to match against  (NOT NULL)
367  * @head - profile list to walk  (NOT NULL)
368  * @info - info message if there was an error (NOT NULL)
369  *
370  * Do a linear search on the profiles in the list.  There is a matching
371  * preference where an exact match is preferred over a name which uses
372  * expressions to match, and matching expressions with the greatest
373  * xmatch_len are preferred.
374  *
375  * Requires: @head not be shared or have appropriate locks held
376  *
377  * Returns: profile or NULL if no match found
378  */
379 static struct aa_profile *__attach_match(const struct linux_binprm *bprm,
380 					 const char *name,
381 					 struct list_head *head,
382 					 const char **info)
383 {
384 	int candidate_len = 0, candidate_xattrs = 0;
385 	bool conflict = false;
386 	struct aa_profile *profile, *candidate = NULL;
387 
388 	AA_BUG(!name);
389 	AA_BUG(!head);
390 
391 	list_for_each_entry_rcu(profile, head, base.list) {
392 		if (profile->label.flags & FLAG_NULL &&
393 		    &profile->label == ns_unconfined(profile->ns))
394 			continue;
395 
396 		/* Find the "best" matching profile. Profiles must
397 		 * match the path and extended attributes (if any)
398 		 * associated with the file. A more specific path
399 		 * match will be preferred over a less specific one,
400 		 * and a match with more matching extended attributes
401 		 * will be preferred over one with fewer. If the best
402 		 * match has both the same level of path specificity
403 		 * and the same number of matching extended attributes
404 		 * as another profile, signal a conflict and refuse to
405 		 * match.
406 		 */
407 		if (profile->xmatch) {
408 			unsigned int state, count;
409 			u32 perm;
410 
411 			state = aa_dfa_leftmatch(profile->xmatch, DFA_START,
412 						 name, &count);
413 			perm = dfa_user_allow(profile->xmatch, state);
414 			/* any accepting state means a valid match. */
415 			if (perm & MAY_EXEC) {
416 				int ret;
417 
418 				if (count < candidate_len)
419 					continue;
420 
421 				ret = aa_xattrs_match(bprm, profile, state);
422 				/* Fail matching if the xattrs don't match */
423 				if (ret < 0)
424 					continue;
425 
426 				/*
427 				 * TODO: allow for more flexible best match
428 				 *
429 				 * The new match isn't more specific
430 				 * than the current best match
431 				 */
432 				if (count == candidate_len &&
433 				    ret <= candidate_xattrs) {
434 					/* Match is equivalent, so conflict */
435 					if (ret == candidate_xattrs)
436 						conflict = true;
437 					continue;
438 				}
439 
440 				/* Either the same length with more matching
441 				 * xattrs, or a longer match
442 				 */
443 				candidate = profile;
444 				candidate_len = profile->xmatch_len;
445 				candidate_xattrs = ret;
446 				conflict = false;
447 			}
448 		} else if (!strcmp(profile->base.name, name))
449 			/*
450 			 * old exact non-re match, without conditionals such
451 			 * as xattrs. no more searching required
452 			 */
453 			return profile;
454 	}
455 
456 	if (conflict) {
457 		*info = "conflicting profile attachments";
458 		return NULL;
459 	}
460 
461 	return candidate;
462 }
463 
464 /**
465  * find_attach - do attachment search for unconfined processes
466  * @bprm - binprm structure of transitioning task
467  * @ns: the current namespace  (NOT NULL)
468  * @list: list to search  (NOT NULL)
469  * @name: the executable name to match against  (NOT NULL)
470  * @info: info message if there was an error
471  *
472  * Returns: label or NULL if no match found
473  */
474 static struct aa_label *find_attach(const struct linux_binprm *bprm,
475 				    struct aa_ns *ns, struct list_head *list,
476 				    const char *name, const char **info)
477 {
478 	struct aa_profile *profile;
479 
480 	rcu_read_lock();
481 	profile = aa_get_profile(__attach_match(bprm, name, list, info));
482 	rcu_read_unlock();
483 
484 	return profile ? &profile->label : NULL;
485 }
486 
487 static const char *next_name(int xtype, const char *name)
488 {
489 	return NULL;
490 }
491 
492 /**
493  * x_table_lookup - lookup an x transition name via transition table
494  * @profile: current profile (NOT NULL)
495  * @xindex: index into x transition table
496  * @name: returns: name tested to find label (NOT NULL)
497  *
498  * Returns: refcounted label, or NULL on failure (MAYBE NULL)
499  */
500 struct aa_label *x_table_lookup(struct aa_profile *profile, u32 xindex,
501 				const char **name)
502 {
503 	struct aa_label *label = NULL;
504 	u32 xtype = xindex & AA_X_TYPE_MASK;
505 	int index = xindex & AA_X_INDEX_MASK;
506 
507 	AA_BUG(!name);
508 
509 	/* index is guaranteed to be in range, validated at load time */
510 	/* TODO: move lookup parsing to unpack time so this is a straight
511 	 *       index into the resultant label
512 	 */
513 	for (*name = profile->file.trans.table[index]; !label && *name;
514 	     *name = next_name(xtype, *name)) {
515 		if (xindex & AA_X_CHILD) {
516 			struct aa_profile *new_profile;
517 			/* release by caller */
518 			new_profile = aa_find_child(profile, *name);
519 			if (new_profile)
520 				label = &new_profile->label;
521 			continue;
522 		}
523 		label = aa_label_parse(&profile->label, *name, GFP_KERNEL,
524 				       true, false);
525 		if (IS_ERR(label))
526 			label = NULL;
527 	}
528 
529 	/* released by caller */
530 
531 	return label;
532 }
533 
534 /**
535  * x_to_label - get target label for a given xindex
536  * @profile: current profile  (NOT NULL)
537  * @bprm: binprm structure of transitioning task
538  * @name: name to lookup (NOT NULL)
539  * @xindex: index into x transition table
540  * @lookupname: returns: name used in lookup if one was specified (NOT NULL)
541  *
542  * find label for a transition index
543  *
544  * Returns: refcounted label or NULL if not found available
545  */
546 static struct aa_label *x_to_label(struct aa_profile *profile,
547 				   const struct linux_binprm *bprm,
548 				   const char *name, u32 xindex,
549 				   const char **lookupname,
550 				   const char **info)
551 {
552 	struct aa_label *new = NULL;
553 	struct aa_ns *ns = profile->ns;
554 	u32 xtype = xindex & AA_X_TYPE_MASK;
555 	const char *stack = NULL;
556 
557 	switch (xtype) {
558 	case AA_X_NONE:
559 		/* fail exec unless ix || ux fallback - handled by caller */
560 		*lookupname = NULL;
561 		break;
562 	case AA_X_TABLE:
563 		/* TODO: fix when perm mapping done at unload */
564 		stack = profile->file.trans.table[xindex & AA_X_INDEX_MASK];
565 		if (*stack != '&') {
566 			/* released by caller */
567 			new = x_table_lookup(profile, xindex, lookupname);
568 			stack = NULL;
569 			break;
570 		}
571 		/* fall through - to X_NAME */
572 	case AA_X_NAME:
573 		if (xindex & AA_X_CHILD)
574 			/* released by caller */
575 			new = find_attach(bprm, ns, &profile->base.profiles,
576 					  name, info);
577 		else
578 			/* released by caller */
579 			new = find_attach(bprm, ns, &ns->base.profiles,
580 					  name, info);
581 		*lookupname = name;
582 		break;
583 	}
584 
585 	if (!new) {
586 		if (xindex & AA_X_INHERIT) {
587 			/* (p|c|n)ix - don't change profile but do
588 			 * use the newest version
589 			 */
590 			*info = "ix fallback";
591 			/* no profile && no error */
592 			new = aa_get_newest_label(&profile->label);
593 		} else if (xindex & AA_X_UNCONFINED) {
594 			new = aa_get_newest_label(ns_unconfined(profile->ns));
595 			*info = "ux fallback";
596 		}
597 	}
598 
599 	if (new && stack) {
600 		/* base the stack on post domain transition */
601 		struct aa_label *base = new;
602 
603 		new = aa_label_parse(base, stack, GFP_KERNEL, true, false);
604 		if (IS_ERR(new))
605 			new = NULL;
606 		aa_put_label(base);
607 	}
608 
609 	/* released by caller */
610 	return new;
611 }
612 
613 static struct aa_label *profile_transition(struct aa_profile *profile,
614 					   const struct linux_binprm *bprm,
615 					   char *buffer, struct path_cond *cond,
616 					   bool *secure_exec)
617 {
618 	struct aa_label *new = NULL;
619 	struct aa_profile *component;
620 	struct label_it i;
621 	const char *info = NULL, *name = NULL, *target = NULL;
622 	unsigned int state = profile->file.start;
623 	struct aa_perms perms = {};
624 	bool nonewprivs = false;
625 	int error = 0;
626 
627 	AA_BUG(!profile);
628 	AA_BUG(!bprm);
629 	AA_BUG(!buffer);
630 
631 	error = aa_path_name(&bprm->file->f_path, profile->path_flags, buffer,
632 			     &name, &info, profile->disconnected);
633 	if (error) {
634 		if (profile_unconfined(profile) ||
635 		    (profile->label.flags & FLAG_IX_ON_NAME_ERROR)) {
636 			AA_DEBUG("name lookup ix on error");
637 			error = 0;
638 			new = aa_get_newest_label(&profile->label);
639 		}
640 		name = bprm->filename;
641 		goto audit;
642 	}
643 
644 	if (profile_unconfined(profile)) {
645 		new = find_attach(bprm, profile->ns,
646 				  &profile->ns->base.profiles, name, &info);
647 		if (new) {
648 			AA_DEBUG("unconfined attached to new label");
649 			return new;
650 		}
651 		AA_DEBUG("unconfined exec no attachment");
652 		return aa_get_newest_label(&profile->label);
653 	}
654 
655 	/* find exec permissions for name */
656 	state = aa_str_perms(profile->file.dfa, state, name, cond, &perms);
657 	if (perms.allow & MAY_EXEC) {
658 		/* exec permission determine how to transition */
659 		new = x_to_label(profile, bprm, name, perms.xindex, &target,
660 				 &info);
661 		if (new && new->proxy == profile->label.proxy && info) {
662 			/* hack ix fallback - improve how this is detected */
663 			goto audit;
664 		} else if (!new) {
665 			error = -EACCES;
666 			info = "profile transition not found";
667 			/* remove MAY_EXEC to audit as failure */
668 			perms.allow &= ~MAY_EXEC;
669 		} else {
670 			/* verify that each component's xattr requirements are
671 			 * met, and fail execution otherwise
672 			 */
673 			label_for_each(i, new, component) {
674 				if (aa_xattrs_match(bprm, component, state) <
675 				    0) {
676 					error = -EACCES;
677 					info = "required xattrs not present";
678 					perms.allow &= ~MAY_EXEC;
679 					aa_put_label(new);
680 					new = NULL;
681 					goto audit;
682 				}
683 			}
684 		}
685 	} else if (COMPLAIN_MODE(profile)) {
686 		/* no exec permission - learning mode */
687 		struct aa_profile *new_profile = NULL;
688 
689 		new_profile = aa_new_null_profile(profile, false, name,
690 						  GFP_KERNEL);
691 		if (!new_profile) {
692 			error = -ENOMEM;
693 			info = "could not create null profile";
694 		} else {
695 			error = -EACCES;
696 			new = &new_profile->label;
697 		}
698 		perms.xindex |= AA_X_UNSAFE;
699 	} else
700 		/* fail exec */
701 		error = -EACCES;
702 
703 	if (!new)
704 		goto audit;
705 
706 
707 	if (!(perms.xindex & AA_X_UNSAFE)) {
708 		if (DEBUG_ON) {
709 			dbg_printk("apparmor: scrubbing environment variables"
710 				   " for %s profile=", name);
711 			aa_label_printk(new, GFP_KERNEL);
712 			dbg_printk("\n");
713 		}
714 		*secure_exec = true;
715 	}
716 
717 audit:
718 	aa_audit_file(profile, &perms, OP_EXEC, MAY_EXEC, name, target, new,
719 		      cond->uid, info, error);
720 	if (!new || nonewprivs) {
721 		aa_put_label(new);
722 		return ERR_PTR(error);
723 	}
724 
725 	return new;
726 }
727 
728 static int profile_onexec(struct aa_profile *profile, struct aa_label *onexec,
729 			  bool stack, const struct linux_binprm *bprm,
730 			  char *buffer, struct path_cond *cond,
731 			  bool *secure_exec)
732 {
733 	unsigned int state = profile->file.start;
734 	struct aa_perms perms = {};
735 	const char *xname = NULL, *info = "change_profile onexec";
736 	int error = -EACCES;
737 
738 	AA_BUG(!profile);
739 	AA_BUG(!onexec);
740 	AA_BUG(!bprm);
741 	AA_BUG(!buffer);
742 
743 	if (profile_unconfined(profile)) {
744 		/* change_profile on exec already granted */
745 		/*
746 		 * NOTE: Domain transitions from unconfined are allowed
747 		 * even when no_new_privs is set because this aways results
748 		 * in a further reduction of permissions.
749 		 */
750 		return 0;
751 	}
752 
753 	error = aa_path_name(&bprm->file->f_path, profile->path_flags, buffer,
754 			     &xname, &info, profile->disconnected);
755 	if (error) {
756 		if (profile_unconfined(profile) ||
757 		    (profile->label.flags & FLAG_IX_ON_NAME_ERROR)) {
758 			AA_DEBUG("name lookup ix on error");
759 			error = 0;
760 		}
761 		xname = bprm->filename;
762 		goto audit;
763 	}
764 
765 	/* find exec permissions for name */
766 	state = aa_str_perms(profile->file.dfa, state, xname, cond, &perms);
767 	if (!(perms.allow & AA_MAY_ONEXEC)) {
768 		info = "no change_onexec valid for executable";
769 		goto audit;
770 	}
771 	/* test if this exec can be paired with change_profile onexec.
772 	 * onexec permission is linked to exec with a standard pairing
773 	 * exec\0change_profile
774 	 */
775 	state = aa_dfa_null_transition(profile->file.dfa, state);
776 	error = change_profile_perms(profile, onexec, stack, AA_MAY_ONEXEC,
777 				     state, &perms);
778 	if (error) {
779 		perms.allow &= ~AA_MAY_ONEXEC;
780 		goto audit;
781 	}
782 
783 	if (!(perms.xindex & AA_X_UNSAFE)) {
784 		if (DEBUG_ON) {
785 			dbg_printk("apparmor: scrubbing environment "
786 				   "variables for %s label=", xname);
787 			aa_label_printk(onexec, GFP_KERNEL);
788 			dbg_printk("\n");
789 		}
790 		*secure_exec = true;
791 	}
792 
793 audit:
794 	return aa_audit_file(profile, &perms, OP_EXEC, AA_MAY_ONEXEC, xname,
795 			     NULL, onexec, cond->uid, info, error);
796 }
797 
798 /* ensure none ns domain transitions are correctly applied with onexec */
799 
800 static struct aa_label *handle_onexec(struct aa_label *label,
801 				      struct aa_label *onexec, bool stack,
802 				      const struct linux_binprm *bprm,
803 				      char *buffer, struct path_cond *cond,
804 				      bool *unsafe)
805 {
806 	struct aa_profile *profile;
807 	struct aa_label *new;
808 	int error;
809 
810 	AA_BUG(!label);
811 	AA_BUG(!onexec);
812 	AA_BUG(!bprm);
813 	AA_BUG(!buffer);
814 
815 	if (!stack) {
816 		error = fn_for_each_in_ns(label, profile,
817 				profile_onexec(profile, onexec, stack,
818 					       bprm, buffer, cond, unsafe));
819 		if (error)
820 			return ERR_PTR(error);
821 		new = fn_label_build_in_ns(label, profile, GFP_KERNEL,
822 				aa_get_newest_label(onexec),
823 				profile_transition(profile, bprm, buffer,
824 						   cond, unsafe));
825 
826 	} else {
827 		/* TODO: determine how much we want to loosen this */
828 		error = fn_for_each_in_ns(label, profile,
829 				profile_onexec(profile, onexec, stack, bprm,
830 					       buffer, cond, unsafe));
831 		if (error)
832 			return ERR_PTR(error);
833 		new = fn_label_build_in_ns(label, profile, GFP_KERNEL,
834 				aa_label_merge(&profile->label, onexec,
835 					       GFP_KERNEL),
836 				profile_transition(profile, bprm, buffer,
837 						   cond, unsafe));
838 	}
839 
840 	if (new)
841 		return new;
842 
843 	/* TODO: get rid of GLOBAL_ROOT_UID */
844 	error = fn_for_each_in_ns(label, profile,
845 			aa_audit_file(profile, &nullperms, OP_CHANGE_ONEXEC,
846 				      AA_MAY_ONEXEC, bprm->filename, NULL,
847 				      onexec, GLOBAL_ROOT_UID,
848 				      "failed to build target label", -ENOMEM));
849 	return ERR_PTR(error);
850 }
851 
852 /**
853  * apparmor_bprm_set_creds - set the new creds on the bprm struct
854  * @bprm: binprm for the exec  (NOT NULL)
855  *
856  * Returns: %0 or error on failure
857  *
858  * TODO: once the other paths are done see if we can't refactor into a fn
859  */
860 int apparmor_bprm_set_creds(struct linux_binprm *bprm)
861 {
862 	struct aa_task_ctx *ctx;
863 	struct aa_label *label, *new = NULL;
864 	struct aa_profile *profile;
865 	char *buffer = NULL;
866 	const char *info = NULL;
867 	int error = 0;
868 	bool unsafe = false;
869 	struct path_cond cond = {
870 		file_inode(bprm->file)->i_uid,
871 		file_inode(bprm->file)->i_mode
872 	};
873 
874 	if (bprm->called_set_creds)
875 		return 0;
876 
877 	ctx = task_ctx(current);
878 	AA_BUG(!cred_label(bprm->cred));
879 	AA_BUG(!ctx);
880 
881 	label = aa_get_newest_label(cred_label(bprm->cred));
882 
883 	/*
884 	 * Detect no new privs being set, and store the label it
885 	 * occurred under. Ideally this would happen when nnp
886 	 * is set but there isn't a good way to do that yet.
887 	 *
888 	 * Testing for unconfined must be done before the subset test
889 	 */
890 	if ((bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS) && !unconfined(label) &&
891 	    !ctx->nnp)
892 		ctx->nnp = aa_get_label(label);
893 
894 	/* buffer freed below, name is pointer into buffer */
895 	buffer = aa_get_buffer(false);
896 	if (!buffer) {
897 		error = -ENOMEM;
898 		goto done;
899 	}
900 
901 	/* Test for onexec first as onexec override other x transitions. */
902 	if (ctx->onexec)
903 		new = handle_onexec(label, ctx->onexec, ctx->token,
904 				    bprm, buffer, &cond, &unsafe);
905 	else
906 		new = fn_label_build(label, profile, GFP_KERNEL,
907 				profile_transition(profile, bprm, buffer,
908 						   &cond, &unsafe));
909 
910 	AA_BUG(!new);
911 	if (IS_ERR(new)) {
912 		error = PTR_ERR(new);
913 		goto done;
914 	} else if (!new) {
915 		error = -ENOMEM;
916 		goto done;
917 	}
918 
919 	/* Policy has specified a domain transitions. If no_new_privs and
920 	 * confined ensure the transition is to confinement that is subset
921 	 * of the confinement when the task entered no new privs.
922 	 *
923 	 * NOTE: Domain transitions from unconfined and to stacked
924 	 * subsets are allowed even when no_new_privs is set because this
925 	 * aways results in a further reduction of permissions.
926 	 */
927 	if ((bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS) &&
928 	    !unconfined(label) && !aa_label_is_subset(new, ctx->nnp)) {
929 		error = -EPERM;
930 		info = "no new privs";
931 		goto audit;
932 	}
933 
934 	if (bprm->unsafe & LSM_UNSAFE_SHARE) {
935 		/* FIXME: currently don't mediate shared state */
936 		;
937 	}
938 
939 	if (bprm->unsafe & (LSM_UNSAFE_PTRACE)) {
940 		/* TODO: test needs to be profile of label to new */
941 		error = may_change_ptraced_domain(new, &info);
942 		if (error)
943 			goto audit;
944 	}
945 
946 	if (unsafe) {
947 		if (DEBUG_ON) {
948 			dbg_printk("scrubbing environment variables for %s "
949 				   "label=", bprm->filename);
950 			aa_label_printk(new, GFP_KERNEL);
951 			dbg_printk("\n");
952 		}
953 		bprm->secureexec = 1;
954 	}
955 
956 	if (label->proxy != new->proxy) {
957 		/* when transitioning clear unsafe personality bits */
958 		if (DEBUG_ON) {
959 			dbg_printk("apparmor: clearing unsafe personality "
960 				   "bits. %s label=", bprm->filename);
961 			aa_label_printk(new, GFP_KERNEL);
962 			dbg_printk("\n");
963 		}
964 		bprm->per_clear |= PER_CLEAR_ON_SETID;
965 	}
966 	aa_put_label(cred_label(bprm->cred));
967 	/* transfer reference, released when cred is freed */
968 	set_cred_label(bprm->cred, new);
969 
970 done:
971 	aa_put_label(label);
972 	aa_put_buffer(buffer);
973 
974 	return error;
975 
976 audit:
977 	error = fn_for_each(label, profile,
978 			aa_audit_file(profile, &nullperms, OP_EXEC, MAY_EXEC,
979 				      bprm->filename, NULL, new,
980 				      file_inode(bprm->file)->i_uid, info,
981 				      error));
982 	aa_put_label(new);
983 	goto done;
984 }
985 
986 /*
987  * Functions for self directed profile change
988  */
989 
990 
991 /* helper fn for change_hat
992  *
993  * Returns: label for hat transition OR ERR_PTR.  Does NOT return NULL
994  */
995 static struct aa_label *build_change_hat(struct aa_profile *profile,
996 					 const char *name, bool sibling)
997 {
998 	struct aa_profile *root, *hat = NULL;
999 	const char *info = NULL;
1000 	int error = 0;
1001 
1002 	if (sibling && PROFILE_IS_HAT(profile)) {
1003 		root = aa_get_profile_rcu(&profile->parent);
1004 	} else if (!sibling && !PROFILE_IS_HAT(profile)) {
1005 		root = aa_get_profile(profile);
1006 	} else {
1007 		info = "conflicting target types";
1008 		error = -EPERM;
1009 		goto audit;
1010 	}
1011 
1012 	hat = aa_find_child(root, name);
1013 	if (!hat) {
1014 		error = -ENOENT;
1015 		if (COMPLAIN_MODE(profile)) {
1016 			hat = aa_new_null_profile(profile, true, name,
1017 						  GFP_KERNEL);
1018 			if (!hat) {
1019 				info = "failed null profile create";
1020 				error = -ENOMEM;
1021 			}
1022 		}
1023 	}
1024 	aa_put_profile(root);
1025 
1026 audit:
1027 	aa_audit_file(profile, &nullperms, OP_CHANGE_HAT, AA_MAY_CHANGEHAT,
1028 		      name, hat ? hat->base.hname : NULL,
1029 		      hat ? &hat->label : NULL, GLOBAL_ROOT_UID, info,
1030 		      error);
1031 	if (!hat || (error && error != -ENOENT))
1032 		return ERR_PTR(error);
1033 	/* if hat && error - complain mode, already audited and we adjust for
1034 	 * complain mode allow by returning hat->label
1035 	 */
1036 	return &hat->label;
1037 }
1038 
1039 /* helper fn for changing into a hat
1040  *
1041  * Returns: label for hat transition or ERR_PTR. Does not return NULL
1042  */
1043 static struct aa_label *change_hat(struct aa_label *label, const char *hats[],
1044 				   int count, int flags)
1045 {
1046 	struct aa_profile *profile, *root, *hat = NULL;
1047 	struct aa_label *new;
1048 	struct label_it it;
1049 	bool sibling = false;
1050 	const char *name, *info = NULL;
1051 	int i, error;
1052 
1053 	AA_BUG(!label);
1054 	AA_BUG(!hats);
1055 	AA_BUG(count < 1);
1056 
1057 	if (PROFILE_IS_HAT(labels_profile(label)))
1058 		sibling = true;
1059 
1060 	/*find first matching hat */
1061 	for (i = 0; i < count && !hat; i++) {
1062 		name = hats[i];
1063 		label_for_each_in_ns(it, labels_ns(label), label, profile) {
1064 			if (sibling && PROFILE_IS_HAT(profile)) {
1065 				root = aa_get_profile_rcu(&profile->parent);
1066 			} else if (!sibling && !PROFILE_IS_HAT(profile)) {
1067 				root = aa_get_profile(profile);
1068 			} else {	/* conflicting change type */
1069 				info = "conflicting targets types";
1070 				error = -EPERM;
1071 				goto fail;
1072 			}
1073 			hat = aa_find_child(root, name);
1074 			aa_put_profile(root);
1075 			if (!hat) {
1076 				if (!COMPLAIN_MODE(profile))
1077 					goto outer_continue;
1078 				/* complain mode succeed as if hat */
1079 			} else if (!PROFILE_IS_HAT(hat)) {
1080 				info = "target not hat";
1081 				error = -EPERM;
1082 				aa_put_profile(hat);
1083 				goto fail;
1084 			}
1085 			aa_put_profile(hat);
1086 		}
1087 		/* found a hat for all profiles in ns */
1088 		goto build;
1089 outer_continue:
1090 	;
1091 	}
1092 	/* no hats that match, find appropriate error
1093 	 *
1094 	 * In complain mode audit of the failure is based off of the first
1095 	 * hat supplied.  This is done due how userspace interacts with
1096 	 * change_hat.
1097 	 */
1098 	name = NULL;
1099 	label_for_each_in_ns(it, labels_ns(label), label, profile) {
1100 		if (!list_empty(&profile->base.profiles)) {
1101 			info = "hat not found";
1102 			error = -ENOENT;
1103 			goto fail;
1104 		}
1105 	}
1106 	info = "no hats defined";
1107 	error = -ECHILD;
1108 
1109 fail:
1110 	label_for_each_in_ns(it, labels_ns(label), label, profile) {
1111 		/*
1112 		 * no target as it has failed to be found or built
1113 		 *
1114 		 * change_hat uses probing and should not log failures
1115 		 * related to missing hats
1116 		 */
1117 		/* TODO: get rid of GLOBAL_ROOT_UID */
1118 		if (count > 1 || COMPLAIN_MODE(profile)) {
1119 			aa_audit_file(profile, &nullperms, OP_CHANGE_HAT,
1120 				      AA_MAY_CHANGEHAT, name, NULL, NULL,
1121 				      GLOBAL_ROOT_UID, info, error);
1122 		}
1123 	}
1124 	return ERR_PTR(error);
1125 
1126 build:
1127 	new = fn_label_build_in_ns(label, profile, GFP_KERNEL,
1128 				   build_change_hat(profile, name, sibling),
1129 				   aa_get_label(&profile->label));
1130 	if (!new) {
1131 		info = "label build failed";
1132 		error = -ENOMEM;
1133 		goto fail;
1134 	} /* else if (IS_ERR) build_change_hat has logged error so return new */
1135 
1136 	return new;
1137 }
1138 
1139 /**
1140  * aa_change_hat - change hat to/from subprofile
1141  * @hats: vector of hat names to try changing into (MAYBE NULL if @count == 0)
1142  * @count: number of hat names in @hats
1143  * @token: magic value to validate the hat change
1144  * @flags: flags affecting behavior of the change
1145  *
1146  * Returns %0 on success, error otherwise.
1147  *
1148  * Change to the first profile specified in @hats that exists, and store
1149  * the @hat_magic in the current task context.  If the count == 0 and the
1150  * @token matches that stored in the current task context, return to the
1151  * top level profile.
1152  *
1153  * change_hat only applies to profiles in the current ns, and each profile
1154  * in the ns must make the same transition otherwise change_hat will fail.
1155  */
1156 int aa_change_hat(const char *hats[], int count, u64 token, int flags)
1157 {
1158 	const struct cred *cred;
1159 	struct aa_task_ctx *ctx = task_ctx(current);
1160 	struct aa_label *label, *previous, *new = NULL, *target = NULL;
1161 	struct aa_profile *profile;
1162 	struct aa_perms perms = {};
1163 	const char *info = NULL;
1164 	int error = 0;
1165 
1166 	/* released below */
1167 	cred = get_current_cred();
1168 	label = aa_get_newest_cred_label(cred);
1169 	previous = aa_get_newest_label(ctx->previous);
1170 
1171 	/*
1172 	 * Detect no new privs being set, and store the label it
1173 	 * occurred under. Ideally this would happen when nnp
1174 	 * is set but there isn't a good way to do that yet.
1175 	 *
1176 	 * Testing for unconfined must be done before the subset test
1177 	 */
1178 	if (task_no_new_privs(current) && !unconfined(label) && !ctx->nnp)
1179 		ctx->nnp = aa_get_label(label);
1180 
1181 	if (unconfined(label)) {
1182 		info = "unconfined can not change_hat";
1183 		error = -EPERM;
1184 		goto fail;
1185 	}
1186 
1187 	if (count) {
1188 		new = change_hat(label, hats, count, flags);
1189 		AA_BUG(!new);
1190 		if (IS_ERR(new)) {
1191 			error = PTR_ERR(new);
1192 			new = NULL;
1193 			/* already audited */
1194 			goto out;
1195 		}
1196 
1197 		error = may_change_ptraced_domain(new, &info);
1198 		if (error)
1199 			goto fail;
1200 
1201 		/*
1202 		 * no new privs prevents domain transitions that would
1203 		 * reduce restrictions.
1204 		 */
1205 		if (task_no_new_privs(current) && !unconfined(label) &&
1206 		    !aa_label_is_subset(new, ctx->nnp)) {
1207 			/* not an apparmor denial per se, so don't log it */
1208 			AA_DEBUG("no_new_privs - change_hat denied");
1209 			error = -EPERM;
1210 			goto out;
1211 		}
1212 
1213 		if (flags & AA_CHANGE_TEST)
1214 			goto out;
1215 
1216 		target = new;
1217 		error = aa_set_current_hat(new, token);
1218 		if (error == -EACCES)
1219 			/* kill task in case of brute force attacks */
1220 			goto kill;
1221 	} else if (previous && !(flags & AA_CHANGE_TEST)) {
1222 		/*
1223 		 * no new privs prevents domain transitions that would
1224 		 * reduce restrictions.
1225 		 */
1226 		if (task_no_new_privs(current) && !unconfined(label) &&
1227 		    !aa_label_is_subset(previous, ctx->nnp)) {
1228 			/* not an apparmor denial per se, so don't log it */
1229 			AA_DEBUG("no_new_privs - change_hat denied");
1230 			error = -EPERM;
1231 			goto out;
1232 		}
1233 
1234 		/* Return to saved label.  Kill task if restore fails
1235 		 * to avoid brute force attacks
1236 		 */
1237 		target = previous;
1238 		error = aa_restore_previous_label(token);
1239 		if (error) {
1240 			if (error == -EACCES)
1241 				goto kill;
1242 			goto fail;
1243 		}
1244 	} /* else ignore @flags && restores when there is no saved profile */
1245 
1246 out:
1247 	aa_put_label(new);
1248 	aa_put_label(previous);
1249 	aa_put_label(label);
1250 	put_cred(cred);
1251 
1252 	return error;
1253 
1254 kill:
1255 	info = "failed token match";
1256 	perms.kill = AA_MAY_CHANGEHAT;
1257 
1258 fail:
1259 	fn_for_each_in_ns(label, profile,
1260 		aa_audit_file(profile, &perms, OP_CHANGE_HAT,
1261 			      AA_MAY_CHANGEHAT, NULL, NULL, target,
1262 			      GLOBAL_ROOT_UID, info, error));
1263 
1264 	goto out;
1265 }
1266 
1267 
1268 static int change_profile_perms_wrapper(const char *op, const char *name,
1269 					struct aa_profile *profile,
1270 					struct aa_label *target, bool stack,
1271 					u32 request, struct aa_perms *perms)
1272 {
1273 	const char *info = NULL;
1274 	int error = 0;
1275 
1276 	if (!error)
1277 		error = change_profile_perms(profile, target, stack, request,
1278 					     profile->file.start, perms);
1279 	if (error)
1280 		error = aa_audit_file(profile, perms, op, request, name,
1281 				      NULL, target, GLOBAL_ROOT_UID, info,
1282 				      error);
1283 
1284 	return error;
1285 }
1286 
1287 /**
1288  * aa_change_profile - perform a one-way profile transition
1289  * @fqname: name of profile may include namespace (NOT NULL)
1290  * @onexec: whether this transition is to take place immediately or at exec
1291  * @flags: flags affecting change behavior
1292  *
1293  * Change to new profile @name.  Unlike with hats, there is no way
1294  * to change back.  If @name isn't specified the current profile name is
1295  * used.
1296  * If @onexec then the transition is delayed until
1297  * the next exec.
1298  *
1299  * Returns %0 on success, error otherwise.
1300  */
1301 int aa_change_profile(const char *fqname, int flags)
1302 {
1303 	struct aa_label *label, *new = NULL, *target = NULL;
1304 	struct aa_profile *profile;
1305 	struct aa_perms perms = {};
1306 	const char *info = NULL;
1307 	const char *auditname = fqname;		/* retain leading & if stack */
1308 	bool stack = flags & AA_CHANGE_STACK;
1309 	struct aa_task_ctx *ctx = task_ctx(current);
1310 	int error = 0;
1311 	char *op;
1312 	u32 request;
1313 
1314 	label = aa_get_current_label();
1315 
1316 	/*
1317 	 * Detect no new privs being set, and store the label it
1318 	 * occurred under. Ideally this would happen when nnp
1319 	 * is set but there isn't a good way to do that yet.
1320 	 *
1321 	 * Testing for unconfined must be done before the subset test
1322 	 */
1323 	if (task_no_new_privs(current) && !unconfined(label) && !ctx->nnp)
1324 		ctx->nnp = aa_get_label(label);
1325 
1326 	if (!fqname || !*fqname) {
1327 		AA_DEBUG("no profile name");
1328 		return -EINVAL;
1329 	}
1330 
1331 	if (flags & AA_CHANGE_ONEXEC) {
1332 		request = AA_MAY_ONEXEC;
1333 		if (stack)
1334 			op = OP_STACK_ONEXEC;
1335 		else
1336 			op = OP_CHANGE_ONEXEC;
1337 	} else {
1338 		request = AA_MAY_CHANGE_PROFILE;
1339 		if (stack)
1340 			op = OP_STACK;
1341 		else
1342 			op = OP_CHANGE_PROFILE;
1343 	}
1344 
1345 	label = aa_get_current_label();
1346 
1347 	if (*fqname == '&') {
1348 		stack = true;
1349 		/* don't have label_parse() do stacking */
1350 		fqname++;
1351 	}
1352 	target = aa_label_parse(label, fqname, GFP_KERNEL, true, false);
1353 	if (IS_ERR(target)) {
1354 		struct aa_profile *tprofile;
1355 
1356 		info = "label not found";
1357 		error = PTR_ERR(target);
1358 		target = NULL;
1359 		/*
1360 		 * TODO: fixme using labels_profile is not right - do profile
1361 		 * per complain profile
1362 		 */
1363 		if ((flags & AA_CHANGE_TEST) ||
1364 		    !COMPLAIN_MODE(labels_profile(label)))
1365 			goto audit;
1366 		/* released below */
1367 		tprofile = aa_new_null_profile(labels_profile(label), false,
1368 					       fqname, GFP_KERNEL);
1369 		if (!tprofile) {
1370 			info = "failed null profile create";
1371 			error = -ENOMEM;
1372 			goto audit;
1373 		}
1374 		target = &tprofile->label;
1375 		goto check;
1376 	}
1377 
1378 	/*
1379 	 * self directed transitions only apply to current policy ns
1380 	 * TODO: currently requiring perms for stacking and straight change
1381 	 *       stacking doesn't strictly need this. Determine how much
1382 	 *       we want to loosen this restriction for stacking
1383 	 *
1384 	 * if (!stack) {
1385 	 */
1386 	error = fn_for_each_in_ns(label, profile,
1387 			change_profile_perms_wrapper(op, auditname,
1388 						     profile, target, stack,
1389 						     request, &perms));
1390 	if (error)
1391 		/* auditing done in change_profile_perms_wrapper */
1392 		goto out;
1393 
1394 	/* } */
1395 
1396 check:
1397 	/* check if tracing task is allowed to trace target domain */
1398 	error = may_change_ptraced_domain(target, &info);
1399 	if (error && !fn_for_each_in_ns(label, profile,
1400 					COMPLAIN_MODE(profile)))
1401 		goto audit;
1402 
1403 	/* TODO: add permission check to allow this
1404 	 * if ((flags & AA_CHANGE_ONEXEC) && !current_is_single_threaded()) {
1405 	 *      info = "not a single threaded task";
1406 	 *      error = -EACCES;
1407 	 *      goto audit;
1408 	 * }
1409 	 */
1410 	if (flags & AA_CHANGE_TEST)
1411 		goto out;
1412 
1413 	/* stacking is always a subset, so only check the nonstack case */
1414 	if (!stack) {
1415 		new = fn_label_build_in_ns(label, profile, GFP_KERNEL,
1416 					   aa_get_label(target),
1417 					   aa_get_label(&profile->label));
1418 		/*
1419 		 * no new privs prevents domain transitions that would
1420 		 * reduce restrictions.
1421 		 */
1422 		if (task_no_new_privs(current) && !unconfined(label) &&
1423 		    !aa_label_is_subset(new, ctx->nnp)) {
1424 			/* not an apparmor denial per se, so don't log it */
1425 			AA_DEBUG("no_new_privs - change_hat denied");
1426 			error = -EPERM;
1427 			goto out;
1428 		}
1429 	}
1430 
1431 	if (!(flags & AA_CHANGE_ONEXEC)) {
1432 		/* only transition profiles in the current ns */
1433 		if (stack)
1434 			new = aa_label_merge(label, target, GFP_KERNEL);
1435 		if (IS_ERR_OR_NULL(new)) {
1436 			info = "failed to build target label";
1437 			if (!new)
1438 				error = -ENOMEM;
1439 			else
1440 				error = PTR_ERR(new);
1441 			new = NULL;
1442 			perms.allow = 0;
1443 			goto audit;
1444 		}
1445 		error = aa_replace_current_label(new);
1446 	} else {
1447 		if (new) {
1448 			aa_put_label(new);
1449 			new = NULL;
1450 		}
1451 
1452 		/* full transition will be built in exec path */
1453 		error = aa_set_current_onexec(target, stack);
1454 	}
1455 
1456 audit:
1457 	error = fn_for_each_in_ns(label, profile,
1458 			aa_audit_file(profile, &perms, op, request, auditname,
1459 				      NULL, new ? new : target,
1460 				      GLOBAL_ROOT_UID, info, error));
1461 
1462 out:
1463 	aa_put_label(new);
1464 	aa_put_label(target);
1465 	aa_put_label(label);
1466 
1467 	return error;
1468 }
1469