domain.c 38.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
 * AppArmor security module
 *
 * This file contains AppArmor policy attachment and domain transitions
 *
 * Copyright (C) 2002-2008 Novell/SUSE
 * Copyright 2009-2010 Canonical Ltd.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, version 2 of the
 * License.
 */

#include <linux/errno.h>
#include <linux/fdtable.h>
#include <linux/file.h>
#include <linux/mount.h>
#include <linux/syscalls.h>
#include <linux/tracehook.h>
#include <linux/personality.h>
22
#include <linux/xattr.h>
23 24 25

#include "include/audit.h"
#include "include/apparmorfs.h"
26
#include "include/cred.h"
27 28 29 30 31 32
#include "include/domain.h"
#include "include/file.h"
#include "include/ipc.h"
#include "include/match.h"
#include "include/path.h"
#include "include/policy.h"
33
#include "include/policy_ns.h"
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

/**
 * aa_free_domain_entries - free entries in a domain table
 * @domain: the domain table to free  (MAYBE NULL)
 */
void aa_free_domain_entries(struct aa_domain *domain)
{
	int i;
	if (domain) {
		if (!domain->table)
			return;

		for (i = 0; i < domain->size; i++)
			kzfree(domain->table[i]);
		kzfree(domain->table);
		domain->table = NULL;
	}
}

/**
 * may_change_ptraced_domain - check if can change profile on ptraced task
55 56
 * @to_label: profile to change to  (NOT NULL)
 * @info: message if there is an error
57
 *
58
 * Check if current is ptraced and if so if the tracing task is allowed
59 60 61 62
 * to trace the new domain
 *
 * Returns: %0 or error if change not allowed
 */
63 64
static int may_change_ptraced_domain(struct aa_label *to_label,
				     const char **info)
65 66
{
	struct task_struct *tracer;
67
	struct aa_label *tracerl = NULL;
68 69 70
	int error = 0;

	rcu_read_lock();
71
	tracer = ptrace_parent(current);
72
	if (tracer)
73
		/* released below */
74
		tracerl = aa_get_task_label(tracer);
75 76

	/* not ptraced */
77
	if (!tracer || unconfined(tracerl))
78 79
		goto out;

80
	error = aa_may_ptrace(tracerl, to_label, PTRACE_MODE_ATTACH);
81 82

out:
83
	rcu_read_unlock();
84
	aa_put_label(tracerl);
85

86 87
	if (error)
		*info = "ptrace prevents transition";
88 89 90
	return error;
}

91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
/**** TODO: dedup to aa_label_match - needs perm and dfa, merging
 * specifically this is an exact copy of aa_label_match except
 * aa_compute_perms is replaced with aa_compute_fperms
 * and policy.dfa with file.dfa
 ****/
/* match a profile and its associated ns component if needed
 * Assumes visibility test has already been done.
 * If a subns profile is not to be matched should be prescreened with
 * visibility test.
 */
static inline unsigned int match_component(struct aa_profile *profile,
					   struct aa_profile *tp,
					   bool stack, unsigned int state)
{
	const char *ns_name;

	if (stack)
		state = aa_dfa_match(profile->file.dfa, state, "&");
	if (profile->ns == tp->ns)
		return aa_dfa_match(profile->file.dfa, state, tp->base.hname);

	/* try matching with namespace name and then profile */
	ns_name = aa_ns_name(profile->ns, tp->ns, true);
	state = aa_dfa_match_len(profile->file.dfa, state, ":", 1);
	state = aa_dfa_match(profile->file.dfa, state, ns_name);
	state = aa_dfa_match_len(profile->file.dfa, state, ":", 1);
	return aa_dfa_match(profile->file.dfa, state, tp->base.hname);
}

/**
 * label_compound_match - find perms for full compound label
 * @profile: profile to find perms for
 * @label: label to check access permissions for
 * @stack: whether this is a stacking request
 * @start: state to start match in
 * @subns: whether to do permission checks on components in a subns
 * @request: permissions to request
 * @perms: perms struct to set
 *
 * Returns: 0 on success else ERROR
 *
 * For the label A//&B//&C this does the perm match for A//&B//&C
 * @perms should be preinitialized with allperms OR a previous permission
 *        check to be stacked.
 */
static int label_compound_match(struct aa_profile *profile,
				struct aa_label *label, bool stack,
				unsigned int state, bool subns, u32 request,
				struct aa_perms *perms)
{
	struct aa_profile *tp;
	struct label_it i;
	struct path_cond cond = { };

	/* find first subcomponent that is visible */
	label_for_each(i, label, tp) {
		if (!aa_ns_visible(profile->ns, tp->ns, subns))
			continue;
		state = match_component(profile, tp, stack, state);
		if (!state)
			goto fail;
		goto next;
	}

	/* no component visible */
	*perms = allperms;
	return 0;

next:
	label_for_each_cont(i, label, tp) {
		if (!aa_ns_visible(profile->ns, tp->ns, subns))
			continue;
		state = aa_dfa_match(profile->file.dfa, state, "//&");
		state = match_component(profile, tp, false, state);
		if (!state)
			goto fail;
	}
	*perms = aa_compute_fperms(profile->file.dfa, state, &cond);
	aa_apply_modes_to_perms(profile, perms);
	if ((perms->allow & request) != request)
		return -EACCES;

	return 0;

fail:
	*perms = nullperms;
	return -EACCES;
}

/**
 * label_components_match - find perms for all subcomponents of a label
 * @profile: profile to find perms for
 * @label: label to check access permissions for
 * @stack: whether this is a stacking request
 * @start: state to start match in
 * @subns: whether to do permission checks on components in a subns
 * @request: permissions to request
 * @perms: an initialized perms struct to add accumulation to
 *
 * Returns: 0 on success else ERROR
 *
 * For the label A//&B//&C this does the perm match for each of A and B and C
 * @perms should be preinitialized with allperms OR a previous permission
 *        check to be stacked.
 */
static int label_components_match(struct aa_profile *profile,
				  struct aa_label *label, bool stack,
				  unsigned int start, bool subns, u32 request,
				  struct aa_perms *perms)
{
	struct aa_profile *tp;
	struct label_it i;
	struct aa_perms tmp;
	struct path_cond cond = { };
	unsigned int state = 0;

