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