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