	/* find first subcomponent to test */
	label_for_each(i, label, tp) {
		if (!aa_ns_visible(profile->ns, tp->ns, subns))
			continue;
		state = match_component(profile, tp, stack, start);
		if (!state)
			goto fail;
		goto next;
	}

	/* no subcomponents visible - no change in perms */
	return 0;

next:
	tmp = aa_compute_fperms(profile->file.dfa, state, &cond);
	aa_apply_modes_to_perms(profile, &tmp);
	aa_perms_accum(perms, &tmp);
	label_for_each_cont(i, label, tp) {
		if (!aa_ns_visible(profile->ns, tp->ns, subns))
			continue;
		state = match_component(profile, tp, stack, start);
		if (!state)
			goto fail;
		tmp = aa_compute_fperms(profile->file.dfa, state, &cond);
		aa_apply_modes_to_perms(profile, &tmp);
		aa_perms_accum(perms, &tmp);
	}

	if ((perms->allow & request) != request)
		return -EACCES;

	return 0;

fail:
	*perms = nullperms;
	return -EACCES;
}

/**
 * label_match - do a multi-component label match
 * @profile: profile to match against (NOT NULL)
 * @label: label to match (NOT NULL)
 * @stack: whether this is a stacking request
 * @state: state to start in
 * @subns: whether to match subns components
 * @request: permission request
 * @perms: Returns computed perms (NOT NULL)
 *
 * Returns: the state the match finished in, may be the none matching state
 */
static int label_match(struct aa_profile *profile, struct aa_label *label,
		       bool stack, unsigned int state, bool subns, u32 request,
		       struct aa_perms *perms)
{
	int error;

	*perms = nullperms;
	error = label_compound_match(profile, label, stack, state, subns,
				     request, perms);
	if (!error)
		return error;

	*perms = allperms;
	return label_components_match(profile, label, stack, state, subns,
				      request, perms);
}

/******* end TODO: dedup *****/

276 277 278
/**
 * change_profile_perms - find permissions for change_profile
 * @profile: the current profile  (NOT NULL)
279 280
 * @target: label to transition to (NOT NULL)
 * @stack: whether this is a stacking request
281 282 283
 * @request: requested perms
 * @start: state to start matching in
 *
284
 *
285
 * Returns: permission set
286 287 288
 *
 * currently only matches full label A//&B//&C or individual components A, B, C
 * not arbitrary combinations. Eg. A//&B, C
289
 */
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
static int change_profile_perms(struct aa_profile *profile,
				struct aa_label *target, bool stack,
				u32 request, unsigned int start,
				struct aa_perms *perms)
{
	if (profile_unconfined(profile)) {
		perms->allow = AA_MAY_CHANGE_PROFILE | AA_MAY_ONEXEC;
		perms->audit = perms->quiet = perms->kill = 0;
		return 0;
	}

	/* TODO: add profile in ns screening */
	return label_match(profile, target, stack, start, true, request, perms);
}

305 306 307 308
/**
 * aa_xattrs_match - check whether a file matches the xattrs defined in profile
 * @bprm: binprm struct for the process to validate
 * @profile: profile to match against (NOT NULL)
309
 * @state: state to start match in
310 311 312 313
 *
 * Returns: number of extended attributes that matched, or < 0 on error
 */
static int aa_xattrs_match(const struct linux_binprm *bprm,
314
			   struct aa_profile *profile, unsigned int state)
315 316
{
	int i;
317
	ssize_t size;
318 319 320 321 322 323 324
	struct dentry *d;
	char *value = NULL;
	int value_size = 0, ret = profile->xattr_count;

	if (!bprm || !profile->xattr_count)
		return 0;

325 326 327
	/* transition from exec match to xattr set */
	state = aa_dfa_null_transition(profile->xmatch, state);

328 329 330 331 332
	d = bprm->file->f_path.dentry;

	for (i = 0; i < profile->xattr_count; i++) {
		size = vfs_getxattr_alloc(d, profile->xattrs[i], &value,
					  value_size, GFP_KERNEL);
333 334
		if (size >= 0) {
			u32 perm;
335

336 337 338 339 340
			/* Check the xattr value, not just presence */
			state = aa_dfa_match_len(profile->xmatch, state, value,
						 size);
			perm = dfa_user_allow(profile->xmatch, state);
			if (!(perm & MAY_EXEC)) {
341 342 343
				ret = -EINVAL;
				goto out;
			}
344 345 346 347 348 349 350 351 352 353
		}
		/* transition to next element */
		state = aa_dfa_null_transition(profile->xmatch, state);
		if (size < 0) {
			/*
			 * No xattr match, so verify if transition to
			 * next element was valid. IFF so the xattr
			 * was optional.
			 */
			if (!state) {
354 355 356
				ret = -EINVAL;
				goto out;
			}
357 358
			/* don't count missing optional xattr as matched */
			ret--;
359 360 361 362 363 364 365 366
		}
	}

out:
	kfree(value);
	return ret;
}

367 368
/**
 * __attach_match_ - find an attachment match
369
 * @bprm - binprm structure of transitioning task
370 371
 * @name - to match against  (NOT NULL)
 * @head - profile list to walk  (NOT NULL)
372
 * @info - info message if there was an error (NOT NULL)
373 374 375 376 377 378 379 380 381 382
 *
 * Do a linear search on the profiles in the list.  There is a matching
 * preference where an exact match is preferred over a name which uses
 * expressions to match, and matching expressions with the greatest
 * xmatch_len are preferred.
 *
 * Requires: @head not be shared or have appropriate locks held
 *
 * Returns: profile or NULL if no match found
 */
383 384
static struct aa_profile *__attach_match(const struct linux_binprm *bprm,
					 const char *name,
385 386
					 struct list_head *head,
					 const char **info)
