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