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