387
{
388
	int candidate_len = 0, candidate_xattrs = 0;
389
	bool conflict = false;
390 391
	struct aa_profile *profile, *candidate = NULL;

392 393 394
	AA_BUG(!name);
	AA_BUG(!head);

395
	list_for_each_entry_rcu(profile, head, base.list) {
396 397
		if (profile->label.flags & FLAG_NULL &&
		    &profile->label == ns_unconfined(profile->ns))
398
			continue;
399

400 401 402 403 404 405 406 407 408 409 410
		/* Find the "best" matching profile. Profiles must
		 * match the path and extended attributes (if any)
		 * associated with the file. A more specific path
		 * match will be preferred over a less specific one,
		 * and a match with more matching extended attributes
		 * will be preferred over one with fewer. If the best
		 * match has both the same level of path specificity
		 * and the same number of matching extended attributes
		 * as another profile, signal a conflict and refuse to
		 * match.
		 */
411
		if (profile->xmatch) {
412
			unsigned int state, count;
413 414
			u32 perm;

415 416
			state = aa_dfa_leftmatch(profile->xmatch, DFA_START,
						 name, &count);
417 418 419
			perm = dfa_user_allow(profile->xmatch, state);
			/* any accepting state means a valid match. */
			if (perm & MAY_EXEC) {
420 421 422 423
				int ret;

				if (count < candidate_len)
					continue;
424

425
				ret = aa_xattrs_match(bprm, profile, state);
426 427 428 429
				/* Fail matching if the xattrs don't match */
				if (ret < 0)
					continue;

430 431 432 433
				/*
				 * TODO: allow for more flexible best match
				 *
				 * The new match isn't more specific
434 435
				 * than the current best match
				 */
436 437
				if (count == candidate_len &&
				    ret <= candidate_xattrs) {
438
					/* Match is equivalent, so conflict */
439
					if (ret == candidate_xattrs)
440
						conflict = true;
441
					continue;
442
				}
443 444 445 446 447

				/* Either the same length with more matching
				 * xattrs, or a longer match
				 */
				candidate = profile;
448 449
				candidate_len = profile->xmatch_len;
				candidate_xattrs = ret;
450
				conflict = false;
451
			}
452 453 454 455 456
		} else if (!strcmp(profile->base.name, name))
			/*
			 * old exact non-re match, without conditionals such
			 * as xattrs. no more searching required
			 */
457 458 459
			return profile;
	}

460 461 462 463 464
	if (conflict) {
		*info = "conflicting profile attachments";
		return NULL;
	}

465 466 467 468 469
	return candidate;
}

/**
 * find_attach - do attachment search for unconfined processes
470
 * @bprm - binprm structure of transitioning task
471 472 473
 * @ns: the current namespace  (NOT NULL)
 * @list: list to search  (NOT NULL)
 * @name: the executable name to match against  (NOT NULL)
474
 * @info: info message if there was an error
475
 *
476
 * Returns: label or NULL if no match found
477
 */
478 479
static struct aa_label *find_attach(const struct linux_binprm *bprm,
				    struct aa_ns *ns, struct list_head *list,
480
				    const char *name, const char **info)
481 482 483
{
	struct aa_profile *profile;

484
	rcu_read_lock();
485
	profile = aa_get_profile(__attach_match(bprm, name, list, info));
486
	rcu_read_unlock();
487

488
	return profile ? &profile->label : NULL;
489 490 491 492 493 494 495 496 497 498 499
}

static const char *next_name(int xtype, const char *name)
{
	return NULL;
}

/**
 * x_table_lookup - lookup an x transition name via transition table
 * @profile: current profile (NOT NULL)
 * @xindex: index into x transition table
500
 * @name: returns: name tested to find label (NOT NULL)
501
 *
502
 * Returns: refcounted label, or NULL on failure (MAYBE NULL)
503
 */
J
John Johansen 已提交
504 505
struct aa_label *x_table_lookup(struct aa_profile *profile, u32 xindex,
				const char **name)
506
{
507
	struct aa_label *label = NULL;
508 509 510
	u32 xtype = xindex & AA_X_TYPE_MASK;
	int index = xindex & AA_X_INDEX_MASK;

511
	AA_BUG(!name);
512

513 514 515 516 517 518
	/* index is guaranteed to be in range, validated at load time */
	/* TODO: move lookup parsing to unpack time so this is a straight
	 *       index into the resultant label
	 */
	for (*name = profile->file.trans.table[index]; !label && *name;
	     *name = next_name(xtype, *name)) {
519
		if (xindex & AA_X_CHILD) {
520
			struct aa_profile *new_profile;
521
			/* release by caller */
522 523 524
			new_profile = aa_find_child(profile, *name);
			if (new_profile)
				label = &new_profile->label;
525 526
			continue;
		}
527 528 529 530
		label = aa_label_parse(&profile->label, *name, GFP_ATOMIC,
				       true, false);
		if (IS_ERR(label))
			label = NULL;
531 532 533
	}

	/* released by caller */
534 535

	return label;
536 537 538
}

/**
539
 * x_to_label - get target label for a given xindex
540
 * @profile: current profile  (NOT NULL)
541
 * @bprm: binprm structure of transitioning task
542 543
 * @name: name to lookup (NOT NULL)
 * @xindex: index into x transition table
544
 * @lookupname: returns: name used in lookup if one was specified (NOT NULL)
545
 *
546
 * find label for a transition index
547
 *
548
 * Returns: refcounted label or NULL if not found available
549
 */
550
static struct aa_label *x_to_label(struct aa_profile *profile,
551
				   const struct linux_binprm *bprm,
552 553 554
				   const char *name, u32 xindex,
				   const char **lookupname,
				   const char **info)
