LoadPin: Ignore the "contents" argument of the LSM hooks
[platform/kernel/linux-starfive.git] / security / apparmor / label.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * AppArmor security module
4  *
5  * This file contains AppArmor label definitions
6  *
7  * Copyright 2017 Canonical Ltd.
8  */
9
10 #include <linux/audit.h>
11 #include <linux/seq_file.h>
12 #include <linux/sort.h>
13
14 #include "include/apparmor.h"
15 #include "include/cred.h"
16 #include "include/label.h"
17 #include "include/policy.h"
18 #include "include/secid.h"
19
20
21 /*
22  * the aa_label represents the set of profiles confining an object
23  *
24  * Labels maintain a reference count to the set of pointers they reference
25  * Labels are ref counted by
26  *   tasks and object via the security field/security context off the field
27  *   code - will take a ref count on a label if it needs the label
28  *          beyond what is possible with an rcu_read_lock.
29  *   profiles - each profile is a label
30  *   secids - a pinned secid will keep a refcount of the label it is
31  *          referencing
32  *   objects - inode, files, sockets, ...
33  *
34  * Labels are not ref counted by the label set, so they maybe removed and
35  * freed when no longer in use.
36  *
37  */
38
39 #define PROXY_POISON 97
40 #define LABEL_POISON 100
41
42 static void free_proxy(struct aa_proxy *proxy)
43 {
44         if (proxy) {
45                 /* p->label will not updated any more as p is dead */
46                 aa_put_label(rcu_dereference_protected(proxy->label, true));
47                 memset(proxy, 0, sizeof(*proxy));
48                 RCU_INIT_POINTER(proxy->label, (struct aa_label *)PROXY_POISON);
49                 kfree(proxy);
50         }
51 }
52
53 void aa_proxy_kref(struct kref *kref)
54 {
55         struct aa_proxy *proxy = container_of(kref, struct aa_proxy, count);
56
57         free_proxy(proxy);
58 }
59
60 struct aa_proxy *aa_alloc_proxy(struct aa_label *label, gfp_t gfp)
61 {
62         struct aa_proxy *new;
63
64         new = kzalloc(sizeof(struct aa_proxy), gfp);
65         if (new) {
66                 kref_init(&new->count);
67                 rcu_assign_pointer(new->label, aa_get_label(label));
68         }
69         return new;
70 }
71
72 /* requires profile list write lock held */
73 void __aa_proxy_redirect(struct aa_label *orig, struct aa_label *new)
74 {
75         struct aa_label *tmp;
76
77         AA_BUG(!orig);
78         AA_BUG(!new);
79         lockdep_assert_held_write(&labels_set(orig)->lock);
80
81         tmp = rcu_dereference_protected(orig->proxy->label,
82                                         &labels_ns(orig)->lock);
83         rcu_assign_pointer(orig->proxy->label, aa_get_label(new));
84         orig->flags |= FLAG_STALE;
85         aa_put_label(tmp);
86 }
87
88 static void __proxy_share(struct aa_label *old, struct aa_label *new)
89 {
90         struct aa_proxy *proxy = new->proxy;
91
92         new->proxy = aa_get_proxy(old->proxy);
93         __aa_proxy_redirect(old, new);
94         aa_put_proxy(proxy);
95 }
96
97
98 /**
99  * ns_cmp - compare ns for label set ordering
100  * @a: ns to compare (NOT NULL)
101  * @b: ns to compare (NOT NULL)
102  *
103  * Returns: <0 if a < b
104  *          ==0 if a == b
105  *          >0  if a > b
106  */
107 static int ns_cmp(struct aa_ns *a, struct aa_ns *b)
108 {
109         int res;
110
111         AA_BUG(!a);
112         AA_BUG(!b);
113         AA_BUG(!a->base.hname);
114         AA_BUG(!b->base.hname);
115
116         if (a == b)
117                 return 0;
118
119         res = a->level - b->level;
120         if (res)
121                 return res;
122
123         return strcmp(a->base.hname, b->base.hname);
124 }
125
126 /**
127  * profile_cmp - profile comparison for set ordering
128  * @a: profile to compare (NOT NULL)
129  * @b: profile to compare (NOT NULL)
130  *
131  * Returns: <0  if a < b
132  *          ==0 if a == b
133  *          >0  if a > b
134  */
135 static int profile_cmp(struct aa_profile *a, struct aa_profile *b)
136 {
137         int res;
138
139         AA_BUG(!a);
140         AA_BUG(!b);
141         AA_BUG(!a->ns);
142         AA_BUG(!b->ns);
143         AA_BUG(!a->base.hname);
144         AA_BUG(!b->base.hname);
145
146         if (a == b || a->base.hname == b->base.hname)
147                 return 0;
148         res = ns_cmp(a->ns, b->ns);
149         if (res)
150                 return res;
151
152         return strcmp(a->base.hname, b->base.hname);
153 }
154
155 /**
156  * vec_cmp - label comparison for set ordering
157  * @a: label to compare (NOT NULL)
158  * @vec: vector of profiles to compare (NOT NULL)
159  * @n: length of @vec
160  *
161  * Returns: <0  if a < vec
162  *          ==0 if a == vec
163  *          >0  if a > vec
164  */
165 static int vec_cmp(struct aa_profile **a, int an, struct aa_profile **b, int bn)
166 {
167         int i;
168
169         AA_BUG(!a);
170         AA_BUG(!*a);
171         AA_BUG(!b);
172         AA_BUG(!*b);
173         AA_BUG(an <= 0);
174         AA_BUG(bn <= 0);
175
176         for (i = 0; i < an && i < bn; i++) {
177                 int res = profile_cmp(a[i], b[i]);
178
179                 if (res != 0)
180                         return res;
181         }
182
183         return an - bn;
184 }
185
186 static bool vec_is_stale(struct aa_profile **vec, int n)
187 {
188         int i;
189
190         AA_BUG(!vec);
191
192         for (i = 0; i < n; i++) {
193                 if (profile_is_stale(vec[i]))
194                         return true;
195         }
196
197         return false;
198 }
199
200 static long accum_vec_flags(struct aa_profile **vec, int n)
201 {
202         long u = FLAG_UNCONFINED;
203         int i;
204
205         AA_BUG(!vec);
206
207         for (i = 0; i < n; i++) {
208                 u |= vec[i]->label.flags & (FLAG_DEBUG1 | FLAG_DEBUG2 |
209                                             FLAG_STALE);
210                 if (!(u & vec[i]->label.flags & FLAG_UNCONFINED))
211                         u &= ~FLAG_UNCONFINED;
212         }
213
214         return u;
215 }
216
217 static int sort_cmp(const void *a, const void *b)
218 {
219         return profile_cmp(*(struct aa_profile **)a, *(struct aa_profile **)b);
220 }
221
222 /*
223  * assumes vec is sorted
224  * Assumes @vec has null terminator at vec[n], and will null terminate
225  * vec[n - dups]
226  */
227 static inline int unique(struct aa_profile **vec, int n)
228 {
229         int i, pos, dups = 0;
230
231         AA_BUG(n < 1);
232         AA_BUG(!vec);
233
234         pos = 0;
235         for (i = 1; i < n; i++) {
236                 int res = profile_cmp(vec[pos], vec[i]);
237
238                 AA_BUG(res > 0, "vec not sorted");
239                 if (res == 0) {
240                         /* drop duplicate */
241                         aa_put_profile(vec[i]);
242                         dups++;
243                         continue;
244                 }
245                 pos++;
246                 if (dups)
247                         vec[pos] = vec[i];
248         }
249
250         AA_BUG(dups < 0);
251
252         return dups;
253 }
254
255 /**
256  * aa_vec_unique - canonical sort and unique a list of profiles
257  * @n: number of refcounted profiles in the list (@n > 0)
258  * @vec: list of profiles to sort and merge
259  *
260  * Returns: the number of duplicates eliminated == references put
261  *
262  * If @flags & VEC_FLAG_TERMINATE @vec has null terminator at vec[n], and will
263  * null terminate vec[n - dups]
264  */
265 int aa_vec_unique(struct aa_profile **vec, int n, int flags)
266 {
267         int i, dups = 0;
268
269         AA_BUG(n < 1);
270         AA_BUG(!vec);
271
272         /* vecs are usually small and inorder, have a fallback for larger */
273         if (n > 8) {
274                 sort(vec, n, sizeof(struct aa_profile *), sort_cmp, NULL);
275                 dups = unique(vec, n);
276                 goto out;
277         }
278
279         /* insertion sort + unique in one */
280         for (i = 1; i < n; i++) {
281                 struct aa_profile *tmp = vec[i];
282                 int pos, j;
283
284                 for (pos = i - 1 - dups; pos >= 0; pos--) {
285                         int res = profile_cmp(vec[pos], tmp);
286
287                         if (res == 0) {
288                                 /* drop duplicate entry */
289                                 aa_put_profile(tmp);
290                                 dups++;
291                                 goto continue_outer;
292                         } else if (res < 0)
293                                 break;
294                 }
295                 /* pos is at entry < tmp, or index -1. Set to insert pos */
296                 pos++;
297
298                 for (j = i - dups; j > pos; j--)
299                         vec[j] = vec[j - 1];
300                 vec[pos] = tmp;
301 continue_outer:
302                 ;
303         }
304
305         AA_BUG(dups < 0);
306
307 out:
308         if (flags & VEC_FLAG_TERMINATE)
309                 vec[n - dups] = NULL;
310
311         return dups;
312 }
313
314
315 void aa_label_destroy(struct aa_label *label)
316 {
317         AA_BUG(!label);
318
319         if (!label_isprofile(label)) {
320                 struct aa_profile *profile;
321                 struct label_it i;
322
323                 aa_put_str(label->hname);
324
325                 label_for_each(i, label, profile) {
326                         aa_put_profile(profile);
327                         label->vec[i.i] = (struct aa_profile *)
328                                            (LABEL_POISON + (long) i.i);
329                 }
330         }
331
332         if (label->proxy) {
333                 if (rcu_dereference_protected(label->proxy->label, true) == label)
334                         rcu_assign_pointer(label->proxy->label, NULL);
335                 aa_put_proxy(label->proxy);
336         }
337         aa_free_secid(label->secid);
338
339         label->proxy = (struct aa_proxy *) PROXY_POISON + 1;
340 }
341
342 void aa_label_free(struct aa_label *label)
343 {
344         if (!label)
345                 return;
346
347         aa_label_destroy(label);
348         kfree(label);
349 }
350
351 static void label_free_switch(struct aa_label *label)
352 {
353         if (label->flags & FLAG_NS_COUNT)
354                 aa_free_ns(labels_ns(label));
355         else if (label_isprofile(label))
356                 aa_free_profile(labels_profile(label));
357         else
358                 aa_label_free(label);
359 }
360
361 static void label_free_rcu(struct rcu_head *head)
362 {
363         struct aa_label *label = container_of(head, struct aa_label, rcu);
364
365         if (label->flags & FLAG_IN_TREE)
366                 (void) aa_label_remove(label);
367         label_free_switch(label);
368 }
369
370 void aa_label_kref(struct kref *kref)
371 {
372         struct aa_label *label = container_of(kref, struct aa_label, count);
373         struct aa_ns *ns = labels_ns(label);
374
375         if (!ns) {
376                 /* never live, no rcu callback needed, just using the fn */
377                 label_free_switch(label);
378                 return;
379         }
380         /* TODO: update labels_profile macro so it works here */
381         AA_BUG(label_isprofile(label) &&
382                on_list_rcu(&label->vec[0]->base.profiles));
383         AA_BUG(label_isprofile(label) &&
384                on_list_rcu(&label->vec[0]->base.list));
385
386         /* TODO: if compound label and not stale add to reclaim cache */
387         call_rcu(&label->rcu, label_free_rcu);
388 }
389
390 static void label_free_or_put_new(struct aa_label *label, struct aa_label *new)
391 {
392         if (label != new)
393                 /* need to free directly to break circular ref with proxy */
394                 aa_label_free(new);
395         else
396                 aa_put_label(new);
397 }
398
399 bool aa_label_init(struct aa_label *label, int size, gfp_t gfp)
400 {
401         AA_BUG(!label);
402         AA_BUG(size < 1);
403
404         if (aa_alloc_secid(label, gfp) < 0)
405                 return false;
406
407         label->size = size;                     /* doesn't include null */
408         label->vec[size] = NULL;                /* null terminate */
409         kref_init(&label->count);
410         RB_CLEAR_NODE(&label->node);
411
412         return true;
413 }
414
415 /**
416  * aa_label_alloc - allocate a label with a profile vector of @size length
417  * @size: size of profile vector in the label
418  * @proxy: proxy to use OR null if to allocate a new one
419  * @gfp: memory allocation type
420  *
421  * Returns: new label
422  *     else NULL if failed
423  */
424 struct aa_label *aa_label_alloc(int size, struct aa_proxy *proxy, gfp_t gfp)
425 {
426         struct aa_label *new;
427
428         AA_BUG(size < 1);
429
430         /*  + 1 for null terminator entry on vec */
431         new = kzalloc(struct_size(new, vec, size + 1), gfp);
432         AA_DEBUG("%s (%p)\n", __func__, new);
433         if (!new)
434                 goto fail;
435
436         if (!aa_label_init(new, size, gfp))
437                 goto fail;
438
439         if (!proxy) {
440                 proxy = aa_alloc_proxy(new, gfp);
441                 if (!proxy)
442                         goto fail;
443         } else
444                 aa_get_proxy(proxy);
445         /* just set new's proxy, don't redirect proxy here if it was passed in*/
446         new->proxy = proxy;
447
448         return new;
449
450 fail:
451         kfree(new);
452
453         return NULL;
454 }
455
456
457 /**
458  * label_cmp - label comparison for set ordering
459  * @a: label to compare (NOT NULL)
460  * @b: label to compare (NOT NULL)
461  *
462  * Returns: <0  if a < b
463  *          ==0 if a == b
464  *          >0  if a > b
465  */
466 static int label_cmp(struct aa_label *a, struct aa_label *b)
467 {
468         AA_BUG(!b);
469
470         if (a == b)
471                 return 0;
472
473         return vec_cmp(a->vec, a->size, b->vec, b->size);
474 }
475
476 /* helper fn for label_for_each_confined */
477 int aa_label_next_confined(struct aa_label *label, int i)
478 {
479         AA_BUG(!label);
480         AA_BUG(i < 0);
481
482         for (; i < label->size; i++) {
483                 if (!profile_unconfined(label->vec[i]))
484                         return i;
485         }
486
487         return i;
488 }
489
490 /**
491  * __aa_label_next_not_in_set - return the next profile of @sub not in @set
492  * @I: label iterator
493  * @set: label to test against
494  * @sub: label to if is subset of @set
495  *
496  * Returns: profile in @sub that is not in @set, with iterator set pos after
497  *     else NULL if @sub is a subset of @set
498  */
499 struct aa_profile *__aa_label_next_not_in_set(struct label_it *I,
500                                               struct aa_label *set,
501                                               struct aa_label *sub)
502 {
503         AA_BUG(!set);
504         AA_BUG(!I);
505         AA_BUG(I->i < 0);
506         AA_BUG(I->i > set->size);
507         AA_BUG(!sub);
508         AA_BUG(I->j < 0);
509         AA_BUG(I->j > sub->size);
510
511         while (I->j < sub->size && I->i < set->size) {
512                 int res = profile_cmp(sub->vec[I->j], set->vec[I->i]);
513
514                 if (res == 0) {
515                         (I->j)++;
516                         (I->i)++;
517                 } else if (res > 0)
518                         (I->i)++;
519                 else
520                         return sub->vec[(I->j)++];
521         }
522
523         if (I->j < sub->size)
524                 return sub->vec[(I->j)++];
525
526         return NULL;
527 }
528
529 /**
530  * aa_label_is_subset - test if @sub is a subset of @set
531  * @set: label to test against
532  * @sub: label to test if is subset of @set
533  *
534  * Returns: true if @sub is subset of @set
535  *     else false
536  */
537 bool aa_label_is_subset(struct aa_label *set, struct aa_label *sub)
538 {
539         struct label_it i = { };
540
541         AA_BUG(!set);
542         AA_BUG(!sub);
543
544         if (sub == set)
545                 return true;
546
547         return __aa_label_next_not_in_set(&i, set, sub) == NULL;
548 }
549
550 /**
551  * aa_label_is_unconfined_subset - test if @sub is a subset of @set
552  * @set: label to test against
553  * @sub: label to test if is subset of @set
554  *
555  * This checks for subset but taking into account unconfined. IF
556  * @sub contains an unconfined profile that does not have a matching
557  * unconfined in @set then this will not cause the test to fail.
558  * Conversely we don't care about an unconfined in @set that is not in
559  * @sub
560  *
561  * Returns: true if @sub is special_subset of @set
562  *     else false
563  */
564 bool aa_label_is_unconfined_subset(struct aa_label *set, struct aa_label *sub)
565 {
566         struct label_it i = { };
567         struct aa_profile *p;
568
569         AA_BUG(!set);
570         AA_BUG(!sub);
571
572         if (sub == set)
573                 return true;
574
575         do {
576                 p = __aa_label_next_not_in_set(&i, set, sub);
577                 if (p && !profile_unconfined(p))
578                         break;
579         } while (p);
580
581         return p == NULL;
582 }
583
584
585 /**
586  * __label_remove - remove @label from the label set
587  * @l: label to remove
588  * @new: label to redirect to
589  *
590  * Requires: labels_set(@label)->lock write_lock
591  * Returns:  true if the label was in the tree and removed
592  */
593 static bool __label_remove(struct aa_label *label, struct aa_label *new)
594 {
595         struct aa_labelset *ls = labels_set(label);
596
597         AA_BUG(!ls);
598         AA_BUG(!label);
599         lockdep_assert_held_write(&ls->lock);
600
601         if (new)
602                 __aa_proxy_redirect(label, new);
603
604         if (!label_is_stale(label))
605                 __label_make_stale(label);
606
607         if (label->flags & FLAG_IN_TREE) {
608                 rb_erase(&label->node, &ls->root);
609                 label->flags &= ~FLAG_IN_TREE;
610                 return true;
611         }
612
613         return false;
614 }
615
616 /**
617  * __label_replace - replace @old with @new in label set
618  * @old: label to remove from label set
619  * @new: label to replace @old with
620  *
621  * Requires: labels_set(@old)->lock write_lock
622  *           valid ref count be held on @new
623  * Returns: true if @old was in set and replaced by @new
624  *
625  * Note: current implementation requires label set be order in such a way
626  *       that @new directly replaces @old position in the set (ie.
627  *       using pointer comparison of the label address would not work)
628  */
629 static bool __label_replace(struct aa_label *old, struct aa_label *new)
630 {
631         struct aa_labelset *ls = labels_set(old);
632
633         AA_BUG(!ls);
634         AA_BUG(!old);
635         AA_BUG(!new);
636         lockdep_assert_held_write(&ls->lock);
637         AA_BUG(new->flags & FLAG_IN_TREE);
638
639         if (!label_is_stale(old))
640                 __label_make_stale(old);
641
642         if (old->flags & FLAG_IN_TREE) {
643                 rb_replace_node(&old->node, &new->node, &ls->root);
644                 old->flags &= ~FLAG_IN_TREE;
645                 new->flags |= FLAG_IN_TREE;
646                 return true;
647         }
648
649         return false;
650 }
651
652 /**
653  * __label_insert - attempt to insert @l into a label set
654  * @ls: set of labels to insert @l into (NOT NULL)
655  * @label: new label to insert (NOT NULL)
656  * @replace: whether insertion should replace existing entry that is not stale
657  *
658  * Requires: @ls->lock
659  *           caller to hold a valid ref on l
660  *           if @replace is true l has a preallocated proxy associated
661  * Returns: @l if successful in inserting @l - with additional refcount
662  *          else ref counted equivalent label that is already in the set,
663  *          the else condition only happens if @replace is false
664  */
665 static struct aa_label *__label_insert(struct aa_labelset *ls,
666                                        struct aa_label *label, bool replace)
667 {
668         struct rb_node **new, *parent = NULL;
669
670         AA_BUG(!ls);
671         AA_BUG(!label);
672         AA_BUG(labels_set(label) != ls);
673         lockdep_assert_held_write(&ls->lock);
674         AA_BUG(label->flags & FLAG_IN_TREE);
675
676         /* Figure out where to put new node */
677         new = &ls->root.rb_node;
678         while (*new) {
679                 struct aa_label *this = rb_entry(*new, struct aa_label, node);
680                 int result = label_cmp(label, this);
681
682                 parent = *new;
683                 if (result == 0) {
684                         /* !__aa_get_label means queued for destruction,
685                          * so replace in place, however the label has
686                          * died before the replacement so do not share
687                          * the proxy
688                          */
689                         if (!replace && !label_is_stale(this)) {
690                                 if (__aa_get_label(this))
691                                         return this;
692                         } else
693                                 __proxy_share(this, label);
694                         AA_BUG(!__label_replace(this, label));
695                         return aa_get_label(label);
696                 } else if (result < 0)
697                         new = &((*new)->rb_left);
698                 else /* (result > 0) */
699                         new = &((*new)->rb_right);
700         }
701
702         /* Add new node and rebalance tree. */
703         rb_link_node(&label->node, parent, new);
704         rb_insert_color(&label->node, &ls->root);
705         label->flags |= FLAG_IN_TREE;
706
707         return aa_get_label(label);
708 }
709
710 /**
711  * __vec_find - find label that matches @vec in label set
712  * @vec: vec of profiles to find matching label for (NOT NULL)
713  * @n: length of @vec
714  *
715  * Requires: @vec_labelset(vec) lock held
716  *           caller to hold a valid ref on l
717  *
718  * Returns: ref counted @label if matching label is in tree
719  *          ref counted label that is equiv to @l in tree
720  *     else NULL if @vec equiv is not in tree
721  */
722 static struct aa_label *__vec_find(struct aa_profile **vec, int n)
723 {
724         struct rb_node *node;
725
726         AA_BUG(!vec);
727         AA_BUG(!*vec);
728         AA_BUG(n <= 0);
729
730         node = vec_labelset(vec, n)->root.rb_node;
731         while (node) {
732                 struct aa_label *this = rb_entry(node, struct aa_label, node);
733                 int result = vec_cmp(this->vec, this->size, vec, n);
734
735                 if (result > 0)
736                         node = node->rb_left;
737                 else if (result < 0)
738                         node = node->rb_right;
739                 else
740                         return __aa_get_label(this);
741         }
742
743         return NULL;
744 }
745
746 /**
747  * __label_find - find label @label in label set
748  * @label: label to find (NOT NULL)
749  *
750  * Requires: labels_set(@label)->lock held
751  *           caller to hold a valid ref on l
752  *
753  * Returns: ref counted @label if @label is in tree OR
754  *          ref counted label that is equiv to @label in tree
755  *     else NULL if @label or equiv is not in tree
756  */
757 static struct aa_label *__label_find(struct aa_label *label)
758 {
759         AA_BUG(!label);
760
761         return __vec_find(label->vec, label->size);
762 }
763
764
765 /**
766  * aa_label_remove - remove a label from the labelset
767  * @label: label to remove
768  *
769  * Returns: true if @label was removed from the tree
770  *     else @label was not in tree so it could not be removed
771  */
772 bool aa_label_remove(struct aa_label *label)
773 {
774         struct aa_labelset *ls = labels_set(label);
775         unsigned long flags;
776         bool res;
777
778         AA_BUG(!ls);
779
780         write_lock_irqsave(&ls->lock, flags);
781         res = __label_remove(label, ns_unconfined(labels_ns(label)));
782         write_unlock_irqrestore(&ls->lock, flags);
783
784         return res;
785 }
786
787 /**
788  * aa_label_replace - replace a label @old with a new version @new
789  * @old: label to replace
790  * @new: label replacing @old
791  *
792  * Returns: true if @old was in tree and replaced
793  *     else @old was not in tree, and @new was not inserted
794  */
795 bool aa_label_replace(struct aa_label *old, struct aa_label *new)
796 {
797         unsigned long flags;
798         bool res;
799
800         if (name_is_shared(old, new) && labels_ns(old) == labels_ns(new)) {
801                 write_lock_irqsave(&labels_set(old)->lock, flags);
802                 if (old->proxy != new->proxy)
803                         __proxy_share(old, new);
804                 else
805                         __aa_proxy_redirect(old, new);
806                 res = __label_replace(old, new);
807                 write_unlock_irqrestore(&labels_set(old)->lock, flags);
808         } else {
809                 struct aa_label *l;
810                 struct aa_labelset *ls = labels_set(old);
811
812                 write_lock_irqsave(&ls->lock, flags);
813                 res = __label_remove(old, new);
814                 if (labels_ns(old) != labels_ns(new)) {
815                         write_unlock_irqrestore(&ls->lock, flags);
816                         ls = labels_set(new);
817                         write_lock_irqsave(&ls->lock, flags);
818                 }
819                 l = __label_insert(ls, new, true);
820                 res = (l == new);
821                 write_unlock_irqrestore(&ls->lock, flags);
822                 aa_put_label(l);
823         }
824
825         return res;
826 }
827
828 /**
829  * vec_find - find label @l in label set
830  * @vec: array of profiles to find equiv label for (NOT NULL)
831  * @n: length of @vec
832  *
833  * Returns: refcounted label if @vec equiv is in tree
834  *     else NULL if @vec equiv is not in tree
835  */
836 static struct aa_label *vec_find(struct aa_profile **vec, int n)
837 {
838         struct aa_labelset *ls;
839         struct aa_label *label;
840         unsigned long flags;
841
842         AA_BUG(!vec);
843         AA_BUG(!*vec);
844         AA_BUG(n <= 0);
845
846         ls = vec_labelset(vec, n);
847         read_lock_irqsave(&ls->lock, flags);
848         label = __vec_find(vec, n);
849         read_unlock_irqrestore(&ls->lock, flags);
850
851         return label;
852 }
853
854 /* requires sort and merge done first */
855 static struct aa_label *vec_create_and_insert_label(struct aa_profile **vec,
856                                                     int len, gfp_t gfp)
857 {
858         struct aa_label *label = NULL;
859         struct aa_labelset *ls;
860         unsigned long flags;
861         struct aa_label *new;
862         int i;
863
864         AA_BUG(!vec);
865
866         if (len == 1)
867                 return aa_get_label(&vec[0]->label);
868
869         ls = labels_set(&vec[len - 1]->label);
870
871         /* TODO: enable when read side is lockless
872          * check if label exists before taking locks
873          */
874         new = aa_label_alloc(len, NULL, gfp);
875         if (!new)
876                 return NULL;
877
878         for (i = 0; i < len; i++)
879                 new->vec[i] = aa_get_profile(vec[i]);
880
881         write_lock_irqsave(&ls->lock, flags);
882         label = __label_insert(ls, new, false);
883         write_unlock_irqrestore(&ls->lock, flags);
884         label_free_or_put_new(label, new);
885
886         return label;
887 }
888
889 struct aa_label *aa_vec_find_or_create_label(struct aa_profile **vec, int len,
890                                              gfp_t gfp)
891 {
892         struct aa_label *label = vec_find(vec, len);
893
894         if (label)
895                 return label;
896
897         return vec_create_and_insert_label(vec, len, gfp);
898 }
899
900 /**
901  * aa_label_find - find label @label in label set
902  * @label: label to find (NOT NULL)
903  *
904  * Requires: caller to hold a valid ref on l
905  *
906  * Returns: refcounted @label if @label is in tree
907  *          refcounted label that is equiv to @label in tree
908  *     else NULL if @label or equiv is not in tree
909  */
910 struct aa_label *aa_label_find(struct aa_label *label)
911 {
912         AA_BUG(!label);
913
914         return vec_find(label->vec, label->size);
915 }
916
917
918 /**
919  * aa_label_insert - insert label @label into @ls or return existing label
920  * @ls - labelset to insert @label into
921  * @label - label to insert
922  *
923  * Requires: caller to hold a valid ref on @label
924  *
925  * Returns: ref counted @label if successful in inserting @label
926  *     else ref counted equivalent label that is already in the set
927  */
928 struct aa_label *aa_label_insert(struct aa_labelset *ls, struct aa_label *label)
929 {
930         struct aa_label *l;
931         unsigned long flags;
932
933         AA_BUG(!ls);
934         AA_BUG(!label);
935
936         /* check if label exists before taking lock */
937         if (!label_is_stale(label)) {
938                 read_lock_irqsave(&ls->lock, flags);
939                 l = __label_find(label);
940                 read_unlock_irqrestore(&ls->lock, flags);
941                 if (l)
942                         return l;
943         }
944
945         write_lock_irqsave(&ls->lock, flags);
946         l = __label_insert(ls, label, false);
947         write_unlock_irqrestore(&ls->lock, flags);
948
949         return l;
950 }
951
952
953 /**
954  * aa_label_next_in_merge - find the next profile when merging @a and @b
955  * @I: label iterator
956  * @a: label to merge
957  * @b: label to merge
958  *
959  * Returns: next profile
960  *     else null if no more profiles
961  */
962 struct aa_profile *aa_label_next_in_merge(struct label_it *I,
963                                           struct aa_label *a,
964                                           struct aa_label *b)
965 {
966         AA_BUG(!a);
967         AA_BUG(!b);
968         AA_BUG(!I);
969         AA_BUG(I->i < 0);
970         AA_BUG(I->i > a->size);
971         AA_BUG(I->j < 0);
972         AA_BUG(I->j > b->size);
973
974         if (I->i < a->size) {
975                 if (I->j < b->size) {
976                         int res = profile_cmp(a->vec[I->i], b->vec[I->j]);
977
978                         if (res > 0)
979                                 return b->vec[(I->j)++];
980                         if (res == 0)
981                                 (I->j)++;
982                 }
983
984                 return a->vec[(I->i)++];
985         }
986
987         if (I->j < b->size)
988                 return b->vec[(I->j)++];
989
990         return NULL;
991 }
992
993 /**
994  * label_merge_cmp - cmp of @a merging with @b against @z for set ordering
995  * @a: label to merge then compare (NOT NULL)
996  * @b: label to merge then compare (NOT NULL)
997  * @z: label to compare merge against (NOT NULL)
998  *
999  * Assumes: using the most recent versions of @a, @b, and @z
1000  *
1001  * Returns: <0  if a < b
1002  *          ==0 if a == b
1003  *          >0  if a > b
1004  */
1005 static int label_merge_cmp(struct aa_label *a, struct aa_label *b,
1006                            struct aa_label *z)
1007 {
1008         struct aa_profile *p = NULL;
1009         struct label_it i = { };
1010         int k;
1011
1012         AA_BUG(!a);
1013         AA_BUG(!b);
1014         AA_BUG(!z);
1015
1016         for (k = 0;
1017              k < z->size && (p = aa_label_next_in_merge(&i, a, b));
1018              k++) {
1019                 int res = profile_cmp(p, z->vec[k]);
1020
1021                 if (res != 0)
1022                         return res;
1023         }
1024
1025         if (p)
1026                 return 1;
1027         else if (k < z->size)
1028                 return -1;
1029         return 0;
1030 }
1031
1032 /**
1033  * label_merge_insert - create a new label by merging @a and @b
1034  * @new: preallocated label to merge into (NOT NULL)
1035  * @a: label to merge with @b  (NOT NULL)
1036  * @b: label to merge with @a  (NOT NULL)
1037  *
1038  * Requires: preallocated proxy
1039  *
1040  * Returns: ref counted label either @new if merge is unique
1041  *          @a if @b is a subset of @a
1042  *          @b if @a is a subset of @b
1043  *
1044  * NOTE: will not use @new if the merge results in @new == @a or @b
1045  *
1046  *       Must be used within labelset write lock to avoid racing with
1047  *       setting labels stale.
1048  */
1049 static struct aa_label *label_merge_insert(struct aa_label *new,
1050                                            struct aa_label *a,
1051                                            struct aa_label *b)
1052 {
1053         struct aa_label *label;
1054         struct aa_labelset *ls;
1055         struct aa_profile *next;
1056         struct label_it i;
1057         unsigned long flags;
1058         int k = 0, invcount = 0;
1059         bool stale = false;
1060
1061         AA_BUG(!a);
1062         AA_BUG(a->size < 0);
1063         AA_BUG(!b);
1064         AA_BUG(b->size < 0);
1065         AA_BUG(!new);
1066         AA_BUG(new->size < a->size + b->size);
1067
1068         label_for_each_in_merge(i, a, b, next) {
1069                 AA_BUG(!next);
1070                 if (profile_is_stale(next)) {
1071                         new->vec[k] = aa_get_newest_profile(next);
1072                         AA_BUG(!new->vec[k]->label.proxy);
1073                         AA_BUG(!new->vec[k]->label.proxy->label);
1074                         if (next->label.proxy != new->vec[k]->label.proxy)
1075                                 invcount++;
1076                         k++;
1077                         stale = true;
1078                 } else
1079                         new->vec[k++] = aa_get_profile(next);
1080         }
1081         /* set to actual size which is <= allocated len */
1082         new->size = k;
1083         new->vec[k] = NULL;
1084
1085         if (invcount) {
1086                 new->size -= aa_vec_unique(&new->vec[0], new->size,
1087                                            VEC_FLAG_TERMINATE);
1088                 /* TODO: deal with reference labels */
1089                 if (new->size == 1) {
1090                         label = aa_get_label(&new->vec[0]->label);
1091                         return label;
1092                 }
1093         } else if (!stale) {
1094                 /*
1095                  * merge could be same as a || b, note: it is not possible
1096                  * for new->size == a->size == b->size unless a == b
1097                  */
1098                 if (k == a->size)
1099                         return aa_get_label(a);
1100                 else if (k == b->size)
1101                         return aa_get_label(b);
1102         }
1103         new->flags |= accum_vec_flags(new->vec, new->size);
1104         ls = labels_set(new);
1105         write_lock_irqsave(&ls->lock, flags);
1106         label = __label_insert(labels_set(new), new, false);
1107         write_unlock_irqrestore(&ls->lock, flags);
1108
1109         return label;
1110 }
1111
1112 /**
1113  * labelset_of_merge - find which labelset a merged label should be inserted
1114  * @a: label to merge and insert
1115  * @b: label to merge and insert
1116  *
1117  * Returns: labelset that the merged label should be inserted into
1118  */
1119 static struct aa_labelset *labelset_of_merge(struct aa_label *a,
1120                                              struct aa_label *b)
1121 {
1122         struct aa_ns *nsa = labels_ns(a);
1123         struct aa_ns *nsb = labels_ns(b);
1124
1125         if (ns_cmp(nsa, nsb) <= 0)
1126                 return &nsa->labels;
1127         return &nsb->labels;
1128 }
1129
1130 /**
1131  * __label_find_merge - find label that is equiv to merge of @a and @b
1132  * @ls: set of labels to search (NOT NULL)
1133  * @a: label to merge with @b  (NOT NULL)
1134  * @b: label to merge with @a  (NOT NULL)
1135  *
1136  * Requires: ls->lock read_lock held
1137  *
1138  * Returns: ref counted label that is equiv to merge of @a and @b
1139  *     else NULL if merge of @a and @b is not in set
1140  */
1141 static struct aa_label *__label_find_merge(struct aa_labelset *ls,
1142                                            struct aa_label *a,
1143                                            struct aa_label *b)
1144 {
1145         struct rb_node *node;
1146
1147         AA_BUG(!ls);
1148         AA_BUG(!a);
1149         AA_BUG(!b);
1150
1151         if (a == b)
1152                 return __label_find(a);
1153
1154         node  = ls->root.rb_node;
1155         while (node) {
1156                 struct aa_label *this = container_of(node, struct aa_label,
1157                                                      node);
1158                 int result = label_merge_cmp(a, b, this);
1159
1160                 if (result < 0)
1161                         node = node->rb_left;
1162                 else if (result > 0)
1163                         node = node->rb_right;
1164                 else
1165                         return __aa_get_label(this);
1166         }
1167
1168         return NULL;
1169 }
1170
1171
1172 /**
1173  * aa_label_find_merge - find label that is equiv to merge of @a and @b
1174  * @a: label to merge with @b  (NOT NULL)
1175  * @b: label to merge with @a  (NOT NULL)
1176  *
1177  * Requires: labels be fully constructed with a valid ns
1178  *
1179  * Returns: ref counted label that is equiv to merge of @a and @b
1180  *     else NULL if merge of @a and @b is not in set
1181  */
1182 struct aa_label *aa_label_find_merge(struct aa_label *a, struct aa_label *b)
1183 {
1184         struct aa_labelset *ls;
1185         struct aa_label *label, *ar = NULL, *br = NULL;
1186         unsigned long flags;
1187
1188         AA_BUG(!a);
1189         AA_BUG(!b);
1190
1191         if (label_is_stale(a))
1192                 a = ar = aa_get_newest_label(a);
1193         if (label_is_stale(b))
1194                 b = br = aa_get_newest_label(b);
1195         ls = labelset_of_merge(a, b);
1196         read_lock_irqsave(&ls->lock, flags);
1197         label = __label_find_merge(ls, a, b);
1198         read_unlock_irqrestore(&ls->lock, flags);
1199         aa_put_label(ar);
1200         aa_put_label(br);
1201
1202         return label;
1203 }
1204
1205 /**
1206  * aa_label_merge - attempt to insert new merged label of @a and @b
1207  * @ls: set of labels to insert label into (NOT NULL)
1208  * @a: label to merge with @b  (NOT NULL)
1209  * @b: label to merge with @a  (NOT NULL)
1210  * @gfp: memory allocation type
1211  *
1212  * Requires: caller to hold valid refs on @a and @b
1213  *           labels be fully constructed with a valid ns
1214  *
1215  * Returns: ref counted new label if successful in inserting merge of a & b
1216  *     else ref counted equivalent label that is already in the set.
1217  *     else NULL if could not create label (-ENOMEM)
1218  */
1219 struct aa_label *aa_label_merge(struct aa_label *a, struct aa_label *b,
1220                                 gfp_t gfp)
1221 {
1222         struct aa_label *label = NULL;
1223
1224         AA_BUG(!a);
1225         AA_BUG(!b);
1226
1227         if (a == b)
1228                 return aa_get_newest_label(a);
1229
1230         /* TODO: enable when read side is lockless
1231          * check if label exists before taking locks
1232         if (!label_is_stale(a) && !label_is_stale(b))
1233                 label = aa_label_find_merge(a, b);
1234         */
1235
1236         if (!label) {
1237                 struct aa_label *new;
1238
1239                 a = aa_get_newest_label(a);
1240                 b = aa_get_newest_label(b);
1241
1242                 /* could use label_merge_len(a, b), but requires double
1243                  * comparison for small savings
1244                  */
1245                 new = aa_label_alloc(a->size + b->size, NULL, gfp);
1246                 if (!new)
1247                         goto out;
1248
1249                 label = label_merge_insert(new, a, b);
1250                 label_free_or_put_new(label, new);
1251 out:
1252                 aa_put_label(a);
1253                 aa_put_label(b);
1254         }
1255
1256         return label;
1257 }
1258
1259 static inline bool label_is_visible(struct aa_profile *profile,
1260                                     struct aa_label *label)
1261 {
1262         return aa_ns_visible(profile->ns, labels_ns(label), true);
1263 }
1264
1265 /* match a profile and its associated ns component if needed
1266  * Assumes visibility test has already been done.
1267  * If a subns profile is not to be matched should be prescreened with
1268  * visibility test.
1269  */
1270 static inline unsigned int match_component(struct aa_profile *profile,
1271                                            struct aa_profile *tp,
1272                                            unsigned int state)
1273 {
1274         const char *ns_name;
1275
1276         if (profile->ns == tp->ns)
1277                 return aa_dfa_match(profile->policy.dfa, state, tp->base.hname);
1278
1279         /* try matching with namespace name and then profile */
1280         ns_name = aa_ns_name(profile->ns, tp->ns, true);
1281         state = aa_dfa_match_len(profile->policy.dfa, state, ":", 1);
1282         state = aa_dfa_match(profile->policy.dfa, state, ns_name);
1283         state = aa_dfa_match_len(profile->policy.dfa, state, ":", 1);
1284         return aa_dfa_match(profile->policy.dfa, state, tp->base.hname);
1285 }
1286
1287 /**
1288  * label_compound_match - find perms for full compound label
1289  * @profile: profile to find perms for
1290  * @label: label to check access permissions for
1291  * @start: state to start match in
1292  * @subns: whether to do permission checks on components in a subns
1293  * @request: permissions to request
1294  * @perms: perms struct to set
1295  *
1296  * Returns: 0 on success else ERROR
1297  *
1298  * For the label A//&B//&C this does the perm match for A//&B//&C
1299  * @perms should be preinitialized with allperms OR a previous permission
1300  *        check to be stacked.
1301  */
1302 static int label_compound_match(struct aa_profile *profile,
1303                                 struct aa_label *label,
1304                                 unsigned int state, bool subns, u32 request,
1305                                 struct aa_perms *perms)
1306 {
1307         struct aa_profile *tp;
1308         struct label_it i;
1309
1310         /* find first subcomponent that is visible */
1311         label_for_each(i, label, tp) {
1312                 if (!aa_ns_visible(profile->ns, tp->ns, subns))
1313                         continue;
1314                 state = match_component(profile, tp, state);
1315                 if (!state)
1316                         goto fail;
1317                 goto next;
1318         }
1319
1320         /* no component visible */
1321         *perms = allperms;
1322         return 0;
1323
1324 next:
1325         label_for_each_cont(i, label, tp) {
1326                 if (!aa_ns_visible(profile->ns, tp->ns, subns))
1327                         continue;
1328                 state = aa_dfa_match(profile->policy.dfa, state, "//&");
1329                 state = match_component(profile, tp, state);
1330                 if (!state)
1331                         goto fail;
1332         }
1333         aa_compute_perms(profile->policy.dfa, state, perms);
1334         aa_apply_modes_to_perms(profile, perms);
1335         if ((perms->allow & request) != request)
1336                 return -EACCES;
1337
1338         return 0;
1339
1340 fail:
1341         *perms = nullperms;
1342         return state;
1343 }
1344
1345 /**
1346  * label_components_match - find perms for all subcomponents of a label
1347  * @profile: profile to find perms for
1348  * @label: label to check access permissions for
1349  * @start: state to start match in
1350  * @subns: whether to do permission checks on components in a subns
1351  * @request: permissions to request
1352  * @perms: an initialized perms struct to add accumulation to
1353  *
1354  * Returns: 0 on success else ERROR
1355  *
1356  * For the label A//&B//&C this does the perm match for each of A and B and C
1357  * @perms should be preinitialized with allperms OR a previous permission
1358  *        check to be stacked.
1359  */
1360 static int label_components_match(struct aa_profile *profile,
1361                                   struct aa_label *label, unsigned int start,
1362                                   bool subns, u32 request,
1363                                   struct aa_perms *perms)
1364 {
1365         struct aa_profile *tp;
1366         struct label_it i;
1367         struct aa_perms tmp;
1368         unsigned int state = 0;
1369
1370         /* find first subcomponent to test */
1371         label_for_each(i, label, tp) {
1372                 if (!aa_ns_visible(profile->ns, tp->ns, subns))
1373                         continue;
1374                 state = match_component(profile, tp, start);
1375                 if (!state)
1376                         goto fail;
1377                 goto next;
1378         }
1379
1380         /* no subcomponents visible - no change in perms */
1381         return 0;
1382
1383 next:
1384         aa_compute_perms(profile->policy.dfa, state, &tmp);
1385         aa_apply_modes_to_perms(profile, &tmp);
1386         aa_perms_accum(perms, &tmp);
1387         label_for_each_cont(i, label, tp) {
1388                 if (!aa_ns_visible(profile->ns, tp->ns, subns))
1389                         continue;
1390                 state = match_component(profile, tp, start);
1391                 if (!state)
1392                         goto fail;
1393                 aa_compute_perms(profile->policy.dfa, state, &tmp);
1394                 aa_apply_modes_to_perms(profile, &tmp);
1395                 aa_perms_accum(perms, &tmp);
1396         }
1397
1398         if ((perms->allow & request) != request)
1399                 return -EACCES;
1400
1401         return 0;
1402
1403 fail:
1404         *perms = nullperms;
1405         return -EACCES;
1406 }
1407
1408 /**
1409  * aa_label_match - do a multi-component label match
1410  * @profile: profile to match against (NOT NULL)
1411  * @label: label to match (NOT NULL)
1412  * @state: state to start in
1413  * @subns: whether to match subns components
1414  * @request: permission request
1415  * @perms: Returns computed perms (NOT NULL)
1416  *
1417  * Returns: the state the match finished in, may be the none matching state
1418  */
1419 int aa_label_match(struct aa_profile *profile, struct aa_label *label,
1420                    unsigned int state, bool subns, u32 request,
1421                    struct aa_perms *perms)
1422 {
1423         int error = label_compound_match(profile, label, state, subns, request,
1424                                          perms);
1425         if (!error)
1426                 return error;
1427
1428         *perms = allperms;
1429         return label_components_match(profile, label, state, subns, request,
1430                                       perms);
1431 }
1432
1433
1434 /**
1435  * aa_update_label_name - update a label to have a stored name
1436  * @ns: ns being viewed from (NOT NULL)
1437  * @label: label to update (NOT NULL)
1438  * @gfp: type of memory allocation
1439  *
1440  * Requires: labels_set(label) not locked in caller
1441  *
1442  * note: only updates the label name if it does not have a name already
1443  *       and if it is in the labelset
1444  */
1445 bool aa_update_label_name(struct aa_ns *ns, struct aa_label *label, gfp_t gfp)
1446 {
1447         struct aa_labelset *ls;
1448         unsigned long flags;
1449         char __counted *name;
1450         bool res = false;
1451
1452         AA_BUG(!ns);
1453         AA_BUG(!label);
1454
1455         if (label->hname || labels_ns(label) != ns)
1456                 return res;
1457
1458         if (aa_label_acntsxprint(&name, ns, label, FLAGS_NONE, gfp) < 0)
1459                 return res;
1460
1461         ls = labels_set(label);
1462         write_lock_irqsave(&ls->lock, flags);
1463         if (!label->hname && label->flags & FLAG_IN_TREE) {
1464                 label->hname = name;
1465                 res = true;
1466         } else
1467                 aa_put_str(name);
1468         write_unlock_irqrestore(&ls->lock, flags);
1469
1470         return res;
1471 }
1472
1473 /*
1474  * cached label name is present and visible
1475  * @label->hname only exists if label is namespace hierachical
1476  */
1477 static inline bool use_label_hname(struct aa_ns *ns, struct aa_label *label,
1478                                    int flags)
1479 {
1480         if (label->hname && (!ns || labels_ns(label) == ns) &&
1481             !(flags & ~FLAG_SHOW_MODE))
1482                 return true;
1483
1484         return false;
1485 }
1486
1487 /* helper macro for snprint routines */
1488 #define update_for_len(total, len, size, str)   \
1489 do {                                    \
1490         size_t ulen = len;              \
1491                                         \
1492         AA_BUG(len < 0);                \
1493         total += ulen;                  \
1494         ulen = min(ulen, size);         \
1495         size -= ulen;                   \
1496         str += ulen;                    \
1497 } while (0)
1498
1499 /**
1500  * aa_profile_snxprint - print a profile name to a buffer
1501  * @str: buffer to write to. (MAY BE NULL if @size == 0)
1502  * @size: size of buffer
1503  * @view: namespace profile is being viewed from
1504  * @profile: profile to view (NOT NULL)
1505  * @flags: whether to include the mode string
1506  * @prev_ns: last ns printed when used in compound print
1507  *
1508  * Returns: size of name written or would be written if larger than
1509  *          available buffer
1510  *
1511  * Note: will not print anything if the profile is not visible
1512  */
1513 static int aa_profile_snxprint(char *str, size_t size, struct aa_ns *view,
1514                                struct aa_profile *profile, int flags,
1515                                struct aa_ns **prev_ns)
1516 {
1517         const char *ns_name = NULL;
1518
1519         AA_BUG(!str && size != 0);
1520         AA_BUG(!profile);
1521
1522         if (!view)
1523                 view = profiles_ns(profile);
1524
1525         if (view != profile->ns &&
1526             (!prev_ns || (*prev_ns != profile->ns))) {
1527                 if (prev_ns)
1528                         *prev_ns = profile->ns;
1529                 ns_name = aa_ns_name(view, profile->ns,
1530                                      flags & FLAG_VIEW_SUBNS);
1531                 if (ns_name == aa_hidden_ns_name) {
1532                         if (flags & FLAG_HIDDEN_UNCONFINED)
1533                                 return snprintf(str, size, "%s", "unconfined");
1534                         return snprintf(str, size, "%s", ns_name);
1535                 }
1536         }
1537
1538         if ((flags & FLAG_SHOW_MODE) && profile != profile->ns->unconfined) {
1539                 const char *modestr = aa_profile_mode_names[profile->mode];
1540
1541                 if (ns_name)
1542                         return snprintf(str, size, ":%s:%s (%s)", ns_name,
1543                                         profile->base.hname, modestr);
1544                 return snprintf(str, size, "%s (%s)", profile->base.hname,
1545                                 modestr);
1546         }
1547
1548         if (ns_name)
1549                 return snprintf(str, size, ":%s:%s", ns_name,
1550                                 profile->base.hname);
1551         return snprintf(str, size, "%s", profile->base.hname);
1552 }
1553
1554 static const char *label_modename(struct aa_ns *ns, struct aa_label *label,
1555                                   int flags)
1556 {
1557         struct aa_profile *profile;
1558         struct label_it i;
1559         int mode = -1, count = 0;
1560
1561         label_for_each(i, label, profile) {
1562                 if (aa_ns_visible(ns, profile->ns, flags & FLAG_VIEW_SUBNS)) {
1563                         count++;
1564                         if (profile == profile->ns->unconfined)
1565                                 /* special case unconfined so stacks with
1566                                  * unconfined don't report as mixed. ie.
1567                                  * profile_foo//&:ns1:unconfined (mixed)
1568                                  */
1569                                 continue;
1570                         if (mode == -1)
1571                                 mode = profile->mode;
1572                         else if (mode != profile->mode)
1573                                 return "mixed";
1574                 }
1575         }
1576
1577         if (count == 0)
1578                 return "-";
1579         if (mode == -1)
1580                 /* everything was unconfined */
1581                 mode = APPARMOR_UNCONFINED;
1582
1583         return aa_profile_mode_names[mode];
1584 }
1585
1586 /* if any visible label is not unconfined the display_mode returns true */
1587 static inline bool display_mode(struct aa_ns *ns, struct aa_label *label,
1588                                 int flags)
1589 {
1590         if ((flags & FLAG_SHOW_MODE)) {
1591                 struct aa_profile *profile;
1592                 struct label_it i;
1593
1594                 label_for_each(i, label, profile) {
1595                         if (aa_ns_visible(ns, profile->ns,
1596                                           flags & FLAG_VIEW_SUBNS) &&
1597                             profile != profile->ns->unconfined)
1598                                 return true;
1599                 }
1600                 /* only ns->unconfined in set of profiles in ns */
1601                 return false;
1602         }
1603
1604         return false;
1605 }
1606
1607 /**
1608  * aa_label_snxprint - print a label name to a string buffer
1609  * @str: buffer to write to. (MAY BE NULL if @size == 0)
1610  * @size: size of buffer
1611  * @ns: namespace profile is being viewed from
1612  * @label: label to view (NOT NULL)
1613  * @flags: whether to include the mode string
1614  *
1615  * Returns: size of name written or would be written if larger than
1616  *          available buffer
1617  *
1618  * Note: labels do not have to be strictly hierarchical to the ns as
1619  *       objects may be shared across different namespaces and thus
1620  *       pickup labeling from each ns.  If a particular part of the
1621  *       label is not visible it will just be excluded.  And if none
1622  *       of the label is visible "---" will be used.
1623  */
1624 int aa_label_snxprint(char *str, size_t size, struct aa_ns *ns,
1625                       struct aa_label *label, int flags)
1626 {
1627         struct aa_profile *profile;
1628         struct aa_ns *prev_ns = NULL;
1629         struct label_it i;
1630         int count = 0, total = 0;
1631         ssize_t len;
1632
1633         AA_BUG(!str && size != 0);
1634         AA_BUG(!label);
1635
1636         if (AA_DEBUG_LABEL && (flags & FLAG_ABS_ROOT)) {
1637                 ns = root_ns;
1638                 len = snprintf(str, size, "_");
1639                 update_for_len(total, len, size, str);
1640         } else if (!ns) {
1641                 ns = labels_ns(label);
1642         }
1643
1644         label_for_each(i, label, profile) {
1645                 if (aa_ns_visible(ns, profile->ns, flags & FLAG_VIEW_SUBNS)) {
1646                         if (count > 0) {
1647                                 len = snprintf(str, size, "//&");
1648                                 update_for_len(total, len, size, str);
1649                         }
1650                         len = aa_profile_snxprint(str, size, ns, profile,
1651                                                   flags & FLAG_VIEW_SUBNS,
1652                                                   &prev_ns);
1653                         update_for_len(total, len, size, str);
1654                         count++;
1655                 }
1656         }
1657
1658         if (count == 0) {
1659                 if (flags & FLAG_HIDDEN_UNCONFINED)
1660                         return snprintf(str, size, "%s", "unconfined");
1661                 return snprintf(str, size, "%s", aa_hidden_ns_name);
1662         }
1663
1664         /* count == 1 && ... is for backwards compat where the mode
1665          * is not displayed for 'unconfined' in the current ns
1666          */
1667         if (display_mode(ns, label, flags)) {
1668                 len = snprintf(str, size, " (%s)",
1669                                label_modename(ns, label, flags));
1670                 update_for_len(total, len, size, str);
1671         }
1672
1673         return total;
1674 }
1675 #undef update_for_len
1676
1677 /**
1678  * aa_label_asxprint - allocate a string buffer and print label into it
1679  * @strp: Returns - the allocated buffer with the label name. (NOT NULL)
1680  * @ns: namespace profile is being viewed from
1681  * @label: label to view (NOT NULL)
1682  * @flags: flags controlling what label info is printed
1683  * @gfp: kernel memory allocation type
1684  *
1685  * Returns: size of name written or would be written if larger than
1686  *          available buffer
1687  */
1688 int aa_label_asxprint(char **strp, struct aa_ns *ns, struct aa_label *label,
1689                       int flags, gfp_t gfp)
1690 {
1691         int size;
1692
1693         AA_BUG(!strp);
1694         AA_BUG(!label);
1695
1696         size = aa_label_snxprint(NULL, 0, ns, label, flags);
1697         if (size < 0)
1698                 return size;
1699
1700         *strp = kmalloc(size + 1, gfp);
1701         if (!*strp)
1702                 return -ENOMEM;
1703         return aa_label_snxprint(*strp, size + 1, ns, label, flags);
1704 }
1705
1706 /**
1707  * aa_label_acntsxprint - allocate a __counted string buffer and print label
1708  * @strp: buffer to write to.
1709  * @ns: namespace profile is being viewed from
1710  * @label: label to view (NOT NULL)
1711  * @flags: flags controlling what label info is printed
1712  * @gfp: kernel memory allocation type
1713  *
1714  * Returns: size of name written or would be written if larger than
1715  *          available buffer
1716  */
1717 int aa_label_acntsxprint(char __counted **strp, struct aa_ns *ns,
1718                          struct aa_label *label, int flags, gfp_t gfp)
1719 {
1720         int size;
1721
1722         AA_BUG(!strp);
1723         AA_BUG(!label);
1724
1725         size = aa_label_snxprint(NULL, 0, ns, label, flags);
1726         if (size < 0)
1727                 return size;
1728
1729         *strp = aa_str_alloc(size + 1, gfp);
1730         if (!*strp)
1731                 return -ENOMEM;
1732         return aa_label_snxprint(*strp, size + 1, ns, label, flags);
1733 }
1734
1735
1736 void aa_label_xaudit(struct audit_buffer *ab, struct aa_ns *ns,
1737                      struct aa_label *label, int flags, gfp_t gfp)
1738 {
1739         const char *str;
1740         char *name = NULL;
1741         int len;
1742
1743         AA_BUG(!ab);
1744         AA_BUG(!label);
1745
1746         if (!use_label_hname(ns, label, flags) ||
1747             display_mode(ns, label, flags)) {
1748                 len  = aa_label_asxprint(&name, ns, label, flags, gfp);
1749                 if (len < 0) {
1750                         AA_DEBUG("label print error");
1751                         return;
1752                 }
1753                 str = name;
1754         } else {
1755                 str = (char *) label->hname;
1756                 len = strlen(str);
1757         }
1758         if (audit_string_contains_control(str, len))
1759                 audit_log_n_hex(ab, str, len);
1760         else
1761                 audit_log_n_string(ab, str, len);
1762
1763         kfree(name);
1764 }
1765
1766 void aa_label_seq_xprint(struct seq_file *f, struct aa_ns *ns,
1767                          struct aa_label *label, int flags, gfp_t gfp)
1768 {
1769         AA_BUG(!f);
1770         AA_BUG(!label);
1771
1772         if (!use_label_hname(ns, label, flags)) {
1773                 char *str;
1774                 int len;
1775
1776                 len = aa_label_asxprint(&str, ns, label, flags, gfp);
1777                 if (len < 0) {
1778                         AA_DEBUG("label print error");
1779                         return;
1780                 }
1781                 seq_puts(f, str);
1782                 kfree(str);
1783         } else if (display_mode(ns, label, flags))
1784                 seq_printf(f, "%s (%s)", label->hname,
1785                            label_modename(ns, label, flags));
1786         else
1787                 seq_puts(f, label->hname);
1788 }
1789
1790 void aa_label_xprintk(struct aa_ns *ns, struct aa_label *label, int flags,
1791                       gfp_t gfp)
1792 {
1793         AA_BUG(!label);
1794
1795         if (!use_label_hname(ns, label, flags)) {
1796                 char *str;
1797                 int len;
1798
1799                 len = aa_label_asxprint(&str, ns, label, flags, gfp);
1800                 if (len < 0) {
1801                         AA_DEBUG("label print error");
1802                         return;
1803                 }
1804                 pr_info("%s", str);
1805                 kfree(str);
1806         } else if (display_mode(ns, label, flags))
1807                 pr_info("%s (%s)", label->hname,
1808                        label_modename(ns, label, flags));
1809         else
1810                 pr_info("%s", label->hname);
1811 }
1812
1813 void aa_label_audit(struct audit_buffer *ab, struct aa_label *label, gfp_t gfp)
1814 {
1815         struct aa_ns *ns = aa_get_current_ns();
1816
1817         aa_label_xaudit(ab, ns, label, FLAG_VIEW_SUBNS, gfp);
1818         aa_put_ns(ns);
1819 }
1820
1821 void aa_label_seq_print(struct seq_file *f, struct aa_label *label, gfp_t gfp)
1822 {
1823         struct aa_ns *ns = aa_get_current_ns();
1824
1825         aa_label_seq_xprint(f, ns, label, FLAG_VIEW_SUBNS, gfp);
1826         aa_put_ns(ns);
1827 }
1828
1829 void aa_label_printk(struct aa_label *label, gfp_t gfp)
1830 {
1831         struct aa_ns *ns = aa_get_current_ns();
1832
1833         aa_label_xprintk(ns, label, FLAG_VIEW_SUBNS, gfp);
1834         aa_put_ns(ns);
1835 }
1836
1837 static int label_count_strn_entries(const char *str, size_t n)
1838 {
1839         const char *end = str + n;
1840         const char *split;
1841         int count = 1;
1842
1843         AA_BUG(!str);
1844
1845         for (split = aa_label_strn_split(str, end - str);
1846              split;
1847              split = aa_label_strn_split(str, end - str)) {
1848                 count++;
1849                 str = split + 3;
1850         }
1851
1852         return count;
1853 }
1854
1855 /*
1856  * ensure stacks with components like
1857  *   :ns:A//&B
1858  * have :ns: applied to both 'A' and 'B' by making the lookup relative
1859  * to the base if the lookup specifies an ns, else making the stacked lookup
1860  * relative to the last embedded ns in the string.
1861  */
1862 static struct aa_profile *fqlookupn_profile(struct aa_label *base,
1863                                             struct aa_label *currentbase,
1864                                             const char *str, size_t n)
1865 {
1866         const char *first = skipn_spaces(str, n);
1867
1868         if (first && *first == ':')
1869                 return aa_fqlookupn_profile(base, str, n);
1870
1871         return aa_fqlookupn_profile(currentbase, str, n);
1872 }
1873
1874 /**
1875  * aa_label_strn_parse - parse, validate and convert a text string to a label
1876  * @base: base label to use for lookups (NOT NULL)
1877  * @str: null terminated text string (NOT NULL)
1878  * @n: length of str to parse, will stop at \0 if encountered before n
1879  * @gfp: allocation type
1880  * @create: true if should create compound labels if they don't exist
1881  * @force_stack: true if should stack even if no leading &
1882  *
1883  * Returns: the matching refcounted label if present
1884  *     else ERRPTR
1885  */
1886 struct aa_label *aa_label_strn_parse(struct aa_label *base, const char *str,
1887                                      size_t n, gfp_t gfp, bool create,
1888                                      bool force_stack)
1889 {
1890         DEFINE_VEC(profile, vec);
1891         struct aa_label *label, *currbase = base;
1892         int i, len, stack = 0, error;
1893         const char *end = str + n;
1894         const char *split;
1895
1896         AA_BUG(!base);
1897         AA_BUG(!str);
1898
1899         str = skipn_spaces(str, n);
1900         if (str == NULL || (AA_DEBUG_LABEL && *str == '_' &&
1901                             base != &root_ns->unconfined->label))
1902                 return ERR_PTR(-EINVAL);
1903
1904         len = label_count_strn_entries(str, end - str);
1905         if (*str == '&' || force_stack) {
1906                 /* stack on top of base */
1907                 stack = base->size;
1908                 len += stack;
1909                 if (*str == '&')
1910                         str++;
1911         }
1912
1913         error = vec_setup(profile, vec, len, gfp);
1914         if (error)
1915                 return ERR_PTR(error);
1916
1917         for (i = 0; i < stack; i++)
1918                 vec[i] = aa_get_profile(base->vec[i]);
1919
1920         for (split = aa_label_strn_split(str, end - str), i = stack;
1921              split && i < len; i++) {
1922                 vec[i] = fqlookupn_profile(base, currbase, str, split - str);
1923                 if (!vec[i])
1924                         goto fail;
1925                 /*
1926                  * if component specified a new ns it becomes the new base
1927                  * so that subsequent lookups are relative to it
1928                  */
1929                 if (vec[i]->ns != labels_ns(currbase))
1930                         currbase = &vec[i]->label;
1931                 str = split + 3;
1932                 split = aa_label_strn_split(str, end - str);
1933         }
1934         /* last element doesn't have a split */
1935         if (i < len) {
1936                 vec[i] = fqlookupn_profile(base, currbase, str, end - str);
1937                 if (!vec[i])
1938                         goto fail;
1939         }
1940         if (len == 1)
1941                 /* no need to free vec as len < LOCAL_VEC_ENTRIES */
1942                 return &vec[0]->label;
1943
1944         len -= aa_vec_unique(vec, len, VEC_FLAG_TERMINATE);
1945         /* TODO: deal with reference labels */
1946         if (len == 1) {
1947                 label = aa_get_label(&vec[0]->label);
1948                 goto out;
1949         }
1950
1951         if (create)
1952                 label = aa_vec_find_or_create_label(vec, len, gfp);
1953         else
1954                 label = vec_find(vec, len);
1955         if (!label)
1956                 goto fail;
1957
1958 out:
1959         /* use adjusted len from after vec_unique, not original */
1960         vec_cleanup(profile, vec, len);
1961         return label;
1962
1963 fail:
1964         label = ERR_PTR(-ENOENT);
1965         goto out;
1966 }
1967
1968 struct aa_label *aa_label_parse(struct aa_label *base, const char *str,
1969                                 gfp_t gfp, bool create, bool force_stack)
1970 {
1971         return aa_label_strn_parse(base, str, strlen(str), gfp, create,
1972                                    force_stack);
1973 }
1974
1975 /**
1976  * aa_labelset_destroy - remove all labels from the label set
1977  * @ls: label set to cleanup (NOT NULL)
1978  *
1979  * Labels that are removed from the set may still exist beyond the set
1980  * being destroyed depending on their reference counting
1981  */
1982 void aa_labelset_destroy(struct aa_labelset *ls)
1983 {
1984         struct rb_node *node;
1985         unsigned long flags;
1986
1987         AA_BUG(!ls);
1988
1989         write_lock_irqsave(&ls->lock, flags);
1990         for (node = rb_first(&ls->root); node; node = rb_first(&ls->root)) {
1991                 struct aa_label *this = rb_entry(node, struct aa_label, node);
1992
1993                 if (labels_ns(this) != root_ns)
1994                         __label_remove(this,
1995                                        ns_unconfined(labels_ns(this)->parent));
1996                 else
1997                         __label_remove(this, NULL);
1998         }
1999         write_unlock_irqrestore(&ls->lock, flags);
2000 }
2001
2002 /*
2003  * @ls: labelset to init (NOT NULL)
2004  */
2005 void aa_labelset_init(struct aa_labelset *ls)
2006 {
2007         AA_BUG(!ls);
2008
2009         rwlock_init(&ls->lock);
2010         ls->root = RB_ROOT;
2011 }
2012
2013 static struct aa_label *labelset_next_stale(struct aa_labelset *ls)
2014 {
2015         struct aa_label *label;
2016         struct rb_node *node;
2017         unsigned long flags;
2018
2019         AA_BUG(!ls);
2020
2021         read_lock_irqsave(&ls->lock, flags);
2022
2023         __labelset_for_each(ls, node) {
2024                 label = rb_entry(node, struct aa_label, node);
2025                 if ((label_is_stale(label) ||
2026                      vec_is_stale(label->vec, label->size)) &&
2027                     __aa_get_label(label))
2028                         goto out;
2029
2030         }
2031         label = NULL;
2032
2033 out:
2034         read_unlock_irqrestore(&ls->lock, flags);
2035
2036         return label;
2037 }
2038
2039 /**
2040  * __label_update - insert updated version of @label into labelset
2041  * @label - the label to update/replace
2042  *
2043  * Returns: new label that is up to date
2044  *     else NULL on failure
2045  *
2046  * Requires: @ns lock be held
2047  *
2048  * Note: worst case is the stale @label does not get updated and has
2049  *       to be updated at a later time.
2050  */
2051 static struct aa_label *__label_update(struct aa_label *label)
2052 {
2053         struct aa_label *new, *tmp;
2054         struct aa_labelset *ls;
2055         unsigned long flags;
2056         int i, invcount = 0;
2057
2058         AA_BUG(!label);
2059         AA_BUG(!mutex_is_locked(&labels_ns(label)->lock));
2060
2061         new = aa_label_alloc(label->size, label->proxy, GFP_KERNEL);
2062         if (!new)
2063                 return NULL;
2064
2065         /*
2066          * while holding the ns_lock will stop profile replacement, removal,
2067          * and label updates, label merging and removal can be occurring
2068          */
2069         ls = labels_set(label);
2070         write_lock_irqsave(&ls->lock, flags);
2071         for (i = 0; i < label->size; i++) {
2072                 AA_BUG(!label->vec[i]);
2073                 new->vec[i] = aa_get_newest_profile(label->vec[i]);
2074                 AA_BUG(!new->vec[i]);
2075                 AA_BUG(!new->vec[i]->label.proxy);
2076                 AA_BUG(!new->vec[i]->label.proxy->label);
2077                 if (new->vec[i]->label.proxy != label->vec[i]->label.proxy)
2078                         invcount++;
2079         }
2080
2081         /* updated stale label by being removed/renamed from labelset */
2082         if (invcount) {
2083                 new->size -= aa_vec_unique(&new->vec[0], new->size,
2084                                            VEC_FLAG_TERMINATE);
2085                 /* TODO: deal with reference labels */
2086                 if (new->size == 1) {
2087                         tmp = aa_get_label(&new->vec[0]->label);
2088                         AA_BUG(tmp == label);
2089                         goto remove;
2090                 }
2091                 if (labels_set(label) != labels_set(new)) {
2092                         write_unlock_irqrestore(&ls->lock, flags);
2093                         tmp = aa_label_insert(labels_set(new), new);
2094                         write_lock_irqsave(&ls->lock, flags);
2095                         goto remove;
2096                 }
2097         } else
2098                 AA_BUG(labels_ns(label) != labels_ns(new));
2099
2100         tmp = __label_insert(labels_set(label), new, true);
2101 remove:
2102         /* ensure label is removed, and redirected correctly */
2103         __label_remove(label, tmp);
2104         write_unlock_irqrestore(&ls->lock, flags);
2105         label_free_or_put_new(tmp, new);
2106
2107         return tmp;
2108 }
2109
2110 /**
2111  * __labelset_update - update labels in @ns
2112  * @ns: namespace to update labels in  (NOT NULL)
2113  *
2114  * Requires: @ns lock be held
2115  *
2116  * Walk the labelset ensuring that all labels are up to date and valid
2117  * Any label that has a stale component is marked stale and replaced and
2118  * by an updated version.
2119  *
2120  * If failures happen due to memory pressures then stale labels will
2121  * be left in place until the next pass.
2122  */
2123 static void __labelset_update(struct aa_ns *ns)
2124 {
2125         struct aa_label *label;
2126
2127         AA_BUG(!ns);
2128         AA_BUG(!mutex_is_locked(&ns->lock));
2129
2130         do {
2131                 label = labelset_next_stale(&ns->labels);
2132                 if (label) {
2133                         struct aa_label *l = __label_update(label);
2134
2135                         aa_put_label(l);
2136                         aa_put_label(label);
2137                 }
2138         } while (label);
2139 }
2140
2141 /**
2142  * __aa_labelset_update_subtree - update all labels with a stale component
2143  * @ns: ns to start update at (NOT NULL)
2144  *
2145  * Requires: @ns lock be held
2146  *
2147  * Invalidates labels based on @p in @ns and any children namespaces.
2148  */
2149 void __aa_labelset_update_subtree(struct aa_ns *ns)
2150 {
2151         struct aa_ns *child;
2152
2153         AA_BUG(!ns);
2154         AA_BUG(!mutex_is_locked(&ns->lock));
2155
2156         __labelset_update(ns);
2157
2158         list_for_each_entry(child, &ns->sub_ns, base.list) {
2159                 mutex_lock_nested(&child->lock, child->level);
2160                 __aa_labelset_update_subtree(child);
2161                 mutex_unlock(&child->lock);
2162         }
2163 }