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