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