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