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