Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * AppArmor security module
0004  *
0005  * This file contains AppArmor label definitions
0006  *
0007  * Copyright 2017 Canonical Ltd.
0008  */
0009 
0010 #include <linux/audit.h>
0011 #include <linux/seq_file.h>
0012 #include <linux/sort.h>
0013 
0014 #include "include/apparmor.h"
0015 #include "include/cred.h"
0016 #include "include/label.h"
0017 #include "include/policy.h"
0018 #include "include/secid.h"
0019 
0020 
0021 /*
0022  * the aa_label represents the set of profiles confining an object
0023  *
0024  * Labels maintain a reference count to the set of pointers they reference
0025  * Labels are ref counted by
0026  *   tasks and object via the security field/security context off the field
0027  *   code - will take a ref count on a label if it needs the label
0028  *          beyond what is possible with an rcu_read_lock.
0029  *   profiles - each profile is a label
0030  *   secids - a pinned secid will keep a refcount of the label it is
0031  *          referencing
0032  *   objects - inode, files, sockets, ...
0033  *
0034  * Labels are not ref counted by the label set, so they maybe removed and
0035  * freed when no longer in use.
0036  *
0037  */
0038 
0039 #define PROXY_POISON 97
0040 #define LABEL_POISON 100
0041 
0042 static void free_proxy(struct aa_proxy *proxy)
0043 {
0044     if (proxy) {
0045         /* p->label will not updated any more as p is dead */
0046         aa_put_label(rcu_dereference_protected(proxy->label, true));
0047         memset(proxy, 0, sizeof(*proxy));
0048         RCU_INIT_POINTER(proxy->label, (struct aa_label *)PROXY_POISON);
0049         kfree(proxy);
0050     }
0051 }
0052 
0053 void aa_proxy_kref(struct kref *kref)
0054 {
0055     struct aa_proxy *proxy = container_of(kref, struct aa_proxy, count);
0056 
0057     free_proxy(proxy);
0058 }
0059 
0060 struct aa_proxy *aa_alloc_proxy(struct aa_label *label, gfp_t gfp)
0061 {
0062     struct aa_proxy *new;
0063 
0064     new = kzalloc(sizeof(struct aa_proxy), gfp);
0065     if (new) {
0066         kref_init(&new->count);
0067         rcu_assign_pointer(new->label, aa_get_label(label));
0068     }
0069     return new;
0070 }
0071 
0072 /* requires profile list write lock held */
0073 void __aa_proxy_redirect(struct aa_label *orig, struct aa_label *new)
0074 {
0075     struct aa_label *tmp;
0076 
0077     AA_BUG(!orig);
0078     AA_BUG(!new);
0079     lockdep_assert_held_write(&labels_set(orig)->lock);
0080 
0081     tmp = rcu_dereference_protected(orig->proxy->label,
0082                     &labels_ns(orig)->lock);
0083     rcu_assign_pointer(orig->proxy->label, aa_get_label(new));
0084     orig->flags |= FLAG_STALE;
0085     aa_put_label(tmp);
0086 }
0087 
0088 static void __proxy_share(struct aa_label *old, struct aa_label *new)
0089 {
0090     struct aa_proxy *proxy = new->proxy;
0091 
0092     new->proxy = aa_get_proxy(old->proxy);
0093     __aa_proxy_redirect(old, new);
0094     aa_put_proxy(proxy);
0095 }
0096 
0097 
0098 /**
0099  * ns_cmp - compare ns for label set ordering
0100  * @a: ns to compare (NOT NULL)
0101  * @b: ns to compare (NOT NULL)
0102  *
0103  * Returns: <0 if a < b
0104  *          ==0 if a == b
0105  *          >0  if a > b
0106  */
0107 static int ns_cmp(struct aa_ns *a, struct aa_ns *b)
0108 {
0109     int res;
0110 
0111     AA_BUG(!a);
0112     AA_BUG(!b);
0113     AA_BUG(!a->base.hname);
0114     AA_BUG(!b->base.hname);
0115 
0116     if (a == b)
0117         return 0;
0118 
0119     res = a->level - b->level;
0120     if (res)
0121         return res;
0122 
0123     return strcmp(a->base.hname, b->base.hname);
0124 }
0125 
0126 /**
0127  * profile_cmp - profile comparison for set ordering
0128  * @a: profile to compare (NOT NULL)
0129  * @b: profile to compare (NOT NULL)
0130  *
0131  * Returns: <0  if a < b
0132  *          ==0 if a == b
0133  *          >0  if a > b
0134  */
0135 static int profile_cmp(struct aa_profile *a, struct aa_profile *b)
0136 {
0137     int res;
0138 
0139     AA_BUG(!a);
0140     AA_BUG(!b);
0141     AA_BUG(!a->ns);
0142     AA_BUG(!b->ns);
0143     AA_BUG(!a->base.hname);
0144     AA_BUG(!b->base.hname);
0145 
0146     if (a == b || a->base.hname == b->base.hname)
0147         return 0;
0148     res = ns_cmp(a->ns, b->ns);
0149     if (res)
0150         return res;
0151 
0152     return strcmp(a->base.hname, b->base.hname);
0153 }
0154 
0155 /**
0156  * vec_cmp - label comparison for set ordering
0157  * @a: label to compare (NOT NULL)
0158  * @vec: vector of profiles to compare (NOT NULL)
0159  * @n: length of @vec
0160  *
0161  * Returns: <0  if a < vec
0162  *          ==0 if a == vec
0163  *          >0  if a > vec
0164  */
0165 static int vec_cmp(struct aa_profile **a, int an, struct aa_profile **b, int bn)
0166 {
0167     int i;
0168 
0169     AA_BUG(!a);
0170     AA_BUG(!*a);
0171     AA_BUG(!b);
0172     AA_BUG(!*b);
0173     AA_BUG(an <= 0);
0174     AA_BUG(bn <= 0);
0175 
0176     for (i = 0; i < an && i < bn; i++) {
0177         int res = profile_cmp(a[i], b[i]);
0178 
0179         if (res != 0)
0180             return res;
0181     }
0182 
0183     return an - bn;
0184 }
0185 
0186 static bool vec_is_stale(struct aa_profile **vec, int n)
0187 {
0188     int i;
0189 
0190     AA_BUG(!vec);
0191 
0192     for (i = 0; i < n; i++) {
0193         if (profile_is_stale(vec[i]))
0194             return true;
0195     }
0196 
0197     return false;
0198 }
0199 
0200 static long union_vec_flags(struct aa_profile **vec, int n, long mask)
0201 {
0202     long u = 0;
0203     int i;
0204 
0205     AA_BUG(!vec);
0206 
0207     for (i = 0; i < n; i++) {
0208         u |= vec[i]->label.flags & mask;
0209     }
0210 
0211     return u;
0212 }
0213 
0214 static int sort_cmp(const void *a, const void *b)
0215 {
0216     return profile_cmp(*(struct aa_profile **)a, *(struct aa_profile **)b);
0217 }
0218 
0219 /*
0220  * assumes vec is sorted
0221  * Assumes @vec has null terminator at vec[n], and will null terminate
0222  * vec[n - dups]
0223  */
0224 static inline int unique(struct aa_profile **vec, int n)
0225 {
0226     int i, pos, dups = 0;
0227 
0228     AA_BUG(n < 1);
0229     AA_BUG(!vec);
0230 
0231     pos = 0;
0232     for (i = 1; i < n; i++) {
0233         int res = profile_cmp(vec[pos], vec[i]);
0234 
0235         AA_BUG(res > 0, "vec not sorted");
0236         if (res == 0) {
0237             /* drop duplicate */
0238             aa_put_profile(vec[i]);
0239             dups++;
0240             continue;
0241         }
0242         pos++;
0243         if (dups)
0244             vec[pos] = vec[i];
0245     }
0246 
0247     AA_BUG(dups < 0);
0248 
0249     return dups;
0250 }
0251 
0252 /**
0253  * aa_vec_unique - canonical sort and unique a list of profiles
0254  * @n: number of refcounted profiles in the list (@n > 0)
0255  * @vec: list of profiles to sort and merge
0256  *
0257  * Returns: the number of duplicates eliminated == references put
0258  *
0259  * If @flags & VEC_FLAG_TERMINATE @vec has null terminator at vec[n], and will
0260  * null terminate vec[n - dups]
0261  */
0262 int aa_vec_unique(struct aa_profile **vec, int n, int flags)
0263 {
0264     int i, dups = 0;
0265 
0266     AA_BUG(n < 1);
0267     AA_BUG(!vec);
0268 
0269     /* vecs are usually small and inorder, have a fallback for larger */
0270     if (n > 8) {
0271         sort(vec, n, sizeof(struct aa_profile *), sort_cmp, NULL);
0272         dups = unique(vec, n);
0273         goto out;
0274     }
0275 
0276     /* insertion sort + unique in one */
0277     for (i = 1; i < n; i++) {
0278         struct aa_profile *tmp = vec[i];
0279         int pos, j;
0280 
0281         for (pos = i - 1 - dups; pos >= 0; pos--) {
0282             int res = profile_cmp(vec[pos], tmp);
0283 
0284             if (res == 0) {
0285                 /* drop duplicate entry */
0286                 aa_put_profile(tmp);
0287                 dups++;
0288                 goto continue_outer;
0289             } else if (res < 0)
0290                 break;
0291         }
0292         /* pos is at entry < tmp, or index -1. Set to insert pos */
0293         pos++;
0294 
0295         for (j = i - dups; j > pos; j--)
0296             vec[j] = vec[j - 1];
0297         vec[pos] = tmp;
0298 continue_outer:
0299         ;
0300     }
0301 
0302     AA_BUG(dups < 0);
0303 
0304 out:
0305     if (flags & VEC_FLAG_TERMINATE)
0306         vec[n - dups] = NULL;
0307 
0308     return dups;
0309 }
0310 
0311 
0312 void aa_label_destroy(struct aa_label *label)
0313 {
0314     AA_BUG(!label);
0315 
0316     if (!label_isprofile(label)) {
0317         struct aa_profile *profile;
0318         struct label_it i;
0319 
0320         aa_put_str(label->hname);
0321 
0322         label_for_each(i, label, profile) {
0323             aa_put_profile(profile);
0324             label->vec[i.i] = (struct aa_profile *)
0325                        (LABEL_POISON + (long) i.i);
0326         }
0327     }
0328 
0329     if (label->proxy) {
0330         if (rcu_dereference_protected(label->proxy->label, true) == label)
0331             rcu_assign_pointer(label->proxy->label, NULL);
0332         aa_put_proxy(label->proxy);
0333     }
0334     aa_free_secid(label->secid);
0335 
0336     label->proxy = (struct aa_proxy *) PROXY_POISON + 1;
0337 }
0338 
0339 void aa_label_free(struct aa_label *label)
0340 {
0341     if (!label)
0342         return;
0343 
0344     aa_label_destroy(label);
0345     kfree(label);
0346 }
0347 
0348 static void label_free_switch(struct aa_label *label)
0349 {
0350     if (label->flags & FLAG_NS_COUNT)
0351         aa_free_ns(labels_ns(label));
0352     else if (label_isprofile(label))
0353         aa_free_profile(labels_profile(label));
0354     else
0355         aa_label_free(label);
0356 }
0357 
0358 static void label_free_rcu(struct rcu_head *head)
0359 {
0360     struct aa_label *label = container_of(head, struct aa_label, rcu);
0361 
0362     if (label->flags & FLAG_IN_TREE)
0363         (void) aa_label_remove(label);
0364     label_free_switch(label);
0365 }
0366 
0367 void aa_label_kref(struct kref *kref)
0368 {
0369     struct aa_label *label = container_of(kref, struct aa_label, count);
0370     struct aa_ns *ns = labels_ns(label);
0371 
0372     if (!ns) {
0373         /* never live, no rcu callback needed, just using the fn */
0374         label_free_switch(label);
0375         return;
0376     }
0377     /* TODO: update labels_profile macro so it works here */
0378     AA_BUG(label_isprofile(label) &&
0379            on_list_rcu(&label->vec[0]->base.profiles));
0380     AA_BUG(label_isprofile(label) &&
0381            on_list_rcu(&label->vec[0]->base.list));
0382 
0383     /* TODO: if compound label and not stale add to reclaim cache */
0384     call_rcu(&label->rcu, label_free_rcu);
0385 }
0386 
0387 static void label_free_or_put_new(struct aa_label *label, struct aa_label *new)
0388 {
0389     if (label != new)
0390         /* need to free directly to break circular ref with proxy */
0391         aa_label_free(new);
0392     else
0393         aa_put_label(new);
0394 }
0395 
0396 bool aa_label_init(struct aa_label *label, int size, gfp_t gfp)
0397 {
0398     AA_BUG(!label);
0399     AA_BUG(size < 1);
0400 
0401     if (aa_alloc_secid(label, gfp) < 0)
0402         return false;
0403 
0404     label->size = size;         /* doesn't include null */
0405     label->vec[size] = NULL;        /* null terminate */
0406     kref_init(&label->count);
0407     RB_CLEAR_NODE(&label->node);
0408 
0409     return true;
0410 }
0411 
0412 /**
0413  * aa_label_alloc - allocate a label with a profile vector of @size length
0414  * @size: size of profile vector in the label
0415  * @proxy: proxy to use OR null if to allocate a new one
0416  * @gfp: memory allocation type
0417  *
0418  * Returns: new label
0419  *     else NULL if failed
0420  */
0421 struct aa_label *aa_label_alloc(int size, struct aa_proxy *proxy, gfp_t gfp)
0422 {
0423     struct aa_label *new;
0424 
0425     AA_BUG(size < 1);
0426 
0427     /*  + 1 for null terminator entry on vec */
0428     new = kzalloc(struct_size(new, vec, size + 1), gfp);
0429     AA_DEBUG("%s (%p)\n", __func__, new);
0430     if (!new)
0431         goto fail;
0432 
0433     if (!aa_label_init(new, size, gfp))
0434         goto fail;
0435 
0436     if (!proxy) {
0437         proxy = aa_alloc_proxy(new, gfp);
0438         if (!proxy)
0439             goto fail;
0440     } else
0441         aa_get_proxy(proxy);
0442     /* just set new's proxy, don't redirect proxy here if it was passed in*/
0443     new->proxy = proxy;
0444 
0445     return new;
0446 
0447 fail:
0448     kfree(new);
0449 
0450     return NULL;
0451 }
0452 
0453 
0454 /**
0455  * label_cmp - label comparison for set ordering
0456  * @a: label to compare (NOT NULL)
0457  * @b: label to compare (NOT NULL)
0458  *
0459  * Returns: <0  if a < b
0460  *          ==0 if a == b
0461  *          >0  if a > b
0462  */
0463 static int label_cmp(struct aa_label *a, struct aa_label *b)
0464 {
0465     AA_BUG(!b);
0466 
0467     if (a == b)
0468         return 0;
0469 
0470     return vec_cmp(a->vec, a->size, b->vec, b->size);
0471 }
0472 
0473 /* helper fn for label_for_each_confined */
0474 int aa_label_next_confined(struct aa_label *label, int i)
0475 {
0476     AA_BUG(!label);
0477     AA_BUG(i < 0);
0478 
0479     for (; i < label->size; i++) {
0480         if (!profile_unconfined(label->vec[i]))
0481             return i;
0482     }
0483 
0484     return i;
0485 }
0486 
0487 /**
0488  * __aa_label_next_not_in_set - return the next profile of @sub not in @set
0489  * @I: label iterator
0490  * @set: label to test against
0491  * @sub: label to if is subset of @set
0492  *
0493  * Returns: profile in @sub that is not in @set, with iterator set pos after
0494  *     else NULL if @sub is a subset of @set
0495  */
0496 struct aa_profile *__aa_label_next_not_in_set(struct label_it *I,
0497                           struct aa_label *set,
0498                           struct aa_label *sub)
0499 {
0500     AA_BUG(!set);
0501     AA_BUG(!I);
0502     AA_BUG(I->i < 0);
0503     AA_BUG(I->i > set->size);
0504     AA_BUG(!sub);
0505     AA_BUG(I->j < 0);
0506     AA_BUG(I->j > sub->size);
0507 
0508     while (I->j < sub->size && I->i < set->size) {
0509         int res = profile_cmp(sub->vec[I->j], set->vec[I->i]);
0510 
0511         if (res == 0) {
0512             (I->j)++;
0513             (I->i)++;
0514         } else if (res > 0)
0515             (I->i)++;
0516         else
0517             return sub->vec[(I->j)++];
0518     }
0519 
0520     if (I->j < sub->size)
0521         return sub->vec[(I->j)++];
0522 
0523     return NULL;
0524 }
0525 
0526 /**
0527  * aa_label_is_subset - test if @sub is a subset of @set
0528  * @set: label to test against
0529  * @sub: label to test if is subset of @set
0530  *
0531  * Returns: true if @sub is subset of @set
0532  *     else false
0533  */
0534 bool aa_label_is_subset(struct aa_label *set, struct aa_label *sub)
0535 {
0536     struct label_it i = { };
0537 
0538     AA_BUG(!set);
0539     AA_BUG(!sub);
0540 
0541     if (sub == set)
0542         return true;
0543 
0544     return __aa_label_next_not_in_set(&i, set, sub) == NULL;
0545 }
0546 
0547 /**
0548  * aa_label_is_unconfined_subset - test if @sub is a subset of @set
0549  * @set: label to test against
0550  * @sub: label to test if is subset of @set
0551  *
0552  * This checks for subset but taking into account unconfined. IF
0553  * @sub contains an unconfined profile that does not have a matching
0554  * unconfined in @set then this will not cause the test to fail.
0555  * Conversely we don't care about an unconfined in @set that is not in
0556  * @sub
0557  *
0558  * Returns: true if @sub is special_subset of @set
0559  *     else false
0560  */
0561 bool aa_label_is_unconfined_subset(struct aa_label *set, struct aa_label *sub)
0562 {
0563     struct label_it i = { };
0564     struct aa_profile *p;
0565 
0566     AA_BUG(!set);
0567     AA_BUG(!sub);
0568 
0569     if (sub == set)
0570         return true;
0571 
0572     do {
0573         p = __aa_label_next_not_in_set(&i, set, sub);
0574         if (p && !profile_unconfined(p))
0575             break;
0576     } while (p);
0577 
0578     return p == NULL;
0579 }
0580 
0581 
0582 /**
0583  * __label_remove - remove @label from the label set
0584  * @l: label to remove
0585  * @new: label to redirect to
0586  *
0587  * Requires: labels_set(@label)->lock write_lock
0588  * Returns:  true if the label was in the tree and removed
0589  */
0590 static bool __label_remove(struct aa_label *label, struct aa_label *new)
0591 {
0592     struct aa_labelset *ls = labels_set(label);
0593 
0594     AA_BUG(!ls);
0595     AA_BUG(!label);
0596     lockdep_assert_held_write(&ls->lock);
0597 
0598     if (new)
0599         __aa_proxy_redirect(label, new);
0600 
0601     if (!label_is_stale(label))
0602         __label_make_stale(label);
0603 
0604     if (label->flags & FLAG_IN_TREE) {
0605         rb_erase(&label->node, &ls->root);
0606         label->flags &= ~FLAG_IN_TREE;
0607         return true;
0608     }
0609 
0610     return false;
0611 }
0612 
0613 /**
0614  * __label_replace - replace @old with @new in label set
0615  * @old: label to remove from label set
0616  * @new: label to replace @old with
0617  *
0618  * Requires: labels_set(@old)->lock write_lock
0619  *           valid ref count be held on @new
0620  * Returns: true if @old was in set and replaced by @new
0621  *
0622  * Note: current implementation requires label set be order in such a way
0623  *       that @new directly replaces @old position in the set (ie.
0624  *       using pointer comparison of the label address would not work)
0625  */
0626 static bool __label_replace(struct aa_label *old, struct aa_label *new)
0627 {
0628     struct aa_labelset *ls = labels_set(old);
0629 
0630     AA_BUG(!ls);
0631     AA_BUG(!old);
0632     AA_BUG(!new);
0633     lockdep_assert_held_write(&ls->lock);
0634     AA_BUG(new->flags & FLAG_IN_TREE);
0635 
0636     if (!label_is_stale(old))
0637         __label_make_stale(old);
0638 
0639     if (old->flags & FLAG_IN_TREE) {
0640         rb_replace_node(&old->node, &new->node, &ls->root);
0641         old->flags &= ~FLAG_IN_TREE;
0642         new->flags |= FLAG_IN_TREE;
0643         return true;
0644     }
0645 
0646     return false;
0647 }
0648 
0649 /**
0650  * __label_insert - attempt to insert @l into a label set
0651  * @ls: set of labels to insert @l into (NOT NULL)
0652  * @label: new label to insert (NOT NULL)
0653  * @replace: whether insertion should replace existing entry that is not stale
0654  *
0655  * Requires: @ls->lock
0656  *           caller to hold a valid ref on l
0657  *           if @replace is true l has a preallocated proxy associated
0658  * Returns: @l if successful in inserting @l - with additional refcount
0659  *          else ref counted equivalent label that is already in the set,
0660  *          the else condition only happens if @replace is false
0661  */
0662 static struct aa_label *__label_insert(struct aa_labelset *ls,
0663                        struct aa_label *label, bool replace)
0664 {
0665     struct rb_node **new, *parent = NULL;
0666 
0667     AA_BUG(!ls);
0668     AA_BUG(!label);
0669     AA_BUG(labels_set(label) != ls);
0670     lockdep_assert_held_write(&ls->lock);
0671     AA_BUG(label->flags & FLAG_IN_TREE);
0672 
0673     /* Figure out where to put new node */
0674     new = &ls->root.rb_node;
0675     while (*new) {
0676         struct aa_label *this = rb_entry(*new, struct aa_label, node);
0677         int result = label_cmp(label, this);
0678 
0679         parent = *new;
0680         if (result == 0) {
0681             /* !__aa_get_label means queued for destruction,
0682              * so replace in place, however the label has
0683              * died before the replacement so do not share
0684              * the proxy
0685              */
0686             if (!replace && !label_is_stale(this)) {
0687                 if (__aa_get_label(this))
0688                     return this;
0689             } else
0690                 __proxy_share(this, label);
0691             AA_BUG(!__label_replace(this, label));
0692             return aa_get_label(label);
0693         } else if (result < 0)
0694             new = &((*new)->rb_left);
0695         else /* (result > 0) */
0696             new = &((*new)->rb_right);
0697     }
0698 
0699     /* Add new node and rebalance tree. */
0700     rb_link_node(&label->node, parent, new);
0701     rb_insert_color(&label->node, &ls->root);
0702     label->flags |= FLAG_IN_TREE;
0703 
0704     return aa_get_label(label);
0705 }
0706 
0707 /**
0708  * __vec_find - find label that matches @vec in label set
0709  * @vec: vec of profiles to find matching label for (NOT NULL)
0710  * @n: length of @vec
0711  *
0712  * Requires: @vec_labelset(vec) lock held
0713  *           caller to hold a valid ref on l
0714  *
0715  * Returns: ref counted @label if matching label is in tree
0716  *          ref counted label that is equiv to @l in tree
0717  *     else NULL if @vec equiv is not in tree
0718  */
0719 static struct aa_label *__vec_find(struct aa_profile **vec, int n)
0720 {
0721     struct rb_node *node;
0722 
0723     AA_BUG(!vec);
0724     AA_BUG(!*vec);
0725     AA_BUG(n <= 0);
0726 
0727     node = vec_labelset(vec, n)->root.rb_node;
0728     while (node) {
0729         struct aa_label *this = rb_entry(node, struct aa_label, node);
0730         int result = vec_cmp(this->vec, this->size, vec, n);
0731 
0732         if (result > 0)
0733             node = node->rb_left;
0734         else if (result < 0)
0735             node = node->rb_right;
0736         else
0737             return __aa_get_label(this);
0738     }
0739 
0740     return NULL;
0741 }
0742 
0743 /**
0744  * __label_find - find label @label in label set
0745  * @label: label to find (NOT NULL)
0746  *
0747  * Requires: labels_set(@label)->lock held
0748  *           caller to hold a valid ref on l
0749  *
0750  * Returns: ref counted @label if @label is in tree OR
0751  *          ref counted label that is equiv to @label in tree
0752  *     else NULL if @label or equiv is not in tree
0753  */
0754 static struct aa_label *__label_find(struct aa_label *label)
0755 {
0756     AA_BUG(!label);
0757 
0758     return __vec_find(label->vec, label->size);
0759 }
0760 
0761 
0762 /**
0763  * aa_label_remove - remove a label from the labelset
0764  * @label: label to remove
0765  *
0766  * Returns: true if @label was removed from the tree
0767  *     else @label was not in tree so it could not be removed
0768  */
0769 bool aa_label_remove(struct aa_label *label)
0770 {
0771     struct aa_labelset *ls = labels_set(label);
0772     unsigned long flags;
0773     bool res;
0774 
0775     AA_BUG(!ls);
0776 
0777     write_lock_irqsave(&ls->lock, flags);
0778     res = __label_remove(label, ns_unconfined(labels_ns(label)));
0779     write_unlock_irqrestore(&ls->lock, flags);
0780 
0781     return res;
0782 }
0783 
0784 /**
0785  * aa_label_replace - replace a label @old with a new version @new
0786  * @old: label to replace
0787  * @new: label replacing @old
0788  *
0789  * Returns: true if @old was in tree and replaced
0790  *     else @old was not in tree, and @new was not inserted
0791  */
0792 bool aa_label_replace(struct aa_label *old, struct aa_label *new)
0793 {
0794     unsigned long flags;
0795     bool res;
0796 
0797     if (name_is_shared(old, new) && labels_ns(old) == labels_ns(new)) {
0798         write_lock_irqsave(&labels_set(old)->lock, flags);
0799         if (old->proxy != new->proxy)
0800             __proxy_share(old, new);
0801         else
0802             __aa_proxy_redirect(old, new);
0803         res = __label_replace(old, new);
0804         write_unlock_irqrestore(&labels_set(old)->lock, flags);
0805     } else {
0806         struct aa_label *l;
0807         struct aa_labelset *ls = labels_set(old);
0808 
0809         write_lock_irqsave(&ls->lock, flags);
0810         res = __label_remove(old, new);
0811         if (labels_ns(old) != labels_ns(new)) {
0812             write_unlock_irqrestore(&ls->lock, flags);
0813             ls = labels_set(new);
0814             write_lock_irqsave(&ls->lock, flags);
0815         }
0816         l = __label_insert(ls, new, true);
0817         res = (l == new);
0818         write_unlock_irqrestore(&ls->lock, flags);
0819         aa_put_label(l);
0820     }
0821 
0822     return res;
0823 }
0824 
0825 /**
0826  * vec_find - find label @l in label set
0827  * @vec: array of profiles to find equiv label for (NOT NULL)
0828  * @n: length of @vec
0829  *
0830  * Returns: refcounted label if @vec equiv is in tree
0831  *     else NULL if @vec equiv is not in tree
0832  */
0833 static struct aa_label *vec_find(struct aa_profile **vec, int n)
0834 {
0835     struct aa_labelset *ls;
0836     struct aa_label *label;
0837     unsigned long flags;
0838 
0839     AA_BUG(!vec);
0840     AA_BUG(!*vec);
0841     AA_BUG(n <= 0);
0842 
0843     ls = vec_labelset(vec, n);
0844     read_lock_irqsave(&ls->lock, flags);
0845     label = __vec_find(vec, n);
0846     read_unlock_irqrestore(&ls->lock, flags);
0847 
0848     return label;
0849 }
0850 
0851 /* requires sort and merge done first */
0852 static struct aa_label *vec_create_and_insert_label(struct aa_profile **vec,
0853                             int len, gfp_t gfp)
0854 {
0855     struct aa_label *label = NULL;
0856     struct aa_labelset *ls;
0857     unsigned long flags;
0858     struct aa_label *new;
0859     int i;
0860 
0861     AA_BUG(!vec);
0862 
0863     if (len == 1)
0864         return aa_get_label(&vec[0]->label);
0865 
0866     ls = labels_set(&vec[len - 1]->label);
0867 
0868     /* TODO: enable when read side is lockless
0869      * check if label exists before taking locks
0870      */
0871     new = aa_label_alloc(len, NULL, gfp);
0872     if (!new)
0873         return NULL;
0874 
0875     for (i = 0; i < len; i++)
0876         new->vec[i] = aa_get_profile(vec[i]);
0877 
0878     write_lock_irqsave(&ls->lock, flags);
0879     label = __label_insert(ls, new, false);
0880     write_unlock_irqrestore(&ls->lock, flags);
0881     label_free_or_put_new(label, new);
0882 
0883     return label;
0884 }
0885 
0886 struct aa_label *aa_vec_find_or_create_label(struct aa_profile **vec, int len,
0887                          gfp_t gfp)
0888 {
0889     struct aa_label *label = vec_find(vec, len);
0890 
0891     if (label)
0892         return label;
0893 
0894     return vec_create_and_insert_label(vec, len, gfp);
0895 }
0896 
0897 /**
0898  * aa_label_find - find label @label in label set
0899  * @label: label to find (NOT NULL)
0900  *
0901  * Requires: caller to hold a valid ref on l
0902  *
0903  * Returns: refcounted @label if @label is in tree
0904  *          refcounted label that is equiv to @label in tree
0905  *     else NULL if @label or equiv is not in tree
0906  */
0907 struct aa_label *aa_label_find(struct aa_label *label)
0908 {
0909     AA_BUG(!label);
0910 
0911     return vec_find(label->vec, label->size);
0912 }
0913 
0914 
0915 /**
0916  * aa_label_insert - insert label @label into @ls or return existing label
0917  * @ls - labelset to insert @label into
0918  * @label - label to insert
0919  *
0920  * Requires: caller to hold a valid ref on @label
0921  *
0922  * Returns: ref counted @label if successful in inserting @label
0923  *     else ref counted equivalent label that is already in the set
0924  */
0925 struct aa_label *aa_label_insert(struct aa_labelset *ls, struct aa_label *label)
0926 {
0927     struct aa_label *l;
0928     unsigned long flags;
0929 
0930     AA_BUG(!ls);
0931     AA_BUG(!label);
0932 
0933     /* check if label exists before taking lock */
0934     if (!label_is_stale(label)) {
0935         read_lock_irqsave(&ls->lock, flags);
0936         l = __label_find(label);
0937         read_unlock_irqrestore(&ls->lock, flags);
0938         if (l)
0939             return l;
0940     }
0941 
0942     write_lock_irqsave(&ls->lock, flags);
0943     l = __label_insert(ls, label, false);
0944     write_unlock_irqrestore(&ls->lock, flags);
0945 
0946     return l;
0947 }
0948 
0949 
0950 /**
0951  * aa_label_next_in_merge - find the next profile when merging @a and @b
0952  * @I: label iterator
0953  * @a: label to merge
0954  * @b: label to merge
0955  *
0956  * Returns: next profile
0957  *     else null if no more profiles
0958  */
0959 struct aa_profile *aa_label_next_in_merge(struct label_it *I,
0960                       struct aa_label *a,
0961                       struct aa_label *b)
0962 {
0963     AA_BUG(!a);
0964     AA_BUG(!b);
0965     AA_BUG(!I);
0966     AA_BUG(I->i < 0);
0967     AA_BUG(I->i > a->size);
0968     AA_BUG(I->j < 0);
0969     AA_BUG(I->j > b->size);
0970 
0971     if (I->i < a->size) {
0972         if (I->j < b->size) {
0973             int res = profile_cmp(a->vec[I->i], b->vec[I->j]);
0974 
0975             if (res > 0)
0976                 return b->vec[(I->j)++];
0977             if (res == 0)
0978                 (I->j)++;
0979         }
0980 
0981         return a->vec[(I->i)++];
0982     }
0983 
0984     if (I->j < b->size)
0985         return b->vec[(I->j)++];
0986 
0987     return NULL;
0988 }
0989 
0990 /**
0991  * label_merge_cmp - cmp of @a merging with @b against @z for set ordering
0992  * @a: label to merge then compare (NOT NULL)
0993  * @b: label to merge then compare (NOT NULL)
0994  * @z: label to compare merge against (NOT NULL)
0995  *
0996  * Assumes: using the most recent versions of @a, @b, and @z
0997  *
0998  * Returns: <0  if a < b
0999  *          ==0 if a == b
1000  *          >0  if a > b
1001  */
1002 static int label_merge_cmp(struct aa_label *a, struct aa_label *b,
1003                struct aa_label *z)
1004 {
1005     struct aa_profile *p = NULL;
1006     struct label_it i = { };
1007     int k;
1008 
1009     AA_BUG(!a);
1010     AA_BUG(!b);
1011     AA_BUG(!z);
1012 
1013     for (k = 0;
1014          k < z->size && (p = aa_label_next_in_merge(&i, a, b));
1015          k++) {
1016         int res = profile_cmp(p, z->vec[k]);
1017 
1018         if (res != 0)
1019             return res;
1020     }
1021 
1022     if (p)
1023         return 1;
1024     else if (k < z->size)
1025         return -1;
1026     return 0;
1027 }
1028 
1029 /**
1030  * label_merge_insert - create a new label by merging @a and @b
1031  * @new: preallocated label to merge into (NOT NULL)
1032  * @a: label to merge with @b  (NOT NULL)
1033  * @b: label to merge with @a  (NOT NULL)
1034  *
1035  * Requires: preallocated proxy
1036  *
1037  * Returns: ref counted label either @new if merge is unique
1038  *          @a if @b is a subset of @a
1039  *          @b if @a is a subset of @b
1040  *
1041  * NOTE: will not use @new if the merge results in @new == @a or @b
1042  *
1043  *       Must be used within labelset write lock to avoid racing with
1044  *       setting labels stale.
1045  */
1046 static struct aa_label *label_merge_insert(struct aa_label *new,
1047                        struct aa_label *a,
1048                        struct aa_label *b)
1049 {
1050     struct aa_label *label;
1051     struct aa_labelset *ls;
1052     struct aa_profile *next;
1053     struct label_it i;
1054     unsigned long flags;
1055     int k = 0, invcount = 0;
1056     bool stale = false;
1057 
1058     AA_BUG(!a);
1059     AA_BUG(a->size < 0);
1060     AA_BUG(!b);
1061     AA_BUG(b->size < 0);
1062     AA_BUG(!new);
1063     AA_BUG(new->size < a->size + b->size);
1064 
1065     label_for_each_in_merge(i, a, b, next) {
1066         AA_BUG(!next);
1067         if (profile_is_stale(next)) {
1068             new->vec[k] = aa_get_newest_profile(next);
1069             AA_BUG(!new->vec[k]->label.proxy);
1070             AA_BUG(!new->vec[k]->label.proxy->label);
1071             if (next->label.proxy != new->vec[k]->label.proxy)
1072                 invcount++;
1073             k++;
1074             stale = true;
1075         } else
1076             new->vec[k++] = aa_get_profile(next);
1077     }
1078     /* set to actual size which is <= allocated len */
1079     new->size = k;
1080     new->vec[k] = NULL;
1081 
1082     if (invcount) {
1083         new->size -= aa_vec_unique(&new->vec[0], new->size,
1084                        VEC_FLAG_TERMINATE);
1085         /* TODO: deal with reference labels */
1086         if (new->size == 1) {
1087             label = aa_get_label(&new->vec[0]->label);
1088             return label;
1089         }
1090     } else if (!stale) {
1091         /*
1092          * merge could be same as a || b, note: it is not possible
1093          * for new->size == a->size == b->size unless a == b
1094          */
1095         if (k == a->size)
1096             return aa_get_label(a);
1097         else if (k == b->size)
1098             return aa_get_label(b);
1099     }
1100     new->flags |= union_vec_flags(new->vec, new->size, FLAG_UNCONFINED |
1101                           FLAG_DEBUG1 | FLAG_DEBUG2);
1102     ls = labels_set(new);
1103     write_lock_irqsave(&ls->lock, flags);
1104     label = __label_insert(labels_set(new), new, false);
1105     write_unlock_irqrestore(&ls->lock, flags);
1106 
1107     return label;
1108 }
1109 
1110 /**
1111  * labelset_of_merge - find which labelset a merged label should be inserted
1112  * @a: label to merge and insert
1113  * @b: label to merge and insert
1114  *
1115  * Returns: labelset that the merged label should be inserted into
1116  */
1117 static struct aa_labelset *labelset_of_merge(struct aa_label *a,
1118                          struct aa_label *b)
1119 {
1120     struct aa_ns *nsa = labels_ns(a);
1121     struct aa_ns *nsb = labels_ns(b);
1122 
1123     if (ns_cmp(nsa, nsb) <= 0)
1124         return &nsa->labels;
1125     return &nsb->labels;
1126 }
1127 
1128 /**
1129  * __label_find_merge - find label that is equiv to merge of @a and @b
1130  * @ls: set of labels to search (NOT NULL)
1131  * @a: label to merge with @b  (NOT NULL)
1132  * @b: label to merge with @a  (NOT NULL)
1133  *
1134  * Requires: ls->lock read_lock held
1135  *
1136  * Returns: ref counted label that is equiv to merge of @a and @b
1137  *     else NULL if merge of @a and @b is not in set
1138  */
1139 static struct aa_label *__label_find_merge(struct aa_labelset *ls,
1140                        struct aa_label *a,
1141                        struct aa_label *b)
1142 {
1143     struct rb_node *node;
1144 
1145     AA_BUG(!ls);
1146     AA_BUG(!a);
1147     AA_BUG(!b);
1148 
1149     if (a == b)
1150         return __label_find(a);
1151 
1152     node  = ls->root.rb_node;
1153     while (node) {
1154         struct aa_label *this = container_of(node, struct aa_label,
1155                              node);
1156         int result = label_merge_cmp(a, b, this);
1157 
1158         if (result < 0)
1159             node = node->rb_left;
1160         else if (result > 0)
1161             node = node->rb_right;
1162         else
1163             return __aa_get_label(this);
1164     }
1165 
1166     return NULL;
1167 }
1168 
1169 
1170 /**
1171  * aa_label_find_merge - find label that is equiv to merge of @a and @b
1172  * @a: label to merge with @b  (NOT NULL)
1173  * @b: label to merge with @a  (NOT NULL)
1174  *
1175  * Requires: labels be fully constructed with a valid ns
1176  *
1177  * Returns: ref counted label that is equiv to merge of @a and @b
1178  *     else NULL if merge of @a and @b is not in set
1179  */
1180 struct aa_label *aa_label_find_merge(struct aa_label *a, struct aa_label *b)
1181 {
1182     struct aa_labelset *ls;
1183     struct aa_label *label, *ar = NULL, *br = NULL;
1184     unsigned long flags;
1185 
1186     AA_BUG(!a);
1187     AA_BUG(!b);
1188 
1189     if (label_is_stale(a))
1190         a = ar = aa_get_newest_label(a);
1191     if (label_is_stale(b))
1192         b = br = aa_get_newest_label(b);
1193     ls = labelset_of_merge(a, b);
1194     read_lock_irqsave(&ls->lock, flags);
1195     label = __label_find_merge(ls, a, b);
1196     read_unlock_irqrestore(&ls->lock, flags);
1197     aa_put_label(ar);
1198     aa_put_label(br);
1199 
1200     return label;
1201 }
1202 
1203 /**
1204  * aa_label_merge - attempt to insert new merged label of @a and @b
1205  * @ls: set of labels to insert label into (NOT NULL)
1206  * @a: label to merge with @b  (NOT NULL)
1207  * @b: label to merge with @a  (NOT NULL)
1208  * @gfp: memory allocation type
1209  *
1210  * Requires: caller to hold valid refs on @a and @b
1211  *           labels be fully constructed with a valid ns
1212  *
1213  * Returns: ref counted new label if successful in inserting merge of a & b
1214  *     else ref counted equivalent label that is already in the set.
1215  *     else NULL if could not create label (-ENOMEM)
1216  */
1217 struct aa_label *aa_label_merge(struct aa_label *a, struct aa_label *b,
1218                 gfp_t gfp)
1219 {
1220     struct aa_label *label = NULL;
1221 
1222     AA_BUG(!a);
1223     AA_BUG(!b);
1224 
1225     if (a == b)
1226         return aa_get_newest_label(a);
1227 
1228     /* TODO: enable when read side is lockless
1229      * check if label exists before taking locks
1230     if (!label_is_stale(a) && !label_is_stale(b))
1231         label = aa_label_find_merge(a, b);
1232     */
1233 
1234     if (!label) {
1235         struct aa_label *new;
1236 
1237         a = aa_get_newest_label(a);
1238         b = aa_get_newest_label(b);
1239 
1240         /* could use label_merge_len(a, b), but requires double
1241          * comparison for small savings
1242          */
1243         new = aa_label_alloc(a->size + b->size, NULL, gfp);
1244         if (!new)
1245             goto out;
1246 
1247         label = label_merge_insert(new, a, b);
1248         label_free_or_put_new(label, new);
1249 out:
1250         aa_put_label(a);
1251         aa_put_label(b);
1252     }
1253 
1254     return label;
1255 }
1256 
1257 static inline bool label_is_visible(struct aa_profile *profile,
1258                     struct aa_label *label)
1259 {
1260     return aa_ns_visible(profile->ns, labels_ns(label), true);
1261 }
1262 
1263 /* match a profile and its associated ns component if needed
1264  * Assumes visibility test has already been done.
1265  * If a subns profile is not to be matched should be prescreened with
1266  * visibility test.
1267  */
1268 static inline unsigned int match_component(struct aa_profile *profile,
1269                        struct aa_profile *tp,
1270                        unsigned int state)
1271 {
1272     const char *ns_name;
1273 
1274     if (profile->ns == tp->ns)
1275         return aa_dfa_match(profile->policy.dfa, state, tp->base.hname);
1276 
1277     /* try matching with namespace name and then profile */
1278     ns_name = aa_ns_name(profile->ns, tp->ns, true);
1279     state = aa_dfa_match_len(profile->policy.dfa, state, ":", 1);
1280     state = aa_dfa_match(profile->policy.dfa, state, ns_name);
1281     state = aa_dfa_match_len(profile->policy.dfa, state, ":", 1);
1282     return aa_dfa_match(profile->policy.dfa, state, tp->base.hname);
1283 }
1284 
1285 /**
1286  * label_compound_match - find perms for full compound label
1287  * @profile: profile to find perms for
1288  * @label: label to check access permissions for
1289  * @start: state to start match in
1290  * @subns: whether to do permission checks on components in a subns
1291  * @request: permissions to request
1292  * @perms: perms struct to set
1293  *
1294  * Returns: 0 on success else ERROR
1295  *
1296  * For the label A//&B//&C this does the perm match for A//&B//&C
1297  * @perms should be preinitialized with allperms OR a previous permission
1298  *        check to be stacked.
1299  */
1300 static int label_compound_match(struct aa_profile *profile,
1301                 struct aa_label *label,
1302                 unsigned int state, bool subns, u32 request,
1303                 struct aa_perms *perms)
1304 {
1305     struct aa_profile *tp;
1306     struct label_it i;
1307 
1308     /* find first subcomponent that is visible */
1309     label_for_each(i, label, tp) {
1310         if (!aa_ns_visible(profile->ns, tp->ns, subns))
1311             continue;
1312         state = match_component(profile, tp, state);
1313         if (!state)
1314             goto fail;
1315         goto next;
1316     }
1317 
1318     /* no component visible */
1319     *perms = allperms;
1320     return 0;
1321 
1322 next:
1323     label_for_each_cont(i, label, tp) {
1324         if (!aa_ns_visible(profile->ns, tp->ns, subns))
1325             continue;
1326         state = aa_dfa_match(profile->policy.dfa, state, "//&");
1327         state = match_component(profile, tp, state);
1328         if (!state)
1329             goto fail;
1330     }
1331     aa_compute_perms(profile->policy.dfa, state, perms);
1332     aa_apply_modes_to_perms(profile, perms);
1333     if ((perms->allow & request) != request)
1334         return -EACCES;
1335 
1336     return 0;
1337 
1338 fail:
1339     *perms = nullperms;
1340     return state;
1341 }
1342 
1343 /**
1344  * label_components_match - find perms for all subcomponents of a label
1345  * @profile: profile to find perms for
1346  * @label: label to check access permissions for
1347  * @start: state to start match in
1348  * @subns: whether to do permission checks on components in a subns
1349  * @request: permissions to request
1350  * @perms: an initialized perms struct to add accumulation to
1351  *
1352  * Returns: 0 on success else ERROR
1353  *
1354  * For the label A//&B//&C this does the perm match for each of A and B and C
1355  * @perms should be preinitialized with allperms OR a previous permission
1356  *        check to be stacked.
1357  */
1358 static int label_components_match(struct aa_profile *profile,
1359                   struct aa_label *label, unsigned int start,
1360                   bool subns, u32 request,
1361                   struct aa_perms *perms)
1362 {
1363     struct aa_profile *tp;
1364     struct label_it i;
1365     struct aa_perms tmp;
1366     unsigned int state = 0;
1367 
1368     /* find first subcomponent to test */
1369     label_for_each(i, label, tp) {
1370         if (!aa_ns_visible(profile->ns, tp->ns, subns))
1371             continue;
1372         state = match_component(profile, tp, start);
1373         if (!state)
1374             goto fail;
1375         goto next;
1376     }
1377 
1378     /* no subcomponents visible - no change in perms */
1379     return 0;
1380 
1381 next:
1382     aa_compute_perms(profile->policy.dfa, state, &tmp);
1383     aa_apply_modes_to_perms(profile, &tmp);
1384     aa_perms_accum(perms, &tmp);
1385     label_for_each_cont(i, label, tp) {
1386         if (!aa_ns_visible(profile->ns, tp->ns, subns))
1387             continue;
1388         state = match_component(profile, tp, start);
1389         if (!state)
1390             goto fail;
1391         aa_compute_perms(profile->policy.dfa, state, &tmp);
1392         aa_apply_modes_to_perms(profile, &tmp);
1393         aa_perms_accum(perms, &tmp);
1394     }
1395 
1396     if ((perms->allow & request) != request)
1397         return -EACCES;
1398 
1399     return 0;
1400 
1401 fail:
1402     *perms = nullperms;
1403     return -EACCES;
1404 }
1405 
1406 /**
1407  * aa_label_match - do a multi-component label match
1408  * @profile: profile to match against (NOT NULL)
1409  * @label: label to match (NOT NULL)
1410  * @state: state to start in
1411  * @subns: whether to match subns components
1412  * @request: permission request
1413  * @perms: Returns computed perms (NOT NULL)
1414  *
1415  * Returns: the state the match finished in, may be the none matching state
1416  */
1417 int aa_label_match(struct aa_profile *profile, struct aa_label *label,
1418            unsigned int state, bool subns, u32 request,
1419            struct aa_perms *perms)
1420 {
1421     int error = label_compound_match(profile, label, state, subns, request,
1422                      perms);
1423     if (!error)
1424         return error;
1425 
1426     *perms = allperms;
1427     return label_components_match(profile, label, state, subns, request,
1428                       perms);
1429 }
1430 
1431 
1432 /**
1433  * aa_update_label_name - update a label to have a stored name
1434  * @ns: ns being viewed from (NOT NULL)
1435  * @label: label to update (NOT NULL)
1436  * @gfp: type of memory allocation
1437  *
1438  * Requires: labels_set(label) not locked in caller
1439  *
1440  * note: only updates the label name if it does not have a name already
1441  *       and if it is in the labelset
1442  */
1443 bool aa_update_label_name(struct aa_ns *ns, struct aa_label *label, gfp_t gfp)
1444 {
1445     struct aa_labelset *ls;
1446     unsigned long flags;
1447     char __counted *name;
1448     bool res = false;
1449 
1450     AA_BUG(!ns);
1451     AA_BUG(!label);
1452 
1453     if (label->hname || labels_ns(label) != ns)
1454         return res;
1455 
1456     if (aa_label_acntsxprint(&name, ns, label, FLAGS_NONE, gfp) < 0)
1457         return res;
1458 
1459     ls = labels_set(label);
1460     write_lock_irqsave(&ls->lock, flags);
1461     if (!label->hname && label->flags & FLAG_IN_TREE) {
1462         label->hname = name;
1463         res = true;
1464     } else
1465         aa_put_str(name);
1466     write_unlock_irqrestore(&ls->lock, flags);
1467 
1468     return res;
1469 }
1470 
1471 /*
1472  * cached label name is present and visible
1473  * @label->hname only exists if label is namespace hierachical
1474  */
1475 static inline bool use_label_hname(struct aa_ns *ns, struct aa_label *label,
1476                    int flags)
1477 {
1478     if (label->hname && (!ns || labels_ns(label) == ns) &&
1479         !(flags & ~FLAG_SHOW_MODE))
1480         return true;
1481 
1482     return false;
1483 }
1484 
1485 /* helper macro for snprint routines */
1486 #define update_for_len(total, len, size, str)   \
1487 do {                    \
1488     size_t ulen = len;      \
1489                     \
1490     AA_BUG(len < 0);        \
1491     total += ulen;          \
1492     ulen = min(ulen, size);     \
1493     size -= ulen;           \
1494     str += ulen;            \
1495 } while (0)
1496 
1497 /**
1498  * aa_profile_snxprint - print a profile name to a buffer
1499  * @str: buffer to write to. (MAY BE NULL if @size == 0)
1500  * @size: size of buffer
1501  * @view: namespace profile is being viewed from
1502  * @profile: profile to view (NOT NULL)
1503  * @flags: whether to include the mode string
1504  * @prev_ns: last ns printed when used in compound print
1505  *
1506  * Returns: size of name written or would be written if larger than
1507  *          available buffer
1508  *
1509  * Note: will not print anything if the profile is not visible
1510  */
1511 static int aa_profile_snxprint(char *str, size_t size, struct aa_ns *view,
1512                    struct aa_profile *profile, int flags,
1513                    struct aa_ns **prev_ns)
1514 {
1515     const char *ns_name = NULL;
1516 
1517     AA_BUG(!str && size != 0);
1518     AA_BUG(!profile);
1519 
1520     if (!view)
1521         view = profiles_ns(profile);
1522 
1523     if (view != profile->ns &&
1524         (!prev_ns || (*prev_ns != profile->ns))) {
1525         if (prev_ns)
1526             *prev_ns = profile->ns;
1527         ns_name = aa_ns_name(view, profile->ns,
1528                      flags & FLAG_VIEW_SUBNS);
1529         if (ns_name == aa_hidden_ns_name) {
1530             if (flags & FLAG_HIDDEN_UNCONFINED)
1531                 return snprintf(str, size, "%s", "unconfined");
1532             return snprintf(str, size, "%s", ns_name);
1533         }
1534     }
1535 
1536     if ((flags & FLAG_SHOW_MODE) && profile != profile->ns->unconfined) {
1537         const char *modestr = aa_profile_mode_names[profile->mode];
1538 
1539         if (ns_name)
1540             return snprintf(str, size, ":%s:%s (%s)", ns_name,
1541                     profile->base.hname, modestr);
1542         return snprintf(str, size, "%s (%s)", profile->base.hname,
1543                 modestr);
1544     }
1545 
1546     if (ns_name)
1547         return snprintf(str, size, ":%s:%s", ns_name,
1548                 profile->base.hname);
1549     return snprintf(str, size, "%s", profile->base.hname);
1550 }
1551 
1552 static const char *label_modename(struct aa_ns *ns, struct aa_label *label,
1553                   int flags)
1554 {
1555     struct aa_profile *profile;
1556     struct label_it i;
1557     int mode = -1, count = 0;
1558 
1559     label_for_each(i, label, profile) {
1560         if (aa_ns_visible(ns, profile->ns, flags & FLAG_VIEW_SUBNS)) {
1561             count++;
1562             if (profile == profile->ns->unconfined)
1563                 /* special case unconfined so stacks with
1564                  * unconfined don't report as mixed. ie.
1565                  * profile_foo//&:ns1:unconfined (mixed)
1566                  */
1567                 continue;
1568             if (mode == -1)
1569                 mode = profile->mode;
1570             else if (mode != profile->mode)
1571                 return "mixed";
1572         }
1573     }
1574 
1575     if (count == 0)
1576         return "-";
1577     if (mode == -1)
1578         /* everything was unconfined */
1579         mode = APPARMOR_UNCONFINED;
1580 
1581     return aa_profile_mode_names[mode];
1582 }
1583 
1584 /* if any visible label is not unconfined the display_mode returns true */
1585 static inline bool display_mode(struct aa_ns *ns, struct aa_label *label,
1586                 int flags)
1587 {
1588     if ((flags & FLAG_SHOW_MODE)) {
1589         struct aa_profile *profile;
1590         struct label_it i;
1591 
1592         label_for_each(i, label, profile) {
1593             if (aa_ns_visible(ns, profile->ns,
1594                       flags & FLAG_VIEW_SUBNS) &&
1595                 profile != profile->ns->unconfined)
1596                 return true;
1597         }
1598         /* only ns->unconfined in set of profiles in ns */
1599         return false;
1600     }
1601 
1602     return false;
1603 }
1604 
1605 /**
1606  * aa_label_snxprint - print a label name to a string buffer
1607  * @str: buffer to write to. (MAY BE NULL if @size == 0)
1608  * @size: size of buffer
1609  * @ns: namespace profile is being viewed from
1610  * @label: label to view (NOT NULL)
1611  * @flags: whether to include the mode string
1612  *
1613  * Returns: size of name written or would be written if larger than
1614  *          available buffer
1615  *
1616  * Note: labels do not have to be strictly hierarchical to the ns as
1617  *       objects may be shared across different namespaces and thus
1618  *       pickup labeling from each ns.  If a particular part of the
1619  *       label is not visible it will just be excluded.  And if none
1620  *       of the label is visible "---" will be used.
1621  */
1622 int aa_label_snxprint(char *str, size_t size, struct aa_ns *ns,
1623               struct aa_label *label, int flags)
1624 {
1625     struct aa_profile *profile;
1626     struct aa_ns *prev_ns = NULL;
1627     struct label_it i;
1628     int count = 0, total = 0;
1629     ssize_t len;
1630 
1631     AA_BUG(!str && size != 0);
1632     AA_BUG(!label);
1633 
1634     if (AA_DEBUG_LABEL && (flags & FLAG_ABS_ROOT)) {
1635         ns = root_ns;
1636         len = snprintf(str, size, "_");
1637         update_for_len(total, len, size, str);
1638     } else if (!ns) {
1639         ns = labels_ns(label);
1640     }
1641 
1642     label_for_each(i, label, profile) {
1643         if (aa_ns_visible(ns, profile->ns, flags & FLAG_VIEW_SUBNS)) {
1644             if (count > 0) {
1645                 len = snprintf(str, size, "//&");
1646                 update_for_len(total, len, size, str);
1647             }
1648             len = aa_profile_snxprint(str, size, ns, profile,
1649                           flags & FLAG_VIEW_SUBNS,
1650                           &prev_ns);
1651             update_for_len(total, len, size, str);
1652             count++;
1653         }
1654     }
1655 
1656     if (count == 0) {
1657         if (flags & FLAG_HIDDEN_UNCONFINED)
1658             return snprintf(str, size, "%s", "unconfined");
1659         return snprintf(str, size, "%s", aa_hidden_ns_name);
1660     }
1661 
1662     /* count == 1 && ... is for backwards compat where the mode
1663      * is not displayed for 'unconfined' in the current ns
1664      */
1665     if (display_mode(ns, label, flags)) {
1666         len = snprintf(str, size, " (%s)",
1667                    label_modename(ns, label, flags));
1668         update_for_len(total, len, size, str);
1669     }
1670 
1671     return total;
1672 }
1673 #undef update_for_len
1674 
1675 /**
1676  * aa_label_asxprint - allocate a string buffer and print label into it
1677  * @strp: Returns - the allocated buffer with the label name. (NOT NULL)
1678  * @ns: namespace profile is being viewed from
1679  * @label: label to view (NOT NULL)
1680  * @flags: flags controlling what label info is printed
1681  * @gfp: kernel memory allocation type
1682  *
1683  * Returns: size of name written or would be written if larger than
1684  *          available buffer
1685  */
1686 int aa_label_asxprint(char **strp, struct aa_ns *ns, struct aa_label *label,
1687               int flags, gfp_t gfp)
1688 {
1689     int size;
1690 
1691     AA_BUG(!strp);
1692     AA_BUG(!label);
1693 
1694     size = aa_label_snxprint(NULL, 0, ns, label, flags);
1695     if (size < 0)
1696         return size;
1697 
1698     *strp = kmalloc(size + 1, gfp);
1699     if (!*strp)
1700         return -ENOMEM;
1701     return aa_label_snxprint(*strp, size + 1, ns, label, flags);
1702 }
1703 
1704 /**
1705  * aa_label_acntsxprint - allocate a __counted string buffer and print label
1706  * @strp: buffer to write to.
1707  * @ns: namespace profile is being viewed from
1708  * @label: label to view (NOT NULL)
1709  * @flags: flags controlling what label info is printed
1710  * @gfp: kernel memory allocation type
1711  *
1712  * Returns: size of name written or would be written if larger than
1713  *          available buffer
1714  */
1715 int aa_label_acntsxprint(char __counted **strp, struct aa_ns *ns,
1716              struct aa_label *label, int flags, gfp_t gfp)
1717 {
1718     int size;
1719 
1720     AA_BUG(!strp);
1721     AA_BUG(!label);
1722 
1723     size = aa_label_snxprint(NULL, 0, ns, label, flags);
1724     if (size < 0)
1725         return size;
1726 
1727     *strp = aa_str_alloc(size + 1, gfp);
1728     if (!*strp)
1729         return -ENOMEM;
1730     return aa_label_snxprint(*strp, size + 1, ns, label, flags);
1731 }
1732 
1733 
1734 void aa_label_xaudit(struct audit_buffer *ab, struct aa_ns *ns,
1735              struct aa_label *label, int flags, gfp_t gfp)
1736 {
1737     const char *str;
1738     char *name = NULL;
1739     int len;
1740 
1741     AA_BUG(!ab);
1742     AA_BUG(!label);
1743 
1744     if (!use_label_hname(ns, label, flags) ||
1745         display_mode(ns, label, flags)) {
1746         len  = aa_label_asxprint(&name, ns, label, flags, gfp);
1747         if (len < 0) {
1748             AA_DEBUG("label print error");
1749             return;
1750         }
1751         str = name;
1752     } else {
1753         str = (char *) label->hname;
1754         len = strlen(str);
1755     }
1756     if (audit_string_contains_control(str, len))
1757         audit_log_n_hex(ab, str, len);
1758     else
1759         audit_log_n_string(ab, str, len);
1760 
1761     kfree(name);
1762 }
1763 
1764 void aa_label_seq_xprint(struct seq_file *f, struct aa_ns *ns,
1765              struct aa_label *label, int flags, gfp_t gfp)
1766 {
1767     AA_BUG(!f);
1768     AA_BUG(!label);
1769 
1770     if (!use_label_hname(ns, label, flags)) {
1771         char *str;
1772         int len;
1773 
1774         len = aa_label_asxprint(&str, ns, label, flags, gfp);
1775         if (len < 0) {
1776             AA_DEBUG("label print error");
1777             return;
1778         }
1779         seq_puts(f, str);
1780         kfree(str);
1781     } else if (display_mode(ns, label, flags))
1782         seq_printf(f, "%s (%s)", label->hname,
1783                label_modename(ns, label, flags));
1784     else
1785         seq_puts(f, label->hname);
1786 }
1787 
1788 void aa_label_xprintk(struct aa_ns *ns, struct aa_label *label, int flags,
1789               gfp_t gfp)
1790 {
1791     AA_BUG(!label);
1792 
1793     if (!use_label_hname(ns, label, flags)) {
1794         char *str;
1795         int len;
1796 
1797         len = aa_label_asxprint(&str, ns, label, flags, gfp);
1798         if (len < 0) {
1799             AA_DEBUG("label print error");
1800             return;
1801         }
1802         pr_info("%s", str);
1803         kfree(str);
1804     } else if (display_mode(ns, label, flags))
1805         pr_info("%s (%s)", label->hname,
1806                label_modename(ns, label, flags));
1807     else
1808         pr_info("%s", label->hname);
1809 }
1810 
1811 void aa_label_audit(struct audit_buffer *ab, struct aa_label *label, gfp_t gfp)
1812 {
1813     struct aa_ns *ns = aa_get_current_ns();
1814 
1815     aa_label_xaudit(ab, ns, label, FLAG_VIEW_SUBNS, gfp);
1816     aa_put_ns(ns);
1817 }
1818 
1819 void aa_label_seq_print(struct seq_file *f, struct aa_label *label, gfp_t gfp)
1820 {
1821     struct aa_ns *ns = aa_get_current_ns();
1822 
1823     aa_label_seq_xprint(f, ns, label, FLAG_VIEW_SUBNS, gfp);
1824     aa_put_ns(ns);
1825 }
1826 
1827 void aa_label_printk(struct aa_label *label, gfp_t gfp)
1828 {
1829     struct aa_ns *ns = aa_get_current_ns();
1830 
1831     aa_label_xprintk(ns, label, FLAG_VIEW_SUBNS, gfp);
1832     aa_put_ns(ns);
1833 }
1834 
1835 static int label_count_strn_entries(const char *str, size_t n)
1836 {
1837     const char *end = str + n;
1838     const char *split;
1839     int count = 1;
1840 
1841     AA_BUG(!str);
1842 
1843     for (split = aa_label_strn_split(str, end - str);
1844          split;
1845          split = aa_label_strn_split(str, end - str)) {
1846         count++;
1847         str = split + 3;
1848     }
1849 
1850     return count;
1851 }
1852 
1853 /*
1854  * ensure stacks with components like
1855  *   :ns:A//&B
1856  * have :ns: applied to both 'A' and 'B' by making the lookup relative
1857  * to the base if the lookup specifies an ns, else making the stacked lookup
1858  * relative to the last embedded ns in the string.
1859  */
1860 static struct aa_profile *fqlookupn_profile(struct aa_label *base,
1861                         struct aa_label *currentbase,
1862                         const char *str, size_t n)
1863 {
1864     const char *first = skipn_spaces(str, n);
1865 
1866     if (first && *first == ':')
1867         return aa_fqlookupn_profile(base, str, n);
1868 
1869     return aa_fqlookupn_profile(currentbase, str, n);
1870 }
1871 
1872 /**
1873  * aa_label_strn_parse - parse, validate and convert a text string to a label
1874  * @base: base label to use for lookups (NOT NULL)
1875  * @str: null terminated text string (NOT NULL)
1876  * @n: length of str to parse, will stop at \0 if encountered before n
1877  * @gfp: allocation type
1878  * @create: true if should create compound labels if they don't exist
1879  * @force_stack: true if should stack even if no leading &
1880  *
1881  * Returns: the matching refcounted label if present
1882  *     else ERRPTR
1883  */
1884 struct aa_label *aa_label_strn_parse(struct aa_label *base, const char *str,
1885                      size_t n, gfp_t gfp, bool create,
1886                      bool force_stack)
1887 {
1888     DEFINE_VEC(profile, vec);
1889     struct aa_label *label, *currbase = base;
1890     int i, len, stack = 0, error;
1891     const char *end = str + n;
1892     const char *split;
1893 
1894     AA_BUG(!base);
1895     AA_BUG(!str);
1896 
1897     str = skipn_spaces(str, n);
1898     if (str == NULL || (AA_DEBUG_LABEL && *str == '_' &&
1899                 base != &root_ns->unconfined->label))
1900         return ERR_PTR(-EINVAL);
1901 
1902     len = label_count_strn_entries(str, end - str);
1903     if (*str == '&' || force_stack) {
1904         /* stack on top of base */
1905         stack = base->size;
1906         len += stack;
1907         if (*str == '&')
1908             str++;
1909     }
1910 
1911     error = vec_setup(profile, vec, len, gfp);
1912     if (error)
1913         return ERR_PTR(error);
1914 
1915     for (i = 0; i < stack; i++)
1916         vec[i] = aa_get_profile(base->vec[i]);
1917 
1918     for (split = aa_label_strn_split(str, end - str), i = stack;
1919          split && i < len; i++) {
1920         vec[i] = fqlookupn_profile(base, currbase, str, split - str);
1921         if (!vec[i])
1922             goto fail;
1923         /*
1924          * if component specified a new ns it becomes the new base
1925          * so that subsequent lookups are relative to it
1926          */
1927         if (vec[i]->ns != labels_ns(currbase))
1928             currbase = &vec[i]->label;
1929         str = split + 3;
1930         split = aa_label_strn_split(str, end - str);
1931     }
1932     /* last element doesn't have a split */
1933     if (i < len) {
1934         vec[i] = fqlookupn_profile(base, currbase, str, end - str);
1935         if (!vec[i])
1936             goto fail;
1937     }
1938     if (len == 1)
1939         /* no need to free vec as len < LOCAL_VEC_ENTRIES */
1940         return &vec[0]->label;
1941 
1942     len -= aa_vec_unique(vec, len, VEC_FLAG_TERMINATE);
1943     /* TODO: deal with reference labels */
1944     if (len == 1) {
1945         label = aa_get_label(&vec[0]->label);
1946         goto out;
1947     }
1948 
1949     if (create)
1950         label = aa_vec_find_or_create_label(vec, len, gfp);
1951     else
1952         label = vec_find(vec, len);
1953     if (!label)
1954         goto fail;
1955 
1956 out:
1957     /* use adjusted len from after vec_unique, not original */
1958     vec_cleanup(profile, vec, len);
1959     return label;
1960 
1961 fail:
1962     label = ERR_PTR(-ENOENT);
1963     goto out;
1964 }
1965 
1966 struct aa_label *aa_label_parse(struct aa_label *base, const char *str,
1967                 gfp_t gfp, bool create, bool force_stack)
1968 {
1969     return aa_label_strn_parse(base, str, strlen(str), gfp, create,
1970                    force_stack);
1971 }
1972 
1973 /**
1974  * aa_labelset_destroy - remove all labels from the label set
1975  * @ls: label set to cleanup (NOT NULL)
1976  *
1977  * Labels that are removed from the set may still exist beyond the set
1978  * being destroyed depending on their reference counting
1979  */
1980 void aa_labelset_destroy(struct aa_labelset *ls)
1981 {
1982     struct rb_node *node;
1983     unsigned long flags;
1984 
1985     AA_BUG(!ls);
1986 
1987     write_lock_irqsave(&ls->lock, flags);
1988     for (node = rb_first(&ls->root); node; node = rb_first(&ls->root)) {
1989         struct aa_label *this = rb_entry(node, struct aa_label, node);
1990 
1991         if (labels_ns(this) != root_ns)
1992             __label_remove(this,
1993                        ns_unconfined(labels_ns(this)->parent));
1994         else
1995             __label_remove(this, NULL);
1996     }
1997     write_unlock_irqrestore(&ls->lock, flags);
1998 }
1999 
2000 /*
2001  * @ls: labelset to init (NOT NULL)
2002  */
2003 void aa_labelset_init(struct aa_labelset *ls)
2004 {
2005     AA_BUG(!ls);
2006 
2007     rwlock_init(&ls->lock);
2008     ls->root = RB_ROOT;
2009 }
2010 
2011 static struct aa_label *labelset_next_stale(struct aa_labelset *ls)
2012 {
2013     struct aa_label *label;
2014     struct rb_node *node;
2015     unsigned long flags;
2016 
2017     AA_BUG(!ls);
2018 
2019     read_lock_irqsave(&ls->lock, flags);
2020 
2021     __labelset_for_each(ls, node) {
2022         label = rb_entry(node, struct aa_label, node);
2023         if ((label_is_stale(label) ||
2024              vec_is_stale(label->vec, label->size)) &&
2025             __aa_get_label(label))
2026             goto out;
2027 
2028     }
2029     label = NULL;
2030 
2031 out:
2032     read_unlock_irqrestore(&ls->lock, flags);
2033 
2034     return label;
2035 }
2036 
2037 /**
2038  * __label_update - insert updated version of @label into labelset
2039  * @label - the label to update/replace
2040  *
2041  * Returns: new label that is up to date
2042  *     else NULL on failure
2043  *
2044  * Requires: @ns lock be held
2045  *
2046  * Note: worst case is the stale @label does not get updated and has
2047  *       to be updated at a later time.
2048  */
2049 static struct aa_label *__label_update(struct aa_label *label)
2050 {
2051     struct aa_label *new, *tmp;
2052     struct aa_labelset *ls;
2053     unsigned long flags;
2054     int i, invcount = 0;
2055 
2056     AA_BUG(!label);
2057     AA_BUG(!mutex_is_locked(&labels_ns(label)->lock));
2058 
2059     new = aa_label_alloc(label->size, label->proxy, GFP_KERNEL);
2060     if (!new)
2061         return NULL;
2062 
2063     /*
2064      * while holding the ns_lock will stop profile replacement, removal,
2065      * and label updates, label merging and removal can be occurring
2066      */
2067     ls = labels_set(label);
2068     write_lock_irqsave(&ls->lock, flags);
2069     for (i = 0; i < label->size; i++) {
2070         AA_BUG(!label->vec[i]);
2071         new->vec[i] = aa_get_newest_profile(label->vec[i]);
2072         AA_BUG(!new->vec[i]);
2073         AA_BUG(!new->vec[i]->label.proxy);
2074         AA_BUG(!new->vec[i]->label.proxy->label);
2075         if (new->vec[i]->label.proxy != label->vec[i]->label.proxy)
2076             invcount++;
2077     }
2078 
2079     /* updated stale label by being removed/renamed from labelset */
2080     if (invcount) {
2081         new->size -= aa_vec_unique(&new->vec[0], new->size,
2082                        VEC_FLAG_TERMINATE);
2083         /* TODO: deal with reference labels */
2084         if (new->size == 1) {
2085             tmp = aa_get_label(&new->vec[0]->label);
2086             AA_BUG(tmp == label);
2087             goto remove;
2088         }
2089         if (labels_set(label) != labels_set(new)) {
2090             write_unlock_irqrestore(&ls->lock, flags);
2091             tmp = aa_label_insert(labels_set(new), new);
2092             write_lock_irqsave(&ls->lock, flags);
2093             goto remove;
2094         }
2095     } else
2096         AA_BUG(labels_ns(label) != labels_ns(new));
2097 
2098     tmp = __label_insert(labels_set(label), new, true);
2099 remove:
2100     /* ensure label is removed, and redirected correctly */
2101     __label_remove(label, tmp);
2102     write_unlock_irqrestore(&ls->lock, flags);
2103     label_free_or_put_new(tmp, new);
2104 
2105     return tmp;
2106 }
2107 
2108 /**
2109  * __labelset_update - update labels in @ns
2110  * @ns: namespace to update labels in  (NOT NULL)
2111  *
2112  * Requires: @ns lock be held
2113  *
2114  * Walk the labelset ensuring that all labels are up to date and valid
2115  * Any label that has a stale component is marked stale and replaced and
2116  * by an updated version.
2117  *
2118  * If failures happen due to memory pressures then stale labels will
2119  * be left in place until the next pass.
2120  */
2121 static void __labelset_update(struct aa_ns *ns)
2122 {
2123     struct aa_label *label;
2124 
2125     AA_BUG(!ns);
2126     AA_BUG(!mutex_is_locked(&ns->lock));
2127 
2128     do {
2129         label = labelset_next_stale(&ns->labels);
2130         if (label) {
2131             struct aa_label *l = __label_update(label);
2132 
2133             aa_put_label(l);
2134             aa_put_label(label);
2135         }
2136     } while (label);
2137 }
2138 
2139 /**
2140  * __aa_labelset_update_subtree - update all labels with a stale component
2141  * @ns: ns to start update at (NOT NULL)
2142  *
2143  * Requires: @ns lock be held
2144  *
2145  * Invalidates labels based on @p in @ns and any children namespaces.
2146  */
2147 void __aa_labelset_update_subtree(struct aa_ns *ns)
2148 {
2149     struct aa_ns *child;
2150 
2151     AA_BUG(!ns);
2152     AA_BUG(!mutex_is_locked(&ns->lock));
2153 
2154     __labelset_update(ns);
2155 
2156     list_for_each_entry(child, &ns->sub_ns, base.list) {
2157         mutex_lock_nested(&child->lock, child->level);
2158         __aa_labelset_update_subtree(child);
2159         mutex_unlock(&child->lock);
2160     }
2161 }