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