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