xref: /openbmc/linux/security/selinux/ss/services.c (revision ded1ffea)
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 = initial_sid_to_string[sid];
1326 
1327 			if (!s)
1328 				return -EINVAL;
1329 			*scontext_len = strlen(s) + 1;
1330 			if (!scontext)
1331 				return 0;
1332 			scontextp = kmemdup(s, *scontext_len, GFP_ATOMIC);
1333 			if (!scontextp)
1334 				return -ENOMEM;
1335 			*scontext = scontextp;
1336 			return 0;
1337 		}
1338 		pr_err("SELinux: %s:  called before initial "
1339 		       "load_policy on unknown SID %d\n", __func__, sid);
1340 		return -EINVAL;
1341 	}
1342 	rcu_read_lock();
1343 	policy = rcu_dereference(selinux_state.policy);
1344 	policydb = &policy->policydb;
1345 	sidtab = policy->sidtab;
1346 
1347 	if (force)
1348 		entry = sidtab_search_entry_force(sidtab, sid);
1349 	else
1350 		entry = sidtab_search_entry(sidtab, sid);
1351 	if (!entry) {
1352 		pr_err("SELinux: %s:  unrecognized SID %d\n",
1353 			__func__, sid);
1354 		rc = -EINVAL;
1355 		goto out_unlock;
1356 	}
1357 	if (only_invalid && !entry->context.len)
1358 		goto out_unlock;
1359 
1360 	rc = sidtab_entry_to_string(policydb, sidtab, entry, scontext,
1361 				    scontext_len);
1362 
1363 out_unlock:
1364 	rcu_read_unlock();
1365 	return rc;
1366 
1367 }
1368 
1369 /**
1370  * security_sid_to_context - Obtain a context for a given SID.
1371  * @sid: security identifier, SID
1372  * @scontext: security context
1373  * @scontext_len: length in bytes
1374  *
1375  * Write the string representation of the context associated with @sid
1376  * into a dynamically allocated string of the correct size.  Set @scontext
1377  * to point to this string and set @scontext_len to the length of the string.
1378  */
1379 int security_sid_to_context(u32 sid, char **scontext, u32 *scontext_len)
1380 {
1381 	return security_sid_to_context_core(sid, scontext,
1382 					    scontext_len, 0, 0);
1383 }
1384 
1385 int security_sid_to_context_force(u32 sid,
1386 				  char **scontext, u32 *scontext_len)
1387 {
1388 	return security_sid_to_context_core(sid, scontext,
1389 					    scontext_len, 1, 0);
1390 }
1391 
1392 /**
1393  * security_sid_to_context_inval - Obtain a context for a given SID if it
1394  *                                 is invalid.
1395  * @sid: security identifier, SID
1396  * @scontext: security context
1397  * @scontext_len: length in bytes
1398  *
1399  * Write the string representation of the context associated with @sid
1400  * into a dynamically allocated string of the correct size, but only if the
1401  * context is invalid in the current policy.  Set @scontext to point to
1402  * this string (or NULL if the context is valid) and set @scontext_len to
1403  * the length of the string (or 0 if the context is valid).
1404  */
1405 int security_sid_to_context_inval(u32 sid,
1406 				  char **scontext, u32 *scontext_len)
1407 {
1408 	return security_sid_to_context_core(sid, scontext,
1409 					    scontext_len, 1, 1);
1410 }
1411 
1412 /*
1413  * Caveat:  Mutates scontext.
1414  */
1415 static int string_to_context_struct(struct policydb *pol,
1416 				    struct sidtab *sidtabp,
1417 				    char *scontext,
1418 				    struct context *ctx,
1419 				    u32 def_sid)
1420 {
1421 	struct role_datum *role;
1422 	struct type_datum *typdatum;
1423 	struct user_datum *usrdatum;
1424 	char *scontextp, *p, oldc;
1425 	int rc = 0;
1426 
1427 	context_init(ctx);
1428 
1429 	/* Parse the security context. */
1430 
1431 	rc = -EINVAL;
1432 	scontextp = scontext;
1433 
1434 	/* Extract the user. */
1435 	p = scontextp;
1436 	while (*p && *p != ':')
1437 		p++;
1438 
1439 	if (*p == 0)
1440 		goto out;
1441 
1442 	*p++ = 0;
1443 
1444 	usrdatum = symtab_search(&pol->p_users, scontextp);
1445 	if (!usrdatum)
1446 		goto out;
1447 
1448 	ctx->user = usrdatum->value;
1449 
1450 	/* Extract role. */
1451 	scontextp = p;
1452 	while (*p && *p != ':')
1453 		p++;
1454 
1455 	if (*p == 0)
1456 		goto out;
1457 
1458 	*p++ = 0;
1459 
1460 	role = symtab_search(&pol->p_roles, scontextp);
1461 	if (!role)
1462 		goto out;
1463 	ctx->role = role->value;
1464 
1465 	/* Extract type. */
1466 	scontextp = p;
1467 	while (*p && *p != ':')
1468 		p++;
1469 	oldc = *p;
1470 	*p++ = 0;
1471 
1472 	typdatum = symtab_search(&pol->p_types, scontextp);
1473 	if (!typdatum || typdatum->attribute)
1474 		goto out;
1475 
1476 	ctx->type = typdatum->value;
1477 
1478 	rc = mls_context_to_sid(pol, oldc, p, ctx, sidtabp, def_sid);
1479 	if (rc)
1480 		goto out;
1481 
1482 	/* Check the validity of the new context. */
1483 	rc = -EINVAL;
1484 	if (!policydb_context_isvalid(pol, ctx))
1485 		goto out;
1486 	rc = 0;
1487 out:
1488 	if (rc)
1489 		context_destroy(ctx);
1490 	return rc;
1491 }
1492 
1493 static int security_context_to_sid_core(const char *scontext, u32 scontext_len,
1494 					u32 *sid, u32 def_sid, gfp_t gfp_flags,
1495 					int force)
1496 {
1497 	struct selinux_policy *policy;
1498 	struct policydb *policydb;
1499 	struct sidtab *sidtab;
1500 	char *scontext2, *str = NULL;
1501 	struct context context;
1502 	int rc = 0;
1503 
1504 	/* An empty security context is never valid. */
1505 	if (!scontext_len)
1506 		return -EINVAL;
1507 
1508 	/* Copy the string to allow changes and ensure a NUL terminator */
1509 	scontext2 = kmemdup_nul(scontext, scontext_len, gfp_flags);
1510 	if (!scontext2)
1511 		return -ENOMEM;
1512 
1513 	if (!selinux_initialized()) {
1514 		u32 i;
1515 
1516 		for (i = 1; i < SECINITSID_NUM; i++) {
1517 			const char *s = initial_sid_to_string[i];
1518 
1519 			if (s && !strcmp(s, scontext2)) {
1520 				*sid = i;
1521 				goto out;
1522 			}
1523 		}
1524 		*sid = SECINITSID_KERNEL;
1525 		goto out;
1526 	}
1527 	*sid = SECSID_NULL;
1528 
1529 	if (force) {
1530 		/* Save another copy for storing in uninterpreted form */
1531 		rc = -ENOMEM;
1532 		str = kstrdup(scontext2, gfp_flags);
1533 		if (!str)
1534 			goto out;
1535 	}
1536 retry:
1537 	rcu_read_lock();
1538 	policy = rcu_dereference(selinux_state.policy);
1539 	policydb = &policy->policydb;
1540 	sidtab = policy->sidtab;
1541 	rc = string_to_context_struct(policydb, sidtab, scontext2,
1542 				      &context, def_sid);
1543 	if (rc == -EINVAL && force) {
1544 		context.str = str;
1545 		context.len = strlen(str) + 1;
1546 		str = NULL;
1547 	} else if (rc)
1548 		goto out_unlock;
1549 	rc = sidtab_context_to_sid(sidtab, &context, sid);
1550 	if (rc == -ESTALE) {
1551 		rcu_read_unlock();
1552 		if (context.str) {
1553 			str = context.str;
1554 			context.str = NULL;
1555 		}
1556 		context_destroy(&context);
1557 		goto retry;
1558 	}
1559 	context_destroy(&context);
1560 out_unlock:
1561 	rcu_read_unlock();
1562 out:
1563 	kfree(scontext2);
1564 	kfree(str);
1565 	return rc;
1566 }
1567 
1568 /**
1569  * security_context_to_sid - Obtain a SID for a given security context.
1570  * @scontext: security context
1571  * @scontext_len: length in bytes
1572  * @sid: security identifier, SID
1573  * @gfp: context for the allocation
1574  *
1575  * Obtains a SID associated with the security context that
1576  * has the string representation specified by @scontext.
1577  * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1578  * memory is available, or 0 on success.
1579  */
1580 int security_context_to_sid(const char *scontext, u32 scontext_len, u32 *sid,
1581 			    gfp_t gfp)
1582 {
1583 	return security_context_to_sid_core(scontext, scontext_len,
1584 					    sid, SECSID_NULL, gfp, 0);
1585 }
1586 
1587 int security_context_str_to_sid(const char *scontext, u32 *sid, gfp_t gfp)
1588 {
1589 	return security_context_to_sid(scontext, strlen(scontext),
1590 				       sid, gfp);
1591 }
1592 
1593 /**
1594  * security_context_to_sid_default - Obtain a SID for a given security context,
1595  * falling back to specified default if needed.
1596  *
1597  * @scontext: security context
1598  * @scontext_len: length in bytes
1599  * @sid: security identifier, SID
1600  * @def_sid: default SID to assign on error
1601  * @gfp_flags: the allocator get-free-page (GFP) flags
1602  *
1603  * Obtains a SID associated with the security context that
1604  * has the string representation specified by @scontext.
1605  * The default SID is passed to the MLS layer to be used to allow
1606  * kernel labeling of the MLS field if the MLS field is not present
1607  * (for upgrading to MLS without full relabel).
1608  * Implicitly forces adding of the context even if it cannot be mapped yet.
1609  * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1610  * memory is available, or 0 on success.
1611  */
1612 int security_context_to_sid_default(const char *scontext, u32 scontext_len,
1613 				    u32 *sid, u32 def_sid, gfp_t gfp_flags)
1614 {
1615 	return security_context_to_sid_core(scontext, scontext_len,
1616 					    sid, def_sid, gfp_flags, 1);
1617 }
1618 
1619 int security_context_to_sid_force(const char *scontext, u32 scontext_len,
1620 				  u32 *sid)
1621 {
1622 	return security_context_to_sid_core(scontext, scontext_len,
1623 					    sid, SECSID_NULL, GFP_KERNEL, 1);
1624 }
1625 
1626 static int compute_sid_handle_invalid_context(
1627 	struct selinux_policy *policy,
1628 	struct sidtab_entry *sentry,
1629 	struct sidtab_entry *tentry,
1630 	u16 tclass,
1631 	struct context *newcontext)
1632 {
1633 	struct policydb *policydb = &policy->policydb;
1634 	struct sidtab *sidtab = policy->sidtab;
1635 	char *s = NULL, *t = NULL, *n = NULL;
1636 	u32 slen, tlen, nlen;
1637 	struct audit_buffer *ab;
1638 
1639 	if (sidtab_entry_to_string(policydb, sidtab, sentry, &s, &slen))
1640 		goto out;
1641 	if (sidtab_entry_to_string(policydb, sidtab, tentry, &t, &tlen))
1642 		goto out;
1643 	if (context_struct_to_string(policydb, newcontext, &n, &nlen))
1644 		goto out;
1645 	ab = audit_log_start(audit_context(), GFP_ATOMIC, AUDIT_SELINUX_ERR);
1646 	if (!ab)
1647 		goto out;
1648 	audit_log_format(ab,
1649 			 "op=security_compute_sid invalid_context=");
1650 	/* no need to record the NUL with untrusted strings */
1651 	audit_log_n_untrustedstring(ab, n, nlen - 1);
1652 	audit_log_format(ab, " scontext=%s tcontext=%s tclass=%s",
1653 			 s, t, sym_name(policydb, SYM_CLASSES, tclass-1));
1654 	audit_log_end(ab);
1655 out:
1656 	kfree(s);
1657 	kfree(t);
1658 	kfree(n);
1659 	if (!enforcing_enabled())
1660 		return 0;
1661 	return -EACCES;
1662 }
1663 
1664 static void filename_compute_type(struct policydb *policydb,
1665 				  struct context *newcontext,
1666 				  u32 stype, u32 ttype, u16 tclass,
1667 				  const char *objname)
1668 {
1669 	struct filename_trans_key ft;
1670 	struct filename_trans_datum *datum;
1671 
1672 	/*
1673 	 * Most filename trans rules are going to live in specific directories
1674 	 * like /dev or /var/run.  This bitmap will quickly skip rule searches
1675 	 * if the ttype does not contain any rules.
1676 	 */
1677 	if (!ebitmap_get_bit(&policydb->filename_trans_ttypes, ttype))
1678 		return;
1679 
1680 	ft.ttype = ttype;
1681 	ft.tclass = tclass;
1682 	ft.name = objname;
1683 
1684 	datum = policydb_filenametr_search(policydb, &ft);
1685 	while (datum) {
1686 		if (ebitmap_get_bit(&datum->stypes, stype - 1)) {
1687 			newcontext->type = datum->otype;
1688 			return;
1689 		}
1690 		datum = datum->next;
1691 	}
1692 }
1693 
1694 static int security_compute_sid(u32 ssid,
1695 				u32 tsid,
1696 				u16 orig_tclass,
1697 				u16 specified,
1698 				const char *objname,
1699 				u32 *out_sid,
1700 				bool kern)
1701 {
1702 	struct selinux_policy *policy;
1703 	struct policydb *policydb;
1704 	struct sidtab *sidtab;
1705 	struct class_datum *cladatum;
1706 	struct context *scontext, *tcontext, newcontext;
1707 	struct sidtab_entry *sentry, *tentry;
1708 	struct avtab_key avkey;
1709 	struct avtab_node *avnode, *node;
1710 	u16 tclass;
1711 	int rc = 0;
1712 	bool sock;
1713 
1714 	if (!selinux_initialized()) {
1715 		switch (orig_tclass) {
1716 		case SECCLASS_PROCESS: /* kernel value */
1717 			*out_sid = ssid;
1718 			break;
1719 		default:
1720 			*out_sid = tsid;
1721 			break;
1722 		}
1723 		goto out;
1724 	}
1725 
1726 retry:
1727 	cladatum = NULL;
1728 	context_init(&newcontext);
1729 
1730 	rcu_read_lock();
1731 
1732 	policy = rcu_dereference(selinux_state.policy);
1733 
1734 	if (kern) {
1735 		tclass = unmap_class(&policy->map, orig_tclass);
1736 		sock = security_is_socket_class(orig_tclass);
1737 	} else {
1738 		tclass = orig_tclass;
1739 		sock = security_is_socket_class(map_class(&policy->map,
1740 							  tclass));
1741 	}
1742 
1743 	policydb = &policy->policydb;
1744 	sidtab = policy->sidtab;
1745 
1746 	sentry = sidtab_search_entry(sidtab, ssid);
1747 	if (!sentry) {
1748 		pr_err("SELinux: %s:  unrecognized SID %d\n",
1749 		       __func__, ssid);
1750 		rc = -EINVAL;
1751 		goto out_unlock;
1752 	}
1753 	tentry = sidtab_search_entry(sidtab, tsid);
1754 	if (!tentry) {
1755 		pr_err("SELinux: %s:  unrecognized SID %d\n",
1756 		       __func__, tsid);
1757 		rc = -EINVAL;
1758 		goto out_unlock;
1759 	}
1760 
1761 	scontext = &sentry->context;
1762 	tcontext = &tentry->context;
1763 
1764 	if (tclass && tclass <= policydb->p_classes.nprim)
1765 		cladatum = policydb->class_val_to_struct[tclass - 1];
1766 
1767 	/* Set the user identity. */
1768 	switch (specified) {
1769 	case AVTAB_TRANSITION:
1770 	case AVTAB_CHANGE:
1771 		if (cladatum && cladatum->default_user == DEFAULT_TARGET) {
1772 			newcontext.user = tcontext->user;
1773 		} else {
1774 			/* notice this gets both DEFAULT_SOURCE and unset */
1775 			/* Use the process user identity. */
1776 			newcontext.user = scontext->user;
1777 		}
1778 		break;
1779 	case AVTAB_MEMBER:
1780 		/* Use the related object owner. */
1781 		newcontext.user = tcontext->user;
1782 		break;
1783 	}
1784 
1785 	/* Set the role to default values. */
1786 	if (cladatum && cladatum->default_role == DEFAULT_SOURCE) {
1787 		newcontext.role = scontext->role;
1788 	} else if (cladatum && cladatum->default_role == DEFAULT_TARGET) {
1789 		newcontext.role = tcontext->role;
1790 	} else {
1791 		if ((tclass == policydb->process_class) || sock)
1792 			newcontext.role = scontext->role;
1793 		else
1794 			newcontext.role = OBJECT_R_VAL;
1795 	}
1796 
1797 	/* Set the type to default values. */
1798 	if (cladatum && cladatum->default_type == DEFAULT_SOURCE) {
1799 		newcontext.type = scontext->type;
1800 	} else if (cladatum && cladatum->default_type == DEFAULT_TARGET) {
1801 		newcontext.type = tcontext->type;
1802 	} else {
1803 		if ((tclass == policydb->process_class) || sock) {
1804 			/* Use the type of process. */
1805 			newcontext.type = scontext->type;
1806 		} else {
1807 			/* Use the type of the related object. */
1808 			newcontext.type = tcontext->type;
1809 		}
1810 	}
1811 
1812 	/* Look for a type transition/member/change rule. */
1813 	avkey.source_type = scontext->type;
1814 	avkey.target_type = tcontext->type;
1815 	avkey.target_class = tclass;
1816 	avkey.specified = specified;
1817 	avnode = avtab_search_node(&policydb->te_avtab, &avkey);
1818 
1819 	/* If no permanent rule, also check for enabled conditional rules */
1820 	if (!avnode) {
1821 		node = avtab_search_node(&policydb->te_cond_avtab, &avkey);
1822 		for (; node; node = avtab_search_node_next(node, specified)) {
1823 			if (node->key.specified & AVTAB_ENABLED) {
1824 				avnode = node;
1825 				break;
1826 			}
1827 		}
1828 	}
1829 
1830 	if (avnode) {
1831 		/* Use the type from the type transition/member/change rule. */
1832 		newcontext.type = avnode->datum.u.data;
1833 	}
1834 
1835 	/* if we have a objname this is a file trans check so check those rules */
1836 	if (objname)
1837 		filename_compute_type(policydb, &newcontext, scontext->type,
1838 				      tcontext->type, tclass, objname);
1839 
1840 	/* Check for class-specific changes. */
1841 	if (specified & AVTAB_TRANSITION) {
1842 		/* Look for a role transition rule. */
1843 		struct role_trans_datum *rtd;
1844 		struct role_trans_key rtk = {
1845 			.role = scontext->role,
1846 			.type = tcontext->type,
1847 			.tclass = tclass,
1848 		};
1849 
1850 		rtd = policydb_roletr_search(policydb, &rtk);
1851 		if (rtd)
1852 			newcontext.role = rtd->new_role;
1853 	}
1854 
1855 	/* Set the MLS attributes.
1856 	   This is done last because it may allocate memory. */
1857 	rc = mls_compute_sid(policydb, scontext, tcontext, tclass, specified,
1858 			     &newcontext, sock);
1859 	if (rc)
1860 		goto out_unlock;
1861 
1862 	/* Check the validity of the context. */
1863 	if (!policydb_context_isvalid(policydb, &newcontext)) {
1864 		rc = compute_sid_handle_invalid_context(policy, sentry,
1865 							tentry, tclass,
1866 							&newcontext);
1867 		if (rc)
1868 			goto out_unlock;
1869 	}
1870 	/* Obtain the sid for the context. */
1871 	rc = sidtab_context_to_sid(sidtab, &newcontext, out_sid);
1872 	if (rc == -ESTALE) {
1873 		rcu_read_unlock();
1874 		context_destroy(&newcontext);
1875 		goto retry;
1876 	}
1877 out_unlock:
1878 	rcu_read_unlock();
1879 	context_destroy(&newcontext);
1880 out:
1881 	return rc;
1882 }
1883 
1884 /**
1885  * security_transition_sid - Compute the SID for a new subject/object.
1886  * @ssid: source security identifier
1887  * @tsid: target security identifier
1888  * @tclass: target security class
1889  * @qstr: object name
1890  * @out_sid: security identifier for new subject/object
1891  *
1892  * Compute a SID to use for labeling a new subject or object in the
1893  * class @tclass based on a SID pair (@ssid, @tsid).
1894  * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1895  * if insufficient memory is available, or %0 if the new SID was
1896  * computed successfully.
1897  */
1898 int security_transition_sid(u32 ssid, u32 tsid, u16 tclass,
1899 			    const struct qstr *qstr, u32 *out_sid)
1900 {
1901 	return security_compute_sid(ssid, tsid, tclass,
1902 				    AVTAB_TRANSITION,
1903 				    qstr ? qstr->name : NULL, out_sid, true);
1904 }
1905 
1906 int security_transition_sid_user(u32 ssid, u32 tsid, u16 tclass,
1907 				 const char *objname, u32 *out_sid)
1908 {
1909 	return security_compute_sid(ssid, tsid, tclass,
1910 				    AVTAB_TRANSITION,
1911 				    objname, out_sid, false);
1912 }
1913 
1914 /**
1915  * security_member_sid - Compute the SID for member selection.
1916  * @ssid: source security identifier
1917  * @tsid: target security identifier
1918  * @tclass: target security class
1919  * @out_sid: security identifier for selected member
1920  *
1921  * Compute a SID to use when selecting a member of a polyinstantiated
1922  * object of class @tclass based on a SID pair (@ssid, @tsid).
1923  * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1924  * if insufficient memory is available, or %0 if the SID was
1925  * computed successfully.
1926  */
1927 int security_member_sid(u32 ssid,
1928 			u32 tsid,
1929 			u16 tclass,
1930 			u32 *out_sid)
1931 {
1932 	return security_compute_sid(ssid, tsid, tclass,
1933 				    AVTAB_MEMBER, NULL,
1934 				    out_sid, false);
1935 }
1936 
1937 /**
1938  * security_change_sid - Compute the SID for object relabeling.
1939  * @ssid: source security identifier
1940  * @tsid: target security identifier
1941  * @tclass: target security class
1942  * @out_sid: security identifier for selected member
1943  *
1944  * Compute a SID to use for relabeling an object of class @tclass
1945  * based on a SID pair (@ssid, @tsid).
1946  * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1947  * if insufficient memory is available, or %0 if the SID was
1948  * computed successfully.
1949  */
1950 int security_change_sid(u32 ssid,
1951 			u32 tsid,
1952 			u16 tclass,
1953 			u32 *out_sid)
1954 {
1955 	return security_compute_sid(ssid, tsid, tclass, AVTAB_CHANGE, NULL,
1956 				    out_sid, false);
1957 }
1958 
1959 static inline int convert_context_handle_invalid_context(
1960 	struct policydb *policydb,
1961 	struct context *context)
1962 {
1963 	char *s;
1964 	u32 len;
1965 
1966 	if (enforcing_enabled())
1967 		return -EINVAL;
1968 
1969 	if (!context_struct_to_string(policydb, context, &s, &len)) {
1970 		pr_warn("SELinux:  Context %s would be invalid if enforcing\n",
1971 			s);
1972 		kfree(s);
1973 	}
1974 	return 0;
1975 }
1976 
1977 /**
1978  * services_convert_context - Convert a security context across policies.
1979  * @args: populated convert_context_args struct
1980  * @oldc: original context
1981  * @newc: converted context
1982  * @gfp_flags: allocation flags
1983  *
1984  * Convert the values in the security context structure @oldc from the values
1985  * specified in the policy @args->oldp to the values specified in the policy
1986  * @args->newp, storing the new context in @newc, and verifying that the
1987  * context is valid under the new policy.
1988  */
1989 int services_convert_context(struct convert_context_args *args,
1990 			     struct context *oldc, struct context *newc,
1991 			     gfp_t gfp_flags)
1992 {
1993 	struct ocontext *oc;
1994 	struct role_datum *role;
1995 	struct type_datum *typdatum;
1996 	struct user_datum *usrdatum;
1997 	char *s;
1998 	u32 len;
1999 	int rc;
2000 
2001 	if (oldc->str) {
2002 		s = kstrdup(oldc->str, gfp_flags);
2003 		if (!s)
2004 			return -ENOMEM;
2005 
2006 		rc = string_to_context_struct(args->newp, NULL, s, newc, SECSID_NULL);
2007 		if (rc == -EINVAL) {
2008 			/*
2009 			 * Retain string representation for later mapping.
2010 			 *
2011 			 * IMPORTANT: We need to copy the contents of oldc->str
2012 			 * back into s again because string_to_context_struct()
2013 			 * may have garbled it.
2014 			 */
2015 			memcpy(s, oldc->str, oldc->len);
2016 			context_init(newc);
2017 			newc->str = s;
2018 			newc->len = oldc->len;
2019 			return 0;
2020 		}
2021 		kfree(s);
2022 		if (rc) {
2023 			/* Other error condition, e.g. ENOMEM. */
2024 			pr_err("SELinux:   Unable to map context %s, rc = %d.\n",
2025 			       oldc->str, -rc);
2026 			return rc;
2027 		}
2028 		pr_info("SELinux:  Context %s became valid (mapped).\n",
2029 			oldc->str);
2030 		return 0;
2031 	}
2032 
2033 	context_init(newc);
2034 
2035 	/* Convert the user. */
2036 	usrdatum = symtab_search(&args->newp->p_users,
2037 				 sym_name(args->oldp, SYM_USERS, oldc->user - 1));
2038 	if (!usrdatum)
2039 		goto bad;
2040 	newc->user = usrdatum->value;
2041 
2042 	/* Convert the role. */
2043 	role = symtab_search(&args->newp->p_roles,
2044 			     sym_name(args->oldp, SYM_ROLES, oldc->role - 1));
2045 	if (!role)
2046 		goto bad;
2047 	newc->role = role->value;
2048 
2049 	/* Convert the type. */
2050 	typdatum = symtab_search(&args->newp->p_types,
2051 				 sym_name(args->oldp, SYM_TYPES, oldc->type - 1));
2052 	if (!typdatum)
2053 		goto bad;
2054 	newc->type = typdatum->value;
2055 
2056 	/* Convert the MLS fields if dealing with MLS policies */
2057 	if (args->oldp->mls_enabled && args->newp->mls_enabled) {
2058 		rc = mls_convert_context(args->oldp, args->newp, oldc, newc);
2059 		if (rc)
2060 			goto bad;
2061 	} else if (!args->oldp->mls_enabled && args->newp->mls_enabled) {
2062 		/*
2063 		 * Switching between non-MLS and MLS policy:
2064 		 * ensure that the MLS fields of the context for all
2065 		 * existing entries in the sidtab are filled in with a
2066 		 * suitable default value, likely taken from one of the
2067 		 * initial SIDs.
2068 		 */
2069 		oc = args->newp->ocontexts[OCON_ISID];
2070 		while (oc && oc->sid[0] != SECINITSID_UNLABELED)
2071 			oc = oc->next;
2072 		if (!oc) {
2073 			pr_err("SELinux:  unable to look up"
2074 				" the initial SIDs list\n");
2075 			goto bad;
2076 		}
2077 		rc = mls_range_set(newc, &oc->context[0].range);
2078 		if (rc)
2079 			goto bad;
2080 	}
2081 
2082 	/* Check the validity of the new context. */
2083 	if (!policydb_context_isvalid(args->newp, newc)) {
2084 		rc = convert_context_handle_invalid_context(args->oldp, oldc);
2085 		if (rc)
2086 			goto bad;
2087 	}
2088 
2089 	return 0;
2090 bad:
2091 	/* Map old representation to string and save it. */
2092 	rc = context_struct_to_string(args->oldp, oldc, &s, &len);
2093 	if (rc)
2094 		return rc;
2095 	context_destroy(newc);
2096 	newc->str = s;
2097 	newc->len = len;
2098 	pr_info("SELinux:  Context %s became invalid (unmapped).\n",
2099 		newc->str);
2100 	return 0;
2101 }
2102 
2103 static void security_load_policycaps(struct selinux_policy *policy)
2104 {
2105 	struct policydb *p;
2106 	unsigned int i;
2107 	struct ebitmap_node *node;
2108 
2109 	p = &policy->policydb;
2110 
2111 	for (i = 0; i < ARRAY_SIZE(selinux_state.policycap); i++)
2112 		WRITE_ONCE(selinux_state.policycap[i],
2113 			ebitmap_get_bit(&p->policycaps, i));
2114 
2115 	for (i = 0; i < ARRAY_SIZE(selinux_policycap_names); i++)
2116 		pr_info("SELinux:  policy capability %s=%d\n",
2117 			selinux_policycap_names[i],
2118 			ebitmap_get_bit(&p->policycaps, i));
2119 
2120 	ebitmap_for_each_positive_bit(&p->policycaps, node, i) {
2121 		if (i >= ARRAY_SIZE(selinux_policycap_names))
2122 			pr_info("SELinux:  unknown policy capability %u\n",
2123 				i);
2124 	}
2125 }
2126 
2127 static int security_preserve_bools(struct selinux_policy *oldpolicy,
2128 				struct selinux_policy *newpolicy);
2129 
2130 static void selinux_policy_free(struct selinux_policy *policy)
2131 {
2132 	if (!policy)
2133 		return;
2134 
2135 	sidtab_destroy(policy->sidtab);
2136 	kfree(policy->map.mapping);
2137 	policydb_destroy(&policy->policydb);
2138 	kfree(policy->sidtab);
2139 	kfree(policy);
2140 }
2141 
2142 static void selinux_policy_cond_free(struct selinux_policy *policy)
2143 {
2144 	cond_policydb_destroy_dup(&policy->policydb);
2145 	kfree(policy);
2146 }
2147 
2148 void selinux_policy_cancel(struct selinux_load_state *load_state)
2149 {
2150 	struct selinux_state *state = &selinux_state;
2151 	struct selinux_policy *oldpolicy;
2152 
2153 	oldpolicy = rcu_dereference_protected(state->policy,
2154 					lockdep_is_held(&state->policy_mutex));
2155 
2156 	sidtab_cancel_convert(oldpolicy->sidtab);
2157 	selinux_policy_free(load_state->policy);
2158 	kfree(load_state->convert_data);
2159 }
2160 
2161 static void selinux_notify_policy_change(u32 seqno)
2162 {
2163 	/* Flush external caches and notify userspace of policy load */
2164 	avc_ss_reset(seqno);
2165 	selnl_notify_policyload(seqno);
2166 	selinux_status_update_policyload(seqno);
2167 	selinux_netlbl_cache_invalidate();
2168 	selinux_xfrm_notify_policyload();
2169 	selinux_ima_measure_state_locked();
2170 }
2171 
2172 void selinux_policy_commit(struct selinux_load_state *load_state)
2173 {
2174 	struct selinux_state *state = &selinux_state;
2175 	struct selinux_policy *oldpolicy, *newpolicy = load_state->policy;
2176 	unsigned long flags;
2177 	u32 seqno;
2178 
2179 	oldpolicy = rcu_dereference_protected(state->policy,
2180 					lockdep_is_held(&state->policy_mutex));
2181 
2182 	/* If switching between different policy types, log MLS status */
2183 	if (oldpolicy) {
2184 		if (oldpolicy->policydb.mls_enabled && !newpolicy->policydb.mls_enabled)
2185 			pr_info("SELinux: Disabling MLS support...\n");
2186 		else if (!oldpolicy->policydb.mls_enabled && newpolicy->policydb.mls_enabled)
2187 			pr_info("SELinux: Enabling MLS support...\n");
2188 	}
2189 
2190 	/* Set latest granting seqno for new policy. */
2191 	if (oldpolicy)
2192 		newpolicy->latest_granting = oldpolicy->latest_granting + 1;
2193 	else
2194 		newpolicy->latest_granting = 1;
2195 	seqno = newpolicy->latest_granting;
2196 
2197 	/* Install the new policy. */
2198 	if (oldpolicy) {
2199 		sidtab_freeze_begin(oldpolicy->sidtab, &flags);
2200 		rcu_assign_pointer(state->policy, newpolicy);
2201 		sidtab_freeze_end(oldpolicy->sidtab, &flags);
2202 	} else {
2203 		rcu_assign_pointer(state->policy, newpolicy);
2204 	}
2205 
2206 	/* Load the policycaps from the new policy */
2207 	security_load_policycaps(newpolicy);
2208 
2209 	if (!selinux_initialized()) {
2210 		/*
2211 		 * After first policy load, the security server is
2212 		 * marked as initialized and ready to handle requests and
2213 		 * any objects created prior to policy load are then labeled.
2214 		 */
2215 		selinux_mark_initialized();
2216 		selinux_complete_init();
2217 	}
2218 
2219 	/* Free the old policy */
2220 	synchronize_rcu();
2221 	selinux_policy_free(oldpolicy);
2222 	kfree(load_state->convert_data);
2223 
2224 	/* Notify others of the policy change */
2225 	selinux_notify_policy_change(seqno);
2226 }
2227 
2228 /**
2229  * security_load_policy - Load a security policy configuration.
2230  * @data: binary policy data
2231  * @len: length of data in bytes
2232  * @load_state: policy load state
2233  *
2234  * Load a new set of security policy configuration data,
2235  * validate it and convert the SID table as necessary.
2236  * This function will flush the access vector cache after
2237  * loading the new policy.
2238  */
2239 int security_load_policy(void *data, size_t len,
2240 			 struct selinux_load_state *load_state)
2241 {
2242 	struct selinux_state *state = &selinux_state;
2243 	struct selinux_policy *newpolicy, *oldpolicy;
2244 	struct selinux_policy_convert_data *convert_data;
2245 	int rc = 0;
2246 	struct policy_file file = { data, len }, *fp = &file;
2247 
2248 	newpolicy = kzalloc(sizeof(*newpolicy), GFP_KERNEL);
2249 	if (!newpolicy)
2250 		return -ENOMEM;
2251 
2252 	newpolicy->sidtab = kzalloc(sizeof(*newpolicy->sidtab), GFP_KERNEL);
2253 	if (!newpolicy->sidtab) {
2254 		rc = -ENOMEM;
2255 		goto err_policy;
2256 	}
2257 
2258 	rc = policydb_read(&newpolicy->policydb, fp);
2259 	if (rc)
2260 		goto err_sidtab;
2261 
2262 	newpolicy->policydb.len = len;
2263 	rc = selinux_set_mapping(&newpolicy->policydb, secclass_map,
2264 				&newpolicy->map);
2265 	if (rc)
2266 		goto err_policydb;
2267 
2268 	rc = policydb_load_isids(&newpolicy->policydb, newpolicy->sidtab);
2269 	if (rc) {
2270 		pr_err("SELinux:  unable to load the initial SIDs\n");
2271 		goto err_mapping;
2272 	}
2273 
2274 	if (!selinux_initialized()) {
2275 		/* First policy load, so no need to preserve state from old policy */
2276 		load_state->policy = newpolicy;
2277 		load_state->convert_data = NULL;
2278 		return 0;
2279 	}
2280 
2281 	oldpolicy = rcu_dereference_protected(state->policy,
2282 					lockdep_is_held(&state->policy_mutex));
2283 
2284 	/* Preserve active boolean values from the old policy */
2285 	rc = security_preserve_bools(oldpolicy, newpolicy);
2286 	if (rc) {
2287 		pr_err("SELinux:  unable to preserve booleans\n");
2288 		goto err_free_isids;
2289 	}
2290 
2291 	/*
2292 	 * Convert the internal representations of contexts
2293 	 * in the new SID table.
2294 	 */
2295 
2296 	convert_data = kmalloc(sizeof(*convert_data), GFP_KERNEL);
2297 	if (!convert_data) {
2298 		rc = -ENOMEM;
2299 		goto err_free_isids;
2300 	}
2301 
2302 	convert_data->args.oldp = &oldpolicy->policydb;
2303 	convert_data->args.newp = &newpolicy->policydb;
2304 
2305 	convert_data->sidtab_params.args = &convert_data->args;
2306 	convert_data->sidtab_params.target = newpolicy->sidtab;
2307 
2308 	rc = sidtab_convert(oldpolicy->sidtab, &convert_data->sidtab_params);
2309 	if (rc) {
2310 		pr_err("SELinux:  unable to convert the internal"
2311 			" representation of contexts in the new SID"
2312 			" table\n");
2313 		goto err_free_convert_data;
2314 	}
2315 
2316 	load_state->policy = newpolicy;
2317 	load_state->convert_data = convert_data;
2318 	return 0;
2319 
2320 err_free_convert_data:
2321 	kfree(convert_data);
2322 err_free_isids:
2323 	sidtab_destroy(newpolicy->sidtab);
2324 err_mapping:
2325 	kfree(newpolicy->map.mapping);
2326 err_policydb:
2327 	policydb_destroy(&newpolicy->policydb);
2328 err_sidtab:
2329 	kfree(newpolicy->sidtab);
2330 err_policy:
2331 	kfree(newpolicy);
2332 
2333 	return rc;
2334 }
2335 
2336 /**
2337  * ocontext_to_sid - Helper to safely get sid for an ocontext
2338  * @sidtab: SID table
2339  * @c: ocontext structure
2340  * @index: index of the context entry (0 or 1)
2341  * @out_sid: pointer to the resulting SID value
2342  *
2343  * For all ocontexts except OCON_ISID the SID fields are populated
2344  * on-demand when needed. Since updating the SID value is an SMP-sensitive
2345  * operation, this helper must be used to do that safely.
2346  *
2347  * WARNING: This function may return -ESTALE, indicating that the caller
2348  * must retry the operation after re-acquiring the policy pointer!
2349  */
2350 static int ocontext_to_sid(struct sidtab *sidtab, struct ocontext *c,
2351 			   size_t index, u32 *out_sid)
2352 {
2353 	int rc;
2354 	u32 sid;
2355 
2356 	/* Ensure the associated sidtab entry is visible to this thread. */
2357 	sid = smp_load_acquire(&c->sid[index]);
2358 	if (!sid) {
2359 		rc = sidtab_context_to_sid(sidtab, &c->context[index], &sid);
2360 		if (rc)
2361 			return rc;
2362 
2363 		/*
2364 		 * Ensure the new sidtab entry is visible to other threads
2365 		 * when they see the SID.
2366 		 */
2367 		smp_store_release(&c->sid[index], sid);
2368 	}
2369 	*out_sid = sid;
2370 	return 0;
2371 }
2372 
2373 /**
2374  * security_port_sid - Obtain the SID for a port.
2375  * @protocol: protocol number
2376  * @port: port number
2377  * @out_sid: security identifier
2378  */
2379 int security_port_sid(u8 protocol, u16 port, u32 *out_sid)
2380 {
2381 	struct selinux_policy *policy;
2382 	struct policydb *policydb;
2383 	struct sidtab *sidtab;
2384 	struct ocontext *c;
2385 	int rc;
2386 
2387 	if (!selinux_initialized()) {
2388 		*out_sid = SECINITSID_PORT;
2389 		return 0;
2390 	}
2391 
2392 retry:
2393 	rc = 0;
2394 	rcu_read_lock();
2395 	policy = rcu_dereference(selinux_state.policy);
2396 	policydb = &policy->policydb;
2397 	sidtab = policy->sidtab;
2398 
2399 	c = policydb->ocontexts[OCON_PORT];
2400 	while (c) {
2401 		if (c->u.port.protocol == protocol &&
2402 		    c->u.port.low_port <= port &&
2403 		    c->u.port.high_port >= port)
2404 			break;
2405 		c = c->next;
2406 	}
2407 
2408 	if (c) {
2409 		rc = ocontext_to_sid(sidtab, c, 0, out_sid);
2410 		if (rc == -ESTALE) {
2411 			rcu_read_unlock();
2412 			goto retry;
2413 		}
2414 		if (rc)
2415 			goto out;
2416 	} else {
2417 		*out_sid = SECINITSID_PORT;
2418 	}
2419 
2420 out:
2421 	rcu_read_unlock();
2422 	return rc;
2423 }
2424 
2425 /**
2426  * security_ib_pkey_sid - Obtain the SID for a pkey.
2427  * @subnet_prefix: Subnet Prefix
2428  * @pkey_num: pkey number
2429  * @out_sid: security identifier
2430  */
2431 int security_ib_pkey_sid(u64 subnet_prefix, u16 pkey_num, u32 *out_sid)
2432 {
2433 	struct selinux_policy *policy;
2434 	struct policydb *policydb;
2435 	struct sidtab *sidtab;
2436 	struct ocontext *c;
2437 	int rc;
2438 
2439 	if (!selinux_initialized()) {
2440 		*out_sid = SECINITSID_UNLABELED;
2441 		return 0;
2442 	}
2443 
2444 retry:
2445 	rc = 0;
2446 	rcu_read_lock();
2447 	policy = rcu_dereference(selinux_state.policy);
2448 	policydb = &policy->policydb;
2449 	sidtab = policy->sidtab;
2450 
2451 	c = policydb->ocontexts[OCON_IBPKEY];
2452 	while (c) {
2453 		if (c->u.ibpkey.low_pkey <= pkey_num &&
2454 		    c->u.ibpkey.high_pkey >= pkey_num &&
2455 		    c->u.ibpkey.subnet_prefix == subnet_prefix)
2456 			break;
2457 
2458 		c = c->next;
2459 	}
2460 
2461 	if (c) {
2462 		rc = ocontext_to_sid(sidtab, c, 0, out_sid);
2463 		if (rc == -ESTALE) {
2464 			rcu_read_unlock();
2465 			goto retry;
2466 		}
2467 		if (rc)
2468 			goto out;
2469 	} else
2470 		*out_sid = SECINITSID_UNLABELED;
2471 
2472 out:
2473 	rcu_read_unlock();
2474 	return rc;
2475 }
2476 
2477 /**
2478  * security_ib_endport_sid - Obtain the SID for a subnet management interface.
2479  * @dev_name: device name
2480  * @port_num: port number
2481  * @out_sid: security identifier
2482  */
2483 int security_ib_endport_sid(const char *dev_name, u8 port_num, u32 *out_sid)
2484 {
2485 	struct selinux_policy *policy;
2486 	struct policydb *policydb;
2487 	struct sidtab *sidtab;
2488 	struct ocontext *c;
2489 	int rc;
2490 
2491 	if (!selinux_initialized()) {
2492 		*out_sid = SECINITSID_UNLABELED;
2493 		return 0;
2494 	}
2495 
2496 retry:
2497 	rc = 0;
2498 	rcu_read_lock();
2499 	policy = rcu_dereference(selinux_state.policy);
2500 	policydb = &policy->policydb;
2501 	sidtab = policy->sidtab;
2502 
2503 	c = policydb->ocontexts[OCON_IBENDPORT];
2504 	while (c) {
2505 		if (c->u.ibendport.port == port_num &&
2506 		    !strncmp(c->u.ibendport.dev_name,
2507 			     dev_name,
2508 			     IB_DEVICE_NAME_MAX))
2509 			break;
2510 
2511 		c = c->next;
2512 	}
2513 
2514 	if (c) {
2515 		rc = ocontext_to_sid(sidtab, c, 0, out_sid);
2516 		if (rc == -ESTALE) {
2517 			rcu_read_unlock();
2518 			goto retry;
2519 		}
2520 		if (rc)
2521 			goto out;
2522 	} else
2523 		*out_sid = SECINITSID_UNLABELED;
2524 
2525 out:
2526 	rcu_read_unlock();
2527 	return rc;
2528 }
2529 
2530 /**
2531  * security_netif_sid - Obtain the SID for a network interface.
2532  * @name: interface name
2533  * @if_sid: interface SID
2534  */
2535 int security_netif_sid(char *name, u32 *if_sid)
2536 {
2537 	struct selinux_policy *policy;
2538 	struct policydb *policydb;
2539 	struct sidtab *sidtab;
2540 	int rc;
2541 	struct ocontext *c;
2542 
2543 	if (!selinux_initialized()) {
2544 		*if_sid = SECINITSID_NETIF;
2545 		return 0;
2546 	}
2547 
2548 retry:
2549 	rc = 0;
2550 	rcu_read_lock();
2551 	policy = rcu_dereference(selinux_state.policy);
2552 	policydb = &policy->policydb;
2553 	sidtab = policy->sidtab;
2554 
2555 	c = policydb->ocontexts[OCON_NETIF];
2556 	while (c) {
2557 		if (strcmp(name, c->u.name) == 0)
2558 			break;
2559 		c = c->next;
2560 	}
2561 
2562 	if (c) {
2563 		rc = ocontext_to_sid(sidtab, c, 0, if_sid);
2564 		if (rc == -ESTALE) {
2565 			rcu_read_unlock();
2566 			goto retry;
2567 		}
2568 		if (rc)
2569 			goto out;
2570 	} else
2571 		*if_sid = SECINITSID_NETIF;
2572 
2573 out:
2574 	rcu_read_unlock();
2575 	return rc;
2576 }
2577 
2578 static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask)
2579 {
2580 	int i, fail = 0;
2581 
2582 	for (i = 0; i < 4; i++)
2583 		if (addr[i] != (input[i] & mask[i])) {
2584 			fail = 1;
2585 			break;
2586 		}
2587 
2588 	return !fail;
2589 }
2590 
2591 /**
2592  * security_node_sid - Obtain the SID for a node (host).
2593  * @domain: communication domain aka address family
2594  * @addrp: address
2595  * @addrlen: address length in bytes
2596  * @out_sid: security identifier
2597  */
2598 int security_node_sid(u16 domain,
2599 		      void *addrp,
2600 		      u32 addrlen,
2601 		      u32 *out_sid)
2602 {
2603 	struct selinux_policy *policy;
2604 	struct policydb *policydb;
2605 	struct sidtab *sidtab;
2606 	int rc;
2607 	struct ocontext *c;
2608 
2609 	if (!selinux_initialized()) {
2610 		*out_sid = SECINITSID_NODE;
2611 		return 0;
2612 	}
2613 
2614 retry:
2615 	rcu_read_lock();
2616 	policy = rcu_dereference(selinux_state.policy);
2617 	policydb = &policy->policydb;
2618 	sidtab = policy->sidtab;
2619 
2620 	switch (domain) {
2621 	case AF_INET: {
2622 		u32 addr;
2623 
2624 		rc = -EINVAL;
2625 		if (addrlen != sizeof(u32))
2626 			goto out;
2627 
2628 		addr = *((u32 *)addrp);
2629 
2630 		c = policydb->ocontexts[OCON_NODE];
2631 		while (c) {
2632 			if (c->u.node.addr == (addr & c->u.node.mask))
2633 				break;
2634 			c = c->next;
2635 		}
2636 		break;
2637 	}
2638 
2639 	case AF_INET6:
2640 		rc = -EINVAL;
2641 		if (addrlen != sizeof(u64) * 2)
2642 			goto out;
2643 		c = policydb->ocontexts[OCON_NODE6];
2644 		while (c) {
2645 			if (match_ipv6_addrmask(addrp, c->u.node6.addr,
2646 						c->u.node6.mask))
2647 				break;
2648 			c = c->next;
2649 		}
2650 		break;
2651 
2652 	default:
2653 		rc = 0;
2654 		*out_sid = SECINITSID_NODE;
2655 		goto out;
2656 	}
2657 
2658 	if (c) {
2659 		rc = ocontext_to_sid(sidtab, c, 0, out_sid);
2660 		if (rc == -ESTALE) {
2661 			rcu_read_unlock();
2662 			goto retry;
2663 		}
2664 		if (rc)
2665 			goto out;
2666 	} else {
2667 		*out_sid = SECINITSID_NODE;
2668 	}
2669 
2670 	rc = 0;
2671 out:
2672 	rcu_read_unlock();
2673 	return rc;
2674 }
2675 
2676 #define SIDS_NEL 25
2677 
2678 /**
2679  * security_get_user_sids - Obtain reachable SIDs for a user.
2680  * @fromsid: starting SID
2681  * @username: username
2682  * @sids: array of reachable SIDs for user
2683  * @nel: number of elements in @sids
2684  *
2685  * Generate the set of SIDs for legal security contexts
2686  * for a given user that can be reached by @fromsid.
2687  * Set *@sids to point to a dynamically allocated
2688  * array containing the set of SIDs.  Set *@nel to the
2689  * number of elements in the array.
2690  */
2691 
2692 int security_get_user_sids(u32 fromsid,
2693 			   char *username,
2694 			   u32 **sids,
2695 			   u32 *nel)
2696 {
2697 	struct selinux_policy *policy;
2698 	struct policydb *policydb;
2699 	struct sidtab *sidtab;
2700 	struct context *fromcon, usercon;
2701 	u32 *mysids = NULL, *mysids2, sid;
2702 	u32 i, j, mynel, maxnel = SIDS_NEL;
2703 	struct user_datum *user;
2704 	struct role_datum *role;
2705 	struct ebitmap_node *rnode, *tnode;
2706 	int rc;
2707 
2708 	*sids = NULL;
2709 	*nel = 0;
2710 
2711 	if (!selinux_initialized())
2712 		return 0;
2713 
2714 	mysids = kcalloc(maxnel, sizeof(*mysids), GFP_KERNEL);
2715 	if (!mysids)
2716 		return -ENOMEM;
2717 
2718 retry:
2719 	mynel = 0;
2720 	rcu_read_lock();
2721 	policy = rcu_dereference(selinux_state.policy);
2722 	policydb = &policy->policydb;
2723 	sidtab = policy->sidtab;
2724 
2725 	context_init(&usercon);
2726 
2727 	rc = -EINVAL;
2728 	fromcon = sidtab_search(sidtab, fromsid);
2729 	if (!fromcon)
2730 		goto out_unlock;
2731 
2732 	rc = -EINVAL;
2733 	user = symtab_search(&policydb->p_users, username);
2734 	if (!user)
2735 		goto out_unlock;
2736 
2737 	usercon.user = user->value;
2738 
2739 	ebitmap_for_each_positive_bit(&user->roles, rnode, i) {
2740 		role = policydb->role_val_to_struct[i];
2741 		usercon.role = i + 1;
2742 		ebitmap_for_each_positive_bit(&role->types, tnode, j) {
2743 			usercon.type = j + 1;
2744 
2745 			if (mls_setup_user_range(policydb, fromcon, user,
2746 						 &usercon))
2747 				continue;
2748 
2749 			rc = sidtab_context_to_sid(sidtab, &usercon, &sid);
2750 			if (rc == -ESTALE) {
2751 				rcu_read_unlock();
2752 				goto retry;
2753 			}
2754 			if (rc)
2755 				goto out_unlock;
2756 			if (mynel < maxnel) {
2757 				mysids[mynel++] = sid;
2758 			} else {
2759 				rc = -ENOMEM;
2760 				maxnel += SIDS_NEL;
2761 				mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
2762 				if (!mysids2)
2763 					goto out_unlock;
2764 				memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
2765 				kfree(mysids);
2766 				mysids = mysids2;
2767 				mysids[mynel++] = sid;
2768 			}
2769 		}
2770 	}
2771 	rc = 0;
2772 out_unlock:
2773 	rcu_read_unlock();
2774 	if (rc || !mynel) {
2775 		kfree(mysids);
2776 		return rc;
2777 	}
2778 
2779 	rc = -ENOMEM;
2780 	mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);
2781 	if (!mysids2) {
2782 		kfree(mysids);
2783 		return rc;
2784 	}
2785 	for (i = 0, j = 0; i < mynel; i++) {
2786 		struct av_decision dummy_avd;
2787 		rc = avc_has_perm_noaudit(fromsid, mysids[i],
2788 					  SECCLASS_PROCESS, /* kernel value */
2789 					  PROCESS__TRANSITION, AVC_STRICT,
2790 					  &dummy_avd);
2791 		if (!rc)
2792 			mysids2[j++] = mysids[i];
2793 		cond_resched();
2794 	}
2795 	kfree(mysids);
2796 	*sids = mysids2;
2797 	*nel = j;
2798 	return 0;
2799 }
2800 
2801 /**
2802  * __security_genfs_sid - Helper to obtain a SID for a file in a filesystem
2803  * @policy: policy
2804  * @fstype: filesystem type
2805  * @path: path from root of mount
2806  * @orig_sclass: file security class
2807  * @sid: SID for path
2808  *
2809  * Obtain a SID to use for a file in a filesystem that
2810  * cannot support xattr or use a fixed labeling behavior like
2811  * transition SIDs or task SIDs.
2812  *
2813  * WARNING: This function may return -ESTALE, indicating that the caller
2814  * must retry the operation after re-acquiring the policy pointer!
2815  */
2816 static inline int __security_genfs_sid(struct selinux_policy *policy,
2817 				       const char *fstype,
2818 				       const char *path,
2819 				       u16 orig_sclass,
2820 				       u32 *sid)
2821 {
2822 	struct policydb *policydb = &policy->policydb;
2823 	struct sidtab *sidtab = policy->sidtab;
2824 	u16 sclass;
2825 	struct genfs *genfs;
2826 	struct ocontext *c;
2827 	int cmp = 0;
2828 
2829 	while (path[0] == '/' && path[1] == '/')
2830 		path++;
2831 
2832 	sclass = unmap_class(&policy->map, orig_sclass);
2833 	*sid = SECINITSID_UNLABELED;
2834 
2835 	for (genfs = policydb->genfs; genfs; genfs = genfs->next) {
2836 		cmp = strcmp(fstype, genfs->fstype);
2837 		if (cmp <= 0)
2838 			break;
2839 	}
2840 
2841 	if (!genfs || cmp)
2842 		return -ENOENT;
2843 
2844 	for (c = genfs->head; c; c = c->next) {
2845 		size_t len = strlen(c->u.name);
2846 		if ((!c->v.sclass || sclass == c->v.sclass) &&
2847 		    (strncmp(c->u.name, path, len) == 0))
2848 			break;
2849 	}
2850 
2851 	if (!c)
2852 		return -ENOENT;
2853 
2854 	return ocontext_to_sid(sidtab, c, 0, sid);
2855 }
2856 
2857 /**
2858  * security_genfs_sid - Obtain a SID for a file in a filesystem
2859  * @fstype: filesystem type
2860  * @path: path from root of mount
2861  * @orig_sclass: file security class
2862  * @sid: SID for path
2863  *
2864  * Acquire policy_rwlock before calling __security_genfs_sid() and release
2865  * it afterward.
2866  */
2867 int security_genfs_sid(const char *fstype,
2868 		       const char *path,
2869 		       u16 orig_sclass,
2870 		       u32 *sid)
2871 {
2872 	struct selinux_policy *policy;
2873 	int retval;
2874 
2875 	if (!selinux_initialized()) {
2876 		*sid = SECINITSID_UNLABELED;
2877 		return 0;
2878 	}
2879 
2880 	do {
2881 		rcu_read_lock();
2882 		policy = rcu_dereference(selinux_state.policy);
2883 		retval = __security_genfs_sid(policy, fstype, path,
2884 					      orig_sclass, sid);
2885 		rcu_read_unlock();
2886 	} while (retval == -ESTALE);
2887 	return retval;
2888 }
2889 
2890 int selinux_policy_genfs_sid(struct selinux_policy *policy,
2891 			const char *fstype,
2892 			const char *path,
2893 			u16 orig_sclass,
2894 			u32 *sid)
2895 {
2896 	/* no lock required, policy is not yet accessible by other threads */
2897 	return __security_genfs_sid(policy, fstype, path, orig_sclass, sid);
2898 }
2899 
2900 /**
2901  * security_fs_use - Determine how to handle labeling for a filesystem.
2902  * @sb: superblock in question
2903  */
2904 int security_fs_use(struct super_block *sb)
2905 {
2906 	struct selinux_policy *policy;
2907 	struct policydb *policydb;
2908 	struct sidtab *sidtab;
2909 	int rc;
2910 	struct ocontext *c;
2911 	struct superblock_security_struct *sbsec = selinux_superblock(sb);
2912 	const char *fstype = sb->s_type->name;
2913 
2914 	if (!selinux_initialized()) {
2915 		sbsec->behavior = SECURITY_FS_USE_NONE;
2916 		sbsec->sid = SECINITSID_UNLABELED;
2917 		return 0;
2918 	}
2919 
2920 retry:
2921 	rcu_read_lock();
2922 	policy = rcu_dereference(selinux_state.policy);
2923 	policydb = &policy->policydb;
2924 	sidtab = policy->sidtab;
2925 
2926 	c = policydb->ocontexts[OCON_FSUSE];
2927 	while (c) {
2928 		if (strcmp(fstype, c->u.name) == 0)
2929 			break;
2930 		c = c->next;
2931 	}
2932 
2933 	if (c) {
2934 		sbsec->behavior = c->v.behavior;
2935 		rc = ocontext_to_sid(sidtab, c, 0, &sbsec->sid);
2936 		if (rc == -ESTALE) {
2937 			rcu_read_unlock();
2938 			goto retry;
2939 		}
2940 		if (rc)
2941 			goto out;
2942 	} else {
2943 		rc = __security_genfs_sid(policy, fstype, "/",
2944 					SECCLASS_DIR, &sbsec->sid);
2945 		if (rc == -ESTALE) {
2946 			rcu_read_unlock();
2947 			goto retry;
2948 		}
2949 		if (rc) {
2950 			sbsec->behavior = SECURITY_FS_USE_NONE;
2951 			rc = 0;
2952 		} else {
2953 			sbsec->behavior = SECURITY_FS_USE_GENFS;
2954 		}
2955 	}
2956 
2957 out:
2958 	rcu_read_unlock();
2959 	return rc;
2960 }
2961 
2962 int security_get_bools(struct selinux_policy *policy,
2963 		       u32 *len, char ***names, int **values)
2964 {
2965 	struct policydb *policydb;
2966 	u32 i;
2967 	int rc;
2968 
2969 	policydb = &policy->policydb;
2970 
2971 	*names = NULL;
2972 	*values = NULL;
2973 
2974 	rc = 0;
2975 	*len = policydb->p_bools.nprim;
2976 	if (!*len)
2977 		goto out;
2978 
2979 	rc = -ENOMEM;
2980 	*names = kcalloc(*len, sizeof(char *), GFP_ATOMIC);
2981 	if (!*names)
2982 		goto err;
2983 
2984 	rc = -ENOMEM;
2985 	*values = kcalloc(*len, sizeof(int), GFP_ATOMIC);
2986 	if (!*values)
2987 		goto err;
2988 
2989 	for (i = 0; i < *len; i++) {
2990 		(*values)[i] = policydb->bool_val_to_struct[i]->state;
2991 
2992 		rc = -ENOMEM;
2993 		(*names)[i] = kstrdup(sym_name(policydb, SYM_BOOLS, i),
2994 				      GFP_ATOMIC);
2995 		if (!(*names)[i])
2996 			goto err;
2997 	}
2998 	rc = 0;
2999 out:
3000 	return rc;
3001 err:
3002 	if (*names) {
3003 		for (i = 0; i < *len; i++)
3004 			kfree((*names)[i]);
3005 		kfree(*names);
3006 	}
3007 	kfree(*values);
3008 	*len = 0;
3009 	*names = NULL;
3010 	*values = NULL;
3011 	goto out;
3012 }
3013 
3014 
3015 int security_set_bools(u32 len, int *values)
3016 {
3017 	struct selinux_state *state = &selinux_state;
3018 	struct selinux_policy *newpolicy, *oldpolicy;
3019 	int rc;
3020 	u32 i, seqno = 0;
3021 
3022 	if (!selinux_initialized())
3023 		return -EINVAL;
3024 
3025 	oldpolicy = rcu_dereference_protected(state->policy,
3026 					lockdep_is_held(&state->policy_mutex));
3027 
3028 	/* Consistency check on number of booleans, should never fail */
3029 	if (WARN_ON(len != oldpolicy->policydb.p_bools.nprim))
3030 		return -EINVAL;
3031 
3032 	newpolicy = kmemdup(oldpolicy, sizeof(*newpolicy), GFP_KERNEL);
3033 	if (!newpolicy)
3034 		return -ENOMEM;
3035 
3036 	/*
3037 	 * Deep copy only the parts of the policydb that might be
3038 	 * modified as a result of changing booleans.
3039 	 */
3040 	rc = cond_policydb_dup(&newpolicy->policydb, &oldpolicy->policydb);
3041 	if (rc) {
3042 		kfree(newpolicy);
3043 		return -ENOMEM;
3044 	}
3045 
3046 	/* Update the boolean states in the copy */
3047 	for (i = 0; i < len; i++) {
3048 		int new_state = !!values[i];
3049 		int old_state = newpolicy->policydb.bool_val_to_struct[i]->state;
3050 
3051 		if (new_state != old_state) {
3052 			audit_log(audit_context(), GFP_ATOMIC,
3053 				AUDIT_MAC_CONFIG_CHANGE,
3054 				"bool=%s val=%d old_val=%d auid=%u ses=%u",
3055 				sym_name(&newpolicy->policydb, SYM_BOOLS, i),
3056 				new_state,
3057 				old_state,
3058 				from_kuid(&init_user_ns, audit_get_loginuid(current)),
3059 				audit_get_sessionid(current));
3060 			newpolicy->policydb.bool_val_to_struct[i]->state = new_state;
3061 		}
3062 	}
3063 
3064 	/* Re-evaluate the conditional rules in the copy */
3065 	evaluate_cond_nodes(&newpolicy->policydb);
3066 
3067 	/* Set latest granting seqno for new policy */
3068 	newpolicy->latest_granting = oldpolicy->latest_granting + 1;
3069 	seqno = newpolicy->latest_granting;
3070 
3071 	/* Install the new policy */
3072 	rcu_assign_pointer(state->policy, newpolicy);
3073 
3074 	/*
3075 	 * Free the conditional portions of the old policydb
3076 	 * that were copied for the new policy, and the oldpolicy
3077 	 * structure itself but not what it references.
3078 	 */
3079 	synchronize_rcu();
3080 	selinux_policy_cond_free(oldpolicy);
3081 
3082 	/* Notify others of the policy change */
3083 	selinux_notify_policy_change(seqno);
3084 	return 0;
3085 }
3086 
3087 int security_get_bool_value(u32 index)
3088 {
3089 	struct selinux_policy *policy;
3090 	struct policydb *policydb;
3091 	int rc;
3092 	u32 len;
3093 
3094 	if (!selinux_initialized())
3095 		return 0;
3096 
3097 	rcu_read_lock();
3098 	policy = rcu_dereference(selinux_state.policy);
3099 	policydb = &policy->policydb;
3100 
3101 	rc = -EFAULT;
3102 	len = policydb->p_bools.nprim;
3103 	if (index >= len)
3104 		goto out;
3105 
3106 	rc = policydb->bool_val_to_struct[index]->state;
3107 out:
3108 	rcu_read_unlock();
3109 	return rc;
3110 }
3111 
3112 static int security_preserve_bools(struct selinux_policy *oldpolicy,
3113 				struct selinux_policy *newpolicy)
3114 {
3115 	int rc, *bvalues = NULL;
3116 	char **bnames = NULL;
3117 	struct cond_bool_datum *booldatum;
3118 	u32 i, nbools = 0;
3119 
3120 	rc = security_get_bools(oldpolicy, &nbools, &bnames, &bvalues);
3121 	if (rc)
3122 		goto out;
3123 	for (i = 0; i < nbools; i++) {
3124 		booldatum = symtab_search(&newpolicy->policydb.p_bools,
3125 					bnames[i]);
3126 		if (booldatum)
3127 			booldatum->state = bvalues[i];
3128 	}
3129 	evaluate_cond_nodes(&newpolicy->policydb);
3130 
3131 out:
3132 	if (bnames) {
3133 		for (i = 0; i < nbools; i++)
3134 			kfree(bnames[i]);
3135 	}
3136 	kfree(bnames);
3137 	kfree(bvalues);
3138 	return rc;
3139 }
3140 
3141 /*
3142  * security_sid_mls_copy() - computes a new sid based on the given
3143  * sid and the mls portion of mls_sid.
3144  */
3145 int security_sid_mls_copy(u32 sid, u32 mls_sid, u32 *new_sid)
3146 {
3147 	struct selinux_policy *policy;
3148 	struct policydb *policydb;
3149 	struct sidtab *sidtab;
3150 	struct context *context1;
3151 	struct context *context2;
3152 	struct context newcon;
3153 	char *s;
3154 	u32 len;
3155 	int rc;
3156 
3157 	if (!selinux_initialized()) {
3158 		*new_sid = sid;
3159 		return 0;
3160 	}
3161 
3162 retry:
3163 	rc = 0;
3164 	context_init(&newcon);
3165 
3166 	rcu_read_lock();
3167 	policy = rcu_dereference(selinux_state.policy);
3168 	policydb = &policy->policydb;
3169 	sidtab = policy->sidtab;
3170 
3171 	if (!policydb->mls_enabled) {
3172 		*new_sid = sid;
3173 		goto out_unlock;
3174 	}
3175 
3176 	rc = -EINVAL;
3177 	context1 = sidtab_search(sidtab, sid);
3178 	if (!context1) {
3179 		pr_err("SELinux: %s:  unrecognized SID %d\n",
3180 			__func__, sid);
3181 		goto out_unlock;
3182 	}
3183 
3184 	rc = -EINVAL;
3185 	context2 = sidtab_search(sidtab, mls_sid);
3186 	if (!context2) {
3187 		pr_err("SELinux: %s:  unrecognized SID %d\n",
3188 			__func__, mls_sid);
3189 		goto out_unlock;
3190 	}
3191 
3192 	newcon.user = context1->user;
3193 	newcon.role = context1->role;
3194 	newcon.type = context1->type;
3195 	rc = mls_context_cpy(&newcon, context2);
3196 	if (rc)
3197 		goto out_unlock;
3198 
3199 	/* Check the validity of the new context. */
3200 	if (!policydb_context_isvalid(policydb, &newcon)) {
3201 		rc = convert_context_handle_invalid_context(policydb,
3202 							&newcon);
3203 		if (rc) {
3204 			if (!context_struct_to_string(policydb, &newcon, &s,
3205 						      &len)) {
3206 				struct audit_buffer *ab;
3207 
3208 				ab = audit_log_start(audit_context(),
3209 						     GFP_ATOMIC,
3210 						     AUDIT_SELINUX_ERR);
3211 				audit_log_format(ab,
3212 						 "op=security_sid_mls_copy invalid_context=");
3213 				/* don't record NUL with untrusted strings */
3214 				audit_log_n_untrustedstring(ab, s, len - 1);
3215 				audit_log_end(ab);
3216 				kfree(s);
3217 			}
3218 			goto out_unlock;
3219 		}
3220 	}
3221 	rc = sidtab_context_to_sid(sidtab, &newcon, new_sid);
3222 	if (rc == -ESTALE) {
3223 		rcu_read_unlock();
3224 		context_destroy(&newcon);
3225 		goto retry;
3226 	}
3227 out_unlock:
3228 	rcu_read_unlock();
3229 	context_destroy(&newcon);
3230 	return rc;
3231 }
3232 
3233 /**
3234  * security_net_peersid_resolve - Compare and resolve two network peer SIDs
3235  * @nlbl_sid: NetLabel SID
3236  * @nlbl_type: NetLabel labeling protocol type
3237  * @xfrm_sid: XFRM SID
3238  * @peer_sid: network peer sid
3239  *
3240  * Description:
3241  * Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be
3242  * resolved into a single SID it is returned via @peer_sid and the function
3243  * returns zero.  Otherwise @peer_sid is set to SECSID_NULL and the function
3244  * returns a negative value.  A table summarizing the behavior is below:
3245  *
3246  *                                 | function return |      @sid
3247  *   ------------------------------+-----------------+-----------------
3248  *   no peer labels                |        0        |    SECSID_NULL
3249  *   single peer label             |        0        |    <peer_label>
3250  *   multiple, consistent labels   |        0        |    <peer_label>
3251  *   multiple, inconsistent labels |    -<errno>     |    SECSID_NULL
3252  *
3253  */
3254 int security_net_peersid_resolve(u32 nlbl_sid, u32 nlbl_type,
3255 				 u32 xfrm_sid,
3256 				 u32 *peer_sid)
3257 {
3258 	struct selinux_policy *policy;
3259 	struct policydb *policydb;
3260 	struct sidtab *sidtab;
3261 	int rc;
3262 	struct context *nlbl_ctx;
3263 	struct context *xfrm_ctx;
3264 
3265 	*peer_sid = SECSID_NULL;
3266 
3267 	/* handle the common (which also happens to be the set of easy) cases
3268 	 * right away, these two if statements catch everything involving a
3269 	 * single or absent peer SID/label */
3270 	if (xfrm_sid == SECSID_NULL) {
3271 		*peer_sid = nlbl_sid;
3272 		return 0;
3273 	}
3274 	/* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a "fallback" label
3275 	 * and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label
3276 	 * is present */
3277 	if (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) {
3278 		*peer_sid = xfrm_sid;
3279 		return 0;
3280 	}
3281 
3282 	if (!selinux_initialized())
3283 		return 0;
3284 
3285 	rcu_read_lock();
3286 	policy = rcu_dereference(selinux_state.policy);
3287 	policydb = &policy->policydb;
3288 	sidtab = policy->sidtab;
3289 
3290 	/*
3291 	 * We don't need to check initialized here since the only way both
3292 	 * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the
3293 	 * security server was initialized and state->initialized was true.
3294 	 */
3295 	if (!policydb->mls_enabled) {
3296 		rc = 0;
3297 		goto out;
3298 	}
3299 
3300 	rc = -EINVAL;
3301 	nlbl_ctx = sidtab_search(sidtab, nlbl_sid);
3302 	if (!nlbl_ctx) {
3303 		pr_err("SELinux: %s:  unrecognized SID %d\n",
3304 		       __func__, nlbl_sid);
3305 		goto out;
3306 	}
3307 	rc = -EINVAL;
3308 	xfrm_ctx = sidtab_search(sidtab, xfrm_sid);
3309 	if (!xfrm_ctx) {
3310 		pr_err("SELinux: %s:  unrecognized SID %d\n",
3311 		       __func__, xfrm_sid);
3312 		goto out;
3313 	}
3314 	rc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES);
3315 	if (rc)
3316 		goto out;
3317 
3318 	/* at present NetLabel SIDs/labels really only carry MLS
3319 	 * information so if the MLS portion of the NetLabel SID
3320 	 * matches the MLS portion of the labeled XFRM SID/label
3321 	 * then pass along the XFRM SID as it is the most
3322 	 * expressive */
3323 	*peer_sid = xfrm_sid;
3324 out:
3325 	rcu_read_unlock();
3326 	return rc;
3327 }
3328 
3329 static int get_classes_callback(void *k, void *d, void *args)
3330 {
3331 	struct class_datum *datum = d;
3332 	char *name = k, **classes = args;
3333 	u32 value = datum->value - 1;
3334 
3335 	classes[value] = kstrdup(name, GFP_ATOMIC);
3336 	if (!classes[value])
3337 		return -ENOMEM;
3338 
3339 	return 0;
3340 }
3341 
3342 int security_get_classes(struct selinux_policy *policy,
3343 			 char ***classes, u32 *nclasses)
3344 {
3345 	struct policydb *policydb;
3346 	int rc;
3347 
3348 	policydb = &policy->policydb;
3349 
3350 	rc = -ENOMEM;
3351 	*nclasses = policydb->p_classes.nprim;
3352 	*classes = kcalloc(*nclasses, sizeof(**classes), GFP_ATOMIC);
3353 	if (!*classes)
3354 		goto out;
3355 
3356 	rc = hashtab_map(&policydb->p_classes.table, get_classes_callback,
3357 			 *classes);
3358 	if (rc) {
3359 		u32 i;
3360 
3361 		for (i = 0; i < *nclasses; i++)
3362 			kfree((*classes)[i]);
3363 		kfree(*classes);
3364 	}
3365 
3366 out:
3367 	return rc;
3368 }
3369 
3370 static int get_permissions_callback(void *k, void *d, void *args)
3371 {
3372 	struct perm_datum *datum = d;
3373 	char *name = k, **perms = args;
3374 	u32 value = datum->value - 1;
3375 
3376 	perms[value] = kstrdup(name, GFP_ATOMIC);
3377 	if (!perms[value])
3378 		return -ENOMEM;
3379 
3380 	return 0;
3381 }
3382 
3383 int security_get_permissions(struct selinux_policy *policy,
3384 			     const char *class, char ***perms, u32 *nperms)
3385 {
3386 	struct policydb *policydb;
3387 	u32 i;
3388 	int rc;
3389 	struct class_datum *match;
3390 
3391 	policydb = &policy->policydb;
3392 
3393 	rc = -EINVAL;
3394 	match = symtab_search(&policydb->p_classes, class);
3395 	if (!match) {
3396 		pr_err("SELinux: %s:  unrecognized class %s\n",
3397 			__func__, class);
3398 		goto out;
3399 	}
3400 
3401 	rc = -ENOMEM;
3402 	*nperms = match->permissions.nprim;
3403 	*perms = kcalloc(*nperms, sizeof(**perms), GFP_ATOMIC);
3404 	if (!*perms)
3405 		goto out;
3406 
3407 	if (match->comdatum) {
3408 		rc = hashtab_map(&match->comdatum->permissions.table,
3409 				 get_permissions_callback, *perms);
3410 		if (rc)
3411 			goto err;
3412 	}
3413 
3414 	rc = hashtab_map(&match->permissions.table, get_permissions_callback,
3415 			 *perms);
3416 	if (rc)
3417 		goto err;
3418 
3419 out:
3420 	return rc;
3421 
3422 err:
3423 	for (i = 0; i < *nperms; i++)
3424 		kfree((*perms)[i]);
3425 	kfree(*perms);
3426 	return rc;
3427 }
3428 
3429 int security_get_reject_unknown(void)
3430 {
3431 	struct selinux_policy *policy;
3432 	int value;
3433 
3434 	if (!selinux_initialized())
3435 		return 0;
3436 
3437 	rcu_read_lock();
3438 	policy = rcu_dereference(selinux_state.policy);
3439 	value = policy->policydb.reject_unknown;
3440 	rcu_read_unlock();
3441 	return value;
3442 }
3443 
3444 int security_get_allow_unknown(void)
3445 {
3446 	struct selinux_policy *policy;
3447 	int value;
3448 
3449 	if (!selinux_initialized())
3450 		return 0;
3451 
3452 	rcu_read_lock();
3453 	policy = rcu_dereference(selinux_state.policy);
3454 	value = policy->policydb.allow_unknown;
3455 	rcu_read_unlock();
3456 	return value;
3457 }
3458 
3459 /**
3460  * security_policycap_supported - Check for a specific policy capability
3461  * @req_cap: capability
3462  *
3463  * Description:
3464  * This function queries the currently loaded policy to see if it supports the
3465  * capability specified by @req_cap.  Returns true (1) if the capability is
3466  * supported, false (0) if it isn't supported.
3467  *
3468  */
3469 int security_policycap_supported(unsigned int req_cap)
3470 {
3471 	struct selinux_policy *policy;
3472 	int rc;
3473 
3474 	if (!selinux_initialized())
3475 		return 0;
3476 
3477 	rcu_read_lock();
3478 	policy = rcu_dereference(selinux_state.policy);
3479 	rc = ebitmap_get_bit(&policy->policydb.policycaps, req_cap);
3480 	rcu_read_unlock();
3481 
3482 	return rc;
3483 }
3484 
3485 struct selinux_audit_rule {
3486 	u32 au_seqno;
3487 	struct context au_ctxt;
3488 };
3489 
3490 void selinux_audit_rule_free(void *vrule)
3491 {
3492 	struct selinux_audit_rule *rule = vrule;
3493 
3494 	if (rule) {
3495 		context_destroy(&rule->au_ctxt);
3496 		kfree(rule);
3497 	}
3498 }
3499 
3500 int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule)
3501 {
3502 	struct selinux_state *state = &selinux_state;
3503 	struct selinux_policy *policy;
3504 	struct policydb *policydb;
3505 	struct selinux_audit_rule *tmprule;
3506 	struct role_datum *roledatum;
3507 	struct type_datum *typedatum;
3508 	struct user_datum *userdatum;
3509 	struct selinux_audit_rule **rule = (struct selinux_audit_rule **)vrule;
3510 	int rc = 0;
3511 
3512 	*rule = NULL;
3513 
3514 	if (!selinux_initialized())
3515 		return -EOPNOTSUPP;
3516 
3517 	switch (field) {
3518 	case AUDIT_SUBJ_USER:
3519 	case AUDIT_SUBJ_ROLE:
3520 	case AUDIT_SUBJ_TYPE:
3521 	case AUDIT_OBJ_USER:
3522 	case AUDIT_OBJ_ROLE:
3523 	case AUDIT_OBJ_TYPE:
3524 		/* only 'equals' and 'not equals' fit user, role, and type */
3525 		if (op != Audit_equal && op != Audit_not_equal)
3526 			return -EINVAL;
3527 		break;
3528 	case AUDIT_SUBJ_SEN:
3529 	case AUDIT_SUBJ_CLR:
3530 	case AUDIT_OBJ_LEV_LOW:
3531 	case AUDIT_OBJ_LEV_HIGH:
3532 		/* we do not allow a range, indicated by the presence of '-' */
3533 		if (strchr(rulestr, '-'))
3534 			return -EINVAL;
3535 		break;
3536 	default:
3537 		/* only the above fields are valid */
3538 		return -EINVAL;
3539 	}
3540 
3541 	tmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL);
3542 	if (!tmprule)
3543 		return -ENOMEM;
3544 	context_init(&tmprule->au_ctxt);
3545 
3546 	rcu_read_lock();
3547 	policy = rcu_dereference(state->policy);
3548 	policydb = &policy->policydb;
3549 	tmprule->au_seqno = policy->latest_granting;
3550 	switch (field) {
3551 	case AUDIT_SUBJ_USER:
3552 	case AUDIT_OBJ_USER:
3553 		userdatum = symtab_search(&policydb->p_users, rulestr);
3554 		if (!userdatum) {
3555 			rc = -EINVAL;
3556 			goto err;
3557 		}
3558 		tmprule->au_ctxt.user = userdatum->value;
3559 		break;
3560 	case AUDIT_SUBJ_ROLE:
3561 	case AUDIT_OBJ_ROLE:
3562 		roledatum = symtab_search(&policydb->p_roles, rulestr);
3563 		if (!roledatum) {
3564 			rc = -EINVAL;
3565 			goto err;
3566 		}
3567 		tmprule->au_ctxt.role = roledatum->value;
3568 		break;
3569 	case AUDIT_SUBJ_TYPE:
3570 	case AUDIT_OBJ_TYPE:
3571 		typedatum = symtab_search(&policydb->p_types, rulestr);
3572 		if (!typedatum) {
3573 			rc = -EINVAL;
3574 			goto err;
3575 		}
3576 		tmprule->au_ctxt.type = typedatum->value;
3577 		break;
3578 	case AUDIT_SUBJ_SEN:
3579 	case AUDIT_SUBJ_CLR:
3580 	case AUDIT_OBJ_LEV_LOW:
3581 	case AUDIT_OBJ_LEV_HIGH:
3582 		rc = mls_from_string(policydb, rulestr, &tmprule->au_ctxt,
3583 				     GFP_ATOMIC);
3584 		if (rc)
3585 			goto err;
3586 		break;
3587 	}
3588 	rcu_read_unlock();
3589 
3590 	*rule = tmprule;
3591 	return 0;
3592 
3593 err:
3594 	rcu_read_unlock();
3595 	selinux_audit_rule_free(tmprule);
3596 	*rule = NULL;
3597 	return rc;
3598 }
3599 
3600 /* Check to see if the rule contains any selinux fields */
3601 int selinux_audit_rule_known(struct audit_krule *rule)
3602 {
3603 	u32 i;
3604 
3605 	for (i = 0; i < rule->field_count; i++) {
3606 		struct audit_field *f = &rule->fields[i];
3607 		switch (f->type) {
3608 		case AUDIT_SUBJ_USER:
3609 		case AUDIT_SUBJ_ROLE:
3610 		case AUDIT_SUBJ_TYPE:
3611 		case AUDIT_SUBJ_SEN:
3612 		case AUDIT_SUBJ_CLR:
3613 		case AUDIT_OBJ_USER:
3614 		case AUDIT_OBJ_ROLE:
3615 		case AUDIT_OBJ_TYPE:
3616 		case AUDIT_OBJ_LEV_LOW:
3617 		case AUDIT_OBJ_LEV_HIGH:
3618 			return 1;
3619 		}
3620 	}
3621 
3622 	return 0;
3623 }
3624 
3625 int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule)
3626 {
3627 	struct selinux_state *state = &selinux_state;
3628 	struct selinux_policy *policy;
3629 	struct context *ctxt;
3630 	struct mls_level *level;
3631 	struct selinux_audit_rule *rule = vrule;
3632 	int match = 0;
3633 
3634 	if (unlikely(!rule)) {
3635 		WARN_ONCE(1, "selinux_audit_rule_match: missing rule\n");
3636 		return -ENOENT;
3637 	}
3638 
3639 	if (!selinux_initialized())
3640 		return 0;
3641 
3642 	rcu_read_lock();
3643 
3644 	policy = rcu_dereference(state->policy);
3645 
3646 	if (rule->au_seqno < policy->latest_granting) {
3647 		match = -ESTALE;
3648 		goto out;
3649 	}
3650 
3651 	ctxt = sidtab_search(policy->sidtab, sid);
3652 	if (unlikely(!ctxt)) {
3653 		WARN_ONCE(1, "selinux_audit_rule_match: unrecognized SID %d\n",
3654 			  sid);
3655 		match = -ENOENT;
3656 		goto out;
3657 	}
3658 
3659 	/* a field/op pair that is not caught here will simply fall through
3660 	   without a match */
3661 	switch (field) {
3662 	case AUDIT_SUBJ_USER:
3663 	case AUDIT_OBJ_USER:
3664 		switch (op) {
3665 		case Audit_equal:
3666 			match = (ctxt->user == rule->au_ctxt.user);
3667 			break;
3668 		case Audit_not_equal:
3669 			match = (ctxt->user != rule->au_ctxt.user);
3670 			break;
3671 		}
3672 		break;
3673 	case AUDIT_SUBJ_ROLE:
3674 	case AUDIT_OBJ_ROLE:
3675 		switch (op) {
3676 		case Audit_equal:
3677 			match = (ctxt->role == rule->au_ctxt.role);
3678 			break;
3679 		case Audit_not_equal:
3680 			match = (ctxt->role != rule->au_ctxt.role);
3681 			break;
3682 		}
3683 		break;
3684 	case AUDIT_SUBJ_TYPE:
3685 	case AUDIT_OBJ_TYPE:
3686 		switch (op) {
3687 		case Audit_equal:
3688 			match = (ctxt->type == rule->au_ctxt.type);
3689 			break;
3690 		case Audit_not_equal:
3691 			match = (ctxt->type != rule->au_ctxt.type);
3692 			break;
3693 		}
3694 		break;
3695 	case AUDIT_SUBJ_SEN:
3696 	case AUDIT_SUBJ_CLR:
3697 	case AUDIT_OBJ_LEV_LOW:
3698 	case AUDIT_OBJ_LEV_HIGH:
3699 		level = ((field == AUDIT_SUBJ_SEN ||
3700 			  field == AUDIT_OBJ_LEV_LOW) ?
3701 			 &ctxt->range.level[0] : &ctxt->range.level[1]);
3702 		switch (op) {
3703 		case Audit_equal:
3704 			match = mls_level_eq(&rule->au_ctxt.range.level[0],
3705 					     level);
3706 			break;
3707 		case Audit_not_equal:
3708 			match = !mls_level_eq(&rule->au_ctxt.range.level[0],
3709 					      level);
3710 			break;
3711 		case Audit_lt:
3712 			match = (mls_level_dom(&rule->au_ctxt.range.level[0],
3713 					       level) &&
3714 				 !mls_level_eq(&rule->au_ctxt.range.level[0],
3715 					       level));
3716 			break;
3717 		case Audit_le:
3718 			match = mls_level_dom(&rule->au_ctxt.range.level[0],
3719 					      level);
3720 			break;
3721 		case Audit_gt:
3722 			match = (mls_level_dom(level,
3723 					      &rule->au_ctxt.range.level[0]) &&
3724 				 !mls_level_eq(level,
3725 					       &rule->au_ctxt.range.level[0]));
3726 			break;
3727 		case Audit_ge:
3728 			match = mls_level_dom(level,
3729 					      &rule->au_ctxt.range.level[0]);
3730 			break;
3731 		}
3732 	}
3733 
3734 out:
3735 	rcu_read_unlock();
3736 	return match;
3737 }
3738 
3739 static int aurule_avc_callback(u32 event)
3740 {
3741 	if (event == AVC_CALLBACK_RESET)
3742 		return audit_update_lsm_rules();
3743 	return 0;
3744 }
3745 
3746 static int __init aurule_init(void)
3747 {
3748 	int err;
3749 
3750 	err = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET);
3751 	if (err)
3752 		panic("avc_add_callback() failed, error %d\n", err);
3753 
3754 	return err;
3755 }
3756 __initcall(aurule_init);
3757 
3758 #ifdef CONFIG_NETLABEL
3759 /**
3760  * security_netlbl_cache_add - Add an entry to the NetLabel cache
3761  * @secattr: the NetLabel packet security attributes
3762  * @sid: the SELinux SID
3763  *
3764  * Description:
3765  * Attempt to cache the context in @ctx, which was derived from the packet in
3766  * @skb, in the NetLabel subsystem cache.  This function assumes @secattr has
3767  * already been initialized.
3768  *
3769  */
3770 static void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr,
3771 				      u32 sid)
3772 {
3773 	u32 *sid_cache;
3774 
3775 	sid_cache = kmalloc(sizeof(*sid_cache), GFP_ATOMIC);
3776 	if (sid_cache == NULL)
3777 		return;
3778 	secattr->cache = netlbl_secattr_cache_alloc(GFP_ATOMIC);
3779 	if (secattr->cache == NULL) {
3780 		kfree(sid_cache);
3781 		return;
3782 	}
3783 
3784 	*sid_cache = sid;
3785 	secattr->cache->free = kfree;
3786 	secattr->cache->data = sid_cache;
3787 	secattr->flags |= NETLBL_SECATTR_CACHE;
3788 }
3789 
3790 /**
3791  * security_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID
3792  * @secattr: the NetLabel packet security attributes
3793  * @sid: the SELinux SID
3794  *
3795  * Description:
3796  * Convert the given NetLabel security attributes in @secattr into a
3797  * SELinux SID.  If the @secattr field does not contain a full SELinux
3798  * SID/context then use SECINITSID_NETMSG as the foundation.  If possible the
3799  * 'cache' field of @secattr is set and the CACHE flag is set; this is to
3800  * allow the @secattr to be used by NetLabel to cache the secattr to SID
3801  * conversion for future lookups.  Returns zero on success, negative values on
3802  * failure.
3803  *
3804  */
3805 int security_netlbl_secattr_to_sid(struct netlbl_lsm_secattr *secattr,
3806 				   u32 *sid)
3807 {
3808 	struct selinux_policy *policy;
3809 	struct policydb *policydb;
3810 	struct sidtab *sidtab;
3811 	int rc;
3812 	struct context *ctx;
3813 	struct context ctx_new;
3814 
3815 	if (!selinux_initialized()) {
3816 		*sid = SECSID_NULL;
3817 		return 0;
3818 	}
3819 
3820 retry:
3821 	rc = 0;
3822 	rcu_read_lock();
3823 	policy = rcu_dereference(selinux_state.policy);
3824 	policydb = &policy->policydb;
3825 	sidtab = policy->sidtab;
3826 
3827 	if (secattr->flags & NETLBL_SECATTR_CACHE)
3828 		*sid = *(u32 *)secattr->cache->data;
3829 	else if (secattr->flags & NETLBL_SECATTR_SECID)
3830 		*sid = secattr->attr.secid;
3831 	else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) {
3832 		rc = -EIDRM;
3833 		ctx = sidtab_search(sidtab, SECINITSID_NETMSG);
3834 		if (ctx == NULL)
3835 			goto out;
3836 
3837 		context_init(&ctx_new);
3838 		ctx_new.user = ctx->user;
3839 		ctx_new.role = ctx->role;
3840 		ctx_new.type = ctx->type;
3841 		mls_import_netlbl_lvl(policydb, &ctx_new, secattr);
3842 		if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
3843 			rc = mls_import_netlbl_cat(policydb, &ctx_new, secattr);
3844 			if (rc)
3845 				goto out;
3846 		}
3847 		rc = -EIDRM;
3848 		if (!mls_context_isvalid(policydb, &ctx_new)) {
3849 			ebitmap_destroy(&ctx_new.range.level[0].cat);
3850 			goto out;
3851 		}
3852 
3853 		rc = sidtab_context_to_sid(sidtab, &ctx_new, sid);
3854 		ebitmap_destroy(&ctx_new.range.level[0].cat);
3855 		if (rc == -ESTALE) {
3856 			rcu_read_unlock();
3857 			goto retry;
3858 		}
3859 		if (rc)
3860 			goto out;
3861 
3862 		security_netlbl_cache_add(secattr, *sid);
3863 	} else
3864 		*sid = SECSID_NULL;
3865 
3866 out:
3867 	rcu_read_unlock();
3868 	return rc;
3869 }
3870 
3871 /**
3872  * security_netlbl_sid_to_secattr - Convert a SELinux SID to a NetLabel secattr
3873  * @sid: the SELinux SID
3874  * @secattr: the NetLabel packet security attributes
3875  *
3876  * Description:
3877  * Convert the given SELinux SID in @sid into a NetLabel security attribute.
3878  * Returns zero on success, negative values on failure.
3879  *
3880  */
3881 int security_netlbl_sid_to_secattr(u32 sid, struct netlbl_lsm_secattr *secattr)
3882 {
3883 	struct selinux_policy *policy;
3884 	struct policydb *policydb;
3885 	int rc;
3886 	struct context *ctx;
3887 
3888 	if (!selinux_initialized())
3889 		return 0;
3890 
3891 	rcu_read_lock();
3892 	policy = rcu_dereference(selinux_state.policy);
3893 	policydb = &policy->policydb;
3894 
3895 	rc = -ENOENT;
3896 	ctx = sidtab_search(policy->sidtab, sid);
3897 	if (ctx == NULL)
3898 		goto out;
3899 
3900 	rc = -ENOMEM;
3901 	secattr->domain = kstrdup(sym_name(policydb, SYM_TYPES, ctx->type - 1),
3902 				  GFP_ATOMIC);
3903 	if (secattr->domain == NULL)
3904 		goto out;
3905 
3906 	secattr->attr.secid = sid;
3907 	secattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID;
3908 	mls_export_netlbl_lvl(policydb, ctx, secattr);
3909 	rc = mls_export_netlbl_cat(policydb, ctx, secattr);
3910 out:
3911 	rcu_read_unlock();
3912 	return rc;
3913 }
3914 #endif /* CONFIG_NETLABEL */
3915 
3916 /**
3917  * __security_read_policy - read the policy.
3918  * @policy: SELinux policy
3919  * @data: binary policy data
3920  * @len: length of data in bytes
3921  *
3922  */
3923 static int __security_read_policy(struct selinux_policy *policy,
3924 				  void *data, size_t *len)
3925 {
3926 	int rc;
3927 	struct policy_file fp;
3928 
3929 	fp.data = data;
3930 	fp.len = *len;
3931 
3932 	rc = policydb_write(&policy->policydb, &fp);
3933 	if (rc)
3934 		return rc;
3935 
3936 	*len = (unsigned long)fp.data - (unsigned long)data;
3937 	return 0;
3938 }
3939 
3940 /**
3941  * security_read_policy - read the policy.
3942  * @data: binary policy data
3943  * @len: length of data in bytes
3944  *
3945  */
3946 int security_read_policy(void **data, size_t *len)
3947 {
3948 	struct selinux_state *state = &selinux_state;
3949 	struct selinux_policy *policy;
3950 
3951 	policy = rcu_dereference_protected(
3952 			state->policy, lockdep_is_held(&state->policy_mutex));
3953 	if (!policy)
3954 		return -EINVAL;
3955 
3956 	*len = policy->policydb.len;
3957 	*data = vmalloc_user(*len);
3958 	if (!*data)
3959 		return -ENOMEM;
3960 
3961 	return __security_read_policy(policy, *data, len);
3962 }
3963 
3964 /**
3965  * security_read_state_kernel - read the policy.
3966  * @data: binary policy data
3967  * @len: length of data in bytes
3968  *
3969  * Allocates kernel memory for reading SELinux policy.
3970  * This function is for internal use only and should not
3971  * be used for returning data to user space.
3972  *
3973  * This function must be called with policy_mutex held.
3974  */
3975 int security_read_state_kernel(void **data, size_t *len)
3976 {
3977 	int err;
3978 	struct selinux_state *state = &selinux_state;
3979 	struct selinux_policy *policy;
3980 
3981 	policy = rcu_dereference_protected(
3982 			state->policy, lockdep_is_held(&state->policy_mutex));
3983 	if (!policy)
3984 		return -EINVAL;
3985 
3986 	*len = policy->policydb.len;
3987 	*data = vmalloc(*len);
3988 	if (!*data)
3989 		return -ENOMEM;
3990 
3991 	err = __security_read_policy(policy, *data, len);
3992 	if (err) {
3993 		vfree(*data);
3994 		*data = NULL;
3995 		*len = 0;
3996 	}
3997 	return err;
3998 }
3999