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