555
{
556
	struct aa_label *new = NULL;
557
	struct aa_ns *ns = profile->ns;
558
	u32 xtype = xindex & AA_X_TYPE_MASK;
559
	const char *stack = NULL;
560 561 562 563

	switch (xtype) {
	case AA_X_NONE:
		/* fail exec unless ix || ux fallback - handled by caller */
564 565 566 567 568 569 570 571 572 573 574 575
		*lookupname = NULL;
		break;
	case AA_X_TABLE:
		/* TODO: fix when perm mapping done at unload */
		stack = profile->file.trans.table[xindex & AA_X_INDEX_MASK];
		if (*stack != '&') {
			/* released by caller */
			new = x_table_lookup(profile, xindex, lookupname);
			stack = NULL;
			break;
		}
		/* fall through to X_NAME */
576 577 578
	case AA_X_NAME:
		if (xindex & AA_X_CHILD)
			/* released by caller */
579
			new = find_attach(bprm, ns, &profile->base.profiles,
580
					  name, info);
581 582
		else
			/* released by caller */
583
			new = find_attach(bprm, ns, &ns->base.profiles,
584
					  name, info);
585
		*lookupname = name;
586 587 588
		break;
	}

589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
	if (!new) {
		if (xindex & AA_X_INHERIT) {
			/* (p|c|n)ix - don't change profile but do
			 * use the newest version
			 */
			*info = "ix fallback";
			/* no profile && no error */
			new = aa_get_newest_label(&profile->label);
		} else if (xindex & AA_X_UNCONFINED) {
			new = aa_get_newest_label(ns_unconfined(profile->ns));
			*info = "ux fallback";
		}
	}

	if (new && stack) {
		/* base the stack on post domain transition */
		struct aa_label *base = new;

		new = aa_label_parse(base, stack, GFP_ATOMIC, true, false);
		if (IS_ERR(new))
			new = NULL;
		aa_put_label(base);
	}

613
	/* released by caller */
614
	return new;
615 616
}

617 618 619 620
static struct aa_label *profile_transition(struct aa_profile *profile,
					   const struct linux_binprm *bprm,
					   char *buffer, struct path_cond *cond,
					   bool *secure_exec)
621
{
622
	struct aa_label *new = NULL;
623 624
	struct aa_profile *component;
	struct label_it i;
625 626
	const char *info = NULL, *name = NULL, *target = NULL;
	unsigned int state = profile->file.start;
627
	struct aa_perms perms = {};
628
	bool nonewprivs = false;
C
Casey Schaufler 已提交
629
	int error = 0;
630

631 632 633
	AA_BUG(!profile);
	AA_BUG(!bprm);
	AA_BUG(!buffer);
634

635
	error = aa_path_name(&bprm->file->f_path, profile->path_flags, buffer,
636
			     &name, &info, profile->disconnected);
637
	if (error) {
638
		if (profile_unconfined(profile) ||
639 640
		    (profile->label.flags & FLAG_IX_ON_NAME_ERROR)) {
			AA_DEBUG("name lookup ix on error");
641
			error = 0;
642 643
			new = aa_get_newest_label(&profile->label);
		}
644 645 646 647
		name = bprm->filename;
		goto audit;
	}

648
	if (profile_unconfined(profile)) {
649 650
		new = find_attach(bprm, profile->ns,
				  &profile->ns->base.profiles, name, &info);
651 652 653 654 655 656
		if (new) {
			AA_DEBUG("unconfined attached to new label");
			return new;
		}
		AA_DEBUG("unconfined exec no attachment");
		return aa_get_newest_label(&profile->label);
657 658 659
	}

	/* find exec permissions for name */
660
	state = aa_str_perms(profile->file.dfa, state, name, cond, &perms);
661 662
	if (perms.allow & MAY_EXEC) {
		/* exec permission determine how to transition */
663 664
		new = x_to_label(profile, bprm, name, perms.xindex, &target,
				 &info);
665 666 667 668 669 670 671 672
		if (new && new->proxy == profile->label.proxy && info) {
			/* hack ix fallback - improve how this is detected */
			goto audit;
		} else if (!new) {
			error = -EACCES;
			info = "profile transition not found";
			/* remove MAY_EXEC to audit as failure */
			perms.allow &= ~MAY_EXEC;
673 674 675 676 677
		} else {
			/* verify that each component's xattr requirements are
			 * met, and fail execution otherwise
			 */
			label_for_each(i, new, component) {
678 679
				if (aa_xattrs_match(bprm, component, state) <
				    0) {
680 681 682 683 684 685 686 687
					error = -EACCES;
					info = "required xattrs not present";
					perms.allow &= ~MAY_EXEC;
					aa_put_label(new);
					new = NULL;
					goto audit;
				}
			}
688 689
		}
	} else if (COMPLAIN_MODE(profile)) {
690
		/* no exec permission - learning mode */
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
		struct aa_profile *new_profile = NULL;
		char *n = kstrdup(name, GFP_ATOMIC);

		if (n) {
			/* name is ptr into buffer */
			long pos = name - buffer;
			/* break per cpu buffer hold */
			put_buffers(buffer);
			new_profile = aa_new_null_profile(profile, false, n,
							  GFP_KERNEL);
			get_buffers(buffer);
			name = buffer + pos;
			strcpy((char *)name, n);
			kfree(n);
		}
706 707 708
		if (!new_profile) {
			error = -ENOMEM;
			info = "could not create null profile";
709
		} else {
710
			error = -EACCES;
711 712
			new = &new_profile->label;
		}
713 714 715 716 717
		perms.xindex |= AA_X_UNSAFE;
	} else
		/* fail exec */
		error = -EACCES;

718 719 720 721 722 723 724 725 726 727 728 729
	if (!new)
		goto audit;


	if (!(perms.xindex & AA_X_UNSAFE)) {
		if (DEBUG_ON) {
			dbg_printk("apparmor: scrubbing environment variables"
				   " for %s profile=", name);
			aa_label_printk(new, GFP_ATOMIC);
			dbg_printk("\n");
		}
		*secure_exec = true;
730 731
	}

732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
audit:
	aa_audit_file(profile, &perms, OP_EXEC, MAY_EXEC, name, target, new,
		      cond->uid, info, error);
	if (!new || nonewprivs) {
		aa_put_label(new);
		return ERR_PTR(error);
	}

	return new;
}

