xref: /linux/security/selinux/ss/services.c (revision f9bff0e31881d03badf191d3b0005839391f5f2b)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Implementation of the security services.
4  *
5  * Authors : Stephen Smalley, <sds@tycho.nsa.gov>
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 	unsigned k;
101 	bool print_unknown_handle = false;
102 
103 	/* Find number of classes in the input mapping */
104 	if (!map)
105 		return -EINVAL;
106 	i = 0;
107 	while (map[i].name)
108 		i++;
109 
110 	/* Allocate space for the class records, plus one for class zero */
111 	out_map->mapping = kcalloc(++i, sizeof(*out_map->mapping), GFP_ATOMIC);
112 	if (!out_map->mapping)
113 		return -ENOMEM;
114 
115 	/* Store the raw class and permission values */
116 	j = 0;
117 	while (map[j].name) {
118 		const struct security_class_mapping *p_in = map + (j++);
119 		struct selinux_mapping *p_out = out_map->mapping + j;
120 
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 |= 1<<i;
211 			if (allow_unknown && !mapping->perms[i])
212 				result |= 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 |= 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 |= 1<<i;
224 			if (!allow_unknown && !mapping->perms[i])
225 				result |= 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 |= 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 	int 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 		int 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 				u32 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_datum *avdatum;
1710 	struct avtab_node *node;
1711 	u16 tclass;
1712 	int rc = 0;
1713 	bool sock;
1714 
1715 	if (!selinux_initialized()) {
1716 		switch (orig_tclass) {
1717 		case SECCLASS_PROCESS: /* kernel value */
1718 			*out_sid = ssid;
1719 			break;
1720 		default:
1721 			*out_sid = tsid;
1722 			break;
1723 		}
1724 		goto out;
1725 	}
1726 
1727 retry:
1728 	cladatum = NULL;
1729 	context_init(&newcontext);
1730 
1731 	rcu_read_lock();
1732 
1733 	policy = rcu_dereference(selinux_state.policy);
1734 
1735 	if (kern) {
1736 		tclass = unmap_class(&policy->map, orig_tclass);
1737 		sock = security_is_socket_class(orig_tclass);
1738 	} else {
1739 		tclass = orig_tclass;
1740 		sock = security_is_socket_class(map_class(&policy->map,
1741 							  tclass));
1742 	}
1743 
1744 	policydb = &policy->policydb;
1745 	sidtab = policy->sidtab;
1746 
1747 	sentry = sidtab_search_entry(sidtab, ssid);
1748 	if (!sentry) {
1749 		pr_err("SELinux: %s:  unrecognized SID %d\n",
1750 		       __func__, ssid);
1751 		rc = -EINVAL;
1752 		goto out_unlock;
1753 	}
1754 	tentry = sidtab_search_entry(sidtab, tsid);
1755 	if (!tentry) {
1756 		pr_err("SELinux: %s:  unrecognized SID %d\n",
1757 		       __func__, tsid);
1758 		rc = -EINVAL;
1759 		goto out_unlock;
1760 	}
1761 
1762 	scontext = &sentry->context;
1763 	tcontext = &tentry->context;
1764 
1765 	if (tclass && tclass <= policydb->p_classes.nprim)
1766 		cladatum = policydb->class_val_to_struct[tclass - 1];
1767 
1768 	/* Set the user identity. */
1769 	switch (specified) {
1770 	case AVTAB_TRANSITION:
1771 	case AVTAB_CHANGE:
1772 		if (cladatum && cladatum->default_user == DEFAULT_TARGET) {
1773 			newcontext.user = tcontext->user;
1774 		} else {
1775 			/* notice this gets both DEFAULT_SOURCE and unset */
1776 			/* Use the process user identity. */
1777 			newcontext.user = scontext->user;
1778 		}
1779 		break;
1780 	case AVTAB_MEMBER:
1781 		/* Use the related object owner. */
1782 		newcontext.user = tcontext->user;
1783 		break;
1784 	}
1785 
1786 	/* Set the role to default values. */
1787 	if (cladatum && cladatum->default_role == DEFAULT_SOURCE) {
1788 		newcontext.role = scontext->role;
1789 	} else if (cladatum && cladatum->default_role == DEFAULT_TARGET) {
1790 		newcontext.role = tcontext->role;
1791 	} else {
1792 		if ((tclass == policydb->process_class) || sock)
1793 			newcontext.role = scontext->role;
1794 		else
1795 			newcontext.role = OBJECT_R_VAL;
1796 	}
1797 
1798 	/* Set the type to default values. */
1799 	if (cladatum && cladatum->default_type == DEFAULT_SOURCE) {
1800 		newcontext.type = scontext->type;
1801 	} else if (cladatum && cladatum->default_type == DEFAULT_TARGET) {
1802 		newcontext.type = tcontext->type;
1803 	} else {
1804 		if ((tclass == policydb->process_class) || sock) {
1805 			/* Use the type of process. */
1806 			newcontext.type = scontext->type;
1807 		} else {
1808 			/* Use the type of the related object. */
1809 			newcontext.type = tcontext->type;
1810 		}
1811 	}
1812 
1813 	/* Look for a type transition/member/change rule. */
1814 	avkey.source_type = scontext->type;
1815 	avkey.target_type = tcontext->type;
1816 	avkey.target_class = tclass;
1817 	avkey.specified = specified;
1818 	avdatum = avtab_search(&policydb->te_avtab, &avkey);
1819 
1820 	/* If no permanent rule, also check for enabled conditional rules */
1821 	if (!avdatum) {
1822 		node = avtab_search_node(&policydb->te_cond_avtab, &avkey);
1823 		for (; node; node = avtab_search_node_next(node, specified)) {
1824 			if (node->key.specified & AVTAB_ENABLED) {
1825 				avdatum = &node->datum;
1826 				break;
1827 			}
1828 		}
1829 	}
1830 
1831 	if (avdatum) {
1832 		/* Use the type from the type transition/member/change rule. */
1833 		newcontext.type = avdatum->u.data;
1834 	}
1835 
1836 	/* if we have a objname this is a file trans check so check those rules */
1837 	if (objname)
1838 		filename_compute_type(policydb, &newcontext, scontext->type,
1839 				      tcontext->type, tclass, objname);
1840 
1841 	/* Check for class-specific changes. */
1842 	if (specified & AVTAB_TRANSITION) {
1843 		/* Look for a role transition rule. */
1844 		struct role_trans_datum *rtd;
1845 		struct role_trans_key rtk = {
1846 			.role = scontext->role,
1847 			.type = tcontext->type,
1848 			.tclass = tclass,
1849 		};
1850 
1851 		rtd = policydb_roletr_search(policydb, &rtk);
1852 		if (rtd)
1853 			newcontext.role = rtd->new_role;
1854 	}
1855 
1856 	/* Set the MLS attributes.
1857 	   This is done last because it may allocate memory. */
1858 	rc = mls_compute_sid(policydb, scontext, tcontext, tclass, specified,
1859 			     &newcontext, sock);
1860 	if (rc)
1861 		goto out_unlock;
1862 
1863 	/* Check the validity of the context. */
1864 	if (!policydb_context_isvalid(policydb, &newcontext)) {
1865 		rc = compute_sid_handle_invalid_context(policy, sentry,
1866 							tentry, tclass,
1867 							&newcontext);
1868 		if (rc)
1869 			goto out_unlock;
1870 	}
1871 	/* Obtain the sid for the context. */
1872 	rc = sidtab_context_to_sid(sidtab, &newcontext, out_sid);
1873 	if (rc == -ESTALE) {
1874 		rcu_read_unlock();
1875 		context_destroy(&newcontext);
1876 		goto retry;
1877 	}
1878 out_unlock:
1879 	rcu_read_unlock();
1880 	context_destroy(&newcontext);
1881 out:
1882 	return rc;
1883 }
1884 
1885 /**
1886  * security_transition_sid - Compute the SID for a new subject/object.
1887  * @ssid: source security identifier
1888  * @tsid: target security identifier
1889  * @tclass: target security class
1890  * @qstr: object name
1891  * @out_sid: security identifier for new subject/object
1892  *
1893  * Compute a SID to use for labeling a new subject or object in the
1894  * class @tclass based on a SID pair (@ssid, @tsid).
1895  * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1896  * if insufficient memory is available, or %0 if the new SID was
1897  * computed successfully.
1898  */
1899 int security_transition_sid(u32 ssid, u32 tsid, u16 tclass,
1900 			    const struct qstr *qstr, u32 *out_sid)
1901 {
1902 	return security_compute_sid(ssid, tsid, tclass,
1903 				    AVTAB_TRANSITION,
1904 				    qstr ? qstr->name : NULL, out_sid, true);
1905 }
1906 
1907 int security_transition_sid_user(u32 ssid, u32 tsid, u16 tclass,
1908 				 const char *objname, u32 *out_sid)
1909 {
1910 	return security_compute_sid(ssid, tsid, tclass,
1911 				    AVTAB_TRANSITION,
1912 				    objname, out_sid, false);
1913 }
1914 
1915 /**
1916  * security_member_sid - Compute the SID for member selection.
1917  * @ssid: source security identifier
1918  * @tsid: target security identifier
1919  * @tclass: target security class
1920  * @out_sid: security identifier for selected member
1921  *
1922  * Compute a SID to use when selecting a member of a polyinstantiated
1923  * object of class @tclass based on a SID pair (@ssid, @tsid).
1924  * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1925  * if insufficient memory is available, or %0 if the SID was
1926  * computed successfully.
1927  */
1928 int security_member_sid(u32 ssid,
1929 			u32 tsid,
1930 			u16 tclass,
1931 			u32 *out_sid)
1932 {
1933 	return security_compute_sid(ssid, tsid, tclass,
1934 				    AVTAB_MEMBER, NULL,
1935 				    out_sid, false);
1936 }
1937 
1938 /**
1939  * security_change_sid - Compute the SID for object relabeling.
1940  * @ssid: source security identifier
1941  * @tsid: target security identifier
1942  * @tclass: target security class
1943  * @out_sid: security identifier for selected member
1944  *
1945  * Compute a SID to use for relabeling an object of class @tclass
1946  * based on a SID pair (@ssid, @tsid).
1947  * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1948  * if insufficient memory is available, or %0 if the SID was
1949  * computed successfully.
1950  */
1951 int security_change_sid(u32 ssid,
1952 			u32 tsid,
1953 			u16 tclass,
1954 			u32 *out_sid)
1955 {
1956 	return security_compute_sid(ssid, tsid, tclass, AVTAB_CHANGE, NULL,
1957 				    out_sid, false);
1958 }
1959 
1960 static inline int convert_context_handle_invalid_context(
1961 	struct policydb *policydb,
1962 	struct context *context)
1963 {
1964 	char *s;
1965 	u32 len;
1966 
1967 	if (enforcing_enabled())
1968 		return -EINVAL;
1969 
1970 	if (!context_struct_to_string(policydb, context, &s, &len)) {
1971 		pr_warn("SELinux:  Context %s would be invalid if enforcing\n",
1972 			s);
1973 		kfree(s);
1974 	}
1975 	return 0;
1976 }
1977 
1978 /**
1979  * services_convert_context - Convert a security context across policies.
1980  * @args: populated convert_context_args struct
1981  * @oldc: original context
1982  * @newc: converted context
1983  * @gfp_flags: allocation flags
1984  *
1985  * Convert the values in the security context structure @oldc from the values
1986  * specified in the policy @args->oldp to the values specified in the policy
1987  * @args->newp, storing the new context in @newc, and verifying that the
1988  * context is valid under the new policy.
1989  */
1990 int services_convert_context(struct convert_context_args *args,
1991 			     struct context *oldc, struct context *newc,
1992 			     gfp_t gfp_flags)
1993 {
1994 	struct ocontext *oc;
1995 	struct role_datum *role;
1996 	struct type_datum *typdatum;
1997 	struct user_datum *usrdatum;
1998 	char *s;
1999 	u32 len;
2000 	int rc;
2001 
2002 	if (oldc->str) {
2003 		s = kstrdup(oldc->str, gfp_flags);
2004 		if (!s)
2005 			return -ENOMEM;
2006 
2007 		rc = string_to_context_struct(args->newp, NULL, s, newc, SECSID_NULL);
2008 		if (rc == -EINVAL) {
2009 			/*
2010 			 * Retain string representation for later mapping.
2011 			 *
2012 			 * IMPORTANT: We need to copy the contents of oldc->str
2013 			 * back into s again because string_to_context_struct()
2014 			 * may have garbled it.
2015 			 */
2016 			memcpy(s, oldc->str, oldc->len);
2017 			context_init(newc);
2018 			newc->str = s;
2019 			newc->len = oldc->len;
2020 			return 0;
2021 		}
2022 		kfree(s);
2023 		if (rc) {
2024 			/* Other error condition, e.g. ENOMEM. */
2025 			pr_err("SELinux:   Unable to map context %s, rc = %d.\n",
2026 			       oldc->str, -rc);
2027 			return rc;
2028 		}
2029 		pr_info("SELinux:  Context %s became valid (mapped).\n",
2030 			oldc->str);
2031 		return 0;
2032 	}
2033 
2034 	context_init(newc);
2035 
2036 	/* Convert the user. */
2037 	usrdatum = symtab_search(&args->newp->p_users,
2038 				 sym_name(args->oldp, SYM_USERS, oldc->user - 1));
2039 	if (!usrdatum)
2040 		goto bad;
2041 	newc->user = usrdatum->value;
2042 
2043 	/* Convert the role. */
2044 	role = symtab_search(&args->newp->p_roles,
2045 			     sym_name(args->oldp, SYM_ROLES, oldc->role - 1));
2046 	if (!role)
2047 		goto bad;
2048 	newc->role = role->value;
2049 
2050 	/* Convert the type. */
2051 	typdatum = symtab_search(&args->newp->p_types,
2052 				 sym_name(args->oldp, SYM_TYPES, oldc->type - 1));
2053 	if (!typdatum)
2054 		goto bad;
2055 	newc->type = typdatum->value;
2056 
2057 	/* Convert the MLS fields if dealing with MLS policies */
2058 	if (args->oldp->mls_enabled && args->newp->mls_enabled) {
2059 		rc = mls_convert_context(args->oldp, args->newp, oldc, newc);
2060 		if (rc)
2061 			goto bad;
2062 	} else if (!args->oldp->mls_enabled && args->newp->mls_enabled) {
2063 		/*
2064 		 * Switching between non-MLS and MLS policy:
2065 		 * ensure that the MLS fields of the context for all
2066 		 * existing entries in the sidtab are filled in with a
2067 		 * suitable default value, likely taken from one of the
2068 		 * initial SIDs.
2069 		 */
2070 		oc = args->newp->ocontexts[OCON_ISID];
2071 		while (oc && oc->sid[0] != SECINITSID_UNLABELED)
2072 			oc = oc->next;
2073 		if (!oc) {
2074 			pr_err("SELinux:  unable to look up"
2075 				" the initial SIDs list\n");
2076 			goto bad;
2077 		}
2078 		rc = mls_range_set(newc, &oc->context[0].range);
2079 		if (rc)
2080 			goto bad;
2081 	}
2082 
2083 	/* Check the validity of the new context. */
2084 	if (!policydb_context_isvalid(args->newp, newc)) {
2085 		rc = convert_context_handle_invalid_context(args->oldp, oldc);
2086 		if (rc)
2087 			goto bad;
2088 	}
2089 
2090 	return 0;
2091 bad:
2092 	/* Map old representation to string and save it. */
2093 	rc = context_struct_to_string(args->oldp, oldc, &s, &len);
2094 	if (rc)
2095 		return rc;
2096 	context_destroy(newc);
2097 	newc->str = s;
2098 	newc->len = len;
2099 	pr_info("SELinux:  Context %s became invalid (unmapped).\n",
2100 		newc->str);
2101 	return 0;
2102 }
2103 
2104 static void security_load_policycaps(struct selinux_policy *policy)
2105 {
2106 	struct policydb *p;
2107 	unsigned int i;
2108 	struct ebitmap_node *node;
2109 
2110 	p = &policy->policydb;
2111 
2112 	for (i = 0; i < ARRAY_SIZE(selinux_state.policycap); i++)
2113 		WRITE_ONCE(selinux_state.policycap[i],
2114 			ebitmap_get_bit(&p->policycaps, i));
2115 
2116 	for (i = 0; i < ARRAY_SIZE(selinux_policycap_names); i++)
2117 		pr_info("SELinux:  policy capability %s=%d\n",
2118 			selinux_policycap_names[i],
2119 			ebitmap_get_bit(&p->policycaps, i));
2120 
2121 	ebitmap_for_each_positive_bit(&p->policycaps, node, i) {
2122 		if (i >= ARRAY_SIZE(selinux_policycap_names))
2123 			pr_info("SELinux:  unknown policy capability %u\n",
2124 				i);
2125 	}
2126 }
2127 
2128 static int security_preserve_bools(struct selinux_policy *oldpolicy,
2129 				struct selinux_policy *newpolicy);
2130 
2131 static void selinux_policy_free(struct selinux_policy *policy)
2132 {
2133 	if (!policy)
2134 		return;
2135 
2136 	sidtab_destroy(policy->sidtab);
2137 	kfree(policy->map.mapping);
2138 	policydb_destroy(&policy->policydb);
2139 	kfree(policy->sidtab);
2140 	kfree(policy);
2141 }
2142 
2143 static void selinux_policy_cond_free(struct selinux_policy *policy)
2144 {
2145 	cond_policydb_destroy_dup(&policy->policydb);
2146 	kfree(policy);
2147 }
2148 
2149 void selinux_policy_cancel(struct selinux_load_state *load_state)
2150 {
2151 	struct selinux_state *state = &selinux_state;
2152 	struct selinux_policy *oldpolicy;
2153 
2154 	oldpolicy = rcu_dereference_protected(state->policy,
2155 					lockdep_is_held(&state->policy_mutex));
2156 
2157 	sidtab_cancel_convert(oldpolicy->sidtab);
2158 	selinux_policy_free(load_state->policy);
2159 	kfree(load_state->convert_data);
2160 }
2161 
2162 static void selinux_notify_policy_change(u32 seqno)
2163 {
2164 	/* Flush external caches and notify userspace of policy load */
2165 	avc_ss_reset(seqno);
2166 	selnl_notify_policyload(seqno);
2167 	selinux_status_update_policyload(seqno);
2168 	selinux_netlbl_cache_invalidate();
2169 	selinux_xfrm_notify_policyload();
2170 	selinux_ima_measure_state_locked();
2171 }
2172 
2173 void selinux_policy_commit(struct selinux_load_state *load_state)
2174 {
2175 	struct selinux_state *state = &selinux_state;
2176 	struct selinux_policy *oldpolicy, *newpolicy = load_state->policy;
2177 	unsigned long flags;
2178 	u32 seqno;
2179 
2180 	oldpolicy = rcu_dereference_protected(state->policy,
2181 					lockdep_is_held(&state->policy_mutex));
2182 
2183 	/* If switching between different policy types, log MLS status */
2184 	if (oldpolicy) {
2185 		if (oldpolicy->policydb.mls_enabled && !newpolicy->policydb.mls_enabled)
2186 			pr_info("SELinux: Disabling MLS support...\n");
2187 		else if (!oldpolicy->policydb.mls_enabled && newpolicy->policydb.mls_enabled)
2188 			pr_info("SELinux: Enabling MLS support...\n");
2189 	}
2190 
2191 	/* Set latest granting seqno for new policy. */
2192 	if (oldpolicy)
2193 		newpolicy->latest_granting = oldpolicy->latest_granting + 1;
2194 	else
2195 		newpolicy->latest_granting = 1;
2196 	seqno = newpolicy->latest_granting;
2197 
2198 	/* Install the new policy. */
2199 	if (oldpolicy) {
2200 		sidtab_freeze_begin(oldpolicy->sidtab, &flags);
2201 		rcu_assign_pointer(state->policy, newpolicy);
2202 		sidtab_freeze_end(oldpolicy->sidtab, &flags);
2203 	} else {
2204 		rcu_assign_pointer(state->policy, newpolicy);
2205 	}
2206 
2207 	/* Load the policycaps from the new policy */
2208 	security_load_policycaps(newpolicy);
2209 
2210 	if (!selinux_initialized()) {
2211 		/*
2212 		 * After first policy load, the security server is
2213 		 * marked as initialized and ready to handle requests and
2214 		 * any objects created prior to policy load are then labeled.
2215 		 */
2216 		selinux_mark_initialized();
2217 		selinux_complete_init();
2218 	}
2219 
2220 	/* Free the old policy */
2221 	synchronize_rcu();
2222 	selinux_policy_free(oldpolicy);
2223 	kfree(load_state->convert_data);
2224 
2225 	/* Notify others of the policy change */
2226 	selinux_notify_policy_change(seqno);
2227 }
2228 
2229 /**
2230  * security_load_policy - Load a security policy configuration.
2231  * @data: binary policy data
2232  * @len: length of data in bytes
2233  * @load_state: policy load state
2234  *
2235  * Load a new set of security policy configuration data,
2236  * validate it and convert the SID table as necessary.
2237  * This function will flush the access vector cache after
2238  * loading the new policy.
2239  */
2240 int security_load_policy(void *data, size_t len,
2241 			 struct selinux_load_state *load_state)
2242 {
2243 	struct selinux_state *state = &selinux_state;
2244 	struct selinux_policy *newpolicy, *oldpolicy;
2245 	struct selinux_policy_convert_data *convert_data;
2246 	int rc = 0;
2247 	struct policy_file file = { data, len }, *fp = &file;
2248 
2249 	newpolicy = kzalloc(sizeof(*newpolicy), GFP_KERNEL);
2250 	if (!newpolicy)
2251 		return -ENOMEM;
2252 
2253 	newpolicy->sidtab = kzalloc(sizeof(*newpolicy->sidtab), GFP_KERNEL);
2254 	if (!newpolicy->sidtab) {
2255 		rc = -ENOMEM;
2256 		goto err_policy;
2257 	}
2258 
2259 	rc = policydb_read(&newpolicy->policydb, fp);
2260 	if (rc)
2261 		goto err_sidtab;
2262 
2263 	newpolicy->policydb.len = len;
2264 	rc = selinux_set_mapping(&newpolicy->policydb, secclass_map,
2265 				&newpolicy->map);
2266 	if (rc)
2267 		goto err_policydb;
2268 
2269 	rc = policydb_load_isids(&newpolicy->policydb, newpolicy->sidtab);
2270 	if (rc) {
2271 		pr_err("SELinux:  unable to load the initial SIDs\n");
2272 		goto err_mapping;
2273 	}
2274 
2275 	if (!selinux_initialized()) {
2276 		/* First policy load, so no need to preserve state from old policy */
2277 		load_state->policy = newpolicy;
2278 		load_state->convert_data = NULL;
2279 		return 0;
2280 	}
2281 
2282 	oldpolicy = rcu_dereference_protected(state->policy,
2283 					lockdep_is_held(&state->policy_mutex));
2284 
2285 	/* Preserve active boolean values from the old policy */
2286 	rc = security_preserve_bools(oldpolicy, newpolicy);
2287 	if (rc) {
2288 		pr_err("SELinux:  unable to preserve booleans\n");
2289 		goto err_free_isids;
2290 	}
2291 
2292 	/*
2293 	 * Convert the internal representations of contexts
2294 	 * in the new SID table.
2295 	 */
2296 
2297 	convert_data = kmalloc(sizeof(*convert_data), GFP_KERNEL);
2298 	if (!convert_data) {
2299 		rc = -ENOMEM;
2300 		goto err_free_isids;
2301 	}
2302 
2303 	convert_data->args.oldp = &oldpolicy->policydb;
2304 	convert_data->args.newp = &newpolicy->policydb;
2305 
2306 	convert_data->sidtab_params.args = &convert_data->args;
2307 	convert_data->sidtab_params.target = newpolicy->sidtab;
2308 
2309 	rc = sidtab_convert(oldpolicy->sidtab, &convert_data->sidtab_params);
2310 	if (rc) {
2311 		pr_err("SELinux:  unable to convert the internal"
2312 			" representation of contexts in the new SID"
2313 			" table\n");
2314 		goto err_free_convert_data;
2315 	}
2316 
2317 	load_state->policy = newpolicy;
2318 	load_state->convert_data = convert_data;
2319 	return 0;
2320 
2321 err_free_convert_data:
2322 	kfree(convert_data);
2323 err_free_isids:
2324 	sidtab_destroy(newpolicy->sidtab);
2325 err_mapping:
2326 	kfree(newpolicy->map.mapping);
2327 err_policydb:
2328 	policydb_destroy(&newpolicy->policydb);
2329 err_sidtab:
2330 	kfree(newpolicy->sidtab);
2331 err_policy:
2332 	kfree(newpolicy);
2333 
2334 	return rc;
2335 }
2336 
2337 /**
2338  * ocontext_to_sid - Helper to safely get sid for an ocontext
2339  * @sidtab: SID table
2340  * @c: ocontext structure
2341  * @index: index of the context entry (0 or 1)
2342  * @out_sid: pointer to the resulting SID value
2343  *
2344  * For all ocontexts except OCON_ISID the SID fields are populated
2345  * on-demand when needed. Since updating the SID value is an SMP-sensitive
2346  * operation, this helper must be used to do that safely.
2347  *
2348  * WARNING: This function may return -ESTALE, indicating that the caller
2349  * must retry the operation after re-acquiring the policy pointer!
2350  */
2351 static int ocontext_to_sid(struct sidtab *sidtab, struct ocontext *c,
2352 			   size_t index, u32 *out_sid)
2353 {
2354 	int rc;
2355 	u32 sid;
2356 
2357 	/* Ensure the associated sidtab entry is visible to this thread. */
2358 	sid = smp_load_acquire(&c->sid[index]);
2359 	if (!sid) {
2360 		rc = sidtab_context_to_sid(sidtab, &c->context[index], &sid);
2361 		if (rc)
2362 			return rc;
2363 
2364 		/*
2365 		 * Ensure the new sidtab entry is visible to other threads
2366 		 * when they see the SID.
2367 		 */
2368 		smp_store_release(&c->sid[index], sid);
2369 	}
2370 	*out_sid = sid;
2371 	return 0;
2372 }
2373 
2374 /**
2375  * security_port_sid - Obtain the SID for a port.
2376  * @protocol: protocol number
2377  * @port: port number
2378  * @out_sid: security identifier
2379  */
2380 int security_port_sid(u8 protocol, u16 port, u32 *out_sid)
2381 {
2382 	struct selinux_policy *policy;
2383 	struct policydb *policydb;
2384 	struct sidtab *sidtab;
2385 	struct ocontext *c;
2386 	int rc;
2387 
2388 	if (!selinux_initialized()) {
2389 		*out_sid = SECINITSID_PORT;
2390 		return 0;
2391 	}
2392 
2393 retry:
2394 	rc = 0;
2395 	rcu_read_lock();
2396 	policy = rcu_dereference(selinux_state.policy);
2397 	policydb = &policy->policydb;
2398 	sidtab = policy->sidtab;
2399 
2400 	c = policydb->ocontexts[OCON_PORT];
2401 	while (c) {
2402 		if (c->u.port.protocol == protocol &&
2403 		    c->u.port.low_port <= port &&
2404 		    c->u.port.high_port >= port)
2405 			break;
2406 		c = c->next;
2407 	}
2408 
2409 	if (c) {
2410 		rc = ocontext_to_sid(sidtab, c, 0, out_sid);
2411 		if (rc == -ESTALE) {
2412 			rcu_read_unlock();
2413 			goto retry;
2414 		}
2415 		if (rc)
2416 			goto out;
2417 	} else {
2418 		*out_sid = SECINITSID_PORT;
2419 	}
2420 
2421 out:
2422 	rcu_read_unlock();
2423 	return rc;
2424 }
2425 
2426 /**
2427  * security_ib_pkey_sid - Obtain the SID for a pkey.
2428  * @subnet_prefix: Subnet Prefix
2429  * @pkey_num: pkey number
2430  * @out_sid: security identifier
2431  */
2432 int security_ib_pkey_sid(u64 subnet_prefix, u16 pkey_num, u32 *out_sid)
2433 {
2434 	struct selinux_policy *policy;
2435 	struct policydb *policydb;
2436 	struct sidtab *sidtab;
2437 	struct ocontext *c;
2438 	int rc;
2439 
2440 	if (!selinux_initialized()) {
2441 		*out_sid = SECINITSID_UNLABELED;
2442 		return 0;
2443 	}
2444 
2445 retry:
2446 	rc = 0;
2447 	rcu_read_lock();
2448 	policy = rcu_dereference(selinux_state.policy);
2449 	policydb = &policy->policydb;
2450 	sidtab = policy->sidtab;
2451 
2452 	c = policydb->ocontexts[OCON_IBPKEY];
2453 	while (c) {
2454 		if (c->u.ibpkey.low_pkey <= pkey_num &&
2455 		    c->u.ibpkey.high_pkey >= pkey_num &&
2456 		    c->u.ibpkey.subnet_prefix == subnet_prefix)
2457 			break;
2458 
2459 		c = c->next;
2460 	}
2461 
2462 	if (c) {
2463 		rc = ocontext_to_sid(sidtab, c, 0, out_sid);
2464 		if (rc == -ESTALE) {
2465 			rcu_read_unlock();
2466 			goto retry;
2467 		}
2468 		if (rc)
2469 			goto out;
2470 	} else
2471 		*out_sid = SECINITSID_UNLABELED;
2472 
2473 out:
2474 	rcu_read_unlock();
2475 	return rc;
2476 }
2477 
2478 /**
2479  * security_ib_endport_sid - Obtain the SID for a subnet management interface.
2480  * @dev_name: device name
2481  * @port_num: port number
2482  * @out_sid: security identifier
2483  */
2484 int security_ib_endport_sid(const char *dev_name, u8 port_num, u32 *out_sid)
2485 {
2486 	struct selinux_policy *policy;
2487 	struct policydb *policydb;
2488 	struct sidtab *sidtab;
2489 	struct ocontext *c;
2490 	int rc;
2491 
2492 	if (!selinux_initialized()) {
2493 		*out_sid = SECINITSID_UNLABELED;
2494 		return 0;
2495 	}
2496 
2497 retry:
2498 	rc = 0;
2499 	rcu_read_lock();
2500 	policy = rcu_dereference(selinux_state.policy);
2501 	policydb = &policy->policydb;
2502 	sidtab = policy->sidtab;
2503 
2504 	c = policydb->ocontexts[OCON_IBENDPORT];
2505 	while (c) {
2506 		if (c->u.ibendport.port == port_num &&
2507 		    !strncmp(c->u.ibendport.dev_name,
2508 			     dev_name,
2509 			     IB_DEVICE_NAME_MAX))
2510 			break;
2511 
2512 		c = c->next;
2513 	}
2514 
2515 	if (c) {
2516 		rc = ocontext_to_sid(sidtab, c, 0, out_sid);
2517 		if (rc == -ESTALE) {
2518 			rcu_read_unlock();
2519 			goto retry;
2520 		}
2521 		if (rc)
2522 			goto out;
2523 	} else
2524 		*out_sid = SECINITSID_UNLABELED;
2525 
2526 out:
2527 	rcu_read_unlock();
2528 	return rc;
2529 }
2530 
2531 /**
2532  * security_netif_sid - Obtain the SID for a network interface.
2533  * @name: interface name
2534  * @if_sid: interface SID
2535  */
2536 int security_netif_sid(char *name, u32 *if_sid)
2537 {
2538 	struct selinux_policy *policy;
2539 	struct policydb *policydb;
2540 	struct sidtab *sidtab;
2541 	int rc;
2542 	struct ocontext *c;
2543 
2544 	if (!selinux_initialized()) {
2545 		*if_sid = SECINITSID_NETIF;
2546 		return 0;
2547 	}
2548 
2549 retry:
2550 	rc = 0;
2551 	rcu_read_lock();
2552 	policy = rcu_dereference(selinux_state.policy);
2553 	policydb = &policy->policydb;
2554 	sidtab = policy->sidtab;
2555 
2556 	c = policydb->ocontexts[OCON_NETIF];
2557 	while (c) {
2558 		if (strcmp(name, c->u.name) == 0)
2559 			break;
2560 		c = c->next;
2561 	}
2562 
2563 	if (c) {
2564 		rc = ocontext_to_sid(sidtab, c, 0, if_sid);
2565 		if (rc == -ESTALE) {
2566 			rcu_read_unlock();
2567 			goto retry;
2568 		}
2569 		if (rc)
2570 			goto out;
2571 	} else
2572 		*if_sid = SECINITSID_NETIF;
2573 
2574 out:
2575 	rcu_read_unlock();
2576 	return rc;
2577 }
2578 
2579 static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask)
2580 {
2581 	int i, fail = 0;
2582 
2583 	for (i = 0; i < 4; i++)
2584 		if (addr[i] != (input[i] & mask[i])) {
2585 			fail = 1;
2586 			break;
2587 		}
2588 
2589 	return !fail;
2590 }
2591 
2592 /**
2593  * security_node_sid - Obtain the SID for a node (host).
2594  * @domain: communication domain aka address family
2595  * @addrp: address
2596  * @addrlen: address length in bytes
2597  * @out_sid: security identifier
2598  */
2599 int security_node_sid(u16 domain,
2600 		      void *addrp,
2601 		      u32 addrlen,
2602 		      u32 *out_sid)
2603 {
2604 	struct selinux_policy *policy;
2605 	struct policydb *policydb;
2606 	struct sidtab *sidtab;
2607 	int rc;
2608 	struct ocontext *c;
2609 
2610 	if (!selinux_initialized()) {
2611 		*out_sid = SECINITSID_NODE;
2612 		return 0;
2613 	}
2614 
2615 retry:
2616 	rcu_read_lock();
2617 	policy = rcu_dereference(selinux_state.policy);
2618 	policydb = &policy->policydb;
2619 	sidtab = policy->sidtab;
2620 
2621 	switch (domain) {
2622 	case AF_INET: {
2623 		u32 addr;
2624 
2625 		rc = -EINVAL;
2626 		if (addrlen != sizeof(u32))
2627 			goto out;
2628 
2629 		addr = *((u32 *)addrp);
2630 
2631 		c = policydb->ocontexts[OCON_NODE];
2632 		while (c) {
2633 			if (c->u.node.addr == (addr & c->u.node.mask))
2634 				break;
2635 			c = c->next;
2636 		}
2637 		break;
2638 	}
2639 
2640 	case AF_INET6:
2641 		rc = -EINVAL;
2642 		if (addrlen != sizeof(u64) * 2)
2643 			goto out;
2644 		c = policydb->ocontexts[OCON_NODE6];
2645 		while (c) {
2646 			if (match_ipv6_addrmask(addrp, c->u.node6.addr,
2647 						c->u.node6.mask))
2648 				break;
2649 			c = c->next;
2650 		}
2651 		break;
2652 
2653 	default:
2654 		rc = 0;
2655 		*out_sid = SECINITSID_NODE;
2656 		goto out;
2657 	}
2658 
2659 	if (c) {
2660 		rc = ocontext_to_sid(sidtab, c, 0, out_sid);
2661 		if (rc == -ESTALE) {
2662 			rcu_read_unlock();
2663 			goto retry;
2664 		}
2665 		if (rc)
2666 			goto out;
2667 	} else {
2668 		*out_sid = SECINITSID_NODE;
2669 	}
2670 
2671 	rc = 0;
2672 out:
2673 	rcu_read_unlock();
2674 	return rc;
2675 }
2676 
2677 #define SIDS_NEL 25
2678 
2679 /**
2680  * security_get_user_sids - Obtain reachable SIDs for a user.
2681  * @fromsid: starting SID
2682  * @username: username
2683  * @sids: array of reachable SIDs for user
2684  * @nel: number of elements in @sids
2685  *
2686  * Generate the set of SIDs for legal security contexts
2687  * for a given user that can be reached by @fromsid.
2688  * Set *@sids to point to a dynamically allocated
2689  * array containing the set of SIDs.  Set *@nel to the
2690  * number of elements in the array.
2691  */
2692 
2693 int security_get_user_sids(u32 fromsid,
2694 			   char *username,
2695 			   u32 **sids,
2696 			   u32 *nel)
2697 {
2698 	struct selinux_policy *policy;
2699 	struct policydb *policydb;
2700 	struct sidtab *sidtab;
2701 	struct context *fromcon, usercon;
2702 	u32 *mysids = NULL, *mysids2, sid;
2703 	u32 i, j, mynel, maxnel = SIDS_NEL;
2704 	struct user_datum *user;
2705 	struct role_datum *role;
2706 	struct ebitmap_node *rnode, *tnode;
2707 	int rc;
2708 
2709 	*sids = NULL;
2710 	*nel = 0;
2711 
2712 	if (!selinux_initialized())
2713 		return 0;
2714 
2715 	mysids = kcalloc(maxnel, sizeof(*mysids), GFP_KERNEL);
2716 	if (!mysids)
2717 		return -ENOMEM;
2718 
2719 retry:
2720 	mynel = 0;
2721 	rcu_read_lock();
2722 	policy = rcu_dereference(selinux_state.policy);
2723 	policydb = &policy->policydb;
2724 	sidtab = policy->sidtab;
2725 
2726 	context_init(&usercon);
2727 
2728 	rc = -EINVAL;
2729 	fromcon = sidtab_search(sidtab, fromsid);
2730 	if (!fromcon)
2731 		goto out_unlock;
2732 
2733 	rc = -EINVAL;
2734 	user = symtab_search(&policydb->p_users, username);
2735 	if (!user)
2736 		goto out_unlock;
2737 
2738 	usercon.user = user->value;
2739 
2740 	ebitmap_for_each_positive_bit(&user->roles, rnode, i) {
2741 		role = policydb->role_val_to_struct[i];
2742 		usercon.role = i + 1;
2743 		ebitmap_for_each_positive_bit(&role->types, tnode, j) {
2744 			usercon.type = j + 1;
2745 
2746 			if (mls_setup_user_range(policydb, fromcon, user,
2747 						 &usercon))
2748 				continue;
2749 
2750 			rc = sidtab_context_to_sid(sidtab, &usercon, &sid);
2751 			if (rc == -ESTALE) {
2752 				rcu_read_unlock();
2753 				goto retry;
2754 			}
2755 			if (rc)
2756 				goto out_unlock;
2757 			if (mynel < maxnel) {
2758 				mysids[mynel++] = sid;
2759 			} else {
2760 				rc = -ENOMEM;
2761 				maxnel += SIDS_NEL;
2762 				mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
2763 				if (!mysids2)
2764 					goto out_unlock;
2765 				memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
2766 				kfree(mysids);
2767 				mysids = mysids2;
2768 				mysids[mynel++] = sid;
2769 			}
2770 		}
2771 	}
2772 	rc = 0;
2773 out_unlock:
2774 	rcu_read_unlock();
2775 	if (rc || !mynel) {
2776 		kfree(mysids);
2777 		return rc;
2778 	}
2779 
2780 	rc = -ENOMEM;
2781 	mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);
2782 	if (!mysids2) {
2783 		kfree(mysids);
2784 		return rc;
2785 	}
2786 	for (i = 0, j = 0; i < mynel; i++) {
2787 		struct av_decision dummy_avd;
2788 		rc = avc_has_perm_noaudit(fromsid, mysids[i],
2789 					  SECCLASS_PROCESS, /* kernel value */
2790 					  PROCESS__TRANSITION, AVC_STRICT,
2791 					  &dummy_avd);
2792 		if (!rc)
2793 			mysids2[j++] = mysids[i];
2794 		cond_resched();
2795 	}
2796 	kfree(mysids);
2797 	*sids = mysids2;
2798 	*nel = j;
2799 	return 0;
2800 }
2801 
2802 /**
2803  * __security_genfs_sid - Helper to obtain a SID for a file in a filesystem
2804  * @policy: policy
2805  * @fstype: filesystem type
2806  * @path: path from root of mount
2807  * @orig_sclass: file security class
2808  * @sid: SID for path
2809  *
2810  * Obtain a SID to use for a file in a filesystem that
2811  * cannot support xattr or use a fixed labeling behavior like
2812  * transition SIDs or task SIDs.
2813  *
2814  * WARNING: This function may return -ESTALE, indicating that the caller
2815  * must retry the operation after re-acquiring the policy pointer!
2816  */
2817 static inline int __security_genfs_sid(struct selinux_policy *policy,
2818 				       const char *fstype,
2819 				       const char *path,
2820 				       u16 orig_sclass,
2821 				       u32 *sid)
2822 {
2823 	struct policydb *policydb = &policy->policydb;
2824 	struct sidtab *sidtab = policy->sidtab;
2825 	int len;
2826 	u16 sclass;
2827 	struct genfs *genfs;
2828 	struct ocontext *c;
2829 	int cmp = 0;
2830 
2831 	while (path[0] == '/' && path[1] == '/')
2832 		path++;
2833 
2834 	sclass = unmap_class(&policy->map, orig_sclass);
2835 	*sid = SECINITSID_UNLABELED;
2836 
2837 	for (genfs = policydb->genfs; genfs; genfs = genfs->next) {
2838 		cmp = strcmp(fstype, genfs->fstype);
2839 		if (cmp <= 0)
2840 			break;
2841 	}
2842 
2843 	if (!genfs || cmp)
2844 		return -ENOENT;
2845 
2846 	for (c = genfs->head; c; c = c->next) {
2847 		len = strlen(c->u.name);
2848 		if ((!c->v.sclass || sclass == c->v.sclass) &&
2849 		    (strncmp(c->u.name, path, len) == 0))
2850 			break;
2851 	}
2852 
2853 	if (!c)
2854 		return -ENOENT;
2855 
2856 	return ocontext_to_sid(sidtab, c, 0, sid);
2857 }
2858 
2859 /**
2860  * security_genfs_sid - Obtain a SID for a file in a filesystem
2861  * @fstype: filesystem type
2862  * @path: path from root of mount
2863  * @orig_sclass: file security class
2864  * @sid: SID for path
2865  *
2866  * Acquire policy_rwlock before calling __security_genfs_sid() and release
2867  * it afterward.
2868  */
2869 int security_genfs_sid(const char *fstype,
2870 		       const char *path,
2871 		       u16 orig_sclass,
2872 		       u32 *sid)
2873 {
2874 	struct selinux_policy *policy;
2875 	int retval;
2876 
2877 	if (!selinux_initialized()) {
2878 		*sid = SECINITSID_UNLABELED;
2879 		return 0;
2880 	}
2881 
2882 	do {
2883 		rcu_read_lock();
2884 		policy = rcu_dereference(selinux_state.policy);
2885 		retval = __security_genfs_sid(policy, fstype, path,
2886 					      orig_sclass, sid);
2887 		rcu_read_unlock();
2888 	} while (retval == -ESTALE);
2889 	return retval;
2890 }
2891 
2892 int selinux_policy_genfs_sid(struct selinux_policy *policy,
2893 			const char *fstype,
2894 			const char *path,
2895 			u16 orig_sclass,
2896 			u32 *sid)
2897 {
2898 	/* no lock required, policy is not yet accessible by other threads */
2899 	return __security_genfs_sid(policy, fstype, path, orig_sclass, sid);
2900 }
2901 
2902 /**
2903  * security_fs_use - Determine how to handle labeling for a filesystem.
2904  * @sb: superblock in question
2905  */
2906 int security_fs_use(struct super_block *sb)
2907 {
2908 	struct selinux_policy *policy;
2909 	struct policydb *policydb;
2910 	struct sidtab *sidtab;
2911 	int rc;
2912 	struct ocontext *c;
2913 	struct superblock_security_struct *sbsec = selinux_superblock(sb);
2914 	const char *fstype = sb->s_type->name;
2915 
2916 	if (!selinux_initialized()) {
2917 		sbsec->behavior = SECURITY_FS_USE_NONE;
2918 		sbsec->sid = SECINITSID_UNLABELED;
2919 		return 0;
2920 	}
2921 
2922 retry:
2923 	rcu_read_lock();
2924 	policy = rcu_dereference(selinux_state.policy);
2925 	policydb = &policy->policydb;
2926 	sidtab = policy->sidtab;
2927 
2928 	c = policydb->ocontexts[OCON_FSUSE];
2929 	while (c) {
2930 		if (strcmp(fstype, c->u.name) == 0)
2931 			break;
2932 		c = c->next;
2933 	}
2934 
2935 	if (c) {
2936 		sbsec->behavior = c->v.behavior;
2937 		rc = ocontext_to_sid(sidtab, c, 0, &sbsec->sid);
2938 		if (rc == -ESTALE) {
2939 			rcu_read_unlock();
2940 			goto retry;
2941 		}
2942 		if (rc)
2943 			goto out;
2944 	} else {
2945 		rc = __security_genfs_sid(policy, fstype, "/",
2946 					SECCLASS_DIR, &sbsec->sid);
2947 		if (rc == -ESTALE) {
2948 			rcu_read_unlock();
2949 			goto retry;
2950 		}
2951 		if (rc) {
2952 			sbsec->behavior = SECURITY_FS_USE_NONE;
2953 			rc = 0;
2954 		} else {
2955 			sbsec->behavior = SECURITY_FS_USE_GENFS;
2956 		}
2957 	}
2958 
2959 out:
2960 	rcu_read_unlock();
2961 	return rc;
2962 }
2963 
2964 int security_get_bools(struct selinux_policy *policy,
2965 		       u32 *len, char ***names, int **values)
2966 {
2967 	struct policydb *policydb;
2968 	u32 i;
2969 	int rc;
2970 
2971 	policydb = &policy->policydb;
2972 
2973 	*names = NULL;
2974 	*values = NULL;
2975 
2976 	rc = 0;
2977 	*len = policydb->p_bools.nprim;
2978 	if (!*len)
2979 		goto out;
2980 
2981 	rc = -ENOMEM;
2982 	*names = kcalloc(*len, sizeof(char *), GFP_ATOMIC);
2983 	if (!*names)
2984 		goto err;
2985 
2986 	rc = -ENOMEM;
2987 	*values = kcalloc(*len, sizeof(int), GFP_ATOMIC);
2988 	if (!*values)
2989 		goto err;
2990 
2991 	for (i = 0; i < *len; i++) {
2992 		(*values)[i] = policydb->bool_val_to_struct[i]->state;
2993 
2994 		rc = -ENOMEM;
2995 		(*names)[i] = kstrdup(sym_name(policydb, SYM_BOOLS, i),
2996 				      GFP_ATOMIC);
2997 		if (!(*names)[i])
2998 			goto err;
2999 	}
3000 	rc = 0;
3001 out:
3002 	return rc;
3003 err:
3004 	if (*names) {
3005 		for (i = 0; i < *len; i++)
3006 			kfree((*names)[i]);
3007 		kfree(*names);
3008 	}
3009 	kfree(*values);
3010 	*len = 0;
3011 	*names = NULL;
3012 	*values = NULL;
3013 	goto out;
3014 }
3015 
3016 
3017 int security_set_bools(u32 len, int *values)
3018 {
3019 	struct selinux_state *state = &selinux_state;
3020 	struct selinux_policy *newpolicy, *oldpolicy;
3021 	int rc;
3022 	u32 i, seqno = 0;
3023 
3024 	if (!selinux_initialized())
3025 		return -EINVAL;
3026 
3027 	oldpolicy = rcu_dereference_protected(state->policy,
3028 					lockdep_is_held(&state->policy_mutex));
3029 
3030 	/* Consistency check on number of booleans, should never fail */
3031 	if (WARN_ON(len != oldpolicy->policydb.p_bools.nprim))
3032 		return -EINVAL;
3033 
3034 	newpolicy = kmemdup(oldpolicy, sizeof(*newpolicy), GFP_KERNEL);
3035 	if (!newpolicy)
3036 		return -ENOMEM;
3037 
3038 	/*
3039 	 * Deep copy only the parts of the policydb that might be
3040 	 * modified as a result of changing booleans.
3041 	 */
3042 	rc = cond_policydb_dup(&newpolicy->policydb, &oldpolicy->policydb);
3043 	if (rc) {
3044 		kfree(newpolicy);
3045 		return -ENOMEM;
3046 	}
3047 
3048 	/* Update the boolean states in the copy */
3049 	for (i = 0; i < len; i++) {
3050 		int new_state = !!values[i];
3051 		int old_state = newpolicy->policydb.bool_val_to_struct[i]->state;
3052 
3053 		if (new_state != old_state) {
3054 			audit_log(audit_context(), GFP_ATOMIC,
3055 				AUDIT_MAC_CONFIG_CHANGE,
3056 				"bool=%s val=%d old_val=%d auid=%u ses=%u",
3057 				sym_name(&newpolicy->policydb, SYM_BOOLS, i),
3058 				new_state,
3059 				old_state,
3060 				from_kuid(&init_user_ns, audit_get_loginuid(current)),
3061 				audit_get_sessionid(current));
3062 			newpolicy->policydb.bool_val_to_struct[i]->state = new_state;
3063 		}
3064 	}
3065 
3066 	/* Re-evaluate the conditional rules in the copy */
3067 	evaluate_cond_nodes(&newpolicy->policydb);
3068 
3069 	/* Set latest granting seqno for new policy */
3070 	newpolicy->latest_granting = oldpolicy->latest_granting + 1;
3071 	seqno = newpolicy->latest_granting;
3072 
3073 	/* Install the new policy */
3074 	rcu_assign_pointer(state->policy, newpolicy);
3075 
3076 	/*
3077 	 * Free the conditional portions of the old policydb
3078 	 * that were copied for the new policy, and the oldpolicy
3079 	 * structure itself but not what it references.
3080 	 */
3081 	synchronize_rcu();
3082 	selinux_policy_cond_free(oldpolicy);
3083 
3084 	/* Notify others of the policy change */
3085 	selinux_notify_policy_change(seqno);
3086 	return 0;
3087 }
3088 
3089 int security_get_bool_value(u32 index)
3090 {
3091 	struct selinux_policy *policy;
3092 	struct policydb *policydb;
3093 	int rc;
3094 	u32 len;
3095 
3096 	if (!selinux_initialized())
3097 		return 0;
3098 
3099 	rcu_read_lock();
3100 	policy = rcu_dereference(selinux_state.policy);
3101 	policydb = &policy->policydb;
3102 
3103 	rc = -EFAULT;
3104 	len = policydb->p_bools.nprim;
3105 	if (index >= len)
3106 		goto out;
3107 
3108 	rc = policydb->bool_val_to_struct[index]->state;
3109 out:
3110 	rcu_read_unlock();
3111 	return rc;
3112 }
3113 
3114 static int security_preserve_bools(struct selinux_policy *oldpolicy,
3115 				struct selinux_policy *newpolicy)
3116 {
3117 	int rc, *bvalues = NULL;
3118 	char **bnames = NULL;
3119 	struct cond_bool_datum *booldatum;
3120 	u32 i, nbools = 0;
3121 
3122 	rc = security_get_bools(oldpolicy, &nbools, &bnames, &bvalues);
3123 	if (rc)
3124 		goto out;
3125 	for (i = 0; i < nbools; i++) {
3126 		booldatum = symtab_search(&newpolicy->policydb.p_bools,
3127 					bnames[i]);
3128 		if (booldatum)
3129 			booldatum->state = bvalues[i];
3130 	}
3131 	evaluate_cond_nodes(&newpolicy->policydb);
3132 
3133 out:
3134 	if (bnames) {
3135 		for (i = 0; i < nbools; i++)
3136 			kfree(bnames[i]);
3137 	}
3138 	kfree(bnames);
3139 	kfree(bvalues);
3140 	return rc;
3141 }
3142 
3143 /*
3144  * security_sid_mls_copy() - computes a new sid based on the given
3145  * sid and the mls portion of mls_sid.
3146  */
3147 int security_sid_mls_copy(u32 sid, u32 mls_sid, u32 *new_sid)
3148 {
3149 	struct selinux_policy *policy;
3150 	struct policydb *policydb;
3151 	struct sidtab *sidtab;
3152 	struct context *context1;
3153 	struct context *context2;
3154 	struct context newcon;
3155 	char *s;
3156 	u32 len;
3157 	int rc;
3158 
3159 	if (!selinux_initialized()) {
3160 		*new_sid = sid;
3161 		return 0;
3162 	}
3163 
3164 retry:
3165 	rc = 0;
3166 	context_init(&newcon);
3167 
3168 	rcu_read_lock();
3169 	policy = rcu_dereference(selinux_state.policy);
3170 	policydb = &policy->policydb;
3171 	sidtab = policy->sidtab;
3172 
3173 	if (!policydb->mls_enabled) {
3174 		*new_sid = sid;
3175 		goto out_unlock;
3176 	}
3177 
3178 	rc = -EINVAL;
3179 	context1 = sidtab_search(sidtab, sid);
3180 	if (!context1) {
3181 		pr_err("SELinux: %s:  unrecognized SID %d\n",
3182 			__func__, sid);
3183 		goto out_unlock;
3184 	}
3185 
3186 	rc = -EINVAL;
3187 	context2 = sidtab_search(sidtab, mls_sid);
3188 	if (!context2) {
3189 		pr_err("SELinux: %s:  unrecognized SID %d\n",
3190 			__func__, mls_sid);
3191 		goto out_unlock;
3192 	}
3193 
3194 	newcon.user = context1->user;
3195 	newcon.role = context1->role;
3196 	newcon.type = context1->type;
3197 	rc = mls_context_cpy(&newcon, context2);
3198 	if (rc)
3199 		goto out_unlock;
3200 
3201 	/* Check the validity of the new context. */
3202 	if (!policydb_context_isvalid(policydb, &newcon)) {
3203 		rc = convert_context_handle_invalid_context(policydb,
3204 							&newcon);
3205 		if (rc) {
3206 			if (!context_struct_to_string(policydb, &newcon, &s,
3207 						      &len)) {
3208 				struct audit_buffer *ab;
3209 
3210 				ab = audit_log_start(audit_context(),
3211 						     GFP_ATOMIC,
3212 						     AUDIT_SELINUX_ERR);
3213 				audit_log_format(ab,
3214 						 "op=security_sid_mls_copy invalid_context=");
3215 				/* don't record NUL with untrusted strings */
3216 				audit_log_n_untrustedstring(ab, s, len - 1);
3217 				audit_log_end(ab);
3218 				kfree(s);
3219 			}
3220 			goto out_unlock;
3221 		}
3222 	}
3223 	rc = sidtab_context_to_sid(sidtab, &newcon, new_sid);
3224 	if (rc == -ESTALE) {
3225 		rcu_read_unlock();
3226 		context_destroy(&newcon);
3227 		goto retry;
3228 	}
3229 out_unlock:
3230 	rcu_read_unlock();
3231 	context_destroy(&newcon);
3232 	return rc;
3233 }
3234 
3235 /**
3236  * security_net_peersid_resolve - Compare and resolve two network peer SIDs
3237  * @nlbl_sid: NetLabel SID
3238  * @nlbl_type: NetLabel labeling protocol type
3239  * @xfrm_sid: XFRM SID
3240  * @peer_sid: network peer sid
3241  *
3242  * Description:
3243  * Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be
3244  * resolved into a single SID it is returned via @peer_sid and the function
3245  * returns zero.  Otherwise @peer_sid is set to SECSID_NULL and the function
3246  * returns a negative value.  A table summarizing the behavior is below:
3247  *
3248  *                                 | function return |      @sid
3249  *   ------------------------------+-----------------+-----------------
3250  *   no peer labels                |        0        |    SECSID_NULL
3251  *   single peer label             |        0        |    <peer_label>
3252  *   multiple, consistent labels   |        0        |    <peer_label>
3253  *   multiple, inconsistent labels |    -<errno>     |    SECSID_NULL
3254  *
3255  */
3256 int security_net_peersid_resolve(u32 nlbl_sid, u32 nlbl_type,
3257 				 u32 xfrm_sid,
3258 				 u32 *peer_sid)
3259 {
3260 	struct selinux_policy *policy;
3261 	struct policydb *policydb;
3262 	struct sidtab *sidtab;
3263 	int rc;
3264 	struct context *nlbl_ctx;
3265 	struct context *xfrm_ctx;
3266 
3267 	*peer_sid = SECSID_NULL;
3268 
3269 	/* handle the common (which also happens to be the set of easy) cases
3270 	 * right away, these two if statements catch everything involving a
3271 	 * single or absent peer SID/label */
3272 	if (xfrm_sid == SECSID_NULL) {
3273 		*peer_sid = nlbl_sid;
3274 		return 0;
3275 	}
3276 	/* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a "fallback" label
3277 	 * and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label
3278 	 * is present */
3279 	if (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) {
3280 		*peer_sid = xfrm_sid;
3281 		return 0;
3282 	}
3283 
3284 	if (!selinux_initialized())
3285 		return 0;
3286 
3287 	rcu_read_lock();
3288 	policy = rcu_dereference(selinux_state.policy);
3289 	policydb = &policy->policydb;
3290 	sidtab = policy->sidtab;
3291 
3292 	/*
3293 	 * We don't need to check initialized here since the only way both
3294 	 * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the
3295 	 * security server was initialized and state->initialized was true.
3296 	 */
3297 	if (!policydb->mls_enabled) {
3298 		rc = 0;
3299 		goto out;
3300 	}
3301 
3302 	rc = -EINVAL;
3303 	nlbl_ctx = sidtab_search(sidtab, nlbl_sid);
3304 	if (!nlbl_ctx) {
3305 		pr_err("SELinux: %s:  unrecognized SID %d\n",
3306 		       __func__, nlbl_sid);
3307 		goto out;
3308 	}
3309 	rc = -EINVAL;
3310 	xfrm_ctx = sidtab_search(sidtab, xfrm_sid);
3311 	if (!xfrm_ctx) {
3312 		pr_err("SELinux: %s:  unrecognized SID %d\n",
3313 		       __func__, xfrm_sid);
3314 		goto out;
3315 	}
3316 	rc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES);
3317 	if (rc)
3318 		goto out;
3319 
3320 	/* at present NetLabel SIDs/labels really only carry MLS
3321 	 * information so if the MLS portion of the NetLabel SID
3322 	 * matches the MLS portion of the labeled XFRM SID/label
3323 	 * then pass along the XFRM SID as it is the most
3324 	 * expressive */
3325 	*peer_sid = xfrm_sid;
3326 out:
3327 	rcu_read_unlock();
3328 	return rc;
3329 }
3330 
3331 static int get_classes_callback(void *k, void *d, void *args)
3332 {
3333 	struct class_datum *datum = d;
3334 	char *name = k, **classes = args;
3335 	int value = datum->value - 1;
3336 
3337 	classes[value] = kstrdup(name, GFP_ATOMIC);
3338 	if (!classes[value])
3339 		return -ENOMEM;
3340 
3341 	return 0;
3342 }
3343 
3344 int security_get_classes(struct selinux_policy *policy,
3345 			 char ***classes, int *nclasses)
3346 {
3347 	struct policydb *policydb;
3348 	int rc;
3349 
3350 	policydb = &policy->policydb;
3351 
3352 	rc = -ENOMEM;
3353 	*nclasses = policydb->p_classes.nprim;
3354 	*classes = kcalloc(*nclasses, sizeof(**classes), GFP_ATOMIC);
3355 	if (!*classes)
3356 		goto out;
3357 
3358 	rc = hashtab_map(&policydb->p_classes.table, get_classes_callback,
3359 			 *classes);
3360 	if (rc) {
3361 		int i;
3362 		for (i = 0; i < *nclasses; i++)
3363 			kfree((*classes)[i]);
3364 		kfree(*classes);
3365 	}
3366 
3367 out:
3368 	return rc;
3369 }
3370 
3371 static int get_permissions_callback(void *k, void *d, void *args)
3372 {
3373 	struct perm_datum *datum = d;
3374 	char *name = k, **perms = args;
3375 	int value = datum->value - 1;
3376 
3377 	perms[value] = kstrdup(name, GFP_ATOMIC);
3378 	if (!perms[value])
3379 		return -ENOMEM;
3380 
3381 	return 0;
3382 }
3383 
3384 int security_get_permissions(struct selinux_policy *policy,
3385 			     char *class, char ***perms, int *nperms)
3386 {
3387 	struct policydb *policydb;
3388 	int rc, i;
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 	int 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