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