static int profile_onexec(struct aa_profile *profile, struct aa_label *onexec,
			  bool stack, const struct linux_binprm *bprm,
			  char *buffer, struct path_cond *cond,
			  bool *secure_exec)
{
	unsigned int state = profile->file.start;
	struct aa_perms perms = {};
	const char *xname = NULL, *info = "change_profile onexec";
	int error = -EACCES;

	AA_BUG(!profile);
	AA_BUG(!onexec);
	AA_BUG(!bprm);
	AA_BUG(!buffer);

	if (profile_unconfined(profile)) {
		/* change_profile on exec already granted */
		/*
		 * NOTE: Domain transitions from unconfined are allowed
		 * even when no_new_privs is set because this aways results
		 * in a further reduction of permissions.
		 */
		return 0;
	}

	error = aa_path_name(&bprm->file->f_path, profile->path_flags, buffer,
			     &xname, &info, profile->disconnected);
	if (error) {
		if (profile_unconfined(profile) ||
		    (profile->label.flags & FLAG_IX_ON_NAME_ERROR)) {
			AA_DEBUG("name lookup ix on error");
			error = 0;
		}
		xname = bprm->filename;
777
		goto audit;
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
	}

	/* find exec permissions for name */
	state = aa_str_perms(profile->file.dfa, state, xname, cond, &perms);
	if (!(perms.allow & AA_MAY_ONEXEC)) {
		info = "no change_onexec valid for executable";
		goto audit;
	}
	/* test if this exec can be paired with change_profile onexec.
	 * onexec permission is linked to exec with a standard pairing
	 * exec\0change_profile
	 */
	state = aa_dfa_null_transition(profile->file.dfa, state);
	error = change_profile_perms(profile, onexec, stack, AA_MAY_ONEXEC,
				     state, &perms);
	if (error) {
		perms.allow &= ~AA_MAY_ONEXEC;
		goto audit;
	}

	if (!(perms.xindex & AA_X_UNSAFE)) {
		if (DEBUG_ON) {
			dbg_printk("apparmor: scrubbing environment "
				   "variables for %s label=", xname);
			aa_label_printk(onexec, GFP_ATOMIC);
			dbg_printk("\n");
		}
		*secure_exec = true;
	}

audit:
	return aa_audit_file(profile, &perms, OP_EXEC, AA_MAY_ONEXEC, xname,
			     NULL, onexec, cond->uid, info, error);
}

/* ensure none ns domain transitions are correctly applied with onexec */

static struct aa_label *handle_onexec(struct aa_label *label,
				      struct aa_label *onexec, bool stack,
				      const struct linux_binprm *bprm,
				      char *buffer, struct path_cond *cond,
				      bool *unsafe)
{
	struct aa_profile *profile;
	struct aa_label *new;
	int error;

	AA_BUG(!label);
	AA_BUG(!onexec);
	AA_BUG(!bprm);
	AA_BUG(!buffer);

	if (!stack) {
		error = fn_for_each_in_ns(label, profile,
				profile_onexec(profile, onexec, stack,
					       bprm, buffer, cond, unsafe));
		if (error)
			return ERR_PTR(error);
		new = fn_label_build_in_ns(label, profile, GFP_ATOMIC,
				aa_get_newest_label(onexec),
				profile_transition(profile, bprm, buffer,
						   cond, unsafe));

	} else {
Z
Zygmunt Krynicki 已提交
842
		/* TODO: determine how much we want to loosen this */
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
		error = fn_for_each_in_ns(label, profile,
				profile_onexec(profile, onexec, stack, bprm,
					       buffer, cond, unsafe));
		if (error)
			return ERR_PTR(error);
		new = fn_label_build_in_ns(label, profile, GFP_ATOMIC,
				aa_label_merge(&profile->label, onexec,
					       GFP_ATOMIC),
				profile_transition(profile, bprm, buffer,
						   cond, unsafe));
	}

	if (new)
		return new;

	/* TODO: get rid of GLOBAL_ROOT_UID */
	error = fn_for_each_in_ns(label, profile,
			aa_audit_file(profile, &nullperms, OP_CHANGE_ONEXEC,
				      AA_MAY_ONEXEC, bprm->filename, NULL,
				      onexec, GLOBAL_ROOT_UID,
				      "failed to build target label", -ENOMEM));
	return ERR_PTR(error);
}

/**
 * apparmor_bprm_set_creds - set the new creds on the bprm struct
 * @bprm: binprm for the exec  (NOT NULL)
 *
 * Returns: %0 or error on failure
 *
 * TODO: once the other paths are done see if we can't refactor into a fn
 */
