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