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