int apparmor_bprm_set_creds(struct linux_binprm *bprm)
{
J
John Johansen 已提交
877
	struct aa_task_ctx *ctx;
878 879 880 881 882 883 884 885 886 887 888
	struct aa_label *label, *new = NULL;
	struct aa_profile *profile;
	char *buffer = NULL;
	const char *info = NULL;
	int error = 0;
	bool unsafe = false;
	struct path_cond cond = {
		file_inode(bprm->file)->i_uid,
		file_inode(bprm->file)->i_mode
	};

889
	if (bprm->called_set_creds)
890 891
		return 0;

892
	ctx = task_ctx(current);
893
	AA_BUG(!cred_label(bprm->cred));
J
John Johansen 已提交
894
	AA_BUG(!ctx);
895

896
	label = aa_get_newest_label(cred_label(bprm->cred));
897

898 899 900 901 902 903 904 905 906 907 908
	/*
	 * Detect no new privs being set, and store the label it
	 * occurred under. Ideally this would happen when nnp
	 * is set but there isn't a good way to do that yet.
	 *
	 * Testing for unconfined must be done before the subset test
	 */
	if ((bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS) && !unconfined(label) &&
	    !ctx->nnp)
		ctx->nnp = aa_get_label(label);

909 910 911
	/* buffer freed below, name is pointer into buffer */
	get_buffers(buffer);
	/* Test for onexec first as onexec override other x transitions. */
J
John Johansen 已提交
912 913
	if (ctx->onexec)
		new = handle_onexec(label, ctx->onexec, ctx->token,
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
				    bprm, buffer, &cond, &unsafe);
	else
		new = fn_label_build(label, profile, GFP_ATOMIC,
				profile_transition(profile, bprm, buffer,
						   &cond, &unsafe));

	AA_BUG(!new);
	if (IS_ERR(new)) {
		error = PTR_ERR(new);
		goto done;
	} else if (!new) {
		error = -ENOMEM;
		goto done;
	}

929 930 931 932 933 934 935 936 937 938 939 940 941 942
	/* Policy has specified a domain transitions. If no_new_privs and
	 * confined ensure the transition is to confinement that is subset
	 * of the confinement when the task entered no new privs.
	 *
	 * NOTE: Domain transitions from unconfined and to stacked
	 * subsets are allowed even when no_new_privs is set because this
	 * aways results in a further reduction of permissions.
	 */
	if ((bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS) &&
	    !unconfined(label) && !aa_label_is_subset(new, ctx->nnp)) {
		error = -EPERM;
		info = "no new privs";
		goto audit;
	}
943 944 945 946 947 948

	if (bprm->unsafe & LSM_UNSAFE_SHARE) {
		/* FIXME: currently don't mediate shared state */
		;
	}

949 950 951
	if (bprm->unsafe & (LSM_UNSAFE_PTRACE)) {
		/* TODO: test needs to be profile of label to new */
		error = may_change_ptraced_domain(new, &info);
952
		if (error)
953 954 955
			goto audit;
	}

956 957 958 959 960 961 962
	if (unsafe) {
		if (DEBUG_ON) {
			dbg_printk("scrubbing environment variables for %s "
				   "label=", bprm->filename);
			aa_label_printk(new, GFP_ATOMIC);
			dbg_printk("\n");
		}
963
		bprm->secureexec = 1;
964 965
	}

966 967 968 969 970 971 972 973 974 975
	if (label->proxy != new->proxy) {
		/* when transitioning clear unsafe personality bits */
		if (DEBUG_ON) {
			dbg_printk("apparmor: clearing unsafe personality "
				   "bits. %s label=", bprm->filename);
			aa_label_printk(new, GFP_ATOMIC);
			dbg_printk("\n");
		}
		bprm->per_clear |= PER_CLEAR_ON_SETID;
	}
976 977 978
	aa_put_label(cred_label(bprm->cred));
	/* transfer reference, released when cred is freed */
	cred_label(bprm->cred) = new;
979

980
done:
981
	aa_put_label(label);
982
	put_buffers(buffer);
983 984

	return error;
985 986 987 988 989 990 991 992 993

audit:
	error = fn_for_each(label, profile,
			aa_audit_file(profile, &nullperms, OP_EXEC, MAY_EXEC,
				      bprm->filename, NULL, new,
				      file_inode(bprm->file)->i_uid, info,
				      error));
	aa_put_label(new);
	goto done;
994 995 996 997 998 999
}

/*
 * Functions for self directed profile change
 */

1000 1001

/* helper fn for change_hat
1002
 *
1003
 * Returns: label for hat transition OR ERR_PTR.  Does NOT return NULL
1004
 */
1005 1006
static struct aa_label *build_change_hat(struct aa_profile *profile,
					 const char *name, bool sibling)
1007
{
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
	struct aa_profile *root, *hat = NULL;
	const char *info = NULL;
	int error = 0;

	if (sibling && PROFILE_IS_HAT(profile)) {
		root = aa_get_profile_rcu(&profile->parent);
	} else if (!sibling && !PROFILE_IS_HAT(profile)) {
		root = aa_get_profile(profile);
	} else {
		info = "conflicting target types";
		error = -EPERM;
		goto audit;
	}

	hat = aa_find_child(root, name);
	if (!hat) {
		error = -ENOENT;
		if (COMPLAIN_MODE(profile)) {
			hat = aa_new_null_profile(profile, true, name,
						  GFP_KERNEL);
			if (!hat) {
				info = "failed null profile create";
				error = -ENOMEM;
			}
		}
	}
	aa_put_profile(root);

audit:
	aa_audit_file(profile, &nullperms, OP_CHANGE_HAT, AA_MAY_CHANGEHAT,
		      name, hat ? hat->base.hname : NULL,
1039
		      hat ? &hat->label : NULL, GLOBAL_ROOT_UID, info,
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
		      error);
	if (!hat || (error && error != -ENOENT))
		return ERR_PTR(error);
	/* if hat && error - complain mode, already audited and we adjust for
	 * complain mode allow by returning hat->label
	 */
	return &hat->label;
}

/* helper fn for changing into a hat
 *
 * Returns: label for hat transition or ERR_PTR. Does not return NULL
 */
static struct aa_label *change_hat(struct aa_label *label, const char *hats[],
				   int count, int flags)
{
	struct aa_profile *profile, *root, *hat = NULL;
	struct aa_label *new;
	struct label_it it;
	bool sibling = false;
	const char *name, *info = NULL;
	int i, error;

	AA_BUG(!label);
	AA_BUG(!hats);
	AA_BUG(count < 1);

	if (PROFILE_IS_HAT(labels_profile(label)))
		sibling = true;

	/*find first matching hat */
	for (i = 0; i < count && !hat; i++) {
		name = hats[i];
		label_for_each_in_ns(it, labels_ns(label), label, profile) {
			if (sibling && PROFILE_IS_HAT(profile)) {
				root = aa_get_profile_rcu(&profile->parent);
			} else if (!sibling && !PROFILE_IS_HAT(profile)) {
				root = aa_get_profile(profile);
			} else {	/* conflicting change type */
				info = "conflicting targets types";
				error = -EPERM;
				goto fail;
			}
			hat = aa_find_child(root, name);
			aa_put_profile(root);
			if (!hat) {
				if (!COMPLAIN_MODE(profile))
					goto outer_continue;
				/* complain mode succeed as if hat */
			} else if (!PROFILE_IS_HAT(hat)) {
				info = "target not hat";
				error = -EPERM;
				aa_put_profile(hat);
				goto fail;
			}
			aa_put_profile(hat);
		}
		/* found a hat for all profiles in ns */
		goto build;
outer_continue:
	;
	}
	/* no hats that match, find appropriate error
	 *
	 * In complain mode audit of the failure is based off of the first
	 * hat supplied.  This is done due how userspace interacts with
	 * change_hat.
	 */
	name = NULL;
	label_for_each_in_ns(it, labels_ns(label), label, profile) {
		if (!list_empty(&profile->base.profiles)) {
			info = "hat not found";
			error = -ENOENT;
			goto fail;
		}
	}
	info = "no hats defined";
	error = -ECHILD;

fail:
	label_for_each_in_ns(it, labels_ns(label), label, profile) {
		/*
		 * no target as it has failed to be found or built
		 *
		 * change_hat uses probing and should not log failures
		 * related to missing hats
		 */
		/* TODO: get rid of GLOBAL_ROOT_UID */
		if (count > 1 || COMPLAIN_MODE(profile)) {
			aa_audit_file(profile, &nullperms, OP_CHANGE_HAT,
				      AA_MAY_CHANGEHAT, name, NULL, NULL,
				      GLOBAL_ROOT_UID, info, error);
		}
	}
	return ERR_PTR(error);

build:
	new = fn_label_build_in_ns(label, profile, GFP_KERNEL,
				   build_change_hat(profile, name, sibling),
				   aa_get_label(&profile->label));
	if (!new) {
		info = "label build failed";
		error = -ENOMEM;
		goto fail;
	} /* else if (IS_ERR) build_change_hat has logged error so return new */

	return new;
1147 1148 1149 1150 1151 1152 1153
}

