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