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