/**
 * aa_change_hat - change hat to/from subprofile
 * @hats: vector of hat names to try changing into (MAYBE NULL if @count == 0)
 * @count: number of hat names in @hats
 * @token: magic value to validate the hat change
1154
 * @flags: flags affecting behavior of the change
1155
 *
1156 1157
 * Returns %0 on success, error otherwise.
 *
1158 1159 1160 1161 1162
 * Change to the first profile specified in @hats that exists, and store
 * the @hat_magic in the current task context.  If the count == 0 and the
 * @token matches that stored in the current task context, return to the
 * top level profile.
 *
1163 1164
 * change_hat only applies to profiles in the current ns, and each profile
 * in the ns must make the same transition otherwise change_hat will fail.
1165
 */
1166
int aa_change_hat(const char *hats[], int count, u64 token, int flags)
1167 1168
{
	const struct cred *cred;
1169
	struct aa_task_ctx *ctx = task_ctx(current);
1170 1171
	struct aa_label *label, *previous, *new = NULL, *target = NULL;
	struct aa_profile *profile;
1172
	struct aa_perms perms = {};
1173
	const char *info = NULL;
1174 1175 1176 1177
	int error = 0;

	/* released below */
	cred = get_current_cred();
1178
	label = aa_get_newest_cred_label(cred);
J
John Johansen 已提交
1179
	previous = aa_get_newest_label(ctx->previous);
1180

1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
	/*
	 * Detect no new privs being set, and store the label it
	 * occurred under. Ideally this would happen when nnp
	 * is set but there isn't a good way to do that yet.
	 *
	 * Testing for unconfined must be done before the subset test
	 */
	if (task_no_new_privs(current) && !unconfined(label) && !ctx->nnp)
		ctx->nnp = aa_get_label(label);

1191
	if (unconfined(label)) {
1192
		info = "unconfined can not change_hat";
1193
		error = -EPERM;
1194
		goto fail;
1195 1196 1197
	}

	if (count) {
1198 1199 1200 1201 1202 1203 1204
		new = change_hat(label, hats, count, flags);
		AA_BUG(!new);
		if (IS_ERR(new)) {
			error = PTR_ERR(new);
			new = NULL;
			/* already audited */
			goto out;
1205 1206
		}

1207 1208 1209
		error = may_change_ptraced_domain(new, &info);
		if (error)
			goto fail;
1210

1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
		/*
		 * no new privs prevents domain transitions that would
		 * reduce restrictions.
		 */
		if (task_no_new_privs(current) && !unconfined(label) &&
		    !aa_label_is_subset(new, ctx->nnp)) {
			/* not an apparmor denial per se, so don't log it */
			AA_DEBUG("no_new_privs - change_hat denied");
			error = -EPERM;
			goto out;
		}

1223 1224 1225 1226 1227 1228 1229 1230 1231
		if (flags & AA_CHANGE_TEST)
			goto out;

		target = new;
		error = aa_set_current_hat(new, token);
		if (error == -EACCES)
			/* kill task in case of brute force attacks */
			goto kill;
	} else if (previous && !(flags & AA_CHANGE_TEST)) {
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
		/*
		 * no new privs prevents domain transitions that would
		 * reduce restrictions.
		 */
		if (task_no_new_privs(current) && !unconfined(label) &&
		    !aa_label_is_subset(previous, ctx->nnp)) {
			/* not an apparmor denial per se, so don't log it */
			AA_DEBUG("no_new_privs - change_hat denied");
			error = -EPERM;
			goto out;
		}

1244
		/* Return to saved label.  Kill task if restore fails
1245 1246
		 * to avoid brute force attacks
		 */
1247
		target = previous;
1248
		error = aa_restore_previous_label(token);
1249 1250 1251 1252 1253 1254
		if (error) {
			if (error == -EACCES)
				goto kill;
			goto fail;
		}
	} /* else ignore @flags && restores when there is no saved profile */
1255 1256

out:
1257 1258
	aa_put_label(new);
	aa_put_label(previous);
1259
	aa_put_label(label);
1260 1261 1262
	put_cred(cred);

	return error;
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274

kill:
	info = "failed token match";
	perms.kill = AA_MAY_CHANGEHAT;

fail:
	fn_for_each_in_ns(label, profile,
		aa_audit_file(profile, &perms, OP_CHANGE_HAT,
			      AA_MAY_CHANGEHAT, NULL, NULL, target,
			      GLOBAL_ROOT_UID, info, error));

	goto out;
1275 1276
}

1277

1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
static int change_profile_perms_wrapper(const char *op, const char *name,
					struct aa_profile *profile,
					struct aa_label *target, bool stack,
					u32 request, struct aa_perms *perms)
{
	const char *info = NULL;
	int error = 0;

	if (!error)
		error = change_profile_perms(profile, target, stack, request,
					     profile->file.start, perms);
	if (error)
		error = aa_audit_file(profile, perms, op, request, name,
				      NULL, target, GLOBAL_ROOT_UID, info,
				      error);

	return error;
}
1296

