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