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