1297 1298
/**
 * aa_change_profile - perform a one-way profile transition
1299
 * @fqname: name of profile may include namespace (NOT NULL)
1300
 * @onexec: whether this transition is to take place immediately or at exec
1301
 * @flags: flags affecting change behavior
1302 1303 1304 1305 1306 1307 1308 1309 1310
 *
 * Change to new profile @name.  Unlike with hats, there is no way
 * to change back.  If @name isn't specified the current profile name is
 * used.
 * If @onexec then the transition is delayed until
 * the next exec.
 *
 * Returns %0 on success, error otherwise.
 */
1311
int aa_change_profile(const char *fqname, int flags)
1312
{
1313 1314
	struct aa_label *label, *new = NULL, *target = NULL;
	struct aa_profile *profile;
1315
	struct aa_perms perms = {};
1316 1317 1318
	const char *info = NULL;
	const char *auditname = fqname;		/* retain leading & if stack */
	bool stack = flags & AA_CHANGE_STACK;
1319
	struct aa_task_ctx *ctx = task_ctx(current);
1320
	int error = 0;
1321
	char *op;
1322 1323
	u32 request;

1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
	label = aa_get_current_label();

	/*
	 * Detect no new privs being set, and store the label it
	 * occurred under. Ideally this would happen when nnp
	 * is set but there isn't a good way to do that yet.
	 *
	 * Testing for unconfined must be done before the subset test
	 */
	if (task_no_new_privs(current) && !unconfined(label) && !ctx->nnp)
		ctx->nnp = aa_get_label(label);

1336 1337
	if (!fqname || !*fqname) {
		AA_DEBUG("no profile name");
1338
		return -EINVAL;
1339
	}
1340

1341
	if (flags & AA_CHANGE_ONEXEC) {
1342
		request = AA_MAY_ONEXEC;
1343 1344 1345 1346
		if (stack)
			op = OP_STACK_ONEXEC;
		else
			op = OP_CHANGE_ONEXEC;
1347 1348
	} else {
		request = AA_MAY_CHANGE_PROFILE;
1349 1350 1351 1352
		if (stack)
			op = OP_STACK;
		else
			op = OP_CHANGE_PROFILE;
1353 1354
	}

1355
	label = aa_get_current_label();
1356

1357 1358 1359 1360
	if (*fqname == '&') {
		stack = true;
		/* don't have label_parse() do stacking */
		fqname++;
1361
	}
1362 1363 1364
	target = aa_label_parse(label, fqname, GFP_KERNEL, true, false);
	if (IS_ERR(target)) {
		struct aa_profile *tprofile;
1365

1366 1367 1368 1369 1370 1371 1372
		info = "label not found";
		error = PTR_ERR(target);
		target = NULL;
		/*
		 * TODO: fixme using labels_profile is not right - do profile
		 * per complain profile
		 */
1373
		if ((flags & AA_CHANGE_TEST) ||
1374
		    !COMPLAIN_MODE(labels_profile(label)))
1375 1376
			goto audit;
		/* released below */
1377 1378 1379
		tprofile = aa_new_null_profile(labels_profile(label), false,
					       fqname, GFP_KERNEL);
		if (!tprofile) {
1380 1381 1382 1383
			info = "failed null profile create";
			error = -ENOMEM;
			goto audit;
		}
1384 1385
		target = &tprofile->label;
		goto check;
1386 1387
	}

1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
	/*
	 * self directed transitions only apply to current policy ns
	 * TODO: currently requiring perms for stacking and straight change
	 *       stacking doesn't strictly need this. Determine how much
	 *       we want to loosen this restriction for stacking
	 *
	 * if (!stack) {
	 */
	error = fn_for_each_in_ns(label, profile,
			change_profile_perms_wrapper(op, auditname,
						     profile, target, stack,
						     request, &perms));
	if (error)
		/* auditing done in change_profile_perms_wrapper */
		goto out;
1403

1404 1405 1406
	/* } */

check:
1407
	/* check if tracing task is allowed to trace target domain */
1408 1409 1410
	error = may_change_ptraced_domain(target, &info);
	if (error && !fn_for_each_in_ns(label, profile,
					COMPLAIN_MODE(profile)))
1411 1412
		goto audit;

1413 1414 1415 1416 1417 1418 1419
	/* TODO: add permission check to allow this
	 * if ((flags & AA_CHANGE_ONEXEC) && !current_is_single_threaded()) {
	 *      info = "not a single threaded task";
	 *      error = -EACCES;
	 *      goto audit;
	 * }
	 */
1420
	if (flags & AA_CHANGE_TEST)
1421
		goto out;
1422

1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
	/* stacking is always a subset, so only check the nonstack case */
	if (!stack) {
		new = fn_label_build_in_ns(label, profile, GFP_KERNEL,
					   aa_get_label(target),
					   aa_get_label(&profile->label));
		/*
		 * no new privs prevents domain transitions that would
		 * reduce restrictions.
		 */
		if (task_no_new_privs(current) && !unconfined(label) &&
		    !aa_label_is_subset(new, ctx->nnp)) {
			/* not an apparmor denial per se, so don't log it */
			AA_DEBUG("no_new_privs - change_hat denied");
			error = -EPERM;
			goto out;
		}
	}

1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
	if (!(flags & AA_CHANGE_ONEXEC)) {
		/* only transition profiles in the current ns */
		if (stack)
			new = aa_label_merge(label, target, GFP_KERNEL);
		if (IS_ERR_OR_NULL(new)) {
			info = "failed to build target label";
			error = PTR_ERR(new);
			new = NULL;
			perms.allow = 0;
			goto audit;
		}
		error = aa_replace_current_label(new);
1453 1454 1455 1456 1457 1458
	} else {
		if (new) {
			aa_put_label(new);
			new = NULL;
		}

1459 1460
		/* full transition will be built in exec path */
		error = aa_set_current_onexec(target, stack);
1461
	}
1462 1463

audit:
1464 1465 1466 1467
	error = fn_for_each_in_ns(label, profile,
			aa_audit_file(profile, &perms, op, request, auditname,
				      NULL, new ? new : target,
				      GLOBAL_ROOT_UID, info, error));
1468

1469 1470 1471
out:
	aa_put_label(new);
	aa_put_label(target);
1472
	aa_put_label(label);
1473 1474 1475

	return error;
}