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