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