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