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