xref: /linux/security/selinux/ss/services.c (revision fcab107abe1ab5be9dbe874baa722372da8f4f73)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Implementation of the security services.
4  *
5  * Authors : Stephen Smalley, <stephen.smalley.work@gmail.com>
6  *	     James Morris <jmorris@redhat.com>
7  *
8  * Updated: Trusted Computer Solutions, Inc. <dgoeddel@trustedcs.com>
9  *
10  *	Support for enhanced MLS infrastructure.
11  *	Support for context based audit filters.
12  *
13  * Updated: Frank Mayer <mayerf@tresys.com> and Karl MacMillan <kmacmillan@tresys.com>
14  *
15  *	Added conditional policy language extensions
16  *
17  * Updated: Hewlett-Packard <paul@paul-moore.com>
18  *
19  *      Added support for NetLabel
20  *      Added support for the policy capability bitmap
21  *
22  * Updated: Chad Sellers <csellers@tresys.com>
23  *
24  *  Added validation of kernel classes and permissions
25  *
26  * Updated: KaiGai Kohei <kaigai@ak.jp.nec.com>
27  *
28  *  Added support for bounds domain and audit messaged on masked permissions
29  *
30  * Updated: Guido Trentalancia <guido@trentalancia.com>
31  *
32  *  Added support for runtime switching of the policy type
33  *
34  * Copyright (C) 2008, 2009 NEC Corporation
35  * Copyright (C) 2006, 2007 Hewlett-Packard Development Company, L.P.
36  * Copyright (C) 2004-2006 Trusted Computer Solutions, Inc.
37  * Copyright (C) 2003 - 2004, 2006 Tresys Technology, LLC
38  * Copyright (C) 2003 Red Hat, Inc., James Morris <jmorris@redhat.com>
39  */
40 #include <linux/kernel.h>
41 #include <linux/slab.h>
42 #include <linux/string.h>
43 #include <linux/spinlock.h>
44 #include <linux/rcupdate.h>
45 #include <linux/errno.h>
46 #include <linux/in.h>
47 #include <linux/sched.h>
48 #include <linux/audit.h>
49 #include <linux/parser.h>
50 #include <linux/vmalloc.h>
51 #include <linux/lsm_hooks.h>
52 #include <net/netlabel.h>
53 
54 #include "flask.h"
55 #include "avc.h"
56 #include "avc_ss.h"
57 #include "security.h"
58 #include "context.h"
59 #include "policydb.h"
60 #include "sidtab.h"
61 #include "services.h"
62 #include "conditional.h"
63 #include "mls.h"
64 #include "objsec.h"
65 #include "netlabel.h"
66 #include "xfrm.h"
67 #include "ebitmap.h"
68 #include "audit.h"
69 #include "policycap_names.h"
70 #include "ima.h"
71 
72 struct selinux_policy_convert_data {
73 	struct convert_context_args args;
74 	struct sidtab_convert_params sidtab_params;
75 };
76 
77 /* Forward declaration. */
78 static int context_struct_to_string(struct policydb *policydb,
79 				    struct context *context,
80 				    char **scontext,
81 				    u32 *scontext_len);
82 
83 static int sidtab_entry_to_string(struct policydb *policydb,
84 				  struct sidtab *sidtab,
85 				  struct sidtab_entry *entry,
86 				  char **scontext,
87 				  u32 *scontext_len);
88 
89 static void context_struct_compute_av(struct policydb *policydb,
90 				      struct context *scontext,
91 				      struct context *tcontext,
92 				      u16 tclass,
93 				      struct av_decision *avd,
94 				      struct extended_perms *xperms);
95 
96 static int selinux_set_mapping(struct policydb *pol,
97 			       const struct security_class_mapping *map,
98 			       struct selinux_map *out_map)
99 {
100 	u16 i, j;
101 	bool print_unknown_handle = false;
102 
103 	/* Find number of classes in the input mapping */
104 	if (!map)
105 		return -EINVAL;
106 	i = 0;
107 	while (map[i].name)
108 		i++;
109 
110 	/* Allocate space for the class records, plus one for class zero */
111 	out_map->mapping = kcalloc(++i, sizeof(*out_map->mapping), GFP_ATOMIC);
112 	if (!out_map->mapping)
113 		return -ENOMEM;
114 
115 	/* Store the raw class and permission values */
116 	j = 0;
117 	while (map[j].name) {
118 		const struct security_class_mapping *p_in = map + (j++);
119 		struct selinux_mapping *p_out = out_map->mapping + j;
120 		u16 k;
121 
122 		/* An empty class string skips ahead */
123 		if (!strcmp(p_in->name, "")) {
124 			p_out->num_perms = 0;
125 			continue;
126 		}
127 
128 		p_out->value = string_to_security_class(pol, p_in->name);
129 		if (!p_out->value) {
130 			pr_info("SELinux:  Class %s not defined in policy.\n",
131 			       p_in->name);
132 			if (pol->reject_unknown)
133 				goto err;
134 			p_out->num_perms = 0;
135 			print_unknown_handle = true;
136 			continue;
137 		}
138 
139 		k = 0;
140 		while (p_in->perms[k]) {
141 			/* An empty permission string skips ahead */
142 			if (!*p_in->perms[k]) {
143 				k++;
144 				continue;
145 			}
146 			p_out->perms[k] = string_to_av_perm(pol, p_out->value,
147 							    p_in->perms[k]);
148 			if (!p_out->perms[k]) {
149 				pr_info("SELinux:  Permission %s in class %s not defined in policy.\n",
150 				       p_in->perms[k], p_in->name);
151 				if (pol->reject_unknown)
152 					goto err;
153 				print_unknown_handle = true;
154 			}
155 
156 			k++;
157 		}
158 		p_out->num_perms = k;
159 	}
160 
161 	if (print_unknown_handle)
162 		pr_info("SELinux: the above unknown classes and permissions will be %s\n",
163 		       pol->allow_unknown ? "allowed" : "denied");
164 
165 	out_map->size = i;
166 	return 0;
167 err:
168 	kfree(out_map->mapping);
169 	out_map->mapping = NULL;
170 	return -EINVAL;
171 }
172 
173 /*
174  * Get real, policy values from mapped values
175  */
176 
177 static u16 unmap_class(struct selinux_map *map, u16 tclass)
178 {
179 	if (tclass < map->size)
180 		return map->mapping[tclass].value;
181 
182 	return tclass;
183 }
184 
185 /*
186  * Get kernel value for class from its policy value
187  */
188 static u16 map_class(struct selinux_map *map, u16 pol_value)
189 {
190 	u16 i;
191 
192 	for (i = 1; i < map->size; i++) {
193 		if (map->mapping[i].value == pol_value)
194 			return i;
195 	}
196 
197 	return SECCLASS_NULL;
198 }
199 
200 static void map_decision(struct selinux_map *map,
201 			 u16 tclass, struct av_decision *avd,
202 			 int allow_unknown)
203 {
204 	if (tclass < map->size) {
205 		struct selinux_mapping *mapping = &map->mapping[tclass];
206 		unsigned int i, n = mapping->num_perms;
207 		u32 result;
208 
209 		for (i = 0, result = 0; i < n; i++) {
210 			if (avd->allowed & mapping->perms[i])
211 				result |= (u32)1<<i;
212 			if (allow_unknown && !mapping->perms[i])
213 				result |= (u32)1<<i;
214 		}
215 		avd->allowed = result;
216 
217 		for (i = 0, result = 0; i < n; i++)
218 			if (avd->auditallow & mapping->perms[i])
219 				result |= (u32)1<<i;
220 		avd->auditallow = result;
221 
222 		for (i = 0, result = 0; i < n; i++) {
223 			if (avd->auditdeny & mapping->perms[i])
224 				result |= (u32)1<<i;
225 			if (!allow_unknown && !mapping->perms[i])
226 				result |= (u32)1<<i;
227 		}
228 		/*
229 		 * In case the kernel has a bug and requests a permission
230 		 * between num_perms and the maximum permission number, we
231 		 * should audit that denial
232 		 */
233 		for (; i < (sizeof(u32)*8); i++)
234 			result |= (u32)1<<i;
235 		avd->auditdeny = result;
236 	}
237 }
238 
239 int security_mls_enabled(void)
240 {
241 	int mls_enabled;
242 	struct selinux_policy *policy;
243 
244 	if (!selinux_initialized())
245 		return 0;
246 
247 	rcu_read_lock();
248 	policy = rcu_dereference(selinux_state.policy);
249 	mls_enabled = policy->policydb.mls_enabled;
250 	rcu_read_unlock();
251 	return mls_enabled;
252 }
253 
254 /*
255  * Return the boolean value of a constraint expression
256  * when it is applied to the specified source and target
257  * security contexts.
258  *
259  * xcontext is a special beast...  It is used by the validatetrans rules
260  * only.  For these rules, scontext is the context before the transition,
261  * tcontext is the context after the transition, and xcontext is the context
262  * of the process performing the transition.  All other callers of
263  * constraint_expr_eval should pass in NULL for xcontext.
264  */
265 static int constraint_expr_eval(struct policydb *policydb,
266 				struct context *scontext,
267 				struct context *tcontext,
268 				struct context *xcontext,
269 				struct constraint_expr *cexpr)
270 {
271 	u32 val1, val2;
272 	struct context *c;
273 	struct role_datum *r1, *r2;
274 	struct mls_level *l1, *l2;
275 	struct constraint_expr *e;
276 	int s[CEXPR_MAXDEPTH];
277 	int sp = -1;
278 
279 	for (e = cexpr; e; e = e->next) {
280 		switch (e->expr_type) {
281 		case CEXPR_NOT:
282 			BUG_ON(sp < 0);
283 			s[sp] = !s[sp];
284 			break;
285 		case CEXPR_AND:
286 			BUG_ON(sp < 1);
287 			sp--;
288 			s[sp] &= s[sp + 1];
289 			break;
290 		case CEXPR_OR:
291 			BUG_ON(sp < 1);
292 			sp--;
293 			s[sp] |= s[sp + 1];
294 			break;
295 		case CEXPR_ATTR:
296 			if (sp == (CEXPR_MAXDEPTH - 1))
297 				return 0;
298 			switch (e->attr) {
299 			case CEXPR_USER:
300 				val1 = scontext->user;
301 				val2 = tcontext->user;
302 				break;
303 			case CEXPR_TYPE:
304 				val1 = scontext->type;
305 				val2 = tcontext->type;
306 				break;
307 			case CEXPR_ROLE:
308 				val1 = scontext->role;
309 				val2 = tcontext->role;
310 				r1 = policydb->role_val_to_struct[val1 - 1];
311 				r2 = policydb->role_val_to_struct[val2 - 1];
312 				switch (e->op) {
313 				case CEXPR_DOM:
314 					s[++sp] = ebitmap_get_bit(&r1->dominates,
315 								  val2 - 1);
316 					continue;
317 				case CEXPR_DOMBY:
318 					s[++sp] = ebitmap_get_bit(&r2->dominates,
319 								  val1 - 1);
320 					continue;
321 				case CEXPR_INCOMP:
322 					s[++sp] = (!ebitmap_get_bit(&r1->dominates,
323 								    val2 - 1) &&
324 						   !ebitmap_get_bit(&r2->dominates,
325 								    val1 - 1));
326 					continue;
327 				default:
328 					break;
329 				}
330 				break;
331 			case CEXPR_L1L2:
332 				l1 = &(scontext->range.level[0]);
333 				l2 = &(tcontext->range.level[0]);
334 				goto mls_ops;
335 			case CEXPR_L1H2:
336 				l1 = &(scontext->range.level[0]);
337 				l2 = &(tcontext->range.level[1]);
338 				goto mls_ops;
339 			case CEXPR_H1L2:
340 				l1 = &(scontext->range.level[1]);
341 				l2 = &(tcontext->range.level[0]);
342 				goto mls_ops;
343 			case CEXPR_H1H2:
344 				l1 = &(scontext->range.level[1]);
345 				l2 = &(tcontext->range.level[1]);
346 				goto mls_ops;
347 			case CEXPR_L1H1:
348 				l1 = &(scontext->range.level[0]);
349 				l2 = &(scontext->range.level[1]);
350 				goto mls_ops;
351 			case CEXPR_L2H2:
352 				l1 = &(tcontext->range.level[0]);
353 				l2 = &(tcontext->range.level[1]);
354 				goto mls_ops;
355 mls_ops:
356 				switch (e->op) {
357 				case CEXPR_EQ:
358 					s[++sp] = mls_level_eq(l1, l2);
359 					continue;
360 				case CEXPR_NEQ:
361 					s[++sp] = !mls_level_eq(l1, l2);
362 					continue;
363 				case CEXPR_DOM:
364 					s[++sp] = mls_level_dom(l1, l2);
365 					continue;
366 				case CEXPR_DOMBY:
367 					s[++sp] = mls_level_dom(l2, l1);
368 					continue;
369 				case CEXPR_INCOMP:
370 					s[++sp] = mls_level_incomp(l2, l1);
371 					continue;
372 				default:
373 					BUG();
374 					return 0;
375 				}
376 				break;
377 			default:
378 				BUG();
379 				return 0;
380 			}
381 
382 			switch (e->op) {
383 			case CEXPR_EQ:
384 				s[++sp] = (val1 == val2);
385 				break;
386 			case CEXPR_NEQ:
387 				s[++sp] = (val1 != val2);
388 				break;
389 			default:
390 				BUG();
391 				return 0;
392 			}
393 			break;
394 		case CEXPR_NAMES:
395 			if (sp == (CEXPR_MAXDEPTH-1))
396 				return 0;
397 			c = scontext;
398 			if (e->attr & CEXPR_TARGET)
399 				c = tcontext;
400 			else if (e->attr & CEXPR_XTARGET) {
401 				c = xcontext;
402 				if (!c) {
403 					BUG();
404 					return 0;
405 				}
406 			}
407 			if (e->attr & CEXPR_USER)
408 				val1 = c->user;
409 			else if (e->attr & CEXPR_ROLE)
410 				val1 = c->role;
411 			else if (e->attr & CEXPR_TYPE)
412 				val1 = c->type;
413 			else {
414 				BUG();
415 				return 0;
416 			}
417 
418 			switch (e->op) {
419 			case CEXPR_EQ:
420 				s[++sp] = ebitmap_get_bit(&e->names, val1 - 1);
421 				break;
422 			case CEXPR_NEQ:
423 				s[++sp] = !ebitmap_get_bit(&e->names, val1 - 1);
424 				break;
425 			default:
426 				BUG();
427 				return 0;
428 			}
429 			break;
430 		default:
431 			BUG();
432 			return 0;
433 		}
434 	}
435 
436 	BUG_ON(sp != 0);
437 	return s[0];
438 }
439 
440 /*
441  * security_dump_masked_av - dumps masked permissions during
442  * security_compute_av due to RBAC, MLS/Constraint and Type bounds.
443  */
444 static int dump_masked_av_helper(void *k, void *d, void *args)
445 {
446 	struct perm_datum *pdatum = d;
447 	char **permission_names = args;
448 
449 	BUG_ON(pdatum->value < 1 || pdatum->value > 32);
450 
451 	permission_names[pdatum->value - 1] = (char *)k;
452 
453 	return 0;
454 }
455 
456 static void security_dump_masked_av(struct policydb *policydb,
457 				    struct context *scontext,
458 				    struct context *tcontext,
459 				    u16 tclass,
460 				    u32 permissions,
461 				    const char *reason)
462 {
463 	struct common_datum *common_dat;
464 	struct class_datum *tclass_dat;
465 	struct audit_buffer *ab;
466 	char *tclass_name;
467 	char *scontext_name = NULL;
468 	char *tcontext_name = NULL;
469 	char *permission_names[32];
470 	int index;
471 	u32 length;
472 	bool need_comma = false;
473 
474 	if (!permissions)
475 		return;
476 
477 	tclass_name = sym_name(policydb, SYM_CLASSES, tclass - 1);
478 	tclass_dat = policydb->class_val_to_struct[tclass - 1];
479 	common_dat = tclass_dat->comdatum;
480 
481 	/* init permission_names */
482 	if (common_dat &&
483 	    hashtab_map(&common_dat->permissions.table,
484 			dump_masked_av_helper, permission_names) < 0)
485 		goto out;
486 
487 	if (hashtab_map(&tclass_dat->permissions.table,
488 			dump_masked_av_helper, permission_names) < 0)
489 		goto out;
490 
491 	/* get scontext/tcontext in text form */
492 	if (context_struct_to_string(policydb, scontext,
493 				     &scontext_name, &length) < 0)
494 		goto out;
495 
496 	if (context_struct_to_string(policydb, tcontext,
497 				     &tcontext_name, &length) < 0)
498 		goto out;
499 
500 	/* audit a message */
501 	ab = audit_log_start(audit_context(),
502 			     GFP_ATOMIC, AUDIT_SELINUX_ERR);
503 	if (!ab)
504 		goto out;
505 
506 	audit_log_format(ab, "op=security_compute_av reason=%s "
507 			 "scontext=%s tcontext=%s tclass=%s perms=",
508 			 reason, scontext_name, tcontext_name, tclass_name);
509 
510 	for (index = 0; index < 32; index++) {
511 		u32 mask = (1 << index);
512 
513 		if ((mask & permissions) == 0)
514 			continue;
515 
516 		audit_log_format(ab, "%s%s",
517 				 need_comma ? "," : "",
518 				 permission_names[index]
519 				 ? permission_names[index] : "????");
520 		need_comma = true;
521 	}
522 	audit_log_end(ab);
523 out:
524 	/* release scontext/tcontext */
525 	kfree(tcontext_name);
526 	kfree(scontext_name);
527 }
528 
529 /*
530  * security_boundary_permission - drops violated permissions
531  * on boundary constraint.
532  */
533 static void type_attribute_bounds_av(struct policydb *policydb,
534 				     struct context *scontext,
535 				     struct context *tcontext,
536 				     u16 tclass,
537 				     struct av_decision *avd)
538 {
539 	struct context lo_scontext;
540 	struct context lo_tcontext, *tcontextp = tcontext;
541 	struct av_decision lo_avd;
542 	struct type_datum *source;
543 	struct type_datum *target;
544 	u32 masked = 0;
545 
546 	source = policydb->type_val_to_struct[scontext->type - 1];
547 	BUG_ON(!source);
548 
549 	if (!source->bounds)
550 		return;
551 
552 	target = policydb->type_val_to_struct[tcontext->type - 1];
553 	BUG_ON(!target);
554 
555 	memset(&lo_avd, 0, sizeof(lo_avd));
556 
557 	memcpy(&lo_scontext, scontext, sizeof(lo_scontext));
558 	lo_scontext.type = source->bounds;
559 
560 	if (target->bounds) {
561 		memcpy(&lo_tcontext, tcontext, sizeof(lo_tcontext));
562 		lo_tcontext.type = target->bounds;
563 		tcontextp = &lo_tcontext;
564 	}
565 
566 	context_struct_compute_av(policydb, &lo_scontext,
567 				  tcontextp,
568 				  tclass,
569 				  &lo_avd,
570 				  NULL);
571 
572 	masked = ~lo_avd.allowed & avd->allowed;
573 
574 	if (likely(!masked))
575 		return;		/* no masked permission */
576 
577 	/* mask violated permissions */
578 	avd->allowed &= ~masked;
579 
580 	/* audit masked permissions */
581 	security_dump_masked_av(policydb, scontext, tcontext,
582 				tclass, masked, "bounds");
583 }
584 
585 /*
586  * Flag which drivers have permissions and which base permissions are covered.
587  */
588 void services_compute_xperms_drivers(
589 		struct extended_perms *xperms,
590 		struct avtab_node *node)
591 {
592 	unsigned int i;
593 
594 	switch (node->datum.u.xperms->specified) {
595 	case AVTAB_XPERMS_IOCTLDRIVER:
596 		xperms->base_perms |= AVC_EXT_IOCTL;
597 		/* if one or more driver has all permissions allowed */
598 		for (i = 0; i < ARRAY_SIZE(xperms->drivers.p); i++)
599 			xperms->drivers.p[i] |= node->datum.u.xperms->perms.p[i];
600 		break;
601 	case AVTAB_XPERMS_IOCTLFUNCTION:
602 		xperms->base_perms |= AVC_EXT_IOCTL;
603 		/* if allowing permissions within a driver */
604 		security_xperm_set(xperms->drivers.p,
605 					node->datum.u.xperms->driver);
606 		break;
607 	case AVTAB_XPERMS_NLMSG:
608 		xperms->base_perms |= AVC_EXT_NLMSG;
609 		/* if allowing permissions within a driver */
610 		security_xperm_set(xperms->drivers.p,
611 					node->datum.u.xperms->driver);
612 		break;
613 	}
614 
615 	xperms->len = 1;
616 }
617 
618 /*
619  * Compute access vectors and extended permissions based on a context
620  * structure pair for the permissions in a particular class.
621  */
622 static void context_struct_compute_av(struct policydb *policydb,
623 				      struct context *scontext,
624 				      struct context *tcontext,
625 				      u16 tclass,
626 				      struct av_decision *avd,
627 				      struct extended_perms *xperms)
628 {
629 	struct constraint_node *constraint;
630 	struct role_allow *ra;
631 	struct avtab_key avkey;
632 	struct avtab_node *node;
633 	struct class_datum *tclass_datum;
634 	struct ebitmap *sattr, *tattr;
635 	struct ebitmap_node *snode, *tnode;
636 	unsigned int i, j;
637 
638 	avd->allowed = 0;
639 	avd->auditallow = 0;
640 	avd->auditdeny = 0xffffffff;
641 	if (xperms) {
642 		memset(xperms, 0, sizeof(*xperms));
643 	}
644 
645 	if (unlikely(!tclass || tclass > policydb->p_classes.nprim)) {
646 		pr_warn_ratelimited("SELinux:  Invalid class %u\n", tclass);
647 		return;
648 	}
649 
650 	tclass_datum = policydb->class_val_to_struct[tclass - 1];
651 
652 	/*
653 	 * If a specific type enforcement rule was defined for
654 	 * this permission check, then use it.
655 	 */
656 	avkey.target_class = tclass;
657 	avkey.specified = AVTAB_AV | AVTAB_XPERMS;
658 	sattr = &policydb->type_attr_map_array[scontext->type - 1];
659 	tattr = &policydb->type_attr_map_array[tcontext->type - 1];
660 	ebitmap_for_each_positive_bit(sattr, snode, i) {
661 		ebitmap_for_each_positive_bit(tattr, tnode, j) {
662 			avkey.source_type = i + 1;
663 			avkey.target_type = j + 1;
664 			for (node = avtab_search_node(&policydb->te_avtab,
665 						      &avkey);
666 			     node;
667 			     node = avtab_search_node_next(node, avkey.specified)) {
668 				if (node->key.specified == AVTAB_ALLOWED)
669 					avd->allowed |= node->datum.u.data;
670 				else if (node->key.specified == AVTAB_AUDITALLOW)
671 					avd->auditallow |= node->datum.u.data;
672 				else if (node->key.specified == AVTAB_AUDITDENY)
673 					avd->auditdeny &= node->datum.u.data;
674 				else if (xperms && (node->key.specified & AVTAB_XPERMS))
675 					services_compute_xperms_drivers(xperms, node);
676 			}
677 
678 			/* Check conditional av table for additional permissions */
679 			cond_compute_av(&policydb->te_cond_avtab, &avkey,
680 					avd, xperms);
681 
682 		}
683 	}
684 
685 	/*
686 	 * Remove any permissions prohibited by a constraint (this includes
687 	 * the MLS policy).
688 	 */
689 	constraint = tclass_datum->constraints;
690 	while (constraint) {
691 		if ((constraint->permissions & (avd->allowed)) &&
692 		    !constraint_expr_eval(policydb, scontext, tcontext, NULL,
693 					  constraint->expr)) {
694 			avd->allowed &= ~(constraint->permissions);
695 		}
696 		constraint = constraint->next;
697 	}
698 
699 	/*
700 	 * If checking process transition permission and the
701 	 * role is changing, then check the (current_role, new_role)
702 	 * pair.
703 	 */
704 	if (tclass == policydb->process_class &&
705 	    (avd->allowed & policydb->process_trans_perms) &&
706 	    scontext->role != tcontext->role) {
707 		for (ra = policydb->role_allow; ra; ra = ra->next) {
708 			if (scontext->role == ra->role &&
709 			    tcontext->role == ra->new_role)
710 				break;
711 		}
712 		if (!ra)
713 			avd->allowed &= ~policydb->process_trans_perms;
714 	}
715 
716 	/*
717 	 * If the given source and target types have boundary
718 	 * constraint, lazy checks have to mask any violated
719 	 * permission and notice it to userspace via audit.
720 	 */
721 	type_attribute_bounds_av(policydb, scontext, tcontext,
722 				 tclass, avd);
723 }
724 
725 static int security_validtrans_handle_fail(struct selinux_policy *policy,
726 					struct sidtab_entry *oentry,
727 					struct sidtab_entry *nentry,
728 					struct sidtab_entry *tentry,
729 					u16 tclass)
730 {
731 	struct policydb *p = &policy->policydb;
732 	struct sidtab *sidtab = policy->sidtab;
733 	char *o = NULL, *n = NULL, *t = NULL;
734 	u32 olen, nlen, tlen;
735 
736 	if (sidtab_entry_to_string(p, sidtab, oentry, &o, &olen))
737 		goto out;
738 	if (sidtab_entry_to_string(p, sidtab, nentry, &n, &nlen))
739 		goto out;
740 	if (sidtab_entry_to_string(p, sidtab, tentry, &t, &tlen))
741 		goto out;
742 	audit_log(audit_context(), GFP_ATOMIC, AUDIT_SELINUX_ERR,
743 		  "op=security_validate_transition seresult=denied"
744 		  " oldcontext=%s newcontext=%s taskcontext=%s tclass=%s",
745 		  o, n, t, sym_name(p, SYM_CLASSES, tclass-1));
746 out:
747 	kfree(o);
748 	kfree(n);
749 	kfree(t);
750 
751 	if (!enforcing_enabled())
752 		return 0;
753 	return -EPERM;
754 }
755 
756 static int security_compute_validatetrans(u32 oldsid, u32 newsid, u32 tasksid,
757 					  u16 orig_tclass, bool user)
758 {
759 	struct selinux_policy *policy;
760 	struct policydb *policydb;
761 	struct sidtab *sidtab;
762 	struct sidtab_entry *oentry;
763 	struct sidtab_entry *nentry;
764 	struct sidtab_entry *tentry;
765 	struct class_datum *tclass_datum;
766 	struct constraint_node *constraint;
767 	u16 tclass;
768 	int rc = 0;
769 
770 
771 	if (!selinux_initialized())
772 		return 0;
773 
774 	rcu_read_lock();
775 
776 	policy = rcu_dereference(selinux_state.policy);
777 	policydb = &policy->policydb;
778 	sidtab = policy->sidtab;
779 
780 	if (!user)
781 		tclass = unmap_class(&policy->map, orig_tclass);
782 	else
783 		tclass = orig_tclass;
784 
785 	if (!tclass || tclass > policydb->p_classes.nprim) {
786 		rc = -EINVAL;
787 		goto out;
788 	}
789 	tclass_datum = policydb->class_val_to_struct[tclass - 1];
790 
791 	oentry = sidtab_search_entry(sidtab, oldsid);
792 	if (!oentry) {
793 		pr_err("SELinux: %s:  unrecognized SID %d\n",
794 			__func__, oldsid);
795 		rc = -EINVAL;
796 		goto out;
797 	}
798 
799 	nentry = sidtab_search_entry(sidtab, newsid);
800 	if (!nentry) {
801 		pr_err("SELinux: %s:  unrecognized SID %d\n",
802 			__func__, newsid);
803 		rc = -EINVAL;
804 		goto out;
805 	}
806 
807 	tentry = sidtab_search_entry(sidtab, tasksid);
808 	if (!tentry) {
809 		pr_err("SELinux: %s:  unrecognized SID %d\n",
810 			__func__, tasksid);
811 		rc = -EINVAL;
812 		goto out;
813 	}
814 
815 	constraint = tclass_datum->validatetrans;
816 	while (constraint) {
817 		if (!constraint_expr_eval(policydb, &oentry->context,
818 					  &nentry->context, &tentry->context,
819 					  constraint->expr)) {
820 			if (user)
821 				rc = -EPERM;
822 			else
823 				rc = security_validtrans_handle_fail(policy,
824 								oentry,
825 								nentry,
826 								tentry,
827 								tclass);
828 			goto out;
829 		}
830 		constraint = constraint->next;
831 	}
832 
833 out:
834 	rcu_read_unlock();
835 	return rc;
836 }
837 
838 int security_validate_transition_user(u32 oldsid, u32 newsid, u32 tasksid,
839 				      u16 tclass)
840 {
841 	return security_compute_validatetrans(oldsid, newsid, tasksid,
842 					      tclass, true);
843 }
844 
845 int security_validate_transition(u32 oldsid, u32 newsid, u32 tasksid,
846 				 u16 orig_tclass)
847 {
848 	return security_compute_validatetrans(oldsid, newsid, tasksid,
849 					      orig_tclass, false);
850 }
851 
852 /*
853  * security_bounded_transition - check whether the given
854  * transition is directed to bounded, or not.
855  * It returns 0, if @newsid is bounded by @oldsid.
856  * Otherwise, it returns error code.
857  *
858  * @oldsid : current security identifier
859  * @newsid : destinated security identifier
860  */
861 int security_bounded_transition(u32 old_sid, u32 new_sid)
862 {
863 	struct selinux_policy *policy;
864 	struct policydb *policydb;
865 	struct sidtab *sidtab;
866 	struct sidtab_entry *old_entry, *new_entry;
867 	struct type_datum *type;
868 	u32 index;
869 	int rc;
870 
871 	if (!selinux_initialized())
872 		return 0;
873 
874 	rcu_read_lock();
875 	policy = rcu_dereference(selinux_state.policy);
876 	policydb = &policy->policydb;
877 	sidtab = policy->sidtab;
878 
879 	rc = -EINVAL;
880 	old_entry = sidtab_search_entry(sidtab, old_sid);
881 	if (!old_entry) {
882 		pr_err("SELinux: %s: unrecognized SID %u\n",
883 		       __func__, old_sid);
884 		goto out;
885 	}
886 
887 	rc = -EINVAL;
888 	new_entry = sidtab_search_entry(sidtab, new_sid);
889 	if (!new_entry) {
890 		pr_err("SELinux: %s: unrecognized SID %u\n",
891 		       __func__, new_sid);
892 		goto out;
893 	}
894 
895 	rc = 0;
896 	/* type/domain unchanged */
897 	if (old_entry->context.type == new_entry->context.type)
898 		goto out;
899 
900 	index = new_entry->context.type;
901 	while (true) {
902 		type = policydb->type_val_to_struct[index - 1];
903 		BUG_ON(!type);
904 
905 		/* not bounded anymore */
906 		rc = -EPERM;
907 		if (!type->bounds)
908 			break;
909 
910 		/* @newsid is bounded by @oldsid */
911 		rc = 0;
912 		if (type->bounds == old_entry->context.type)
913 			break;
914 
915 		index = type->bounds;
916 	}
917 
918 	if (rc) {
919 		char *old_name = NULL;
920 		char *new_name = NULL;
921 		u32 length;
922 
923 		if (!sidtab_entry_to_string(policydb, sidtab, old_entry,
924 					    &old_name, &length) &&
925 		    !sidtab_entry_to_string(policydb, sidtab, new_entry,
926 					    &new_name, &length)) {
927 			audit_log(audit_context(),
928 				  GFP_ATOMIC, AUDIT_SELINUX_ERR,
929 				  "op=security_bounded_transition "
930 				  "seresult=denied "
931 				  "oldcontext=%s newcontext=%s",
932 				  old_name, new_name);
933 		}
934 		kfree(new_name);
935 		kfree(old_name);
936 	}
937 out:
938 	rcu_read_unlock();
939 
940 	return rc;
941 }
942 
943 static void avd_init(struct selinux_policy *policy, struct av_decision *avd)
944 {
945 	avd->allowed = 0;
946 	avd->auditallow = 0;
947 	avd->auditdeny = 0xffffffff;
948 	if (policy)
949 		avd->seqno = policy->latest_granting;
950 	else
951 		avd->seqno = 0;
952 	avd->flags = 0;
953 }
954 
955 static void update_xperms_extended_data(u8 specified,
956 					const struct extended_perms_data *from,
957 					struct extended_perms_data *xp_data)
958 {
959 	unsigned int i;
960 
961 	switch (specified) {
962 	case AVTAB_XPERMS_IOCTLDRIVER:
963 		memset(xp_data->p, 0xff, sizeof(xp_data->p));
964 		break;
965 	case AVTAB_XPERMS_IOCTLFUNCTION:
966 	case AVTAB_XPERMS_NLMSG:
967 		for (i = 0; i < ARRAY_SIZE(xp_data->p); i++)
968 			xp_data->p[i] |= from->p[i];
969 		break;
970 	}
971 
972 }
973 
974 void services_compute_xperms_decision(struct extended_perms_decision *xpermd,
975 					struct avtab_node *node)
976 {
977 	u16 specified;
978 
979 	switch (node->datum.u.xperms->specified) {
980 	case AVTAB_XPERMS_IOCTLFUNCTION:
981 		if (xpermd->base_perm != AVC_EXT_IOCTL ||
982 		    xpermd->driver != node->datum.u.xperms->driver)
983 			return;
984 		break;
985 	case AVTAB_XPERMS_IOCTLDRIVER:
986 		if (xpermd->base_perm != AVC_EXT_IOCTL ||
987 		    !security_xperm_test(node->datum.u.xperms->perms.p,
988 					 xpermd->driver))
989 			return;
990 		break;
991 	case AVTAB_XPERMS_NLMSG:
992 		if (xpermd->base_perm != AVC_EXT_NLMSG ||
993 		    xpermd->driver != node->datum.u.xperms->driver)
994 			return;
995 		break;
996 	default:
997 		pr_warn_once(
998 			"SELinux: unknown extended permission (%u) will be ignored\n",
999 			node->datum.u.xperms->specified);
1000 		return;
1001 	}
1002 
1003 	specified = node->key.specified & ~(AVTAB_ENABLED | AVTAB_ENABLED_OLD);
1004 
1005 	if (specified == AVTAB_XPERMS_ALLOWED) {
1006 		xpermd->used |= XPERMS_ALLOWED;
1007 		update_xperms_extended_data(node->datum.u.xperms->specified,
1008 					    &node->datum.u.xperms->perms,
1009 					    xpermd->allowed);
1010 	} else if (specified == AVTAB_XPERMS_AUDITALLOW) {
1011 		xpermd->used |= XPERMS_AUDITALLOW;
1012 		update_xperms_extended_data(node->datum.u.xperms->specified,
1013 					    &node->datum.u.xperms->perms,
1014 					    xpermd->auditallow);
1015 	} else if (specified == AVTAB_XPERMS_DONTAUDIT) {
1016 		xpermd->used |= XPERMS_DONTAUDIT;
1017 		update_xperms_extended_data(node->datum.u.xperms->specified,
1018 					    &node->datum.u.xperms->perms,
1019 					    xpermd->dontaudit);
1020 	} else {
1021 		pr_warn_once("SELinux: unknown specified key (%u)\n",
1022 			     node->key.specified);
1023 	}
1024 }
1025 
1026 void security_compute_xperms_decision(u32 ssid,
1027 				      u32 tsid,
1028 				      u16 orig_tclass,
1029 				      u8 driver,
1030 				      u8 base_perm,
1031 				      struct extended_perms_decision *xpermd)
1032 {
1033 	struct selinux_policy *policy;
1034 	struct policydb *policydb;
1035 	struct sidtab *sidtab;
1036 	u16 tclass;
1037 	struct context *scontext, *tcontext;
1038 	struct avtab_key avkey;
1039 	struct avtab_node *node;
1040 	struct ebitmap *sattr, *tattr;
1041 	struct ebitmap_node *snode, *tnode;
1042 	unsigned int i, j;
1043 
1044 	xpermd->base_perm = base_perm;
1045 	xpermd->driver = driver;
1046 	xpermd->used = 0;
1047 	memset(xpermd->allowed->p, 0, sizeof(xpermd->allowed->p));
1048 	memset(xpermd->auditallow->p, 0, sizeof(xpermd->auditallow->p));
1049 	memset(xpermd->dontaudit->p, 0, sizeof(xpermd->dontaudit->p));
1050 
1051 	rcu_read_lock();
1052 	if (!selinux_initialized())
1053 		goto allow;
1054 
1055 	policy = rcu_dereference(selinux_state.policy);
1056 	policydb = &policy->policydb;
1057 	sidtab = policy->sidtab;
1058 
1059 	scontext = sidtab_search(sidtab, ssid);
1060 	if (!scontext) {
1061 		pr_err("SELinux: %s:  unrecognized SID %d\n",
1062 		       __func__, ssid);
1063 		goto out;
1064 	}
1065 
1066 	tcontext = sidtab_search(sidtab, tsid);
1067 	if (!tcontext) {
1068 		pr_err("SELinux: %s:  unrecognized SID %d\n",
1069 		       __func__, tsid);
1070 		goto out;
1071 	}
1072 
1073 	tclass = unmap_class(&policy->map, orig_tclass);
1074 	if (unlikely(orig_tclass && !tclass)) {
1075 		if (policydb->allow_unknown)
1076 			goto allow;
1077 		goto out;
1078 	}
1079 
1080 
1081 	if (unlikely(!tclass || tclass > policydb->p_classes.nprim)) {
1082 		pr_warn_ratelimited("SELinux:  Invalid class %hu\n", tclass);
1083 		goto out;
1084 	}
1085 
1086 	avkey.target_class = tclass;
1087 	avkey.specified = AVTAB_XPERMS;
1088 	sattr = &policydb->type_attr_map_array[scontext->type - 1];
1089 	tattr = &policydb->type_attr_map_array[tcontext->type - 1];
1090 	ebitmap_for_each_positive_bit(sattr, snode, i) {
1091 		ebitmap_for_each_positive_bit(tattr, tnode, j) {
1092 			avkey.source_type = i + 1;
1093 			avkey.target_type = j + 1;
1094 			for (node = avtab_search_node(&policydb->te_avtab,
1095 						      &avkey);
1096 			     node;
1097 			     node = avtab_search_node_next(node, avkey.specified))
1098 				services_compute_xperms_decision(xpermd, node);
1099 
1100 			cond_compute_xperms(&policydb->te_cond_avtab,
1101 						&avkey, xpermd);
1102 		}
1103 	}
1104 out:
1105 	rcu_read_unlock();
1106 	return;
1107 allow:
1108 	memset(xpermd->allowed->p, 0xff, sizeof(xpermd->allowed->p));
1109 	goto out;
1110 }
1111 
1112 /**
1113  * security_compute_av - Compute access vector decisions.
1114  * @ssid: source security identifier
1115  * @tsid: target security identifier
1116  * @orig_tclass: target security class
1117  * @avd: access vector decisions
1118  * @xperms: extended permissions
1119  *
1120  * Compute a set of access vector decisions based on the
1121  * SID pair (@ssid, @tsid) for the permissions in @tclass.
1122  */
1123 void security_compute_av(u32 ssid,
1124 			 u32 tsid,
1125 			 u16 orig_tclass,
1126 			 struct av_decision *avd,
1127 			 struct extended_perms *xperms)
1128 {
1129 	struct selinux_policy *policy;
1130 	struct policydb *policydb;
1131 	struct sidtab *sidtab;
1132 	u16 tclass;
1133 	struct context *scontext = NULL, *tcontext = NULL;
1134 
1135 	rcu_read_lock();
1136 	policy = rcu_dereference(selinux_state.policy);
1137 	avd_init(policy, avd);
1138 	xperms->len = 0;
1139 	if (!selinux_initialized())
1140 		goto allow;
1141 
1142 	policydb = &policy->policydb;
1143 	sidtab = policy->sidtab;
1144 
1145 	scontext = sidtab_search(sidtab, ssid);
1146 	if (!scontext) {
1147 		pr_err("SELinux: %s:  unrecognized SID %d\n",
1148 		       __func__, ssid);
1149 		goto out;
1150 	}
1151 
1152 	/* permissive domain? */
1153 	if (ebitmap_get_bit(&policydb->permissive_map, scontext->type))
1154 		avd->flags |= AVD_FLAGS_PERMISSIVE;
1155 
1156 	tcontext = sidtab_search(sidtab, tsid);
1157 	if (!tcontext) {
1158 		pr_err("SELinux: %s:  unrecognized SID %d\n",
1159 		       __func__, tsid);
1160 		goto out;
1161 	}
1162 
1163 	tclass = unmap_class(&policy->map, orig_tclass);
1164 	if (unlikely(orig_tclass && !tclass)) {
1165 		if (policydb->allow_unknown)
1166 			goto allow;
1167 		goto out;
1168 	}
1169 	context_struct_compute_av(policydb, scontext, tcontext, tclass, avd,
1170 				  xperms);
1171 	map_decision(&policy->map, orig_tclass, avd,
1172 		     policydb->allow_unknown);
1173 out:
1174 	rcu_read_unlock();
1175 	return;
1176 allow:
1177 	avd->allowed = 0xffffffff;
1178 	goto out;
1179 }
1180 
1181 void security_compute_av_user(u32 ssid,
1182 			      u32 tsid,
1183 			      u16 tclass,
1184 			      struct av_decision *avd)
1185 {
1186 	struct selinux_policy *policy;
1187 	struct policydb *policydb;
1188 	struct sidtab *sidtab;
1189 	struct context *scontext = NULL, *tcontext = NULL;
1190 
1191 	rcu_read_lock();
1192 	policy = rcu_dereference(selinux_state.policy);
1193 	avd_init(policy, avd);
1194 	if (!selinux_initialized())
1195 		goto allow;
1196 
1197 	policydb = &policy->policydb;
1198 	sidtab = policy->sidtab;
1199 
1200 	scontext = sidtab_search(sidtab, ssid);
1201 	if (!scontext) {
1202 		pr_err("SELinux: %s:  unrecognized SID %d\n",
1203 		       __func__, ssid);
1204 		goto out;
1205 	}
1206 
1207 	/* permissive domain? */
1208 	if (ebitmap_get_bit(&policydb->permissive_map, scontext->type))
1209 		avd->flags |= AVD_FLAGS_PERMISSIVE;
1210 
1211 	tcontext = sidtab_search(sidtab, tsid);
1212 	if (!tcontext) {
1213 		pr_err("SELinux: %s:  unrecognized SID %d\n",
1214 		       __func__, tsid);
1215 		goto out;
1216 	}
1217 
1218 	if (unlikely(!tclass)) {
1219 		if (policydb->allow_unknown)
1220 			goto allow;
1221 		goto out;
1222 	}
1223 
1224 	context_struct_compute_av(policydb, scontext, tcontext, tclass, avd,
1225 				  NULL);
1226  out:
1227 	rcu_read_unlock();
1228 	return;
1229 allow:
1230 	avd->allowed = 0xffffffff;
1231 	goto out;
1232 }
1233 
1234 /*
1235  * Write the security context string representation of
1236  * the context structure `context' into a dynamically
1237  * allocated string of the correct size.  Set `*scontext'
1238  * to point to this string and set `*scontext_len' to
1239  * the length of the string.
1240  */
1241 static int context_struct_to_string(struct policydb *p,
1242 				    struct context *context,
1243 				    char **scontext, u32 *scontext_len)
1244 {
1245 	char *scontextp;
1246 
1247 	if (scontext)
1248 		*scontext = NULL;
1249 	*scontext_len = 0;
1250 
1251 	if (context->len) {
1252 		*scontext_len = context->len;
1253 		if (scontext) {
1254 			*scontext = kstrdup(context->str, GFP_ATOMIC);
1255 			if (!(*scontext))
1256 				return -ENOMEM;
1257 		}
1258 		return 0;
1259 	}
1260 
1261 	/* Compute the size of the context. */
1262 	*scontext_len += strlen(sym_name(p, SYM_USERS, context->user - 1)) + 1;
1263 	*scontext_len += strlen(sym_name(p, SYM_ROLES, context->role - 1)) + 1;
1264 	*scontext_len += strlen(sym_name(p, SYM_TYPES, context->type - 1)) + 1;
1265 	*scontext_len += mls_compute_context_len(p, context);
1266 
1267 	if (!scontext)
1268 		return 0;
1269 
1270 	/* Allocate space for the context; caller must free this space. */
1271 	scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
1272 	if (!scontextp)
1273 		return -ENOMEM;
1274 	*scontext = scontextp;
1275 
1276 	/*
1277 	 * Copy the user name, role name and type name into the context.
1278 	 */
1279 	scontextp += sprintf(scontextp, "%s:%s:%s",
1280 		sym_name(p, SYM_USERS, context->user - 1),
1281 		sym_name(p, SYM_ROLES, context->role - 1),
1282 		sym_name(p, SYM_TYPES, context->type - 1));
1283 
1284 	mls_sid_to_context(p, context, &scontextp);
1285 
1286 	*scontextp = 0;
1287 
1288 	return 0;
1289 }
1290 
1291 static int sidtab_entry_to_string(struct policydb *p,
1292 				  struct sidtab *sidtab,
1293 				  struct sidtab_entry *entry,
1294 				  char **scontext, u32 *scontext_len)
1295 {
1296 	int rc = sidtab_sid2str_get(sidtab, entry, scontext, scontext_len);
1297 
1298 	if (rc != -ENOENT)
1299 		return rc;
1300 
1301 	rc = context_struct_to_string(p, &entry->context, scontext,
1302 				      scontext_len);
1303 	if (!rc && scontext)
1304 		sidtab_sid2str_put(sidtab, entry, *scontext, *scontext_len);
1305 	return rc;
1306 }
1307 
1308 #include "initial_sid_to_string.h"
1309 
1310 int security_sidtab_hash_stats(char *page)
1311 {
1312 	struct selinux_policy *policy;
1313 	int rc;
1314 
1315 	if (!selinux_initialized()) {
1316 		pr_err("SELinux: %s:  called before initial load_policy\n",
1317 		       __func__);
1318 		return -EINVAL;
1319 	}
1320 
1321 	rcu_read_lock();
1322 	policy = rcu_dereference(selinux_state.policy);
1323 	rc = sidtab_hash_stats(policy->sidtab, page);
1324 	rcu_read_unlock();
1325 
1326 	return rc;
1327 }
1328 
1329 const char *security_get_initial_sid_context(u32 sid)
1330 {
1331 	if (unlikely(sid > SECINITSID_NUM))
1332 		return NULL;
1333 	return initial_sid_to_string[sid];
1334 }
1335 
1336 static int security_sid_to_context_core(u32 sid, char **scontext,
1337 					u32 *scontext_len, int force,
1338 					int only_invalid)
1339 {
1340 	struct selinux_policy *policy;
1341 	struct policydb *policydb;
1342 	struct sidtab *sidtab;
1343 	struct sidtab_entry *entry;
1344 	int rc = 0;
1345 
1346 	if (scontext)
1347 		*scontext = NULL;
1348 	*scontext_len  = 0;
1349 
1350 	if (!selinux_initialized()) {
1351 		if (sid <= SECINITSID_NUM) {
1352 			char *scontextp;
1353 			const char *s;
1354 
1355 			/*
1356 			 * Before the policy is loaded, translate
1357 			 * SECINITSID_INIT to "kernel", because systemd and
1358 			 * libselinux < 2.6 take a getcon_raw() result that is
1359 			 * both non-null and not "kernel" to mean that a policy
1360 			 * is already loaded.
1361 			 */
1362 			if (sid == SECINITSID_INIT)
1363 				sid = SECINITSID_KERNEL;
1364 
1365 			s = initial_sid_to_string[sid];
1366 			if (!s)
1367 				return -EINVAL;
1368 			*scontext_len = strlen(s) + 1;
1369 			if (!scontext)
1370 				return 0;
1371 			scontextp = kmemdup(s, *scontext_len, GFP_ATOMIC);
1372 			if (!scontextp)
1373 				return -ENOMEM;
1374 			*scontext = scontextp;
1375 			return 0;
1376 		}
1377 		pr_err("SELinux: %s:  called before initial "
1378 		       "load_policy on unknown SID %d\n", __func__, sid);
1379 		return -EINVAL;
1380 	}
1381 	rcu_read_lock();
1382 	policy = rcu_dereference(selinux_state.policy);
1383 	policydb = &policy->policydb;
1384 	sidtab = policy->sidtab;
1385 
1386 	if (force)
1387 		entry = sidtab_search_entry_force(sidtab, sid);
1388 	else
1389 		entry = sidtab_search_entry(sidtab, sid);
1390 	if (!entry) {
1391 		pr_err("SELinux: %s:  unrecognized SID %d\n",
1392 			__func__, sid);
1393 		rc = -EINVAL;
1394 		goto out_unlock;
1395 	}
1396 	if (only_invalid && !entry->context.len)
1397 		goto out_unlock;
1398 
1399 	rc = sidtab_entry_to_string(policydb, sidtab, entry, scontext,
1400 				    scontext_len);
1401 
1402 out_unlock:
1403 	rcu_read_unlock();
1404 	return rc;
1405 
1406 }
1407 
1408 /**
1409  * security_sid_to_context - Obtain a context for a given SID.
1410  * @sid: security identifier, SID
1411  * @scontext: security context
1412  * @scontext_len: length in bytes
1413  *
1414  * Write the string representation of the context associated with @sid
1415  * into a dynamically allocated string of the correct size.  Set @scontext
1416  * to point to this string and set @scontext_len to the length of the string.
1417  */
1418 int security_sid_to_context(u32 sid, char **scontext, u32 *scontext_len)
1419 {
1420 	return security_sid_to_context_core(sid, scontext,
1421 					    scontext_len, 0, 0);
1422 }
1423 
1424 int security_sid_to_context_force(u32 sid,
1425 				  char **scontext, u32 *scontext_len)
1426 {
1427 	return security_sid_to_context_core(sid, scontext,
1428 					    scontext_len, 1, 0);
1429 }
1430 
1431 /**
1432  * security_sid_to_context_inval - Obtain a context for a given SID if it
1433  *                                 is invalid.
1434  * @sid: security identifier, SID
1435  * @scontext: security context
1436  * @scontext_len: length in bytes
1437  *
1438  * Write the string representation of the context associated with @sid
1439  * into a dynamically allocated string of the correct size, but only if the
1440  * context is invalid in the current policy.  Set @scontext to point to
1441  * this string (or NULL if the context is valid) and set @scontext_len to
1442  * the length of the string (or 0 if the context is valid).
1443  */
1444 int security_sid_to_context_inval(u32 sid,
1445 				  char **scontext, u32 *scontext_len)
1446 {
1447 	return security_sid_to_context_core(sid, scontext,
1448 					    scontext_len, 1, 1);
1449 }
1450 
1451 /*
1452  * Caveat:  Mutates scontext.
1453  */
1454 static int string_to_context_struct(struct policydb *pol,
1455 				    struct sidtab *sidtabp,
1456 				    char *scontext,
1457 				    struct context *ctx,
1458 				    u32 def_sid)
1459 {
1460 	struct role_datum *role;
1461 	struct type_datum *typdatum;
1462 	struct user_datum *usrdatum;
1463 	char *scontextp, *p, oldc;
1464 	int rc = 0;
1465 
1466 	context_init(ctx);
1467 
1468 	/* Parse the security context. */
1469 
1470 	rc = -EINVAL;
1471 	scontextp = scontext;
1472 
1473 	/* Extract the user. */
1474 	p = scontextp;
1475 	while (*p && *p != ':')
1476 		p++;
1477 
1478 	if (*p == 0)
1479 		goto out;
1480 
1481 	*p++ = 0;
1482 
1483 	usrdatum = symtab_search(&pol->p_users, scontextp);
1484 	if (!usrdatum)
1485 		goto out;
1486 
1487 	ctx->user = usrdatum->value;
1488 
1489 	/* Extract role. */
1490 	scontextp = p;
1491 	while (*p && *p != ':')
1492 		p++;
1493 
1494 	if (*p == 0)
1495 		goto out;
1496 
1497 	*p++ = 0;
1498 
1499 	role = symtab_search(&pol->p_roles, scontextp);
1500 	if (!role)
1501 		goto out;
1502 	ctx->role = role->value;
1503 
1504 	/* Extract type. */
1505 	scontextp = p;
1506 	while (*p && *p != ':')
1507 		p++;
1508 	oldc = *p;
1509 	*p++ = 0;
1510 
1511 	typdatum = symtab_search(&pol->p_types, scontextp);
1512 	if (!typdatum || typdatum->attribute)
1513 		goto out;
1514 
1515 	ctx->type = typdatum->value;
1516 
1517 	rc = mls_context_to_sid(pol, oldc, p, ctx, sidtabp, def_sid);
1518 	if (rc)
1519 		goto out;
1520 
1521 	/* Check the validity of the new context. */
1522 	rc = -EINVAL;
1523 	if (!policydb_context_isvalid(pol, ctx))
1524 		goto out;
1525 	rc = 0;
1526 out:
1527 	if (rc)
1528 		context_destroy(ctx);
1529 	return rc;
1530 }
1531 
1532 static int security_context_to_sid_core(const char *scontext, u32 scontext_len,
1533 					u32 *sid, u32 def_sid, gfp_t gfp_flags,
1534 					int force)
1535 {
1536 	struct selinux_policy *policy;
1537 	struct policydb *policydb;
1538 	struct sidtab *sidtab;
1539 	char *scontext2, *str = NULL;
1540 	struct context context;
1541 	int rc = 0;
1542 
1543 	/* An empty security context is never valid. */
1544 	if (!scontext_len)
1545 		return -EINVAL;
1546 
1547 	/* Copy the string to allow changes and ensure a NUL terminator */
1548 	scontext2 = kmemdup_nul(scontext, scontext_len, gfp_flags);
1549 	if (!scontext2)
1550 		return -ENOMEM;
1551 
1552 	if (!selinux_initialized()) {
1553 		u32 i;
1554 
1555 		for (i = 1; i < SECINITSID_NUM; i++) {
1556 			const char *s = initial_sid_to_string[i];
1557 
1558 			if (s && !strcmp(s, scontext2)) {
1559 				*sid = i;
1560 				goto out;
1561 			}
1562 		}
1563 		*sid = SECINITSID_KERNEL;
1564 		goto out;
1565 	}
1566 	*sid = SECSID_NULL;
1567 
1568 	if (force) {
1569 		/* Save another copy for storing in uninterpreted form */
1570 		rc = -ENOMEM;
1571 		str = kstrdup(scontext2, gfp_flags);
1572 		if (!str)
1573 			goto out;
1574 	}
1575 retry:
1576 	rcu_read_lock();
1577 	policy = rcu_dereference(selinux_state.policy);
1578 	policydb = &policy->policydb;
1579 	sidtab = policy->sidtab;
1580 	rc = string_to_context_struct(policydb, sidtab, scontext2,
1581 				      &context, def_sid);
1582 	if (rc == -EINVAL && force) {
1583 		context.str = str;
1584 		context.len = strlen(str) + 1;
1585 		str = NULL;
1586 	} else if (rc)
1587 		goto out_unlock;
1588 	rc = sidtab_context_to_sid(sidtab, &context, sid);
1589 	if (rc == -ESTALE) {
1590 		rcu_read_unlock();
1591 		if (context.str) {
1592 			str = context.str;
1593 			context.str = NULL;
1594 		}
1595 		context_destroy(&context);
1596 		goto retry;
1597 	}
1598 	context_destroy(&context);
1599 out_unlock:
1600 	rcu_read_unlock();
1601 out:
1602 	kfree(scontext2);
1603 	kfree(str);
1604 	return rc;
1605 }
1606 
1607 /**
1608  * security_context_to_sid - Obtain a SID for a given security context.
1609  * @scontext: security context
1610  * @scontext_len: length in bytes
1611  * @sid: security identifier, SID
1612  * @gfp: context for the allocation
1613  *
1614  * Obtains a SID associated with the security context that
1615  * has the string representation specified by @scontext.
1616  * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1617  * memory is available, or 0 on success.
1618  */
1619 int security_context_to_sid(const char *scontext, u32 scontext_len, u32 *sid,
1620 			    gfp_t gfp)
1621 {
1622 	return security_context_to_sid_core(scontext, scontext_len,
1623 					    sid, SECSID_NULL, gfp, 0);
1624 }
1625 
1626 int security_context_str_to_sid(const char *scontext, u32 *sid, gfp_t gfp)
1627 {
1628 	return security_context_to_sid(scontext, strlen(scontext),
1629 				       sid, gfp);
1630 }
1631 
1632 /**
1633  * security_context_to_sid_default - Obtain a SID for a given security context,
1634  * falling back to specified default if needed.
1635  *
1636  * @scontext: security context
1637  * @scontext_len: length in bytes
1638  * @sid: security identifier, SID
1639  * @def_sid: default SID to assign on error
1640  * @gfp_flags: the allocator get-free-page (GFP) flags
1641  *
1642  * Obtains a SID associated with the security context that
1643  * has the string representation specified by @scontext.
1644  * The default SID is passed to the MLS layer to be used to allow
1645  * kernel labeling of the MLS field if the MLS field is not present
1646  * (for upgrading to MLS without full relabel).
1647  * Implicitly forces adding of the context even if it cannot be mapped yet.
1648  * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1649  * memory is available, or 0 on success.
1650  */
1651 int security_context_to_sid_default(const char *scontext, u32 scontext_len,
1652 				    u32 *sid, u32 def_sid, gfp_t gfp_flags)
1653 {
1654 	return security_context_to_sid_core(scontext, scontext_len,
1655 					    sid, def_sid, gfp_flags, 1);
1656 }
1657 
1658 int security_context_to_sid_force(const char *scontext, u32 scontext_len,
1659 				  u32 *sid)
1660 {
1661 	return security_context_to_sid_core(scontext, scontext_len,
1662 					    sid, SECSID_NULL, GFP_KERNEL, 1);
1663 }
1664 
1665 static int compute_sid_handle_invalid_context(
1666 	struct selinux_policy *policy,
1667 	struct sidtab_entry *sentry,
1668 	struct sidtab_entry *tentry,
1669 	u16 tclass,
1670 	struct context *newcontext)
1671 {
1672 	struct policydb *policydb = &policy->policydb;
1673 	struct sidtab *sidtab = policy->sidtab;
1674 	char *s = NULL, *t = NULL, *n = NULL;
1675 	u32 slen, tlen, nlen;
1676 	struct audit_buffer *ab;
1677 
1678 	if (sidtab_entry_to_string(policydb, sidtab, sentry, &s, &slen))
1679 		goto out;
1680 	if (sidtab_entry_to_string(policydb, sidtab, tentry, &t, &tlen))
1681 		goto out;
1682 	if (context_struct_to_string(policydb, newcontext, &n, &nlen))
1683 		goto out;
1684 	ab = audit_log_start(audit_context(), GFP_ATOMIC, AUDIT_SELINUX_ERR);
1685 	if (!ab)
1686 		goto out;
1687 	audit_log_format(ab,
1688 			 "op=security_compute_sid invalid_context=");
1689 	/* no need to record the NUL with untrusted strings */
1690 	audit_log_n_untrustedstring(ab, n, nlen - 1);
1691 	audit_log_format(ab, " scontext=%s tcontext=%s tclass=%s",
1692 			 s, t, sym_name(policydb, SYM_CLASSES, tclass-1));
1693 	audit_log_end(ab);
1694 out:
1695 	kfree(s);
1696 	kfree(t);
1697 	kfree(n);
1698 	if (!enforcing_enabled())
1699 		return 0;
1700 	return -EACCES;
1701 }
1702 
1703 static void filename_compute_type(struct policydb *policydb,
1704 				  struct context *newcontext,
1705 				  u32 stype, u32 ttype, u16 tclass,
1706 				  const char *objname)
1707 {
1708 	struct filename_trans_key ft;
1709 	struct filename_trans_datum *datum;
1710 
1711 	/*
1712 	 * Most filename trans rules are going to live in specific directories
1713 	 * like /dev or /var/run.  This bitmap will quickly skip rule searches
1714 	 * if the ttype does not contain any rules.
1715 	 */
1716 	if (!ebitmap_get_bit(&policydb->filename_trans_ttypes, ttype))
1717 		return;
1718 
1719 	ft.ttype = ttype;
1720 	ft.tclass = tclass;
1721 	ft.name = objname;
1722 
1723 	datum = policydb_filenametr_search(policydb, &ft);
1724 	while (datum) {
1725 		if (ebitmap_get_bit(&datum->stypes, stype - 1)) {
1726 			newcontext->type = datum->otype;
1727 			return;
1728 		}
1729 		datum = datum->next;
1730 	}
1731 }
1732 
1733 static int security_compute_sid(u32 ssid,
1734 				u32 tsid,
1735 				u16 orig_tclass,
1736 				u16 specified,
1737 				const char *objname,
1738 				u32 *out_sid,
1739 				bool kern)
1740 {
1741 	struct selinux_policy *policy;
1742 	struct policydb *policydb;
1743 	struct sidtab *sidtab;
1744 	struct class_datum *cladatum;
1745 	struct context *scontext, *tcontext, newcontext;
1746 	struct sidtab_entry *sentry, *tentry;
1747 	struct avtab_key avkey;
1748 	struct avtab_node *avnode, *node;
1749 	u16 tclass;
1750 	int rc = 0;
1751 	bool sock;
1752 
1753 	if (!selinux_initialized()) {
1754 		switch (orig_tclass) {
1755 		case SECCLASS_PROCESS: /* kernel value */
1756 			*out_sid = ssid;
1757 			break;
1758 		default:
1759 			*out_sid = tsid;
1760 			break;
1761 		}
1762 		goto out;
1763 	}
1764 
1765 retry:
1766 	cladatum = NULL;
1767 	context_init(&newcontext);
1768 
1769 	rcu_read_lock();
1770 
1771 	policy = rcu_dereference(selinux_state.policy);
1772 
1773 	if (kern) {
1774 		tclass = unmap_class(&policy->map, orig_tclass);
1775 		sock = security_is_socket_class(orig_tclass);
1776 	} else {
1777 		tclass = orig_tclass;
1778 		sock = security_is_socket_class(map_class(&policy->map,
1779 							  tclass));
1780 	}
1781 
1782 	policydb = &policy->policydb;
1783 	sidtab = policy->sidtab;
1784 
1785 	sentry = sidtab_search_entry(sidtab, ssid);
1786 	if (!sentry) {
1787 		pr_err("SELinux: %s:  unrecognized SID %d\n",
1788 		       __func__, ssid);
1789 		rc = -EINVAL;
1790 		goto out_unlock;
1791 	}
1792 	tentry = sidtab_search_entry(sidtab, tsid);
1793 	if (!tentry) {
1794 		pr_err("SELinux: %s:  unrecognized SID %d\n",
1795 		       __func__, tsid);
1796 		rc = -EINVAL;
1797 		goto out_unlock;
1798 	}
1799 
1800 	scontext = &sentry->context;
1801 	tcontext = &tentry->context;
1802 
1803 	if (tclass && tclass <= policydb->p_classes.nprim)
1804 		cladatum = policydb->class_val_to_struct[tclass - 1];
1805 
1806 	/* Set the user identity. */
1807 	switch (specified) {
1808 	case AVTAB_TRANSITION:
1809 	case AVTAB_CHANGE:
1810 		if (cladatum && cladatum->default_user == DEFAULT_TARGET) {
1811 			newcontext.user = tcontext->user;
1812 		} else {
1813 			/* notice this gets both DEFAULT_SOURCE and unset */
1814 			/* Use the process user identity. */
1815 			newcontext.user = scontext->user;
1816 		}
1817 		break;
1818 	case AVTAB_MEMBER:
1819 		/* Use the related object owner. */
1820 		newcontext.user = tcontext->user;
1821 		break;
1822 	}
1823 
1824 	/* Set the role to default values. */
1825 	if (cladatum && cladatum->default_role == DEFAULT_SOURCE) {
1826 		newcontext.role = scontext->role;
1827 	} else if (cladatum && cladatum->default_role == DEFAULT_TARGET) {
1828 		newcontext.role = tcontext->role;
1829 	} else {
1830 		if ((tclass == policydb->process_class) || sock)
1831 			newcontext.role = scontext->role;
1832 		else
1833 			newcontext.role = OBJECT_R_VAL;
1834 	}
1835 
1836 	/* Set the type.
1837 	 * Look for a type transition/member/change rule.
1838 	 */
1839 	avkey.source_type = scontext->type;
1840 	avkey.target_type = tcontext->type;
1841 	avkey.target_class = tclass;
1842 	avkey.specified = specified;
1843 	avnode = avtab_search_node(&policydb->te_avtab, &avkey);
1844 
1845 	/* If no permanent rule, also check for enabled conditional rules */
1846 	if (!avnode) {
1847 		node = avtab_search_node(&policydb->te_cond_avtab, &avkey);
1848 		for (; node; node = avtab_search_node_next(node, specified)) {
1849 			if (node->key.specified & AVTAB_ENABLED) {
1850 				avnode = node;
1851 				break;
1852 			}
1853 		}
1854 	}
1855 
1856 	/* If a permanent rule is found, use the type from
1857 	 * the type transition/member/change rule. Otherwise,
1858 	 * set the type to its default values.
1859 	 */
1860 	if (avnode) {
1861 		newcontext.type = avnode->datum.u.data;
1862 	} else if (cladatum && cladatum->default_type == DEFAULT_SOURCE) {
1863 		newcontext.type = scontext->type;
1864 	} else if (cladatum && cladatum->default_type == DEFAULT_TARGET) {
1865 		newcontext.type = tcontext->type;
1866 	} else {
1867 		if ((tclass == policydb->process_class) || sock) {
1868 			/* Use the type of process. */
1869 			newcontext.type = scontext->type;
1870 		} else {
1871 			/* Use the type of the related object. */
1872 			newcontext.type = tcontext->type;
1873 		}
1874 	}
1875 
1876 	/* if we have a objname this is a file trans check so check those rules */
1877 	if (objname)
1878 		filename_compute_type(policydb, &newcontext, scontext->type,
1879 				      tcontext->type, tclass, objname);
1880 
1881 	/* Check for class-specific changes. */
1882 	if (specified & AVTAB_TRANSITION) {
1883 		/* Look for a role transition rule. */
1884 		struct role_trans_datum *rtd;
1885 		struct role_trans_key rtk = {
1886 			.role = scontext->role,
1887 			.type = tcontext->type,
1888 			.tclass = tclass,
1889 		};
1890 
1891 		rtd = policydb_roletr_search(policydb, &rtk);
1892 		if (rtd)
1893 			newcontext.role = rtd->new_role;
1894 	}
1895 
1896 	/* Set the MLS attributes.
1897 	   This is done last because it may allocate memory. */
1898 	rc = mls_compute_sid(policydb, scontext, tcontext, tclass, specified,
1899 			     &newcontext, sock);
1900 	if (rc)
1901 		goto out_unlock;
1902 
1903 	/* Check the validity of the context. */
1904 	if (!policydb_context_isvalid(policydb, &newcontext)) {
1905 		rc = compute_sid_handle_invalid_context(policy, sentry,
1906 							tentry, tclass,
1907 							&newcontext);
1908 		if (rc)
1909 			goto out_unlock;
1910 	}
1911 	/* Obtain the sid for the context. */
1912 	rc = sidtab_context_to_sid(sidtab, &newcontext, out_sid);
1913 	if (rc == -ESTALE) {
1914 		rcu_read_unlock();
1915 		context_destroy(&newcontext);
1916 		goto retry;
1917 	}
1918 out_unlock:
1919 	rcu_read_unlock();
1920 	context_destroy(&newcontext);
1921 out:
1922 	return rc;
1923 }
1924 
1925 /**
1926  * security_transition_sid - Compute the SID for a new subject/object.
1927  * @ssid: source security identifier
1928  * @tsid: target security identifier
1929  * @tclass: target security class
1930  * @qstr: object name
1931  * @out_sid: security identifier for new subject/object
1932  *
1933  * Compute a SID to use for labeling a new subject or object in the
1934  * class @tclass based on a SID pair (@ssid, @tsid).
1935  * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1936  * if insufficient memory is available, or %0 if the new SID was
1937  * computed successfully.
1938  */
1939 int security_transition_sid(u32 ssid, u32 tsid, u16 tclass,
1940 			    const struct qstr *qstr, u32 *out_sid)
1941 {
1942 	return security_compute_sid(ssid, tsid, tclass,
1943 				    AVTAB_TRANSITION,
1944 				    qstr ? qstr->name : NULL, out_sid, true);
1945 }
1946 
1947 int security_transition_sid_user(u32 ssid, u32 tsid, u16 tclass,
1948 				 const char *objname, u32 *out_sid)
1949 {
1950 	return security_compute_sid(ssid, tsid, tclass,
1951 				    AVTAB_TRANSITION,
1952 				    objname, out_sid, false);
1953 }
1954 
1955 /**
1956  * security_member_sid - Compute the SID for member selection.
1957  * @ssid: source security identifier
1958  * @tsid: target security identifier
1959  * @tclass: target security class
1960  * @out_sid: security identifier for selected member
1961  *
1962  * Compute a SID to use when selecting a member of a polyinstantiated
1963  * object of class @tclass based on a SID pair (@ssid, @tsid).
1964  * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1965  * if insufficient memory is available, or %0 if the SID was
1966  * computed successfully.
1967  */
1968 int security_member_sid(u32 ssid,
1969 			u32 tsid,
1970 			u16 tclass,
1971 			u32 *out_sid)
1972 {
1973 	return security_compute_sid(ssid, tsid, tclass,
1974 				    AVTAB_MEMBER, NULL,
1975 				    out_sid, false);
1976 }
1977 
1978 /**
1979  * security_change_sid - Compute the SID for object relabeling.
1980  * @ssid: source security identifier
1981  * @tsid: target security identifier
1982  * @tclass: target security class
1983  * @out_sid: security identifier for selected member
1984  *
1985  * Compute a SID to use for relabeling an object of class @tclass
1986  * based on a SID pair (@ssid, @tsid).
1987  * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1988  * if insufficient memory is available, or %0 if the SID was
1989  * computed successfully.
1990  */
1991 int security_change_sid(u32 ssid,
1992 			u32 tsid,
1993 			u16 tclass,
1994 			u32 *out_sid)
1995 {
1996 	return security_compute_sid(ssid, tsid, tclass, AVTAB_CHANGE, NULL,
1997 				    out_sid, false);
1998 }
1999 
2000 static inline int convert_context_handle_invalid_context(
2001 	struct policydb *policydb,
2002 	struct context *context)
2003 {
2004 	char *s;
2005 	u32 len;
2006 
2007 	if (enforcing_enabled())
2008 		return -EINVAL;
2009 
2010 	if (!context_struct_to_string(policydb, context, &s, &len)) {
2011 		pr_warn("SELinux:  Context %s would be invalid if enforcing\n",
2012 			s);
2013 		kfree(s);
2014 	}
2015 	return 0;
2016 }
2017 
2018 /**
2019  * services_convert_context - Convert a security context across policies.
2020  * @args: populated convert_context_args struct
2021  * @oldc: original context
2022  * @newc: converted context
2023  * @gfp_flags: allocation flags
2024  *
2025  * Convert the values in the security context structure @oldc from the values
2026  * specified in the policy @args->oldp to the values specified in the policy
2027  * @args->newp, storing the new context in @newc, and verifying that the
2028  * context is valid under the new policy.
2029  */
2030 int services_convert_context(struct convert_context_args *args,
2031 			     struct context *oldc, struct context *newc,
2032 			     gfp_t gfp_flags)
2033 {
2034 	struct ocontext *oc;
2035 	struct role_datum *role;
2036 	struct type_datum *typdatum;
2037 	struct user_datum *usrdatum;
2038 	char *s;
2039 	u32 len;
2040 	int rc;
2041 
2042 	if (oldc->str) {
2043 		s = kstrdup(oldc->str, gfp_flags);
2044 		if (!s)
2045 			return -ENOMEM;
2046 
2047 		rc = string_to_context_struct(args->newp, NULL, s, newc, SECSID_NULL);
2048 		if (rc == -EINVAL) {
2049 			/*
2050 			 * Retain string representation for later mapping.
2051 			 *
2052 			 * IMPORTANT: We need to copy the contents of oldc->str
2053 			 * back into s again because string_to_context_struct()
2054 			 * may have garbled it.
2055 			 */
2056 			memcpy(s, oldc->str, oldc->len);
2057 			context_init(newc);
2058 			newc->str = s;
2059 			newc->len = oldc->len;
2060 			return 0;
2061 		}
2062 		kfree(s);
2063 		if (rc) {
2064 			/* Other error condition, e.g. ENOMEM. */
2065 			pr_err("SELinux:   Unable to map context %s, rc = %d.\n",
2066 			       oldc->str, -rc);
2067 			return rc;
2068 		}
2069 		pr_info("SELinux:  Context %s became valid (mapped).\n",
2070 			oldc->str);
2071 		return 0;
2072 	}
2073 
2074 	context_init(newc);
2075 
2076 	/* Convert the user. */
2077 	usrdatum = symtab_search(&args->newp->p_users,
2078 				 sym_name(args->oldp, SYM_USERS, oldc->user - 1));
2079 	if (!usrdatum)
2080 		goto bad;
2081 	newc->user = usrdatum->value;
2082 
2083 	/* Convert the role. */
2084 	role = symtab_search(&args->newp->p_roles,
2085 			     sym_name(args->oldp, SYM_ROLES, oldc->role - 1));
2086 	if (!role)
2087 		goto bad;
2088 	newc->role = role->value;
2089 
2090 	/* Convert the type. */
2091 	typdatum = symtab_search(&args->newp->p_types,
2092 				 sym_name(args->oldp, SYM_TYPES, oldc->type - 1));
2093 	if (!typdatum)
2094 		goto bad;
2095 	newc->type = typdatum->value;
2096 
2097 	/* Convert the MLS fields if dealing with MLS policies */
2098 	if (args->oldp->mls_enabled && args->newp->mls_enabled) {
2099 		rc = mls_convert_context(args->oldp, args->newp, oldc, newc);
2100 		if (rc)
2101 			goto bad;
2102 	} else if (!args->oldp->mls_enabled && args->newp->mls_enabled) {
2103 		/*
2104 		 * Switching between non-MLS and MLS policy:
2105 		 * ensure that the MLS fields of the context for all
2106 		 * existing entries in the sidtab are filled in with a
2107 		 * suitable default value, likely taken from one of the
2108 		 * initial SIDs.
2109 		 */
2110 		oc = args->newp->ocontexts[OCON_ISID];
2111 		while (oc && oc->sid[0] != SECINITSID_UNLABELED)
2112 			oc = oc->next;
2113 		if (!oc) {
2114 			pr_err("SELinux:  unable to look up"
2115 				" the initial SIDs list\n");
2116 			goto bad;
2117 		}
2118 		rc = mls_range_set(newc, &oc->context[0].range);
2119 		if (rc)
2120 			goto bad;
2121 	}
2122 
2123 	/* Check the validity of the new context. */
2124 	if (!policydb_context_isvalid(args->newp, newc)) {
2125 		rc = convert_context_handle_invalid_context(args->oldp, oldc);
2126 		if (rc)
2127 			goto bad;
2128 	}
2129 
2130 	return 0;
2131 bad:
2132 	/* Map old representation to string and save it. */
2133 	rc = context_struct_to_string(args->oldp, oldc, &s, &len);
2134 	if (rc)
2135 		return rc;
2136 	context_destroy(newc);
2137 	newc->str = s;
2138 	newc->len = len;
2139 	pr_info("SELinux:  Context %s became invalid (unmapped).\n",
2140 		newc->str);
2141 	return 0;
2142 }
2143 
2144 static void security_load_policycaps(struct selinux_policy *policy)
2145 {
2146 	struct policydb *p;
2147 	unsigned int i;
2148 	struct ebitmap_node *node;
2149 
2150 	p = &policy->policydb;
2151 
2152 	for (i = 0; i < ARRAY_SIZE(selinux_state.policycap); i++)
2153 		WRITE_ONCE(selinux_state.policycap[i],
2154 			ebitmap_get_bit(&p->policycaps, i));
2155 
2156 	for (i = 0; i < ARRAY_SIZE(selinux_policycap_names); i++)
2157 		pr_info("SELinux:  policy capability %s=%d\n",
2158 			selinux_policycap_names[i],
2159 			ebitmap_get_bit(&p->policycaps, i));
2160 
2161 	ebitmap_for_each_positive_bit(&p->policycaps, node, i) {
2162 		if (i >= ARRAY_SIZE(selinux_policycap_names))
2163 			pr_info("SELinux:  unknown policy capability %u\n",
2164 				i);
2165 	}
2166 }
2167 
2168 static int security_preserve_bools(struct selinux_policy *oldpolicy,
2169 				struct selinux_policy *newpolicy);
2170 
2171 static void selinux_policy_free(struct selinux_policy *policy)
2172 {
2173 	if (!policy)
2174 		return;
2175 
2176 	sidtab_destroy(policy->sidtab);
2177 	kfree(policy->map.mapping);
2178 	policydb_destroy(&policy->policydb);
2179 	kfree(policy->sidtab);
2180 	kfree(policy);
2181 }
2182 
2183 static void selinux_policy_cond_free(struct selinux_policy *policy)
2184 {
2185 	cond_policydb_destroy_dup(&policy->policydb);
2186 	kfree(policy);
2187 }
2188 
2189 void selinux_policy_cancel(struct selinux_load_state *load_state)
2190 {
2191 	struct selinux_state *state = &selinux_state;
2192 	struct selinux_policy *oldpolicy;
2193 
2194 	oldpolicy = rcu_dereference_protected(state->policy,
2195 					lockdep_is_held(&state->policy_mutex));
2196 
2197 	sidtab_cancel_convert(oldpolicy->sidtab);
2198 	selinux_policy_free(load_state->policy);
2199 	kfree(load_state->convert_data);
2200 }
2201 
2202 static void selinux_notify_policy_change(u32 seqno)
2203 {
2204 	/* Flush external caches and notify userspace of policy load */
2205 	avc_ss_reset(seqno);
2206 	selnl_notify_policyload(seqno);
2207 	selinux_status_update_policyload(seqno);
2208 	selinux_netlbl_cache_invalidate();
2209 	selinux_xfrm_notify_policyload();
2210 	selinux_ima_measure_state_locked();
2211 }
2212 
2213 void selinux_policy_commit(struct selinux_load_state *load_state)
2214 {
2215 	struct selinux_state *state = &selinux_state;
2216 	struct selinux_policy *oldpolicy, *newpolicy = load_state->policy;
2217 	unsigned long flags;
2218 	u32 seqno;
2219 
2220 	oldpolicy = rcu_dereference_protected(state->policy,
2221 					lockdep_is_held(&state->policy_mutex));
2222 
2223 	/* If switching between different policy types, log MLS status */
2224 	if (oldpolicy) {
2225 		if (oldpolicy->policydb.mls_enabled && !newpolicy->policydb.mls_enabled)
2226 			pr_info("SELinux: Disabling MLS support...\n");
2227 		else if (!oldpolicy->policydb.mls_enabled && newpolicy->policydb.mls_enabled)
2228 			pr_info("SELinux: Enabling MLS support...\n");
2229 	}
2230 
2231 	/* Set latest granting seqno for new policy. */
2232 	if (oldpolicy)
2233 		newpolicy->latest_granting = oldpolicy->latest_granting + 1;
2234 	else
2235 		newpolicy->latest_granting = 1;
2236 	seqno = newpolicy->latest_granting;
2237 
2238 	/* Install the new policy. */
2239 	if (oldpolicy) {
2240 		sidtab_freeze_begin(oldpolicy->sidtab, &flags);
2241 		rcu_assign_pointer(state->policy, newpolicy);
2242 		sidtab_freeze_end(oldpolicy->sidtab, &flags);
2243 	} else {
2244 		rcu_assign_pointer(state->policy, newpolicy);
2245 	}
2246 
2247 	/* Load the policycaps from the new policy */
2248 	security_load_policycaps(newpolicy);
2249 
2250 	if (!selinux_initialized()) {
2251 		/*
2252 		 * After first policy load, the security server is
2253 		 * marked as initialized and ready to handle requests and
2254 		 * any objects created prior to policy load are then labeled.
2255 		 */
2256 		selinux_mark_initialized();
2257 		selinux_complete_init();
2258 	}
2259 
2260 	/* Free the old policy */
2261 	synchronize_rcu();
2262 	selinux_policy_free(oldpolicy);
2263 	kfree(load_state->convert_data);
2264 
2265 	/* Notify others of the policy change */
2266 	selinux_notify_policy_change(seqno);
2267 }
2268 
2269 /**
2270  * security_load_policy - Load a security policy configuration.
2271  * @data: binary policy data
2272  * @len: length of data in bytes
2273  * @load_state: policy load state
2274  *
2275  * Load a new set of security policy configuration data,
2276  * validate it and convert the SID table as necessary.
2277  * This function will flush the access vector cache after
2278  * loading the new policy.
2279  */
2280 int security_load_policy(void *data, size_t len,
2281 			 struct selinux_load_state *load_state)
2282 {
2283 	struct selinux_state *state = &selinux_state;
2284 	struct selinux_policy *newpolicy, *oldpolicy;
2285 	struct selinux_policy_convert_data *convert_data;
2286 	int rc = 0;
2287 	struct policy_file file = { data, len }, *fp = &file;
2288 
2289 	newpolicy = kzalloc(sizeof(*newpolicy), GFP_KERNEL);
2290 	if (!newpolicy)
2291 		return -ENOMEM;
2292 
2293 	newpolicy->sidtab = kzalloc(sizeof(*newpolicy->sidtab), GFP_KERNEL);
2294 	if (!newpolicy->sidtab) {
2295 		rc = -ENOMEM;
2296 		goto err_policy;
2297 	}
2298 
2299 	rc = policydb_read(&newpolicy->policydb, fp);
2300 	if (rc)
2301 		goto err_sidtab;
2302 
2303 	newpolicy->policydb.len = len;
2304 	rc = selinux_set_mapping(&newpolicy->policydb, secclass_map,
2305 				&newpolicy->map);
2306 	if (rc)
2307 		goto err_policydb;
2308 
2309 	rc = policydb_load_isids(&newpolicy->policydb, newpolicy->sidtab);
2310 	if (rc) {
2311 		pr_err("SELinux:  unable to load the initial SIDs\n");
2312 		goto err_mapping;
2313 	}
2314 
2315 	if (!selinux_initialized()) {
2316 		/* First policy load, so no need to preserve state from old policy */
2317 		load_state->policy = newpolicy;
2318 		load_state->convert_data = NULL;
2319 		return 0;
2320 	}
2321 
2322 	oldpolicy = rcu_dereference_protected(state->policy,
2323 					lockdep_is_held(&state->policy_mutex));
2324 
2325 	/* Preserve active boolean values from the old policy */
2326 	rc = security_preserve_bools(oldpolicy, newpolicy);
2327 	if (rc) {
2328 		pr_err("SELinux:  unable to preserve booleans\n");
2329 		goto err_free_isids;
2330 	}
2331 
2332 	/*
2333 	 * Convert the internal representations of contexts
2334 	 * in the new SID table.
2335 	 */
2336 
2337 	convert_data = kmalloc(sizeof(*convert_data), GFP_KERNEL);
2338 	if (!convert_data) {
2339 		rc = -ENOMEM;
2340 		goto err_free_isids;
2341 	}
2342 
2343 	convert_data->args.oldp = &oldpolicy->policydb;
2344 	convert_data->args.newp = &newpolicy->policydb;
2345 
2346 	convert_data->sidtab_params.args = &convert_data->args;
2347 	convert_data->sidtab_params.target = newpolicy->sidtab;
2348 
2349 	rc = sidtab_convert(oldpolicy->sidtab, &convert_data->sidtab_params);
2350 	if (rc) {
2351 		pr_err("SELinux:  unable to convert the internal"
2352 			" representation of contexts in the new SID"
2353 			" table\n");
2354 		goto err_free_convert_data;
2355 	}
2356 
2357 	load_state->policy = newpolicy;
2358 	load_state->convert_data = convert_data;
2359 	return 0;
2360 
2361 err_free_convert_data:
2362 	kfree(convert_data);
2363 err_free_isids:
2364 	sidtab_destroy(newpolicy->sidtab);
2365 err_mapping:
2366 	kfree(newpolicy->map.mapping);
2367 err_policydb:
2368 	policydb_destroy(&newpolicy->policydb);
2369 err_sidtab:
2370 	kfree(newpolicy->sidtab);
2371 err_policy:
2372 	kfree(newpolicy);
2373 
2374 	return rc;
2375 }
2376 
2377 /**
2378  * ocontext_to_sid - Helper to safely get sid for an ocontext
2379  * @sidtab: SID table
2380  * @c: ocontext structure
2381  * @index: index of the context entry (0 or 1)
2382  * @out_sid: pointer to the resulting SID value
2383  *
2384  * For all ocontexts except OCON_ISID the SID fields are populated
2385  * on-demand when needed. Since updating the SID value is an SMP-sensitive
2386  * operation, this helper must be used to do that safely.
2387  *
2388  * WARNING: This function may return -ESTALE, indicating that the caller
2389  * must retry the operation after re-acquiring the policy pointer!
2390  */
2391 static int ocontext_to_sid(struct sidtab *sidtab, struct ocontext *c,
2392 			   size_t index, u32 *out_sid)
2393 {
2394 	int rc;
2395 	u32 sid;
2396 
2397 	/* Ensure the associated sidtab entry is visible to this thread. */
2398 	sid = smp_load_acquire(&c->sid[index]);
2399 	if (!sid) {
2400 		rc = sidtab_context_to_sid(sidtab, &c->context[index], &sid);
2401 		if (rc)
2402 			return rc;
2403 
2404 		/*
2405 		 * Ensure the new sidtab entry is visible to other threads
2406 		 * when they see the SID.
2407 		 */
2408 		smp_store_release(&c->sid[index], sid);
2409 	}
2410 	*out_sid = sid;
2411 	return 0;
2412 }
2413 
2414 /**
2415  * security_port_sid - Obtain the SID for a port.
2416  * @protocol: protocol number
2417  * @port: port number
2418  * @out_sid: security identifier
2419  */
2420 int security_port_sid(u8 protocol, u16 port, u32 *out_sid)
2421 {
2422 	struct selinux_policy *policy;
2423 	struct policydb *policydb;
2424 	struct sidtab *sidtab;
2425 	struct ocontext *c;
2426 	int rc;
2427 
2428 	if (!selinux_initialized()) {
2429 		*out_sid = SECINITSID_PORT;
2430 		return 0;
2431 	}
2432 
2433 retry:
2434 	rc = 0;
2435 	rcu_read_lock();
2436 	policy = rcu_dereference(selinux_state.policy);
2437 	policydb = &policy->policydb;
2438 	sidtab = policy->sidtab;
2439 
2440 	c = policydb->ocontexts[OCON_PORT];
2441 	while (c) {
2442 		if (c->u.port.protocol == protocol &&
2443 		    c->u.port.low_port <= port &&
2444 		    c->u.port.high_port >= port)
2445 			break;
2446 		c = c->next;
2447 	}
2448 
2449 	if (c) {
2450 		rc = ocontext_to_sid(sidtab, c, 0, out_sid);
2451 		if (rc == -ESTALE) {
2452 			rcu_read_unlock();
2453 			goto retry;
2454 		}
2455 		if (rc)
2456 			goto out;
2457 	} else {
2458 		*out_sid = SECINITSID_PORT;
2459 	}
2460 
2461 out:
2462 	rcu_read_unlock();
2463 	return rc;
2464 }
2465 
2466 /**
2467  * security_ib_pkey_sid - Obtain the SID for a pkey.
2468  * @subnet_prefix: Subnet Prefix
2469  * @pkey_num: pkey number
2470  * @out_sid: security identifier
2471  */
2472 int security_ib_pkey_sid(u64 subnet_prefix, u16 pkey_num, u32 *out_sid)
2473 {
2474 	struct selinux_policy *policy;
2475 	struct policydb *policydb;
2476 	struct sidtab *sidtab;
2477 	struct ocontext *c;
2478 	int rc;
2479 
2480 	if (!selinux_initialized()) {
2481 		*out_sid = SECINITSID_UNLABELED;
2482 		return 0;
2483 	}
2484 
2485 retry:
2486 	rc = 0;
2487 	rcu_read_lock();
2488 	policy = rcu_dereference(selinux_state.policy);
2489 	policydb = &policy->policydb;
2490 	sidtab = policy->sidtab;
2491 
2492 	c = policydb->ocontexts[OCON_IBPKEY];
2493 	while (c) {
2494 		if (c->u.ibpkey.low_pkey <= pkey_num &&
2495 		    c->u.ibpkey.high_pkey >= pkey_num &&
2496 		    c->u.ibpkey.subnet_prefix == subnet_prefix)
2497 			break;
2498 
2499 		c = c->next;
2500 	}
2501 
2502 	if (c) {
2503 		rc = ocontext_to_sid(sidtab, c, 0, out_sid);
2504 		if (rc == -ESTALE) {
2505 			rcu_read_unlock();
2506 			goto retry;
2507 		}
2508 		if (rc)
2509 			goto out;
2510 	} else
2511 		*out_sid = SECINITSID_UNLABELED;
2512 
2513 out:
2514 	rcu_read_unlock();
2515 	return rc;
2516 }
2517 
2518 /**
2519  * security_ib_endport_sid - Obtain the SID for a subnet management interface.
2520  * @dev_name: device name
2521  * @port_num: port number
2522  * @out_sid: security identifier
2523  */
2524 int security_ib_endport_sid(const char *dev_name, u8 port_num, u32 *out_sid)
2525 {
2526 	struct selinux_policy *policy;
2527 	struct policydb *policydb;
2528 	struct sidtab *sidtab;
2529 	struct ocontext *c;
2530 	int rc;
2531 
2532 	if (!selinux_initialized()) {
2533 		*out_sid = SECINITSID_UNLABELED;
2534 		return 0;
2535 	}
2536 
2537 retry:
2538 	rc = 0;
2539 	rcu_read_lock();
2540 	policy = rcu_dereference(selinux_state.policy);
2541 	policydb = &policy->policydb;
2542 	sidtab = policy->sidtab;
2543 
2544 	c = policydb->ocontexts[OCON_IBENDPORT];
2545 	while (c) {
2546 		if (c->u.ibendport.port == port_num &&
2547 		    !strncmp(c->u.ibendport.dev_name,
2548 			     dev_name,
2549 			     IB_DEVICE_NAME_MAX))
2550 			break;
2551 
2552 		c = c->next;
2553 	}
2554 
2555 	if (c) {
2556 		rc = ocontext_to_sid(sidtab, c, 0, out_sid);
2557 		if (rc == -ESTALE) {
2558 			rcu_read_unlock();
2559 			goto retry;
2560 		}
2561 		if (rc)
2562 			goto out;
2563 	} else
2564 		*out_sid = SECINITSID_UNLABELED;
2565 
2566 out:
2567 	rcu_read_unlock();
2568 	return rc;
2569 }
2570 
2571 /**
2572  * security_netif_sid - Obtain the SID for a network interface.
2573  * @name: interface name
2574  * @if_sid: interface SID
2575  */
2576 int security_netif_sid(const char *name, u32 *if_sid)
2577 {
2578 	struct selinux_policy *policy;
2579 	struct policydb *policydb;
2580 	struct sidtab *sidtab;
2581 	int rc;
2582 	struct ocontext *c;
2583 	bool wildcard_support;
2584 
2585 	if (!selinux_initialized()) {
2586 		*if_sid = SECINITSID_NETIF;
2587 		return 0;
2588 	}
2589 
2590 retry:
2591 	rc = 0;
2592 	rcu_read_lock();
2593 	policy = rcu_dereference(selinux_state.policy);
2594 	policydb = &policy->policydb;
2595 	sidtab = policy->sidtab;
2596 	wildcard_support = ebitmap_get_bit(&policydb->policycaps, POLICYDB_CAP_NETIF_WILDCARD);
2597 
2598 	c = policydb->ocontexts[OCON_NETIF];
2599 	while (c) {
2600 		if (wildcard_support) {
2601 			if (match_wildcard(c->u.name, name))
2602 				break;
2603 		} else {
2604 			if (strcmp(c->u.name, name) == 0)
2605 				break;
2606 		}
2607 
2608 		c = c->next;
2609 	}
2610 
2611 	if (c) {
2612 		rc = ocontext_to_sid(sidtab, c, 0, if_sid);
2613 		if (rc == -ESTALE) {
2614 			rcu_read_unlock();
2615 			goto retry;
2616 		}
2617 		if (rc)
2618 			goto out;
2619 	} else
2620 		*if_sid = SECINITSID_NETIF;
2621 
2622 out:
2623 	rcu_read_unlock();
2624 	return rc;
2625 }
2626 
2627 static bool match_ipv6_addrmask(const u32 input[4], const u32 addr[4], const u32 mask[4])
2628 {
2629 	int i;
2630 
2631 	for (i = 0; i < 4; i++)
2632 		if (addr[i] != (input[i] & mask[i]))
2633 			return false;
2634 
2635 	return true;
2636 }
2637 
2638 /**
2639  * security_node_sid - Obtain the SID for a node (host).
2640  * @domain: communication domain aka address family
2641  * @addrp: address
2642  * @addrlen: address length in bytes
2643  * @out_sid: security identifier
2644  */
2645 int security_node_sid(u16 domain,
2646 		      const void *addrp,
2647 		      u32 addrlen,
2648 		      u32 *out_sid)
2649 {
2650 	struct selinux_policy *policy;
2651 	struct policydb *policydb;
2652 	struct sidtab *sidtab;
2653 	int rc;
2654 	struct ocontext *c;
2655 
2656 	if (!selinux_initialized()) {
2657 		*out_sid = SECINITSID_NODE;
2658 		return 0;
2659 	}
2660 
2661 retry:
2662 	rcu_read_lock();
2663 	policy = rcu_dereference(selinux_state.policy);
2664 	policydb = &policy->policydb;
2665 	sidtab = policy->sidtab;
2666 
2667 	switch (domain) {
2668 	case AF_INET: {
2669 		u32 addr;
2670 
2671 		rc = -EINVAL;
2672 		if (addrlen != sizeof(u32))
2673 			goto out;
2674 
2675 		addr = *((const u32 *)addrp);
2676 
2677 		c = policydb->ocontexts[OCON_NODE];
2678 		while (c) {
2679 			if (c->u.node.addr == (addr & c->u.node.mask))
2680 				break;
2681 			c = c->next;
2682 		}
2683 		break;
2684 	}
2685 
2686 	case AF_INET6:
2687 		rc = -EINVAL;
2688 		if (addrlen != sizeof(u64) * 2)
2689 			goto out;
2690 		c = policydb->ocontexts[OCON_NODE6];
2691 		while (c) {
2692 			if (match_ipv6_addrmask(addrp, c->u.node6.addr,
2693 						c->u.node6.mask))
2694 				break;
2695 			c = c->next;
2696 		}
2697 		break;
2698 
2699 	default:
2700 		rc = 0;
2701 		*out_sid = SECINITSID_NODE;
2702 		goto out;
2703 	}
2704 
2705 	if (c) {
2706 		rc = ocontext_to_sid(sidtab, c, 0, out_sid);
2707 		if (rc == -ESTALE) {
2708 			rcu_read_unlock();
2709 			goto retry;
2710 		}
2711 		if (rc)
2712 			goto out;
2713 	} else {
2714 		*out_sid = SECINITSID_NODE;
2715 	}
2716 
2717 	rc = 0;
2718 out:
2719 	rcu_read_unlock();
2720 	return rc;
2721 }
2722 
2723 #define SIDS_NEL 25
2724 
2725 /**
2726  * security_get_user_sids - Obtain reachable SIDs for a user.
2727  * @fromsid: starting SID
2728  * @username: username
2729  * @sids: array of reachable SIDs for user
2730  * @nel: number of elements in @sids
2731  *
2732  * Generate the set of SIDs for legal security contexts
2733  * for a given user that can be reached by @fromsid.
2734  * Set *@sids to point to a dynamically allocated
2735  * array containing the set of SIDs.  Set *@nel to the
2736  * number of elements in the array.
2737  */
2738 
2739 int security_get_user_sids(u32 fromsid,
2740 			   const char *username,
2741 			   u32 **sids,
2742 			   u32 *nel)
2743 {
2744 	struct selinux_policy *policy;
2745 	struct policydb *policydb;
2746 	struct sidtab *sidtab;
2747 	struct context *fromcon, usercon;
2748 	u32 *mysids = NULL, *mysids2, sid;
2749 	u32 i, j, mynel, maxnel = SIDS_NEL;
2750 	struct user_datum *user;
2751 	struct role_datum *role;
2752 	struct ebitmap_node *rnode, *tnode;
2753 	int rc;
2754 
2755 	*sids = NULL;
2756 	*nel = 0;
2757 
2758 	if (!selinux_initialized())
2759 		return 0;
2760 
2761 	mysids = kcalloc(maxnel, sizeof(*mysids), GFP_KERNEL);
2762 	if (!mysids)
2763 		return -ENOMEM;
2764 
2765 retry:
2766 	mynel = 0;
2767 	rcu_read_lock();
2768 	policy = rcu_dereference(selinux_state.policy);
2769 	policydb = &policy->policydb;
2770 	sidtab = policy->sidtab;
2771 
2772 	context_init(&usercon);
2773 
2774 	rc = -EINVAL;
2775 	fromcon = sidtab_search(sidtab, fromsid);
2776 	if (!fromcon)
2777 		goto out_unlock;
2778 
2779 	rc = -EINVAL;
2780 	user = symtab_search(&policydb->p_users, username);
2781 	if (!user)
2782 		goto out_unlock;
2783 
2784 	usercon.user = user->value;
2785 
2786 	ebitmap_for_each_positive_bit(&user->roles, rnode, i) {
2787 		role = policydb->role_val_to_struct[i];
2788 		usercon.role = i + 1;
2789 		ebitmap_for_each_positive_bit(&role->types, tnode, j) {
2790 			usercon.type = j + 1;
2791 
2792 			if (mls_setup_user_range(policydb, fromcon, user,
2793 						 &usercon))
2794 				continue;
2795 
2796 			rc = sidtab_context_to_sid(sidtab, &usercon, &sid);
2797 			if (rc == -ESTALE) {
2798 				rcu_read_unlock();
2799 				goto retry;
2800 			}
2801 			if (rc)
2802 				goto out_unlock;
2803 			if (mynel < maxnel) {
2804 				mysids[mynel++] = sid;
2805 			} else {
2806 				rc = -ENOMEM;
2807 				maxnel += SIDS_NEL;
2808 				mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
2809 				if (!mysids2)
2810 					goto out_unlock;
2811 				memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
2812 				kfree(mysids);
2813 				mysids = mysids2;
2814 				mysids[mynel++] = sid;
2815 			}
2816 		}
2817 	}
2818 	rc = 0;
2819 out_unlock:
2820 	rcu_read_unlock();
2821 	if (rc || !mynel) {
2822 		kfree(mysids);
2823 		return rc;
2824 	}
2825 
2826 	rc = -ENOMEM;
2827 	mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);
2828 	if (!mysids2) {
2829 		kfree(mysids);
2830 		return rc;
2831 	}
2832 	for (i = 0, j = 0; i < mynel; i++) {
2833 		struct av_decision dummy_avd;
2834 		rc = avc_has_perm_noaudit(fromsid, mysids[i],
2835 					  SECCLASS_PROCESS, /* kernel value */
2836 					  PROCESS__TRANSITION, AVC_STRICT,
2837 					  &dummy_avd);
2838 		if (!rc)
2839 			mysids2[j++] = mysids[i];
2840 		cond_resched();
2841 	}
2842 	kfree(mysids);
2843 	*sids = mysids2;
2844 	*nel = j;
2845 	return 0;
2846 }
2847 
2848 /**
2849  * __security_genfs_sid - Helper to obtain a SID for a file in a filesystem
2850  * @policy: policy
2851  * @fstype: filesystem type
2852  * @path: path from root of mount
2853  * @orig_sclass: file security class
2854  * @sid: SID for path
2855  *
2856  * Obtain a SID to use for a file in a filesystem that
2857  * cannot support xattr or use a fixed labeling behavior like
2858  * transition SIDs or task SIDs.
2859  *
2860  * WARNING: This function may return -ESTALE, indicating that the caller
2861  * must retry the operation after re-acquiring the policy pointer!
2862  */
2863 static inline int __security_genfs_sid(struct selinux_policy *policy,
2864 				       const char *fstype,
2865 				       const char *path,
2866 				       u16 orig_sclass,
2867 				       u32 *sid)
2868 {
2869 	struct policydb *policydb = &policy->policydb;
2870 	struct sidtab *sidtab = policy->sidtab;
2871 	u16 sclass;
2872 	struct genfs *genfs;
2873 	struct ocontext *c;
2874 	int cmp = 0;
2875 	bool wildcard;
2876 
2877 	while (path[0] == '/' && path[1] == '/')
2878 		path++;
2879 
2880 	sclass = unmap_class(&policy->map, orig_sclass);
2881 	*sid = SECINITSID_UNLABELED;
2882 
2883 	for (genfs = policydb->genfs; genfs; genfs = genfs->next) {
2884 		cmp = strcmp(fstype, genfs->fstype);
2885 		if (cmp <= 0)
2886 			break;
2887 	}
2888 
2889 	if (!genfs || cmp)
2890 		return -ENOENT;
2891 
2892 	wildcard = ebitmap_get_bit(&policy->policydb.policycaps,
2893 				   POLICYDB_CAP_GENFS_SECLABEL_WILDCARD);
2894 	for (c = genfs->head; c; c = c->next) {
2895 		if (!c->v.sclass || sclass == c->v.sclass) {
2896 			if (wildcard) {
2897 				if (match_wildcard(c->u.name, path))
2898 					break;
2899 			} else {
2900 				size_t len = strlen(c->u.name);
2901 
2902 				if ((strncmp(c->u.name, path, len)) == 0)
2903 					break;
2904 			}
2905 		}
2906 	}
2907 
2908 	if (!c)
2909 		return -ENOENT;
2910 
2911 	return ocontext_to_sid(sidtab, c, 0, sid);
2912 }
2913 
2914 /**
2915  * security_genfs_sid - Obtain a SID for a file in a filesystem
2916  * @fstype: filesystem type
2917  * @path: path from root of mount
2918  * @orig_sclass: file security class
2919  * @sid: SID for path
2920  *
2921  * Acquire policy_rwlock before calling __security_genfs_sid() and release
2922  * it afterward.
2923  */
2924 int security_genfs_sid(const char *fstype,
2925 		       const char *path,
2926 		       u16 orig_sclass,
2927 		       u32 *sid)
2928 {
2929 	struct selinux_policy *policy;
2930 	int retval;
2931 
2932 	if (!selinux_initialized()) {
2933 		*sid = SECINITSID_UNLABELED;
2934 		return 0;
2935 	}
2936 
2937 	do {
2938 		rcu_read_lock();
2939 		policy = rcu_dereference(selinux_state.policy);
2940 		retval = __security_genfs_sid(policy, fstype, path,
2941 					      orig_sclass, sid);
2942 		rcu_read_unlock();
2943 	} while (retval == -ESTALE);
2944 	return retval;
2945 }
2946 
2947 int selinux_policy_genfs_sid(struct selinux_policy *policy,
2948 			const char *fstype,
2949 			const char *path,
2950 			u16 orig_sclass,
2951 			u32 *sid)
2952 {
2953 	/* no lock required, policy is not yet accessible by other threads */
2954 	return __security_genfs_sid(policy, fstype, path, orig_sclass, sid);
2955 }
2956 
2957 /**
2958  * security_fs_use - Determine how to handle labeling for a filesystem.
2959  * @sb: superblock in question
2960  */
2961 int security_fs_use(struct super_block *sb)
2962 {
2963 	struct selinux_policy *policy;
2964 	struct policydb *policydb;
2965 	struct sidtab *sidtab;
2966 	int rc;
2967 	struct ocontext *c;
2968 	struct superblock_security_struct *sbsec = selinux_superblock(sb);
2969 	const char *fstype = sb->s_type->name;
2970 
2971 	if (!selinux_initialized()) {
2972 		sbsec->behavior = SECURITY_FS_USE_NONE;
2973 		sbsec->sid = SECINITSID_UNLABELED;
2974 		return 0;
2975 	}
2976 
2977 retry:
2978 	rcu_read_lock();
2979 	policy = rcu_dereference(selinux_state.policy);
2980 	policydb = &policy->policydb;
2981 	sidtab = policy->sidtab;
2982 
2983 	c = policydb->ocontexts[OCON_FSUSE];
2984 	while (c) {
2985 		if (strcmp(fstype, c->u.name) == 0)
2986 			break;
2987 		c = c->next;
2988 	}
2989 
2990 	if (c) {
2991 		sbsec->behavior = c->v.behavior;
2992 		rc = ocontext_to_sid(sidtab, c, 0, &sbsec->sid);
2993 		if (rc == -ESTALE) {
2994 			rcu_read_unlock();
2995 			goto retry;
2996 		}
2997 		if (rc)
2998 			goto out;
2999 	} else {
3000 		rc = __security_genfs_sid(policy, fstype, "/",
3001 					SECCLASS_DIR, &sbsec->sid);
3002 		if (rc == -ESTALE) {
3003 			rcu_read_unlock();
3004 			goto retry;
3005 		}
3006 		if (rc) {
3007 			sbsec->behavior = SECURITY_FS_USE_NONE;
3008 			rc = 0;
3009 		} else {
3010 			sbsec->behavior = SECURITY_FS_USE_GENFS;
3011 		}
3012 	}
3013 
3014 out:
3015 	rcu_read_unlock();
3016 	return rc;
3017 }
3018 
3019 int security_get_bools(struct selinux_policy *policy,
3020 		       u32 *len, char ***names, int **values)
3021 {
3022 	struct policydb *policydb;
3023 	u32 i;
3024 	int rc;
3025 
3026 	policydb = &policy->policydb;
3027 
3028 	*names = NULL;
3029 	*values = NULL;
3030 
3031 	rc = 0;
3032 	*len = policydb->p_bools.nprim;
3033 	if (!*len)
3034 		goto out;
3035 
3036 	rc = -ENOMEM;
3037 	*names = kcalloc(*len, sizeof(char *), GFP_ATOMIC);
3038 	if (!*names)
3039 		goto err;
3040 
3041 	rc = -ENOMEM;
3042 	*values = kcalloc(*len, sizeof(int), GFP_ATOMIC);
3043 	if (!*values)
3044 		goto err;
3045 
3046 	for (i = 0; i < *len; i++) {
3047 		(*values)[i] = policydb->bool_val_to_struct[i]->state;
3048 
3049 		rc = -ENOMEM;
3050 		(*names)[i] = kstrdup(sym_name(policydb, SYM_BOOLS, i),
3051 				      GFP_ATOMIC);
3052 		if (!(*names)[i])
3053 			goto err;
3054 	}
3055 	rc = 0;
3056 out:
3057 	return rc;
3058 err:
3059 	if (*names) {
3060 		for (i = 0; i < *len; i++)
3061 			kfree((*names)[i]);
3062 		kfree(*names);
3063 	}
3064 	kfree(*values);
3065 	*len = 0;
3066 	*names = NULL;
3067 	*values = NULL;
3068 	goto out;
3069 }
3070 
3071 
3072 int security_set_bools(u32 len, const int *values)
3073 {
3074 	struct selinux_state *state = &selinux_state;
3075 	struct selinux_policy *newpolicy, *oldpolicy;
3076 	int rc;
3077 	u32 i, seqno = 0;
3078 
3079 	if (!selinux_initialized())
3080 		return -EINVAL;
3081 
3082 	oldpolicy = rcu_dereference_protected(state->policy,
3083 					lockdep_is_held(&state->policy_mutex));
3084 
3085 	/* Consistency check on number of booleans, should never fail */
3086 	if (WARN_ON(len != oldpolicy->policydb.p_bools.nprim))
3087 		return -EINVAL;
3088 
3089 	newpolicy = kmemdup(oldpolicy, sizeof(*newpolicy), GFP_KERNEL);
3090 	if (!newpolicy)
3091 		return -ENOMEM;
3092 
3093 	/*
3094 	 * Deep copy only the parts of the policydb that might be
3095 	 * modified as a result of changing booleans.
3096 	 */
3097 	rc = cond_policydb_dup(&newpolicy->policydb, &oldpolicy->policydb);
3098 	if (rc) {
3099 		kfree(newpolicy);
3100 		return -ENOMEM;
3101 	}
3102 
3103 	/* Update the boolean states in the copy */
3104 	for (i = 0; i < len; i++) {
3105 		int new_state = !!values[i];
3106 		int old_state = newpolicy->policydb.bool_val_to_struct[i]->state;
3107 
3108 		if (new_state != old_state) {
3109 			audit_log(audit_context(), GFP_ATOMIC,
3110 				AUDIT_MAC_CONFIG_CHANGE,
3111 				"bool=%s val=%d old_val=%d auid=%u ses=%u",
3112 				sym_name(&newpolicy->policydb, SYM_BOOLS, i),
3113 				new_state,
3114 				old_state,
3115 				from_kuid(&init_user_ns, audit_get_loginuid(current)),
3116 				audit_get_sessionid(current));
3117 			newpolicy->policydb.bool_val_to_struct[i]->state = new_state;
3118 		}
3119 	}
3120 
3121 	/* Re-evaluate the conditional rules in the copy */
3122 	evaluate_cond_nodes(&newpolicy->policydb);
3123 
3124 	/* Set latest granting seqno for new policy */
3125 	newpolicy->latest_granting = oldpolicy->latest_granting + 1;
3126 	seqno = newpolicy->latest_granting;
3127 
3128 	/* Install the new policy */
3129 	rcu_assign_pointer(state->policy, newpolicy);
3130 
3131 	/*
3132 	 * Free the conditional portions of the old policydb
3133 	 * that were copied for the new policy, and the oldpolicy
3134 	 * structure itself but not what it references.
3135 	 */
3136 	synchronize_rcu();
3137 	selinux_policy_cond_free(oldpolicy);
3138 
3139 	/* Notify others of the policy change */
3140 	selinux_notify_policy_change(seqno);
3141 	return 0;
3142 }
3143 
3144 int security_get_bool_value(u32 index)
3145 {
3146 	struct selinux_policy *policy;
3147 	struct policydb *policydb;
3148 	int rc;
3149 	u32 len;
3150 
3151 	if (!selinux_initialized())
3152 		return 0;
3153 
3154 	rcu_read_lock();
3155 	policy = rcu_dereference(selinux_state.policy);
3156 	policydb = &policy->policydb;
3157 
3158 	rc = -EFAULT;
3159 	len = policydb->p_bools.nprim;
3160 	if (index >= len)
3161 		goto out;
3162 
3163 	rc = policydb->bool_val_to_struct[index]->state;
3164 out:
3165 	rcu_read_unlock();
3166 	return rc;
3167 }
3168 
3169 static int security_preserve_bools(struct selinux_policy *oldpolicy,
3170 				struct selinux_policy *newpolicy)
3171 {
3172 	int rc, *bvalues = NULL;
3173 	char **bnames = NULL;
3174 	struct cond_bool_datum *booldatum;
3175 	u32 i, nbools = 0;
3176 
3177 	rc = security_get_bools(oldpolicy, &nbools, &bnames, &bvalues);
3178 	if (rc)
3179 		goto out;
3180 	for (i = 0; i < nbools; i++) {
3181 		booldatum = symtab_search(&newpolicy->policydb.p_bools,
3182 					bnames[i]);
3183 		if (booldatum)
3184 			booldatum->state = bvalues[i];
3185 	}
3186 	evaluate_cond_nodes(&newpolicy->policydb);
3187 
3188 out:
3189 	if (bnames) {
3190 		for (i = 0; i < nbools; i++)
3191 			kfree(bnames[i]);
3192 	}
3193 	kfree(bnames);
3194 	kfree(bvalues);
3195 	return rc;
3196 }
3197 
3198 /*
3199  * security_sid_mls_copy() - computes a new sid based on the given
3200  * sid and the mls portion of mls_sid.
3201  */
3202 int security_sid_mls_copy(u32 sid, u32 mls_sid, u32 *new_sid)
3203 {
3204 	struct selinux_policy *policy;
3205 	struct policydb *policydb;
3206 	struct sidtab *sidtab;
3207 	struct context *context1;
3208 	struct context *context2;
3209 	struct context newcon;
3210 	char *s;
3211 	u32 len;
3212 	int rc;
3213 
3214 	if (!selinux_initialized()) {
3215 		*new_sid = sid;
3216 		return 0;
3217 	}
3218 
3219 retry:
3220 	rc = 0;
3221 	context_init(&newcon);
3222 
3223 	rcu_read_lock();
3224 	policy = rcu_dereference(selinux_state.policy);
3225 	policydb = &policy->policydb;
3226 	sidtab = policy->sidtab;
3227 
3228 	if (!policydb->mls_enabled) {
3229 		*new_sid = sid;
3230 		goto out_unlock;
3231 	}
3232 
3233 	rc = -EINVAL;
3234 	context1 = sidtab_search(sidtab, sid);
3235 	if (!context1) {
3236 		pr_err("SELinux: %s:  unrecognized SID %d\n",
3237 			__func__, sid);
3238 		goto out_unlock;
3239 	}
3240 
3241 	rc = -EINVAL;
3242 	context2 = sidtab_search(sidtab, mls_sid);
3243 	if (!context2) {
3244 		pr_err("SELinux: %s:  unrecognized SID %d\n",
3245 			__func__, mls_sid);
3246 		goto out_unlock;
3247 	}
3248 
3249 	newcon.user = context1->user;
3250 	newcon.role = context1->role;
3251 	newcon.type = context1->type;
3252 	rc = mls_context_cpy(&newcon, context2);
3253 	if (rc)
3254 		goto out_unlock;
3255 
3256 	/* Check the validity of the new context. */
3257 	if (!policydb_context_isvalid(policydb, &newcon)) {
3258 		rc = convert_context_handle_invalid_context(policydb,
3259 							&newcon);
3260 		if (rc) {
3261 			if (!context_struct_to_string(policydb, &newcon, &s,
3262 						      &len)) {
3263 				struct audit_buffer *ab;
3264 
3265 				ab = audit_log_start(audit_context(),
3266 						     GFP_ATOMIC,
3267 						     AUDIT_SELINUX_ERR);
3268 				audit_log_format(ab,
3269 						 "op=security_sid_mls_copy invalid_context=");
3270 				/* don't record NUL with untrusted strings */
3271 				audit_log_n_untrustedstring(ab, s, len - 1);
3272 				audit_log_end(ab);
3273 				kfree(s);
3274 			}
3275 			goto out_unlock;
3276 		}
3277 	}
3278 	rc = sidtab_context_to_sid(sidtab, &newcon, new_sid);
3279 	if (rc == -ESTALE) {
3280 		rcu_read_unlock();
3281 		context_destroy(&newcon);
3282 		goto retry;
3283 	}
3284 out_unlock:
3285 	rcu_read_unlock();
3286 	context_destroy(&newcon);
3287 	return rc;
3288 }
3289 
3290 /**
3291  * security_net_peersid_resolve - Compare and resolve two network peer SIDs
3292  * @nlbl_sid: NetLabel SID
3293  * @nlbl_type: NetLabel labeling protocol type
3294  * @xfrm_sid: XFRM SID
3295  * @peer_sid: network peer sid
3296  *
3297  * Description:
3298  * Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be
3299  * resolved into a single SID it is returned via @peer_sid and the function
3300  * returns zero.  Otherwise @peer_sid is set to SECSID_NULL and the function
3301  * returns a negative value.  A table summarizing the behavior is below:
3302  *
3303  *                                 | function return |      @sid
3304  *   ------------------------------+-----------------+-----------------
3305  *   no peer labels                |        0        |    SECSID_NULL
3306  *   single peer label             |        0        |    <peer_label>
3307  *   multiple, consistent labels   |        0        |    <peer_label>
3308  *   multiple, inconsistent labels |    -<errno>     |    SECSID_NULL
3309  *
3310  */
3311 int security_net_peersid_resolve(u32 nlbl_sid, u32 nlbl_type,
3312 				 u32 xfrm_sid,
3313 				 u32 *peer_sid)
3314 {
3315 	struct selinux_policy *policy;
3316 	struct policydb *policydb;
3317 	struct sidtab *sidtab;
3318 	int rc;
3319 	struct context *nlbl_ctx;
3320 	struct context *xfrm_ctx;
3321 
3322 	*peer_sid = SECSID_NULL;
3323 
3324 	/* handle the common (which also happens to be the set of easy) cases
3325 	 * right away, these two if statements catch everything involving a
3326 	 * single or absent peer SID/label */
3327 	if (xfrm_sid == SECSID_NULL) {
3328 		*peer_sid = nlbl_sid;
3329 		return 0;
3330 	}
3331 	/* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a "fallback" label
3332 	 * and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label
3333 	 * is present */
3334 	if (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) {
3335 		*peer_sid = xfrm_sid;
3336 		return 0;
3337 	}
3338 
3339 	if (!selinux_initialized())
3340 		return 0;
3341 
3342 	rcu_read_lock();
3343 	policy = rcu_dereference(selinux_state.policy);
3344 	policydb = &policy->policydb;
3345 	sidtab = policy->sidtab;
3346 
3347 	/*
3348 	 * We don't need to check initialized here since the only way both
3349 	 * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the
3350 	 * security server was initialized and state->initialized was true.
3351 	 */
3352 	if (!policydb->mls_enabled) {
3353 		rc = 0;
3354 		goto out;
3355 	}
3356 
3357 	rc = -EINVAL;
3358 	nlbl_ctx = sidtab_search(sidtab, nlbl_sid);
3359 	if (!nlbl_ctx) {
3360 		pr_err("SELinux: %s:  unrecognized SID %d\n",
3361 		       __func__, nlbl_sid);
3362 		goto out;
3363 	}
3364 	rc = -EINVAL;
3365 	xfrm_ctx = sidtab_search(sidtab, xfrm_sid);
3366 	if (!xfrm_ctx) {
3367 		pr_err("SELinux: %s:  unrecognized SID %d\n",
3368 		       __func__, xfrm_sid);
3369 		goto out;
3370 	}
3371 	rc = (mls_context_equal(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES);
3372 	if (rc)
3373 		goto out;
3374 
3375 	/* at present NetLabel SIDs/labels really only carry MLS
3376 	 * information so if the MLS portion of the NetLabel SID
3377 	 * matches the MLS portion of the labeled XFRM SID/label
3378 	 * then pass along the XFRM SID as it is the most
3379 	 * expressive */
3380 	*peer_sid = xfrm_sid;
3381 out:
3382 	rcu_read_unlock();
3383 	return rc;
3384 }
3385 
3386 static int get_classes_callback(void *k, void *d, void *args)
3387 {
3388 	struct class_datum *datum = d;
3389 	char *name = k, **classes = args;
3390 	u32 value = datum->value - 1;
3391 
3392 	classes[value] = kstrdup(name, GFP_ATOMIC);
3393 	if (!classes[value])
3394 		return -ENOMEM;
3395 
3396 	return 0;
3397 }
3398 
3399 int security_get_classes(struct selinux_policy *policy,
3400 			 char ***classes, u32 *nclasses)
3401 {
3402 	struct policydb *policydb;
3403 	int rc;
3404 
3405 	policydb = &policy->policydb;
3406 
3407 	rc = -ENOMEM;
3408 	*nclasses = policydb->p_classes.nprim;
3409 	*classes = kcalloc(*nclasses, sizeof(**classes), GFP_ATOMIC);
3410 	if (!*classes)
3411 		goto out;
3412 
3413 	rc = hashtab_map(&policydb->p_classes.table, get_classes_callback,
3414 			 *classes);
3415 	if (rc) {
3416 		u32 i;
3417 
3418 		for (i = 0; i < *nclasses; i++)
3419 			kfree((*classes)[i]);
3420 		kfree(*classes);
3421 	}
3422 
3423 out:
3424 	return rc;
3425 }
3426 
3427 static int get_permissions_callback(void *k, void *d, void *args)
3428 {
3429 	struct perm_datum *datum = d;
3430 	char *name = k, **perms = args;
3431 	u32 value = datum->value - 1;
3432 
3433 	perms[value] = kstrdup(name, GFP_ATOMIC);
3434 	if (!perms[value])
3435 		return -ENOMEM;
3436 
3437 	return 0;
3438 }
3439 
3440 int security_get_permissions(struct selinux_policy *policy,
3441 			     const char *class, char ***perms, u32 *nperms)
3442 {
3443 	struct policydb *policydb;
3444 	u32 i;
3445 	int rc;
3446 	struct class_datum *match;
3447 
3448 	policydb = &policy->policydb;
3449 
3450 	rc = -EINVAL;
3451 	match = symtab_search(&policydb->p_classes, class);
3452 	if (!match) {
3453 		pr_err("SELinux: %s:  unrecognized class %s\n",
3454 			__func__, class);
3455 		goto out;
3456 	}
3457 
3458 	rc = -ENOMEM;
3459 	*nperms = match->permissions.nprim;
3460 	*perms = kcalloc(*nperms, sizeof(**perms), GFP_ATOMIC);
3461 	if (!*perms)
3462 		goto out;
3463 
3464 	if (match->comdatum) {
3465 		rc = hashtab_map(&match->comdatum->permissions.table,
3466 				 get_permissions_callback, *perms);
3467 		if (rc)
3468 			goto err;
3469 	}
3470 
3471 	rc = hashtab_map(&match->permissions.table, get_permissions_callback,
3472 			 *perms);
3473 	if (rc)
3474 		goto err;
3475 
3476 out:
3477 	return rc;
3478 
3479 err:
3480 	for (i = 0; i < *nperms; i++)
3481 		kfree((*perms)[i]);
3482 	kfree(*perms);
3483 	return rc;
3484 }
3485 
3486 int security_get_reject_unknown(void)
3487 {
3488 	struct selinux_policy *policy;
3489 	int value;
3490 
3491 	if (!selinux_initialized())
3492 		return 0;
3493 
3494 	rcu_read_lock();
3495 	policy = rcu_dereference(selinux_state.policy);
3496 	value = policy->policydb.reject_unknown;
3497 	rcu_read_unlock();
3498 	return value;
3499 }
3500 
3501 int security_get_allow_unknown(void)
3502 {
3503 	struct selinux_policy *policy;
3504 	int value;
3505 
3506 	if (!selinux_initialized())
3507 		return 0;
3508 
3509 	rcu_read_lock();
3510 	policy = rcu_dereference(selinux_state.policy);
3511 	value = policy->policydb.allow_unknown;
3512 	rcu_read_unlock();
3513 	return value;
3514 }
3515 
3516 /**
3517  * security_policycap_supported - Check for a specific policy capability
3518  * @req_cap: capability
3519  *
3520  * Description:
3521  * This function queries the currently loaded policy to see if it supports the
3522  * capability specified by @req_cap.  Returns true (1) if the capability is
3523  * supported, false (0) if it isn't supported.
3524  *
3525  */
3526 int security_policycap_supported(unsigned int req_cap)
3527 {
3528 	struct selinux_policy *policy;
3529 	int rc;
3530 
3531 	if (!selinux_initialized())
3532 		return 0;
3533 
3534 	rcu_read_lock();
3535 	policy = rcu_dereference(selinux_state.policy);
3536 	rc = ebitmap_get_bit(&policy->policydb.policycaps, req_cap);
3537 	rcu_read_unlock();
3538 
3539 	return rc;
3540 }
3541 
3542 struct selinux_audit_rule {
3543 	u32 au_seqno;
3544 	struct context au_ctxt;
3545 };
3546 
3547 void selinux_audit_rule_free(void *vrule)
3548 {
3549 	struct selinux_audit_rule *rule = vrule;
3550 
3551 	if (rule) {
3552 		context_destroy(&rule->au_ctxt);
3553 		kfree(rule);
3554 	}
3555 }
3556 
3557 int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule,
3558 			    gfp_t gfp)
3559 {
3560 	struct selinux_state *state = &selinux_state;
3561 	struct selinux_policy *policy;
3562 	struct policydb *policydb;
3563 	struct selinux_audit_rule *tmprule;
3564 	struct role_datum *roledatum;
3565 	struct type_datum *typedatum;
3566 	struct user_datum *userdatum;
3567 	struct selinux_audit_rule **rule = (struct selinux_audit_rule **)vrule;
3568 	int rc = 0;
3569 
3570 	*rule = NULL;
3571 
3572 	if (!selinux_initialized())
3573 		return -EOPNOTSUPP;
3574 
3575 	switch (field) {
3576 	case AUDIT_SUBJ_USER:
3577 	case AUDIT_SUBJ_ROLE:
3578 	case AUDIT_SUBJ_TYPE:
3579 	case AUDIT_OBJ_USER:
3580 	case AUDIT_OBJ_ROLE:
3581 	case AUDIT_OBJ_TYPE:
3582 		/* only 'equals' and 'not equals' fit user, role, and type */
3583 		if (op != Audit_equal && op != Audit_not_equal)
3584 			return -EINVAL;
3585 		break;
3586 	case AUDIT_SUBJ_SEN:
3587 	case AUDIT_SUBJ_CLR:
3588 	case AUDIT_OBJ_LEV_LOW:
3589 	case AUDIT_OBJ_LEV_HIGH:
3590 		/* we do not allow a range, indicated by the presence of '-' */
3591 		if (strchr(rulestr, '-'))
3592 			return -EINVAL;
3593 		break;
3594 	default:
3595 		/* only the above fields are valid */
3596 		return -EINVAL;
3597 	}
3598 
3599 	tmprule = kzalloc(sizeof(struct selinux_audit_rule), gfp);
3600 	if (!tmprule)
3601 		return -ENOMEM;
3602 	context_init(&tmprule->au_ctxt);
3603 
3604 	rcu_read_lock();
3605 	policy = rcu_dereference(state->policy);
3606 	policydb = &policy->policydb;
3607 	tmprule->au_seqno = policy->latest_granting;
3608 	switch (field) {
3609 	case AUDIT_SUBJ_USER:
3610 	case AUDIT_OBJ_USER:
3611 		userdatum = symtab_search(&policydb->p_users, rulestr);
3612 		if (!userdatum) {
3613 			rc = -EINVAL;
3614 			goto err;
3615 		}
3616 		tmprule->au_ctxt.user = userdatum->value;
3617 		break;
3618 	case AUDIT_SUBJ_ROLE:
3619 	case AUDIT_OBJ_ROLE:
3620 		roledatum = symtab_search(&policydb->p_roles, rulestr);
3621 		if (!roledatum) {
3622 			rc = -EINVAL;
3623 			goto err;
3624 		}
3625 		tmprule->au_ctxt.role = roledatum->value;
3626 		break;
3627 	case AUDIT_SUBJ_TYPE:
3628 	case AUDIT_OBJ_TYPE:
3629 		typedatum = symtab_search(&policydb->p_types, rulestr);
3630 		if (!typedatum) {
3631 			rc = -EINVAL;
3632 			goto err;
3633 		}
3634 		tmprule->au_ctxt.type = typedatum->value;
3635 		break;
3636 	case AUDIT_SUBJ_SEN:
3637 	case AUDIT_SUBJ_CLR:
3638 	case AUDIT_OBJ_LEV_LOW:
3639 	case AUDIT_OBJ_LEV_HIGH:
3640 		rc = mls_from_string(policydb, rulestr, &tmprule->au_ctxt,
3641 				     GFP_ATOMIC);
3642 		if (rc)
3643 			goto err;
3644 		break;
3645 	}
3646 	rcu_read_unlock();
3647 
3648 	*rule = tmprule;
3649 	return 0;
3650 
3651 err:
3652 	rcu_read_unlock();
3653 	selinux_audit_rule_free(tmprule);
3654 	*rule = NULL;
3655 	return rc;
3656 }
3657 
3658 /* Check to see if the rule contains any selinux fields */
3659 int selinux_audit_rule_known(struct audit_krule *rule)
3660 {
3661 	u32 i;
3662 
3663 	for (i = 0; i < rule->field_count; i++) {
3664 		struct audit_field *f = &rule->fields[i];
3665 		switch (f->type) {
3666 		case AUDIT_SUBJ_USER:
3667 		case AUDIT_SUBJ_ROLE:
3668 		case AUDIT_SUBJ_TYPE:
3669 		case AUDIT_SUBJ_SEN:
3670 		case AUDIT_SUBJ_CLR:
3671 		case AUDIT_OBJ_USER:
3672 		case AUDIT_OBJ_ROLE:
3673 		case AUDIT_OBJ_TYPE:
3674 		case AUDIT_OBJ_LEV_LOW:
3675 		case AUDIT_OBJ_LEV_HIGH:
3676 			return 1;
3677 		}
3678 	}
3679 
3680 	return 0;
3681 }
3682 
3683 int selinux_audit_rule_match(struct lsm_prop *prop, u32 field, u32 op, void *vrule)
3684 {
3685 	struct selinux_state *state = &selinux_state;
3686 	struct selinux_policy *policy;
3687 	struct context *ctxt;
3688 	struct mls_level *level;
3689 	struct selinux_audit_rule *rule = vrule;
3690 	int match = 0;
3691 
3692 	if (unlikely(!rule)) {
3693 		WARN_ONCE(1, "selinux_audit_rule_match: missing rule\n");
3694 		return -ENOENT;
3695 	}
3696 
3697 	if (!selinux_initialized())
3698 		return 0;
3699 
3700 	rcu_read_lock();
3701 
3702 	policy = rcu_dereference(state->policy);
3703 
3704 	if (rule->au_seqno < policy->latest_granting) {
3705 		match = -ESTALE;
3706 		goto out;
3707 	}
3708 
3709 	ctxt = sidtab_search(policy->sidtab, prop->selinux.secid);
3710 	if (unlikely(!ctxt)) {
3711 		WARN_ONCE(1, "selinux_audit_rule_match: unrecognized SID %d\n",
3712 			  prop->selinux.secid);
3713 		match = -ENOENT;
3714 		goto out;
3715 	}
3716 
3717 	/* a field/op pair that is not caught here will simply fall through
3718 	   without a match */
3719 	switch (field) {
3720 	case AUDIT_SUBJ_USER:
3721 	case AUDIT_OBJ_USER:
3722 		switch (op) {
3723 		case Audit_equal:
3724 			match = (ctxt->user == rule->au_ctxt.user);
3725 			break;
3726 		case Audit_not_equal:
3727 			match = (ctxt->user != rule->au_ctxt.user);
3728 			break;
3729 		}
3730 		break;
3731 	case AUDIT_SUBJ_ROLE:
3732 	case AUDIT_OBJ_ROLE:
3733 		switch (op) {
3734 		case Audit_equal:
3735 			match = (ctxt->role == rule->au_ctxt.role);
3736 			break;
3737 		case Audit_not_equal:
3738 			match = (ctxt->role != rule->au_ctxt.role);
3739 			break;
3740 		}
3741 		break;
3742 	case AUDIT_SUBJ_TYPE:
3743 	case AUDIT_OBJ_TYPE:
3744 		switch (op) {
3745 		case Audit_equal:
3746 			match = (ctxt->type == rule->au_ctxt.type);
3747 			break;
3748 		case Audit_not_equal:
3749 			match = (ctxt->type != rule->au_ctxt.type);
3750 			break;
3751 		}
3752 		break;
3753 	case AUDIT_SUBJ_SEN:
3754 	case AUDIT_SUBJ_CLR:
3755 	case AUDIT_OBJ_LEV_LOW:
3756 	case AUDIT_OBJ_LEV_HIGH:
3757 		level = ((field == AUDIT_SUBJ_SEN ||
3758 			  field == AUDIT_OBJ_LEV_LOW) ?
3759 			 &ctxt->range.level[0] : &ctxt->range.level[1]);
3760 		switch (op) {
3761 		case Audit_equal:
3762 			match = mls_level_eq(&rule->au_ctxt.range.level[0],
3763 					     level);
3764 			break;
3765 		case Audit_not_equal:
3766 			match = !mls_level_eq(&rule->au_ctxt.range.level[0],
3767 					      level);
3768 			break;
3769 		case Audit_lt:
3770 			match = (mls_level_dom(&rule->au_ctxt.range.level[0],
3771 					       level) &&
3772 				 !mls_level_eq(&rule->au_ctxt.range.level[0],
3773 					       level));
3774 			break;
3775 		case Audit_le:
3776 			match = mls_level_dom(&rule->au_ctxt.range.level[0],
3777 					      level);
3778 			break;
3779 		case Audit_gt:
3780 			match = (mls_level_dom(level,
3781 					      &rule->au_ctxt.range.level[0]) &&
3782 				 !mls_level_eq(level,
3783 					       &rule->au_ctxt.range.level[0]));
3784 			break;
3785 		case Audit_ge:
3786 			match = mls_level_dom(level,
3787 					      &rule->au_ctxt.range.level[0]);
3788 			break;
3789 		}
3790 	}
3791 
3792 out:
3793 	rcu_read_unlock();
3794 	return match;
3795 }
3796 
3797 static int aurule_avc_callback(u32 event)
3798 {
3799 	if (event == AVC_CALLBACK_RESET)
3800 		return audit_update_lsm_rules();
3801 	return 0;
3802 }
3803 
3804 static int __init aurule_init(void)
3805 {
3806 	int err;
3807 
3808 	err = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET);
3809 	if (err)
3810 		panic("avc_add_callback() failed, error %d\n", err);
3811 
3812 	return err;
3813 }
3814 __initcall(aurule_init);
3815 
3816 #ifdef CONFIG_NETLABEL
3817 /**
3818  * security_netlbl_cache_add - Add an entry to the NetLabel cache
3819  * @secattr: the NetLabel packet security attributes
3820  * @sid: the SELinux SID
3821  *
3822  * Description:
3823  * Attempt to cache the context in @ctx, which was derived from the packet in
3824  * @skb, in the NetLabel subsystem cache.  This function assumes @secattr has
3825  * already been initialized.
3826  *
3827  */
3828 static void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr,
3829 				      u32 sid)
3830 {
3831 	u32 *sid_cache;
3832 
3833 	sid_cache = kmalloc(sizeof(*sid_cache), GFP_ATOMIC);
3834 	if (sid_cache == NULL)
3835 		return;
3836 	secattr->cache = netlbl_secattr_cache_alloc(GFP_ATOMIC);
3837 	if (secattr->cache == NULL) {
3838 		kfree(sid_cache);
3839 		return;
3840 	}
3841 
3842 	*sid_cache = sid;
3843 	secattr->cache->free = kfree;
3844 	secattr->cache->data = sid_cache;
3845 	secattr->flags |= NETLBL_SECATTR_CACHE;
3846 }
3847 
3848 /**
3849  * security_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID
3850  * @secattr: the NetLabel packet security attributes
3851  * @sid: the SELinux SID
3852  *
3853  * Description:
3854  * Convert the given NetLabel security attributes in @secattr into a
3855  * SELinux SID.  If the @secattr field does not contain a full SELinux
3856  * SID/context then use SECINITSID_NETMSG as the foundation.  If possible the
3857  * 'cache' field of @secattr is set and the CACHE flag is set; this is to
3858  * allow the @secattr to be used by NetLabel to cache the secattr to SID
3859  * conversion for future lookups.  Returns zero on success, negative values on
3860  * failure.
3861  *
3862  */
3863 int security_netlbl_secattr_to_sid(struct netlbl_lsm_secattr *secattr,
3864 				   u32 *sid)
3865 {
3866 	struct selinux_policy *policy;
3867 	struct policydb *policydb;
3868 	struct sidtab *sidtab;
3869 	int rc;
3870 	struct context *ctx;
3871 	struct context ctx_new;
3872 
3873 	if (!selinux_initialized()) {
3874 		*sid = SECSID_NULL;
3875 		return 0;
3876 	}
3877 
3878 retry:
3879 	rc = 0;
3880 	rcu_read_lock();
3881 	policy = rcu_dereference(selinux_state.policy);
3882 	policydb = &policy->policydb;
3883 	sidtab = policy->sidtab;
3884 
3885 	if (secattr->flags & NETLBL_SECATTR_CACHE)
3886 		*sid = *(u32 *)secattr->cache->data;
3887 	else if (secattr->flags & NETLBL_SECATTR_SECID)
3888 		*sid = secattr->attr.secid;
3889 	else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) {
3890 		rc = -EIDRM;
3891 		ctx = sidtab_search(sidtab, SECINITSID_NETMSG);
3892 		if (ctx == NULL)
3893 			goto out;
3894 
3895 		context_init(&ctx_new);
3896 		ctx_new.user = ctx->user;
3897 		ctx_new.role = ctx->role;
3898 		ctx_new.type = ctx->type;
3899 		mls_import_netlbl_lvl(policydb, &ctx_new, secattr);
3900 		if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
3901 			rc = mls_import_netlbl_cat(policydb, &ctx_new, secattr);
3902 			if (rc)
3903 				goto out;
3904 		}
3905 		rc = -EIDRM;
3906 		if (!mls_context_isvalid(policydb, &ctx_new)) {
3907 			ebitmap_destroy(&ctx_new.range.level[0].cat);
3908 			goto out;
3909 		}
3910 
3911 		rc = sidtab_context_to_sid(sidtab, &ctx_new, sid);
3912 		ebitmap_destroy(&ctx_new.range.level[0].cat);
3913 		if (rc == -ESTALE) {
3914 			rcu_read_unlock();
3915 			goto retry;
3916 		}
3917 		if (rc)
3918 			goto out;
3919 
3920 		security_netlbl_cache_add(secattr, *sid);
3921 	} else
3922 		*sid = SECSID_NULL;
3923 
3924 out:
3925 	rcu_read_unlock();
3926 	return rc;
3927 }
3928 
3929 /**
3930  * security_netlbl_sid_to_secattr - Convert a SELinux SID to a NetLabel secattr
3931  * @sid: the SELinux SID
3932  * @secattr: the NetLabel packet security attributes
3933  *
3934  * Description:
3935  * Convert the given SELinux SID in @sid into a NetLabel security attribute.
3936  * Returns zero on success, negative values on failure.
3937  *
3938  */
3939 int security_netlbl_sid_to_secattr(u32 sid, struct netlbl_lsm_secattr *secattr)
3940 {
3941 	struct selinux_policy *policy;
3942 	struct policydb *policydb;
3943 	int rc;
3944 	struct context *ctx;
3945 
3946 	if (!selinux_initialized())
3947 		return 0;
3948 
3949 	rcu_read_lock();
3950 	policy = rcu_dereference(selinux_state.policy);
3951 	policydb = &policy->policydb;
3952 
3953 	rc = -ENOENT;
3954 	ctx = sidtab_search(policy->sidtab, sid);
3955 	if (ctx == NULL)
3956 		goto out;
3957 
3958 	rc = -ENOMEM;
3959 	secattr->domain = kstrdup(sym_name(policydb, SYM_TYPES, ctx->type - 1),
3960 				  GFP_ATOMIC);
3961 	if (secattr->domain == NULL)
3962 		goto out;
3963 
3964 	secattr->attr.secid = sid;
3965 	secattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID;
3966 	mls_export_netlbl_lvl(policydb, ctx, secattr);
3967 	rc = mls_export_netlbl_cat(policydb, ctx, secattr);
3968 out:
3969 	rcu_read_unlock();
3970 	return rc;
3971 }
3972 #endif /* CONFIG_NETLABEL */
3973 
3974 /**
3975  * __security_read_policy - read the policy.
3976  * @policy: SELinux policy
3977  * @data: binary policy data
3978  * @len: length of data in bytes
3979  *
3980  */
3981 static int __security_read_policy(struct selinux_policy *policy,
3982 				  void *data, size_t *len)
3983 {
3984 	int rc;
3985 	struct policy_file fp;
3986 
3987 	fp.data = data;
3988 	fp.len = *len;
3989 
3990 	rc = policydb_write(&policy->policydb, &fp);
3991 	if (rc)
3992 		return rc;
3993 
3994 	*len = (unsigned long)fp.data - (unsigned long)data;
3995 	return 0;
3996 }
3997 
3998 /**
3999  * security_read_policy - read the policy.
4000  * @data: binary policy data
4001  * @len: length of data in bytes
4002  *
4003  */
4004 int security_read_policy(void **data, size_t *len)
4005 {
4006 	struct selinux_state *state = &selinux_state;
4007 	struct selinux_policy *policy;
4008 
4009 	policy = rcu_dereference_protected(
4010 			state->policy, lockdep_is_held(&state->policy_mutex));
4011 	if (!policy)
4012 		return -EINVAL;
4013 
4014 	*len = policy->policydb.len;
4015 	*data = vmalloc_user(*len);
4016 	if (!*data)
4017 		return -ENOMEM;
4018 
4019 	return __security_read_policy(policy, *data, len);
4020 }
4021 
4022 /**
4023  * security_read_state_kernel - read the policy.
4024  * @data: binary policy data
4025  * @len: length of data in bytes
4026  *
4027  * Allocates kernel memory for reading SELinux policy.
4028  * This function is for internal use only and should not
4029  * be used for returning data to user space.
4030  *
4031  * This function must be called with policy_mutex held.
4032  */
4033 int security_read_state_kernel(void **data, size_t *len)
4034 {
4035 	int err;
4036 	struct selinux_state *state = &selinux_state;
4037 	struct selinux_policy *policy;
4038 
4039 	policy = rcu_dereference_protected(
4040 			state->policy, lockdep_is_held(&state->policy_mutex));
4041 	if (!policy)
4042 		return -EINVAL;
4043 
4044 	*len = policy->policydb.len;
4045 	*data = vmalloc(*len);
4046 	if (!*data)
4047 		return -ENOMEM;
4048 
4049 	err = __security_read_policy(policy, *data, len);
4050 	if (err) {
4051 		vfree(*data);
4052 		*data = NULL;
4053 		*len = 0;
4054 	}
4055 	return err;
4056 }
4057