2 * Implementation of the security services.
4 * Authors : Stephen Smalley, <sds@epoch.ncsc.mil>
5 * James Morris <jmorris@redhat.com>
7 * Updated: Trusted Computer Solutions, Inc. <dgoeddel@trustedcs.com>
9 * Support for enhanced MLS infrastructure.
10 * Support for context based audit filters.
12 * Updated: Frank Mayer <mayerf@tresys.com> and Karl MacMillan <kmacmillan@tresys.com>
14 * Added conditional policy language extensions
16 * Updated: Hewlett-Packard <paul.moore@hp.com>
18 * Added support for NetLabel
19 * Added support for the policy capability bitmap
21 * Updated: Chad Sellers <csellers@tresys.com>
23 * Added validation of kernel classes and permissions
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.
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>
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>
54 #include "conditional.h"
62 extern void selnl_notify_policyload(u32 seqno);
63 unsigned int policydb_loaded_version;
65 int selinux_policycap_netpeer;
66 int selinux_policycap_openperm;
69 * This is declared in avc.c
71 extern const struct selinux_class_perm selinux_class_perm;
73 static DEFINE_RWLOCK(policy_rwlock);
75 static struct sidtab sidtab;
76 struct policydb policydb;
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
85 static u32 latest_granting;
87 /* Forward declaration. */
88 static int context_struct_to_string(struct context *context, char **scontext,
91 static int context_struct_compute_av(struct context *scontext,
92 struct context *tcontext,
95 struct av_decision *avd);
97 * Return the boolean value of a constraint expression
98 * when it is applied to the specified source and target
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.
107 static int constraint_expr_eval(struct context *scontext,
108 struct context *tcontext,
109 struct context *xcontext,
110 struct constraint_expr *cexpr)
114 struct role_datum *r1, *r2;
115 struct mls_level *l1, *l2;
116 struct constraint_expr *e;
117 int s[CEXPR_MAXDEPTH];
120 for (e = cexpr; e; e = e->next) {
121 switch (e->expr_type) {
137 if (sp == (CEXPR_MAXDEPTH-1))
141 val1 = scontext->user;
142 val2 = tcontext->user;
145 val1 = scontext->type;
146 val2 = tcontext->type;
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];
155 s[++sp] = ebitmap_get_bit(&r1->dominates,
159 s[++sp] = ebitmap_get_bit(&r2->dominates,
163 s[++sp] = (!ebitmap_get_bit(&r1->dominates,
165 !ebitmap_get_bit(&r2->dominates,
173 l1 = &(scontext->range.level[0]);
174 l2 = &(tcontext->range.level[0]);
177 l1 = &(scontext->range.level[0]);
178 l2 = &(tcontext->range.level[1]);
181 l1 = &(scontext->range.level[1]);
182 l2 = &(tcontext->range.level[0]);
185 l1 = &(scontext->range.level[1]);
186 l2 = &(tcontext->range.level[1]);
189 l1 = &(scontext->range.level[0]);
190 l2 = &(scontext->range.level[1]);
193 l1 = &(tcontext->range.level[0]);
194 l2 = &(tcontext->range.level[1]);
199 s[++sp] = mls_level_eq(l1, l2);
202 s[++sp] = !mls_level_eq(l1, l2);
205 s[++sp] = mls_level_dom(l1, l2);
208 s[++sp] = mls_level_dom(l2, l1);
211 s[++sp] = mls_level_incomp(l2, l1);
225 s[++sp] = (val1 == val2);
228 s[++sp] = (val1 != val2);
236 if (sp == (CEXPR_MAXDEPTH-1))
239 if (e->attr & CEXPR_TARGET)
241 else if (e->attr & CEXPR_XTARGET) {
248 if (e->attr & CEXPR_USER)
250 else if (e->attr & CEXPR_ROLE)
252 else if (e->attr & CEXPR_TYPE)
261 s[++sp] = ebitmap_get_bit(&e->names, val1 - 1);
264 s[++sp] = !ebitmap_get_bit(&e->names, val1 - 1);
282 * security_boundary_permission - drops violated permissions
283 * on boundary constraint.
285 static void type_attribute_bounds_av(struct context *scontext,
286 struct context *tcontext,
289 struct av_decision *avd)
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];
300 if (source->bounds) {
301 memset(&lo_avd, 0, sizeof(lo_avd));
303 memcpy(&lo_scontext, scontext, sizeof(lo_scontext));
304 lo_scontext.type = source->bounds;
306 context_struct_compute_av(&lo_scontext,
311 if ((lo_avd.allowed & avd->allowed) == avd->allowed)
312 return; /* no masked permission */
313 masked = ~lo_avd.allowed & avd->allowed;
316 if (target->bounds) {
317 memset(&lo_avd, 0, sizeof(lo_avd));
319 memcpy(&lo_tcontext, tcontext, sizeof(lo_tcontext));
320 lo_tcontext.type = target->bounds;
322 context_struct_compute_av(scontext,
327 if ((lo_avd.allowed & avd->allowed) == avd->allowed)
328 return; /* no masked permission */
329 masked = ~lo_avd.allowed & avd->allowed;
332 if (source->bounds && target->bounds) {
333 memset(&lo_avd, 0, sizeof(lo_avd));
335 * lo_scontext and lo_tcontext are already
339 context_struct_compute_av(&lo_scontext,
344 if ((lo_avd.allowed & avd->allowed) == avd->allowed)
345 return; /* no masked permission */
346 masked = ~lo_avd.allowed & avd->allowed;
350 struct audit_buffer *ab;
352 = policydb.p_type_val_to_name[source->value - 1];
354 = policydb.p_type_val_to_name[target->value - 1];
356 = policydb.p_class_val_to_name[tclass - 1];
358 /* mask violated permissions */
359 avd->allowed &= ~masked;
361 /* notice to userspace via audit message */
362 ab = audit_log_start(current->audit_context,
363 GFP_ATOMIC, AUDIT_SELINUX_ERR);
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);
376 * Compute access vectors based on a context structure pair for
377 * the permissions in a particular class.
379 static int context_struct_compute_av(struct context *scontext,
380 struct context *tcontext,
383 struct av_decision *avd)
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;
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.
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;
407 * Initialize the access vectors to the default values.
411 avd->auditdeny = 0xffffffff;
412 avd->seqno = latest_granting;
416 * Check for all the invalid cases.
418 * - tclass > policy and > kernel
419 * - tclass > policy but is a userspace class
420 * - tclass > policy but we do not allow unknowns
422 if (unlikely(!tclass))
424 if (unlikely(tclass > policydb.p_classes.nprim))
425 if (tclass > kdefs->cts_len ||
426 !kdefs->class_to_string[tclass] ||
427 !policydb.allow_unknown)
431 * Kernel class and we allow unknown so pad the allow decision
432 * the pad will be all 1 for unknown classes.
434 if (tclass <= kdefs->cts_len && policydb.allow_unknown)
435 avd->allowed = policydb.undefined_perms[tclass - 1];
438 * Not in policy. Since decision is completed (all 1 or all 0) return.
440 if (unlikely(tclass > policydb.p_classes.nprim))
443 tclass_datum = policydb.class_val_to_struct[tclass - 1];
446 * If a specific type enforcement rule was defined for
447 * this permission check, then use it.
449 avkey.target_class = tclass;
450 avkey.specified = AVTAB_AV;
451 sattr = &policydb.type_attr_map[scontext->type - 1];
452 tattr = &policydb.type_attr_map[tcontext->type - 1];
453 ebitmap_for_each_positive_bit(sattr, snode, i) {
454 ebitmap_for_each_positive_bit(tattr, tnode, j) {
455 avkey.source_type = i + 1;
456 avkey.target_type = j + 1;
457 for (node = avtab_search_node(&policydb.te_avtab, &avkey);
459 node = avtab_search_node_next(node, avkey.specified)) {
460 if (node->key.specified == AVTAB_ALLOWED)
461 avd->allowed |= node->datum.data;
462 else if (node->key.specified == AVTAB_AUDITALLOW)
463 avd->auditallow |= node->datum.data;
464 else if (node->key.specified == AVTAB_AUDITDENY)
465 avd->auditdeny &= node->datum.data;
468 /* Check conditional av table for additional permissions */
469 cond_compute_av(&policydb.te_cond_avtab, &avkey, avd);
475 * Remove any permissions prohibited by a constraint (this includes
478 constraint = tclass_datum->constraints;
480 if ((constraint->permissions & (avd->allowed)) &&
481 !constraint_expr_eval(scontext, tcontext, NULL,
483 avd->allowed = (avd->allowed) & ~(constraint->permissions);
485 constraint = constraint->next;
489 * If checking process transition permission and the
490 * role is changing, then check the (current_role, new_role)
493 if (tclass == SECCLASS_PROCESS &&
494 (avd->allowed & (PROCESS__TRANSITION | PROCESS__DYNTRANSITION)) &&
495 scontext->role != tcontext->role) {
496 for (ra = policydb.role_allow; ra; ra = ra->next) {
497 if (scontext->role == ra->role &&
498 tcontext->role == ra->new_role)
502 avd->allowed = (avd->allowed) & ~(PROCESS__TRANSITION |
503 PROCESS__DYNTRANSITION);
507 * If the given source and target types have boundary
508 * constraint, lazy checks have to mask any violated
509 * permission and notice it to userspace via audit.
511 type_attribute_bounds_av(scontext, tcontext,
512 tclass, requested, avd);
517 if (!tclass || tclass > kdefs->cts_len ||
518 !kdefs->class_to_string[tclass]) {
519 if (printk_ratelimit())
520 printk(KERN_ERR "SELinux: %s: unrecognized class %d\n",
526 * Known to the kernel, but not to the policy.
527 * Handle as a denial (allowed is 0).
532 static int security_validtrans_handle_fail(struct context *ocontext,
533 struct context *ncontext,
534 struct context *tcontext,
537 char *o = NULL, *n = NULL, *t = NULL;
538 u32 olen, nlen, tlen;
540 if (context_struct_to_string(ocontext, &o, &olen) < 0)
542 if (context_struct_to_string(ncontext, &n, &nlen) < 0)
544 if (context_struct_to_string(tcontext, &t, &tlen) < 0)
546 audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
547 "security_validate_transition: denied for"
548 " oldcontext=%s newcontext=%s taskcontext=%s tclass=%s",
549 o, n, t, policydb.p_class_val_to_name[tclass-1]);
555 if (!selinux_enforcing)
560 int security_validate_transition(u32 oldsid, u32 newsid, u32 tasksid,
563 struct context *ocontext;
564 struct context *ncontext;
565 struct context *tcontext;
566 struct class_datum *tclass_datum;
567 struct constraint_node *constraint;
573 read_lock(&policy_rwlock);
576 * Remap extended Netlink classes for old policy versions.
577 * Do this here rather than socket_type_to_security_class()
578 * in case a newer policy version is loaded, allowing sockets
579 * to remain in the correct class.
581 if (policydb_loaded_version < POLICYDB_VERSION_NLCLASS)
582 if (tclass >= SECCLASS_NETLINK_ROUTE_SOCKET &&
583 tclass <= SECCLASS_NETLINK_DNRT_SOCKET)
584 tclass = SECCLASS_NETLINK_SOCKET;
586 if (!tclass || tclass > policydb.p_classes.nprim) {
587 printk(KERN_ERR "SELinux: %s: unrecognized class %d\n",
592 tclass_datum = policydb.class_val_to_struct[tclass - 1];
594 ocontext = sidtab_search(&sidtab, oldsid);
596 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
602 ncontext = sidtab_search(&sidtab, newsid);
604 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
610 tcontext = sidtab_search(&sidtab, tasksid);
612 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
618 constraint = tclass_datum->validatetrans;
620 if (!constraint_expr_eval(ocontext, ncontext, tcontext,
622 rc = security_validtrans_handle_fail(ocontext, ncontext,
626 constraint = constraint->next;
630 read_unlock(&policy_rwlock);
635 * security_bounded_transition - check whether the given
636 * transition is directed to bounded, or not.
637 * It returns 0, if @newsid is bounded by @oldsid.
638 * Otherwise, it returns error code.
640 * @oldsid : current security identifier
641 * @newsid : destinated security identifier
643 int security_bounded_transition(u32 old_sid, u32 new_sid)
645 struct context *old_context, *new_context;
646 struct type_datum *type;
650 read_lock(&policy_rwlock);
652 old_context = sidtab_search(&sidtab, old_sid);
654 printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n",
659 new_context = sidtab_search(&sidtab, new_sid);
661 printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n",
666 /* type/domain unchaned */
667 if (old_context->type == new_context->type) {
672 index = new_context->type;
674 type = policydb.type_val_to_struct[index - 1];
677 /* not bounded anymore */
683 /* @newsid is bounded by @oldsid */
684 if (type->bounds == old_context->type) {
688 index = type->bounds;
691 read_unlock(&policy_rwlock);
698 * security_compute_av - Compute access vector decisions.
699 * @ssid: source security identifier
700 * @tsid: target security identifier
701 * @tclass: target security class
702 * @requested: requested permissions
703 * @avd: access vector decisions
705 * Compute a set of access vector decisions based on the
706 * SID pair (@ssid, @tsid) for the permissions in @tclass.
707 * Return -%EINVAL if any of the parameters are invalid or %0
708 * if the access vector decisions were computed successfully.
710 int security_compute_av(u32 ssid,
714 struct av_decision *avd)
716 struct context *scontext = NULL, *tcontext = NULL;
719 if (!ss_initialized) {
720 avd->allowed = 0xffffffff;
722 avd->auditdeny = 0xffffffff;
723 avd->seqno = latest_granting;
727 read_lock(&policy_rwlock);
729 scontext = sidtab_search(&sidtab, ssid);
731 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
736 tcontext = sidtab_search(&sidtab, tsid);
738 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
744 rc = context_struct_compute_av(scontext, tcontext, tclass,
747 /* permissive domain? */
748 if (ebitmap_get_bit(&policydb.permissive_map, scontext->type))
749 avd->flags |= AVD_FLAGS_PERMISSIVE;
751 read_unlock(&policy_rwlock);
756 * Write the security context string representation of
757 * the context structure `context' into a dynamically
758 * allocated string of the correct size. Set `*scontext'
759 * to point to this string and set `*scontext_len' to
760 * the length of the string.
762 static int context_struct_to_string(struct context *context, char **scontext, u32 *scontext_len)
770 *scontext_len = context->len;
771 *scontext = kstrdup(context->str, GFP_ATOMIC);
777 /* Compute the size of the context. */
778 *scontext_len += strlen(policydb.p_user_val_to_name[context->user - 1]) + 1;
779 *scontext_len += strlen(policydb.p_role_val_to_name[context->role - 1]) + 1;
780 *scontext_len += strlen(policydb.p_type_val_to_name[context->type - 1]) + 1;
781 *scontext_len += mls_compute_context_len(context);
783 /* Allocate space for the context; caller must free this space. */
784 scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
787 *scontext = scontextp;
790 * Copy the user name, role name and type name into the context.
792 sprintf(scontextp, "%s:%s:%s",
793 policydb.p_user_val_to_name[context->user - 1],
794 policydb.p_role_val_to_name[context->role - 1],
795 policydb.p_type_val_to_name[context->type - 1]);
796 scontextp += strlen(policydb.p_user_val_to_name[context->user - 1]) +
797 1 + strlen(policydb.p_role_val_to_name[context->role - 1]) +
798 1 + strlen(policydb.p_type_val_to_name[context->type - 1]);
800 mls_sid_to_context(context, &scontextp);
807 #include "initial_sid_to_string.h"
809 const char *security_get_initial_sid_context(u32 sid)
811 if (unlikely(sid > SECINITSID_NUM))
813 return initial_sid_to_string[sid];
816 static int security_sid_to_context_core(u32 sid, char **scontext,
817 u32 *scontext_len, int force)
819 struct context *context;
825 if (!ss_initialized) {
826 if (sid <= SECINITSID_NUM) {
829 *scontext_len = strlen(initial_sid_to_string[sid]) + 1;
830 scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
835 strcpy(scontextp, initial_sid_to_string[sid]);
836 *scontext = scontextp;
839 printk(KERN_ERR "SELinux: %s: called before initial "
840 "load_policy on unknown SID %d\n", __func__, sid);
844 read_lock(&policy_rwlock);
846 context = sidtab_search_force(&sidtab, sid);
848 context = sidtab_search(&sidtab, sid);
850 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
855 rc = context_struct_to_string(context, scontext, scontext_len);
857 read_unlock(&policy_rwlock);
864 * security_sid_to_context - Obtain a context for a given SID.
865 * @sid: security identifier, SID
866 * @scontext: security context
867 * @scontext_len: length in bytes
869 * Write the string representation of the context associated with @sid
870 * into a dynamically allocated string of the correct size. Set @scontext
871 * to point to this string and set @scontext_len to the length of the string.
873 int security_sid_to_context(u32 sid, char **scontext, u32 *scontext_len)
875 return security_sid_to_context_core(sid, scontext, scontext_len, 0);
878 int security_sid_to_context_force(u32 sid, char **scontext, u32 *scontext_len)
880 return security_sid_to_context_core(sid, scontext, scontext_len, 1);
884 * Caveat: Mutates scontext.
886 static int string_to_context_struct(struct policydb *pol,
887 struct sidtab *sidtabp,
893 struct role_datum *role;
894 struct type_datum *typdatum;
895 struct user_datum *usrdatum;
896 char *scontextp, *p, oldc;
901 /* Parse the security context. */
904 scontextp = (char *) scontext;
906 /* Extract the user. */
908 while (*p && *p != ':')
916 usrdatum = hashtab_search(pol->p_users.table, scontextp);
920 ctx->user = usrdatum->value;
924 while (*p && *p != ':')
932 role = hashtab_search(pol->p_roles.table, scontextp);
935 ctx->role = role->value;
939 while (*p && *p != ':')
944 typdatum = hashtab_search(pol->p_types.table, scontextp);
945 if (!typdatum || typdatum->attribute)
948 ctx->type = typdatum->value;
950 rc = mls_context_to_sid(pol, oldc, &p, ctx, sidtabp, def_sid);
954 if ((p - scontext) < scontext_len) {
959 /* Check the validity of the new context. */
960 if (!policydb_context_isvalid(pol, ctx)) {
967 context_destroy(ctx);
971 static int security_context_to_sid_core(const char *scontext, u32 scontext_len,
972 u32 *sid, u32 def_sid, gfp_t gfp_flags,
975 char *scontext2, *str = NULL;
976 struct context context;
979 if (!ss_initialized) {
982 for (i = 1; i < SECINITSID_NUM; i++) {
983 if (!strcmp(initial_sid_to_string[i], scontext)) {
988 *sid = SECINITSID_KERNEL;
993 /* Copy the string so that we can modify the copy as we parse it. */
994 scontext2 = kmalloc(scontext_len+1, gfp_flags);
997 memcpy(scontext2, scontext, scontext_len);
998 scontext2[scontext_len] = 0;
1001 /* Save another copy for storing in uninterpreted form */
1002 str = kstrdup(scontext2, gfp_flags);
1009 read_lock(&policy_rwlock);
1010 rc = string_to_context_struct(&policydb, &sidtab,
1011 scontext2, scontext_len,
1013 if (rc == -EINVAL && force) {
1015 context.len = scontext_len;
1019 rc = sidtab_context_to_sid(&sidtab, &context, sid);
1020 context_destroy(&context);
1022 read_unlock(&policy_rwlock);
1029 * security_context_to_sid - Obtain a SID for a given security context.
1030 * @scontext: security context
1031 * @scontext_len: length in bytes
1032 * @sid: security identifier, SID
1034 * Obtains a SID associated with the security context that
1035 * has the string representation specified by @scontext.
1036 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1037 * memory is available, or 0 on success.
1039 int security_context_to_sid(const char *scontext, u32 scontext_len, u32 *sid)
1041 return security_context_to_sid_core(scontext, scontext_len,
1042 sid, SECSID_NULL, GFP_KERNEL, 0);
1046 * security_context_to_sid_default - Obtain a SID for a given security context,
1047 * falling back to specified default if needed.
1049 * @scontext: security context
1050 * @scontext_len: length in bytes
1051 * @sid: security identifier, SID
1052 * @def_sid: default SID to assign on error
1054 * Obtains a SID associated with the security context that
1055 * has the string representation specified by @scontext.
1056 * The default SID is passed to the MLS layer to be used to allow
1057 * kernel labeling of the MLS field if the MLS field is not present
1058 * (for upgrading to MLS without full relabel).
1059 * Implicitly forces adding of the context even if it cannot be mapped yet.
1060 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1061 * memory is available, or 0 on success.
1063 int security_context_to_sid_default(const char *scontext, u32 scontext_len,
1064 u32 *sid, u32 def_sid, gfp_t gfp_flags)
1066 return security_context_to_sid_core(scontext, scontext_len,
1067 sid, def_sid, gfp_flags, 1);
1070 int security_context_to_sid_force(const char *scontext, u32 scontext_len,
1073 return security_context_to_sid_core(scontext, scontext_len,
1074 sid, SECSID_NULL, GFP_KERNEL, 1);
1077 static int compute_sid_handle_invalid_context(
1078 struct context *scontext,
1079 struct context *tcontext,
1081 struct context *newcontext)
1083 char *s = NULL, *t = NULL, *n = NULL;
1084 u32 slen, tlen, nlen;
1086 if (context_struct_to_string(scontext, &s, &slen) < 0)
1088 if (context_struct_to_string(tcontext, &t, &tlen) < 0)
1090 if (context_struct_to_string(newcontext, &n, &nlen) < 0)
1092 audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
1093 "security_compute_sid: invalid context %s"
1097 n, s, t, policydb.p_class_val_to_name[tclass-1]);
1102 if (!selinux_enforcing)
1107 static int security_compute_sid(u32 ssid,
1113 struct context *scontext = NULL, *tcontext = NULL, newcontext;
1114 struct role_trans *roletr = NULL;
1115 struct avtab_key avkey;
1116 struct avtab_datum *avdatum;
1117 struct avtab_node *node;
1120 if (!ss_initialized) {
1122 case SECCLASS_PROCESS:
1132 context_init(&newcontext);
1134 read_lock(&policy_rwlock);
1136 scontext = sidtab_search(&sidtab, ssid);
1138 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
1143 tcontext = sidtab_search(&sidtab, tsid);
1145 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
1151 /* Set the user identity. */
1152 switch (specified) {
1153 case AVTAB_TRANSITION:
1155 /* Use the process user identity. */
1156 newcontext.user = scontext->user;
1159 /* Use the related object owner. */
1160 newcontext.user = tcontext->user;
1164 /* Set the role and type to default values. */
1166 case SECCLASS_PROCESS:
1167 /* Use the current role and type of process. */
1168 newcontext.role = scontext->role;
1169 newcontext.type = scontext->type;
1172 /* Use the well-defined object role. */
1173 newcontext.role = OBJECT_R_VAL;
1174 /* Use the type of the related object. */
1175 newcontext.type = tcontext->type;
1178 /* Look for a type transition/member/change rule. */
1179 avkey.source_type = scontext->type;
1180 avkey.target_type = tcontext->type;
1181 avkey.target_class = tclass;
1182 avkey.specified = specified;
1183 avdatum = avtab_search(&policydb.te_avtab, &avkey);
1185 /* If no permanent rule, also check for enabled conditional rules */
1187 node = avtab_search_node(&policydb.te_cond_avtab, &avkey);
1188 for (; node; node = avtab_search_node_next(node, specified)) {
1189 if (node->key.specified & AVTAB_ENABLED) {
1190 avdatum = &node->datum;
1197 /* Use the type from the type transition/member/change rule. */
1198 newcontext.type = avdatum->data;
1201 /* Check for class-specific changes. */
1203 case SECCLASS_PROCESS:
1204 if (specified & AVTAB_TRANSITION) {
1205 /* Look for a role transition rule. */
1206 for (roletr = policydb.role_tr; roletr;
1207 roletr = roletr->next) {
1208 if (roletr->role == scontext->role &&
1209 roletr->type == tcontext->type) {
1210 /* Use the role transition rule. */
1211 newcontext.role = roletr->new_role;
1221 /* Set the MLS attributes.
1222 This is done last because it may allocate memory. */
1223 rc = mls_compute_sid(scontext, tcontext, tclass, specified, &newcontext);
1227 /* Check the validity of the context. */
1228 if (!policydb_context_isvalid(&policydb, &newcontext)) {
1229 rc = compute_sid_handle_invalid_context(scontext,
1236 /* Obtain the sid for the context. */
1237 rc = sidtab_context_to_sid(&sidtab, &newcontext, out_sid);
1239 read_unlock(&policy_rwlock);
1240 context_destroy(&newcontext);
1246 * security_transition_sid - Compute the SID for a new subject/object.
1247 * @ssid: source security identifier
1248 * @tsid: target security identifier
1249 * @tclass: target security class
1250 * @out_sid: security identifier for new subject/object
1252 * Compute a SID to use for labeling a new subject or object in the
1253 * class @tclass based on a SID pair (@ssid, @tsid).
1254 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1255 * if insufficient memory is available, or %0 if the new SID was
1256 * computed successfully.
1258 int security_transition_sid(u32 ssid,
1263 return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION, out_sid);
1267 * security_member_sid - Compute the SID for member selection.
1268 * @ssid: source security identifier
1269 * @tsid: target security identifier
1270 * @tclass: target security class
1271 * @out_sid: security identifier for selected member
1273 * Compute a SID to use when selecting a member of a polyinstantiated
1274 * object of class @tclass based on a SID pair (@ssid, @tsid).
1275 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1276 * if insufficient memory is available, or %0 if the SID was
1277 * computed successfully.
1279 int security_member_sid(u32 ssid,
1284 return security_compute_sid(ssid, tsid, tclass, AVTAB_MEMBER, out_sid);
1288 * security_change_sid - Compute the SID for object relabeling.
1289 * @ssid: source security identifier
1290 * @tsid: target security identifier
1291 * @tclass: target security class
1292 * @out_sid: security identifier for selected member
1294 * Compute a SID to use for relabeling an object of class @tclass
1295 * based on a SID pair (@ssid, @tsid).
1296 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1297 * if insufficient memory is available, or %0 if the SID was
1298 * computed successfully.
1300 int security_change_sid(u32 ssid,
1305 return security_compute_sid(ssid, tsid, tclass, AVTAB_CHANGE, out_sid);
1309 * Verify that each kernel class that is defined in the
1312 static int validate_classes(struct policydb *p)
1315 struct class_datum *cladatum;
1316 struct perm_datum *perdatum;
1317 u32 nprim, tmp, common_pts_len, perm_val, pol_val;
1319 const struct selinux_class_perm *kdefs = &selinux_class_perm;
1320 const char *def_class, *def_perm, *pol_class;
1321 struct symtab *perms;
1322 bool print_unknown_handle = 0;
1324 if (p->allow_unknown) {
1325 u32 num_classes = kdefs->cts_len;
1326 p->undefined_perms = kcalloc(num_classes, sizeof(u32), GFP_KERNEL);
1327 if (!p->undefined_perms)
1331 for (i = 1; i < kdefs->cts_len; i++) {
1332 def_class = kdefs->class_to_string[i];
1335 if (i > p->p_classes.nprim) {
1337 "SELinux: class %s not defined in policy\n",
1339 if (p->reject_unknown)
1341 if (p->allow_unknown)
1342 p->undefined_perms[i-1] = ~0U;
1343 print_unknown_handle = 1;
1346 pol_class = p->p_class_val_to_name[i-1];
1347 if (strcmp(pol_class, def_class)) {
1349 "SELinux: class %d is incorrect, found %s but should be %s\n",
1350 i, pol_class, def_class);
1354 for (i = 0; i < kdefs->av_pts_len; i++) {
1355 class_val = kdefs->av_perm_to_string[i].tclass;
1356 perm_val = kdefs->av_perm_to_string[i].value;
1357 def_perm = kdefs->av_perm_to_string[i].name;
1358 if (class_val > p->p_classes.nprim)
1360 pol_class = p->p_class_val_to_name[class_val-1];
1361 cladatum = hashtab_search(p->p_classes.table, pol_class);
1363 perms = &cladatum->permissions;
1364 nprim = 1 << (perms->nprim - 1);
1365 if (perm_val > nprim) {
1367 "SELinux: permission %s in class %s not defined in policy\n",
1368 def_perm, pol_class);
1369 if (p->reject_unknown)
1371 if (p->allow_unknown)
1372 p->undefined_perms[class_val-1] |= perm_val;
1373 print_unknown_handle = 1;
1376 perdatum = hashtab_search(perms->table, def_perm);
1377 if (perdatum == NULL) {
1379 "SELinux: permission %s in class %s not found in policy, bad policy\n",
1380 def_perm, pol_class);
1383 pol_val = 1 << (perdatum->value - 1);
1384 if (pol_val != perm_val) {
1386 "SELinux: permission %s in class %s has incorrect value\n",
1387 def_perm, pol_class);
1391 for (i = 0; i < kdefs->av_inherit_len; i++) {
1392 class_val = kdefs->av_inherit[i].tclass;
1393 if (class_val > p->p_classes.nprim)
1395 pol_class = p->p_class_val_to_name[class_val-1];
1396 cladatum = hashtab_search(p->p_classes.table, pol_class);
1398 if (!cladatum->comdatum) {
1400 "SELinux: class %s should have an inherits clause but does not\n",
1404 tmp = kdefs->av_inherit[i].common_base;
1406 while (!(tmp & 0x01)) {
1410 perms = &cladatum->comdatum->permissions;
1411 for (j = 0; j < common_pts_len; j++) {
1412 def_perm = kdefs->av_inherit[i].common_pts[j];
1413 if (j >= perms->nprim) {
1415 "SELinux: permission %s in class %s not defined in policy\n",
1416 def_perm, pol_class);
1417 if (p->reject_unknown)
1419 if (p->allow_unknown)
1420 p->undefined_perms[class_val-1] |= (1 << j);
1421 print_unknown_handle = 1;
1424 perdatum = hashtab_search(perms->table, def_perm);
1425 if (perdatum == NULL) {
1427 "SELinux: permission %s in class %s not found in policy, bad policy\n",
1428 def_perm, pol_class);
1431 if (perdatum->value != j + 1) {
1433 "SELinux: permission %s in class %s has incorrect value\n",
1434 def_perm, pol_class);
1439 if (print_unknown_handle)
1440 printk(KERN_INFO "SELinux: the above unknown classes and permissions will be %s\n",
1441 (security_get_allow_unknown() ? "allowed" : "denied"));
1445 /* Clone the SID into the new SID table. */
1446 static int clone_sid(u32 sid,
1447 struct context *context,
1450 struct sidtab *s = arg;
1452 return sidtab_insert(s, sid, context);
1455 static inline int convert_context_handle_invalid_context(struct context *context)
1459 if (selinux_enforcing) {
1465 if (!context_struct_to_string(context, &s, &len)) {
1467 "SELinux: Context %s would be invalid if enforcing\n",
1475 struct convert_context_args {
1476 struct policydb *oldp;
1477 struct policydb *newp;
1481 * Convert the values in the security context
1482 * structure `c' from the values specified
1483 * in the policy `p->oldp' to the values specified
1484 * in the policy `p->newp'. Verify that the
1485 * context is valid under the new policy.
1487 static int convert_context(u32 key,
1491 struct convert_context_args *args;
1492 struct context oldc;
1493 struct role_datum *role;
1494 struct type_datum *typdatum;
1495 struct user_datum *usrdatum;
1504 s = kstrdup(c->str, GFP_KERNEL);
1509 rc = string_to_context_struct(args->newp, NULL, s,
1510 c->len, &ctx, SECSID_NULL);
1514 "SELinux: Context %s became valid (mapped).\n",
1516 /* Replace string with mapped representation. */
1518 memcpy(c, &ctx, sizeof(*c));
1520 } else if (rc == -EINVAL) {
1521 /* Retain string representation for later mapping. */
1525 /* Other error condition, e.g. ENOMEM. */
1527 "SELinux: Unable to map context %s, rc = %d.\n",
1533 rc = context_cpy(&oldc, c);
1539 /* Convert the user. */
1540 usrdatum = hashtab_search(args->newp->p_users.table,
1541 args->oldp->p_user_val_to_name[c->user - 1]);
1544 c->user = usrdatum->value;
1546 /* Convert the role. */
1547 role = hashtab_search(args->newp->p_roles.table,
1548 args->oldp->p_role_val_to_name[c->role - 1]);
1551 c->role = role->value;
1553 /* Convert the type. */
1554 typdatum = hashtab_search(args->newp->p_types.table,
1555 args->oldp->p_type_val_to_name[c->type - 1]);
1558 c->type = typdatum->value;
1560 rc = mls_convert_context(args->oldp, args->newp, c);
1564 /* Check the validity of the new context. */
1565 if (!policydb_context_isvalid(args->newp, c)) {
1566 rc = convert_context_handle_invalid_context(&oldc);
1571 context_destroy(&oldc);
1576 /* Map old representation to string and save it. */
1577 if (context_struct_to_string(&oldc, &s, &len))
1579 context_destroy(&oldc);
1584 "SELinux: Context %s became invalid (unmapped).\n",
1590 static void security_load_policycaps(void)
1592 selinux_policycap_netpeer = ebitmap_get_bit(&policydb.policycaps,
1593 POLICYDB_CAPABILITY_NETPEER);
1594 selinux_policycap_openperm = ebitmap_get_bit(&policydb.policycaps,
1595 POLICYDB_CAPABILITY_OPENPERM);
1598 extern void selinux_complete_init(void);
1599 static int security_preserve_bools(struct policydb *p);
1602 * security_load_policy - Load a security policy configuration.
1603 * @data: binary policy data
1604 * @len: length of data in bytes
1606 * Load a new set of security policy configuration data,
1607 * validate it and convert the SID table as necessary.
1608 * This function will flush the access vector cache after
1609 * loading the new policy.
1611 int security_load_policy(void *data, size_t len)
1613 struct policydb oldpolicydb, newpolicydb;
1614 struct sidtab oldsidtab, newsidtab;
1615 struct convert_context_args args;
1618 struct policy_file file = { data, len }, *fp = &file;
1620 if (!ss_initialized) {
1622 if (policydb_read(&policydb, fp)) {
1623 avtab_cache_destroy();
1626 if (policydb_load_isids(&policydb, &sidtab)) {
1627 policydb_destroy(&policydb);
1628 avtab_cache_destroy();
1631 /* Verify that the kernel defined classes are correct. */
1632 if (validate_classes(&policydb)) {
1634 "SELinux: the definition of a class is incorrect\n");
1635 sidtab_destroy(&sidtab);
1636 policydb_destroy(&policydb);
1637 avtab_cache_destroy();
1640 security_load_policycaps();
1641 policydb_loaded_version = policydb.policyvers;
1643 seqno = ++latest_granting;
1644 selinux_complete_init();
1645 avc_ss_reset(seqno);
1646 selnl_notify_policyload(seqno);
1647 selinux_netlbl_cache_invalidate();
1648 selinux_xfrm_notify_policyload();
1653 sidtab_hash_eval(&sidtab, "sids");
1656 if (policydb_read(&newpolicydb, fp))
1659 if (sidtab_init(&newsidtab)) {
1660 policydb_destroy(&newpolicydb);
1664 /* Verify that the kernel defined classes are correct. */
1665 if (validate_classes(&newpolicydb)) {
1667 "SELinux: the definition of a class is incorrect\n");
1672 rc = security_preserve_bools(&newpolicydb);
1674 printk(KERN_ERR "SELinux: unable to preserve booleans\n");
1678 /* Clone the SID table. */
1679 sidtab_shutdown(&sidtab);
1680 if (sidtab_map(&sidtab, clone_sid, &newsidtab)) {
1686 * Convert the internal representations of contexts
1687 * in the new SID table.
1689 args.oldp = &policydb;
1690 args.newp = &newpolicydb;
1691 rc = sidtab_map(&newsidtab, convert_context, &args);
1695 /* Save the old policydb and SID table to free later. */
1696 memcpy(&oldpolicydb, &policydb, sizeof policydb);
1697 sidtab_set(&oldsidtab, &sidtab);
1699 /* Install the new policydb and SID table. */
1700 write_lock_irq(&policy_rwlock);
1701 memcpy(&policydb, &newpolicydb, sizeof policydb);
1702 sidtab_set(&sidtab, &newsidtab);
1703 security_load_policycaps();
1704 seqno = ++latest_granting;
1705 policydb_loaded_version = policydb.policyvers;
1706 write_unlock_irq(&policy_rwlock);
1708 /* Free the old policydb and SID table. */
1709 policydb_destroy(&oldpolicydb);
1710 sidtab_destroy(&oldsidtab);
1712 avc_ss_reset(seqno);
1713 selnl_notify_policyload(seqno);
1714 selinux_netlbl_cache_invalidate();
1715 selinux_xfrm_notify_policyload();
1720 sidtab_destroy(&newsidtab);
1721 policydb_destroy(&newpolicydb);
1727 * security_port_sid - Obtain the SID for a port.
1728 * @protocol: protocol number
1729 * @port: port number
1730 * @out_sid: security identifier
1732 int security_port_sid(u8 protocol, u16 port, u32 *out_sid)
1737 read_lock(&policy_rwlock);
1739 c = policydb.ocontexts[OCON_PORT];
1741 if (c->u.port.protocol == protocol &&
1742 c->u.port.low_port <= port &&
1743 c->u.port.high_port >= port)
1750 rc = sidtab_context_to_sid(&sidtab,
1756 *out_sid = c->sid[0];
1758 *out_sid = SECINITSID_PORT;
1762 read_unlock(&policy_rwlock);
1767 * security_netif_sid - Obtain the SID for a network interface.
1768 * @name: interface name
1769 * @if_sid: interface SID
1771 int security_netif_sid(char *name, u32 *if_sid)
1776 read_lock(&policy_rwlock);
1778 c = policydb.ocontexts[OCON_NETIF];
1780 if (strcmp(name, c->u.name) == 0)
1786 if (!c->sid[0] || !c->sid[1]) {
1787 rc = sidtab_context_to_sid(&sidtab,
1792 rc = sidtab_context_to_sid(&sidtab,
1798 *if_sid = c->sid[0];
1800 *if_sid = SECINITSID_NETIF;
1803 read_unlock(&policy_rwlock);
1807 static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask)
1811 for (i = 0; i < 4; i++)
1812 if (addr[i] != (input[i] & mask[i])) {
1821 * security_node_sid - Obtain the SID for a node (host).
1822 * @domain: communication domain aka address family
1824 * @addrlen: address length in bytes
1825 * @out_sid: security identifier
1827 int security_node_sid(u16 domain,
1835 read_lock(&policy_rwlock);
1841 if (addrlen != sizeof(u32)) {
1846 addr = *((u32 *)addrp);
1848 c = policydb.ocontexts[OCON_NODE];
1850 if (c->u.node.addr == (addr & c->u.node.mask))
1858 if (addrlen != sizeof(u64) * 2) {
1862 c = policydb.ocontexts[OCON_NODE6];
1864 if (match_ipv6_addrmask(addrp, c->u.node6.addr,
1872 *out_sid = SECINITSID_NODE;
1878 rc = sidtab_context_to_sid(&sidtab,
1884 *out_sid = c->sid[0];
1886 *out_sid = SECINITSID_NODE;
1890 read_unlock(&policy_rwlock);
1897 * security_get_user_sids - Obtain reachable SIDs for a user.
1898 * @fromsid: starting SID
1899 * @username: username
1900 * @sids: array of reachable SIDs for user
1901 * @nel: number of elements in @sids
1903 * Generate the set of SIDs for legal security contexts
1904 * for a given user that can be reached by @fromsid.
1905 * Set *@sids to point to a dynamically allocated
1906 * array containing the set of SIDs. Set *@nel to the
1907 * number of elements in the array.
1910 int security_get_user_sids(u32 fromsid,
1915 struct context *fromcon, usercon;
1916 u32 *mysids = NULL, *mysids2, sid;
1917 u32 mynel = 0, maxnel = SIDS_NEL;
1918 struct user_datum *user;
1919 struct role_datum *role;
1920 struct ebitmap_node *rnode, *tnode;
1926 if (!ss_initialized)
1929 read_lock(&policy_rwlock);
1931 context_init(&usercon);
1933 fromcon = sidtab_search(&sidtab, fromsid);
1939 user = hashtab_search(policydb.p_users.table, username);
1944 usercon.user = user->value;
1946 mysids = kcalloc(maxnel, sizeof(*mysids), GFP_ATOMIC);
1952 ebitmap_for_each_positive_bit(&user->roles, rnode, i) {
1953 role = policydb.role_val_to_struct[i];
1955 ebitmap_for_each_positive_bit(&role->types, tnode, j) {
1958 if (mls_setup_user_range(fromcon, user, &usercon))
1961 rc = sidtab_context_to_sid(&sidtab, &usercon, &sid);
1964 if (mynel < maxnel) {
1965 mysids[mynel++] = sid;
1968 mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
1973 memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
1976 mysids[mynel++] = sid;
1982 read_unlock(&policy_rwlock);
1988 mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);
1994 for (i = 0, j = 0; i < mynel; i++) {
1995 rc = avc_has_perm_noaudit(fromsid, mysids[i],
1997 PROCESS__TRANSITION, AVC_STRICT,
2000 mysids2[j++] = mysids[i];
2012 * security_genfs_sid - Obtain a SID for a file in a filesystem
2013 * @fstype: filesystem type
2014 * @path: path from root of mount
2015 * @sclass: file security class
2016 * @sid: SID for path
2018 * Obtain a SID to use for a file in a filesystem that
2019 * cannot support xattr or use a fixed labeling behavior like
2020 * transition SIDs or task SIDs.
2022 int security_genfs_sid(const char *fstype,
2028 struct genfs *genfs;
2030 int rc = 0, cmp = 0;
2032 while (path[0] == '/' && path[1] == '/')
2035 read_lock(&policy_rwlock);
2037 for (genfs = policydb.genfs; genfs; genfs = genfs->next) {
2038 cmp = strcmp(fstype, genfs->fstype);
2043 if (!genfs || cmp) {
2044 *sid = SECINITSID_UNLABELED;
2049 for (c = genfs->head; c; c = c->next) {
2050 len = strlen(c->u.name);
2051 if ((!c->v.sclass || sclass == c->v.sclass) &&
2052 (strncmp(c->u.name, path, len) == 0))
2057 *sid = SECINITSID_UNLABELED;
2063 rc = sidtab_context_to_sid(&sidtab,
2072 read_unlock(&policy_rwlock);
2077 * security_fs_use - Determine how to handle labeling for a filesystem.
2078 * @fstype: filesystem type
2079 * @behavior: labeling behavior
2080 * @sid: SID for filesystem (superblock)
2082 int security_fs_use(
2084 unsigned int *behavior,
2090 read_lock(&policy_rwlock);
2092 c = policydb.ocontexts[OCON_FSUSE];
2094 if (strcmp(fstype, c->u.name) == 0)
2100 *behavior = c->v.behavior;
2102 rc = sidtab_context_to_sid(&sidtab,
2110 rc = security_genfs_sid(fstype, "/", SECCLASS_DIR, sid);
2112 *behavior = SECURITY_FS_USE_NONE;
2115 *behavior = SECURITY_FS_USE_GENFS;
2120 read_unlock(&policy_rwlock);
2124 int security_get_bools(int *len, char ***names, int **values)
2126 int i, rc = -ENOMEM;
2128 read_lock(&policy_rwlock);
2132 *len = policydb.p_bools.nprim;
2138 *names = kcalloc(*len, sizeof(char *), GFP_ATOMIC);
2142 *values = kcalloc(*len, sizeof(int), GFP_ATOMIC);
2146 for (i = 0; i < *len; i++) {
2148 (*values)[i] = policydb.bool_val_to_struct[i]->state;
2149 name_len = strlen(policydb.p_bool_val_to_name[i]) + 1;
2150 (*names)[i] = kmalloc(sizeof(char) * name_len, GFP_ATOMIC);
2153 strncpy((*names)[i], policydb.p_bool_val_to_name[i], name_len);
2154 (*names)[i][name_len - 1] = 0;
2158 read_unlock(&policy_rwlock);
2162 for (i = 0; i < *len; i++)
2170 int security_set_bools(int len, int *values)
2173 int lenp, seqno = 0;
2174 struct cond_node *cur;
2176 write_lock_irq(&policy_rwlock);
2178 lenp = policydb.p_bools.nprim;
2184 for (i = 0; i < len; i++) {
2185 if (!!values[i] != policydb.bool_val_to_struct[i]->state) {
2186 audit_log(current->audit_context, GFP_ATOMIC,
2187 AUDIT_MAC_CONFIG_CHANGE,
2188 "bool=%s val=%d old_val=%d auid=%u ses=%u",
2189 policydb.p_bool_val_to_name[i],
2191 policydb.bool_val_to_struct[i]->state,
2192 audit_get_loginuid(current),
2193 audit_get_sessionid(current));
2196 policydb.bool_val_to_struct[i]->state = 1;
2198 policydb.bool_val_to_struct[i]->state = 0;
2201 for (cur = policydb.cond_list; cur; cur = cur->next) {
2202 rc = evaluate_cond_node(&policydb, cur);
2207 seqno = ++latest_granting;
2210 write_unlock_irq(&policy_rwlock);
2212 avc_ss_reset(seqno);
2213 selnl_notify_policyload(seqno);
2214 selinux_xfrm_notify_policyload();
2219 int security_get_bool_value(int bool)
2224 read_lock(&policy_rwlock);
2226 len = policydb.p_bools.nprim;
2232 rc = policydb.bool_val_to_struct[bool]->state;
2234 read_unlock(&policy_rwlock);
2238 static int security_preserve_bools(struct policydb *p)
2240 int rc, nbools = 0, *bvalues = NULL, i;
2241 char **bnames = NULL;
2242 struct cond_bool_datum *booldatum;
2243 struct cond_node *cur;
2245 rc = security_get_bools(&nbools, &bnames, &bvalues);
2248 for (i = 0; i < nbools; i++) {
2249 booldatum = hashtab_search(p->p_bools.table, bnames[i]);
2251 booldatum->state = bvalues[i];
2253 for (cur = p->cond_list; cur; cur = cur->next) {
2254 rc = evaluate_cond_node(p, cur);
2261 for (i = 0; i < nbools; i++)
2270 * security_sid_mls_copy() - computes a new sid based on the given
2271 * sid and the mls portion of mls_sid.
2273 int security_sid_mls_copy(u32 sid, u32 mls_sid, u32 *new_sid)
2275 struct context *context1;
2276 struct context *context2;
2277 struct context newcon;
2282 if (!ss_initialized || !selinux_mls_enabled) {
2287 context_init(&newcon);
2289 read_lock(&policy_rwlock);
2290 context1 = sidtab_search(&sidtab, sid);
2292 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2298 context2 = sidtab_search(&sidtab, mls_sid);
2300 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2306 newcon.user = context1->user;
2307 newcon.role = context1->role;
2308 newcon.type = context1->type;
2309 rc = mls_context_cpy(&newcon, context2);
2313 /* Check the validity of the new context. */
2314 if (!policydb_context_isvalid(&policydb, &newcon)) {
2315 rc = convert_context_handle_invalid_context(&newcon);
2320 rc = sidtab_context_to_sid(&sidtab, &newcon, new_sid);
2324 if (!context_struct_to_string(&newcon, &s, &len)) {
2325 audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2326 "security_sid_mls_copy: invalid context %s", s);
2331 read_unlock(&policy_rwlock);
2332 context_destroy(&newcon);
2338 * security_net_peersid_resolve - Compare and resolve two network peer SIDs
2339 * @nlbl_sid: NetLabel SID
2340 * @nlbl_type: NetLabel labeling protocol type
2341 * @xfrm_sid: XFRM SID
2344 * Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be
2345 * resolved into a single SID it is returned via @peer_sid and the function
2346 * returns zero. Otherwise @peer_sid is set to SECSID_NULL and the function
2347 * returns a negative value. A table summarizing the behavior is below:
2349 * | function return | @sid
2350 * ------------------------------+-----------------+-----------------
2351 * no peer labels | 0 | SECSID_NULL
2352 * single peer label | 0 | <peer_label>
2353 * multiple, consistent labels | 0 | <peer_label>
2354 * multiple, inconsistent labels | -<errno> | SECSID_NULL
2357 int security_net_peersid_resolve(u32 nlbl_sid, u32 nlbl_type,
2362 struct context *nlbl_ctx;
2363 struct context *xfrm_ctx;
2365 /* handle the common (which also happens to be the set of easy) cases
2366 * right away, these two if statements catch everything involving a
2367 * single or absent peer SID/label */
2368 if (xfrm_sid == SECSID_NULL) {
2369 *peer_sid = nlbl_sid;
2372 /* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a "fallback" label
2373 * and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label
2375 if (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) {
2376 *peer_sid = xfrm_sid;
2380 /* we don't need to check ss_initialized here since the only way both
2381 * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the
2382 * security server was initialized and ss_initialized was true */
2383 if (!selinux_mls_enabled) {
2384 *peer_sid = SECSID_NULL;
2388 read_lock(&policy_rwlock);
2390 nlbl_ctx = sidtab_search(&sidtab, nlbl_sid);
2392 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2393 __func__, nlbl_sid);
2397 xfrm_ctx = sidtab_search(&sidtab, xfrm_sid);
2399 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2400 __func__, xfrm_sid);
2404 rc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES);
2407 read_unlock(&policy_rwlock);
2409 /* at present NetLabel SIDs/labels really only carry MLS
2410 * information so if the MLS portion of the NetLabel SID
2411 * matches the MLS portion of the labeled XFRM SID/label
2412 * then pass along the XFRM SID as it is the most
2414 *peer_sid = xfrm_sid;
2416 *peer_sid = SECSID_NULL;
2420 static int get_classes_callback(void *k, void *d, void *args)
2422 struct class_datum *datum = d;
2423 char *name = k, **classes = args;
2424 int value = datum->value - 1;
2426 classes[value] = kstrdup(name, GFP_ATOMIC);
2427 if (!classes[value])
2433 int security_get_classes(char ***classes, int *nclasses)
2437 read_lock(&policy_rwlock);
2439 *nclasses = policydb.p_classes.nprim;
2440 *classes = kcalloc(*nclasses, sizeof(*classes), GFP_ATOMIC);
2444 rc = hashtab_map(policydb.p_classes.table, get_classes_callback,
2448 for (i = 0; i < *nclasses; i++)
2449 kfree((*classes)[i]);
2454 read_unlock(&policy_rwlock);
2458 static int get_permissions_callback(void *k, void *d, void *args)
2460 struct perm_datum *datum = d;
2461 char *name = k, **perms = args;
2462 int value = datum->value - 1;
2464 perms[value] = kstrdup(name, GFP_ATOMIC);
2471 int security_get_permissions(char *class, char ***perms, int *nperms)
2473 int rc = -ENOMEM, i;
2474 struct class_datum *match;
2476 read_lock(&policy_rwlock);
2478 match = hashtab_search(policydb.p_classes.table, class);
2480 printk(KERN_ERR "SELinux: %s: unrecognized class %s\n",
2486 *nperms = match->permissions.nprim;
2487 *perms = kcalloc(*nperms, sizeof(*perms), GFP_ATOMIC);
2491 if (match->comdatum) {
2492 rc = hashtab_map(match->comdatum->permissions.table,
2493 get_permissions_callback, *perms);
2498 rc = hashtab_map(match->permissions.table, get_permissions_callback,
2504 read_unlock(&policy_rwlock);
2508 read_unlock(&policy_rwlock);
2509 for (i = 0; i < *nperms; i++)
2515 int security_get_reject_unknown(void)
2517 return policydb.reject_unknown;
2520 int security_get_allow_unknown(void)
2522 return policydb.allow_unknown;
2526 * security_policycap_supported - Check for a specific policy capability
2527 * @req_cap: capability
2530 * This function queries the currently loaded policy to see if it supports the
2531 * capability specified by @req_cap. Returns true (1) if the capability is
2532 * supported, false (0) if it isn't supported.
2535 int security_policycap_supported(unsigned int req_cap)
2539 read_lock(&policy_rwlock);
2540 rc = ebitmap_get_bit(&policydb.policycaps, req_cap);
2541 read_unlock(&policy_rwlock);
2546 struct selinux_audit_rule {
2548 struct context au_ctxt;
2551 void selinux_audit_rule_free(void *vrule)
2553 struct selinux_audit_rule *rule = vrule;
2556 context_destroy(&rule->au_ctxt);
2561 int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule)
2563 struct selinux_audit_rule *tmprule;
2564 struct role_datum *roledatum;
2565 struct type_datum *typedatum;
2566 struct user_datum *userdatum;
2567 struct selinux_audit_rule **rule = (struct selinux_audit_rule **)vrule;
2572 if (!ss_initialized)
2576 case AUDIT_SUBJ_USER:
2577 case AUDIT_SUBJ_ROLE:
2578 case AUDIT_SUBJ_TYPE:
2579 case AUDIT_OBJ_USER:
2580 case AUDIT_OBJ_ROLE:
2581 case AUDIT_OBJ_TYPE:
2582 /* only 'equals' and 'not equals' fit user, role, and type */
2583 if (op != Audit_equal && op != Audit_not_equal)
2586 case AUDIT_SUBJ_SEN:
2587 case AUDIT_SUBJ_CLR:
2588 case AUDIT_OBJ_LEV_LOW:
2589 case AUDIT_OBJ_LEV_HIGH:
2590 /* we do not allow a range, indicated by the presense of '-' */
2591 if (strchr(rulestr, '-'))
2595 /* only the above fields are valid */
2599 tmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL);
2603 context_init(&tmprule->au_ctxt);
2605 read_lock(&policy_rwlock);
2607 tmprule->au_seqno = latest_granting;
2610 case AUDIT_SUBJ_USER:
2611 case AUDIT_OBJ_USER:
2612 userdatum = hashtab_search(policydb.p_users.table, rulestr);
2616 tmprule->au_ctxt.user = userdatum->value;
2618 case AUDIT_SUBJ_ROLE:
2619 case AUDIT_OBJ_ROLE:
2620 roledatum = hashtab_search(policydb.p_roles.table, rulestr);
2624 tmprule->au_ctxt.role = roledatum->value;
2626 case AUDIT_SUBJ_TYPE:
2627 case AUDIT_OBJ_TYPE:
2628 typedatum = hashtab_search(policydb.p_types.table, rulestr);
2632 tmprule->au_ctxt.type = typedatum->value;
2634 case AUDIT_SUBJ_SEN:
2635 case AUDIT_SUBJ_CLR:
2636 case AUDIT_OBJ_LEV_LOW:
2637 case AUDIT_OBJ_LEV_HIGH:
2638 rc = mls_from_string(rulestr, &tmprule->au_ctxt, GFP_ATOMIC);
2642 read_unlock(&policy_rwlock);
2645 selinux_audit_rule_free(tmprule);
2654 /* Check to see if the rule contains any selinux fields */
2655 int selinux_audit_rule_known(struct audit_krule *rule)
2659 for (i = 0; i < rule->field_count; i++) {
2660 struct audit_field *f = &rule->fields[i];
2662 case AUDIT_SUBJ_USER:
2663 case AUDIT_SUBJ_ROLE:
2664 case AUDIT_SUBJ_TYPE:
2665 case AUDIT_SUBJ_SEN:
2666 case AUDIT_SUBJ_CLR:
2667 case AUDIT_OBJ_USER:
2668 case AUDIT_OBJ_ROLE:
2669 case AUDIT_OBJ_TYPE:
2670 case AUDIT_OBJ_LEV_LOW:
2671 case AUDIT_OBJ_LEV_HIGH:
2679 int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule,
2680 struct audit_context *actx)
2682 struct context *ctxt;
2683 struct mls_level *level;
2684 struct selinux_audit_rule *rule = vrule;
2688 audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2689 "selinux_audit_rule_match: missing rule\n");
2693 read_lock(&policy_rwlock);
2695 if (rule->au_seqno < latest_granting) {
2696 audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2697 "selinux_audit_rule_match: stale rule\n");
2702 ctxt = sidtab_search(&sidtab, sid);
2704 audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2705 "selinux_audit_rule_match: unrecognized SID %d\n",
2711 /* a field/op pair that is not caught here will simply fall through
2714 case AUDIT_SUBJ_USER:
2715 case AUDIT_OBJ_USER:
2718 match = (ctxt->user == rule->au_ctxt.user);
2720 case Audit_not_equal:
2721 match = (ctxt->user != rule->au_ctxt.user);
2725 case AUDIT_SUBJ_ROLE:
2726 case AUDIT_OBJ_ROLE:
2729 match = (ctxt->role == rule->au_ctxt.role);
2731 case Audit_not_equal:
2732 match = (ctxt->role != rule->au_ctxt.role);
2736 case AUDIT_SUBJ_TYPE:
2737 case AUDIT_OBJ_TYPE:
2740 match = (ctxt->type == rule->au_ctxt.type);
2742 case Audit_not_equal:
2743 match = (ctxt->type != rule->au_ctxt.type);
2747 case AUDIT_SUBJ_SEN:
2748 case AUDIT_SUBJ_CLR:
2749 case AUDIT_OBJ_LEV_LOW:
2750 case AUDIT_OBJ_LEV_HIGH:
2751 level = ((field == AUDIT_SUBJ_SEN ||
2752 field == AUDIT_OBJ_LEV_LOW) ?
2753 &ctxt->range.level[0] : &ctxt->range.level[1]);
2756 match = mls_level_eq(&rule->au_ctxt.range.level[0],
2759 case Audit_not_equal:
2760 match = !mls_level_eq(&rule->au_ctxt.range.level[0],
2764 match = (mls_level_dom(&rule->au_ctxt.range.level[0],
2766 !mls_level_eq(&rule->au_ctxt.range.level[0],
2770 match = mls_level_dom(&rule->au_ctxt.range.level[0],
2774 match = (mls_level_dom(level,
2775 &rule->au_ctxt.range.level[0]) &&
2776 !mls_level_eq(level,
2777 &rule->au_ctxt.range.level[0]));
2780 match = mls_level_dom(level,
2781 &rule->au_ctxt.range.level[0]);
2787 read_unlock(&policy_rwlock);
2791 static int (*aurule_callback)(void) = audit_update_lsm_rules;
2793 static int aurule_avc_callback(u32 event, u32 ssid, u32 tsid,
2794 u16 class, u32 perms, u32 *retained)
2798 if (event == AVC_CALLBACK_RESET && aurule_callback)
2799 err = aurule_callback();
2803 static int __init aurule_init(void)
2807 err = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET,
2808 SECSID_NULL, SECSID_NULL, SECCLASS_NULL, 0);
2810 panic("avc_add_callback() failed, error %d\n", err);
2814 __initcall(aurule_init);
2816 #ifdef CONFIG_NETLABEL
2818 * security_netlbl_cache_add - Add an entry to the NetLabel cache
2819 * @secattr: the NetLabel packet security attributes
2820 * @sid: the SELinux SID
2823 * Attempt to cache the context in @ctx, which was derived from the packet in
2824 * @skb, in the NetLabel subsystem cache. This function assumes @secattr has
2825 * already been initialized.
2828 static void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr,
2833 sid_cache = kmalloc(sizeof(*sid_cache), GFP_ATOMIC);
2834 if (sid_cache == NULL)
2836 secattr->cache = netlbl_secattr_cache_alloc(GFP_ATOMIC);
2837 if (secattr->cache == NULL) {
2843 secattr->cache->free = kfree;
2844 secattr->cache->data = sid_cache;
2845 secattr->flags |= NETLBL_SECATTR_CACHE;
2849 * security_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID
2850 * @secattr: the NetLabel packet security attributes
2851 * @sid: the SELinux SID
2854 * Convert the given NetLabel security attributes in @secattr into a
2855 * SELinux SID. If the @secattr field does not contain a full SELinux
2856 * SID/context then use SECINITSID_NETMSG as the foundation. If possibile the
2857 * 'cache' field of @secattr is set and the CACHE flag is set; this is to
2858 * allow the @secattr to be used by NetLabel to cache the secattr to SID
2859 * conversion for future lookups. Returns zero on success, negative values on
2863 int security_netlbl_secattr_to_sid(struct netlbl_lsm_secattr *secattr,
2867 struct context *ctx;
2868 struct context ctx_new;
2870 if (!ss_initialized) {
2875 read_lock(&policy_rwlock);
2877 if (secattr->flags & NETLBL_SECATTR_CACHE) {
2878 *sid = *(u32 *)secattr->cache->data;
2880 } else if (secattr->flags & NETLBL_SECATTR_SECID) {
2881 *sid = secattr->attr.secid;
2883 } else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) {
2884 ctx = sidtab_search(&sidtab, SECINITSID_NETMSG);
2886 goto netlbl_secattr_to_sid_return;
2888 context_init(&ctx_new);
2889 ctx_new.user = ctx->user;
2890 ctx_new.role = ctx->role;
2891 ctx_new.type = ctx->type;
2892 mls_import_netlbl_lvl(&ctx_new, secattr);
2893 if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
2894 if (ebitmap_netlbl_import(&ctx_new.range.level[0].cat,
2895 secattr->attr.mls.cat) != 0)
2896 goto netlbl_secattr_to_sid_return;
2897 memcpy(&ctx_new.range.level[1].cat,
2898 &ctx_new.range.level[0].cat,
2899 sizeof(ctx_new.range.level[0].cat));
2901 if (mls_context_isvalid(&policydb, &ctx_new) != 1)
2902 goto netlbl_secattr_to_sid_return_cleanup;
2904 rc = sidtab_context_to_sid(&sidtab, &ctx_new, sid);
2906 goto netlbl_secattr_to_sid_return_cleanup;
2908 security_netlbl_cache_add(secattr, *sid);
2910 ebitmap_destroy(&ctx_new.range.level[0].cat);
2916 netlbl_secattr_to_sid_return:
2917 read_unlock(&policy_rwlock);
2919 netlbl_secattr_to_sid_return_cleanup:
2920 ebitmap_destroy(&ctx_new.range.level[0].cat);
2921 goto netlbl_secattr_to_sid_return;
2925 * security_netlbl_sid_to_secattr - Convert a SELinux SID to a NetLabel secattr
2926 * @sid: the SELinux SID
2927 * @secattr: the NetLabel packet security attributes
2930 * Convert the given SELinux SID in @sid into a NetLabel security attribute.
2931 * Returns zero on success, negative values on failure.
2934 int security_netlbl_sid_to_secattr(u32 sid, struct netlbl_lsm_secattr *secattr)
2937 struct context *ctx;
2939 if (!ss_initialized)
2942 read_lock(&policy_rwlock);
2943 ctx = sidtab_search(&sidtab, sid);
2946 goto netlbl_sid_to_secattr_failure;
2948 secattr->domain = kstrdup(policydb.p_type_val_to_name[ctx->type - 1],
2950 if (secattr->domain == NULL) {
2952 goto netlbl_sid_to_secattr_failure;
2954 secattr->attr.secid = sid;
2955 secattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID;
2956 mls_export_netlbl_lvl(ctx, secattr);
2957 rc = mls_export_netlbl_cat(ctx, secattr);
2959 goto netlbl_sid_to_secattr_failure;
2960 read_unlock(&policy_rwlock);
2964 netlbl_sid_to_secattr_failure:
2965 read_unlock(&policy_rwlock);
2968 #endif /* CONFIG_NETLABEL */