1 // SPDX-License-Identifier: GPL-2.0-only
3 * Implementation of the security services.
10 * Support for enhanced MLS infrastructure.
11 * Support for context based audit filters.
15 * Added conditional policy language extensions
19 * Added support for NetLabel
20 * Added support for the policy capability bitmap
24 * Added validation of kernel classes and permissions
28 * Added support for bounds domain and audit messaged on masked permissions
32 * Added support for runtime switching of the policy type
34 * Copyright (C) 2008, 2009 NEC Corporation
35 * Copyright (C) 2006, 2007 Hewlett-Packard Development Company, L.P.
36 * Copyright (C) 2004-2006 Trusted Computer Solutions, Inc.
37 * Copyright (C) 2003 - 2004, 2006 Tresys Technology, LLC
40 #include <linux/kernel.h>
41 #include <linux/slab.h>
42 #include <linux/string.h>
43 #include <linux/spinlock.h>
44 #include <linux/rcupdate.h>
45 #include <linux/errno.h>
47 #include <linux/sched.h>
48 #include <linux/audit.h>
49 #include <linux/vmalloc.h>
50 #include <net/netlabel.h>
60 #include "conditional.h"
67 #include "policycap_names.h"
70 /* Forward declaration. */
71 static int context_struct_to_string(struct policydb *policydb,
72 struct context *context,
76 static int sidtab_entry_to_string(struct policydb *policydb,
77 struct sidtab *sidtab,
78 struct sidtab_entry *entry,
82 static void context_struct_compute_av(struct policydb *policydb,
83 struct context *scontext,
84 struct context *tcontext,
86 struct av_decision *avd,
87 struct extended_perms *xperms);
89 static int selinux_set_mapping(struct policydb *pol,
90 struct security_class_mapping *map,
91 struct selinux_map *out_map)
95 bool print_unknown_handle = false;
97 /* Find number of classes in the input mapping */
104 /* Allocate space for the class records, plus one for class zero */
105 out_map->mapping = kcalloc(++i, sizeof(*out_map->mapping), GFP_ATOMIC);
106 if (!out_map->mapping)
109 /* Store the raw class and permission values */
111 while (map[j].name) {
112 struct security_class_mapping *p_in = map + (j++);
113 struct selinux_mapping *p_out = out_map->mapping + j;
115 /* An empty class string skips ahead */
116 if (!strcmp(p_in->name, "")) {
117 p_out->num_perms = 0;
121 p_out->value = string_to_security_class(pol, p_in->name);
123 pr_info("SELinux: Class %s not defined in policy.\n",
125 if (pol->reject_unknown)
127 p_out->num_perms = 0;
128 print_unknown_handle = true;
133 while (p_in->perms[k]) {
134 /* An empty permission string skips ahead */
135 if (!*p_in->perms[k]) {
139 p_out->perms[k] = string_to_av_perm(pol, p_out->value,
141 if (!p_out->perms[k]) {
142 pr_info("SELinux: Permission %s in class %s not defined in policy.\n",
143 p_in->perms[k], p_in->name);
144 if (pol->reject_unknown)
146 print_unknown_handle = true;
151 p_out->num_perms = k;
154 if (print_unknown_handle)
155 pr_info("SELinux: the above unknown classes and permissions will be %s\n",
156 pol->allow_unknown ? "allowed" : "denied");
161 kfree(out_map->mapping);
162 out_map->mapping = NULL;
167 * Get real, policy values from mapped values
170 static u16 unmap_class(struct selinux_map *map, u16 tclass)
172 if (tclass < map->size)
173 return map->mapping[tclass].value;
179 * Get kernel value for class from its policy value
181 static u16 map_class(struct selinux_map *map, u16 pol_value)
185 for (i = 1; i < map->size; i++) {
186 if (map->mapping[i].value == pol_value)
190 return SECCLASS_NULL;
193 static void map_decision(struct selinux_map *map,
194 u16 tclass, struct av_decision *avd,
197 if (tclass < map->size) {
198 struct selinux_mapping *mapping = &map->mapping[tclass];
199 unsigned int i, n = mapping->num_perms;
202 for (i = 0, result = 0; i < n; i++) {
203 if (avd->allowed & mapping->perms[i])
205 if (allow_unknown && !mapping->perms[i])
208 avd->allowed = result;
210 for (i = 0, result = 0; i < n; i++)
211 if (avd->auditallow & mapping->perms[i])
213 avd->auditallow = result;
215 for (i = 0, result = 0; i < n; i++) {
216 if (avd->auditdeny & mapping->perms[i])
218 if (!allow_unknown && !mapping->perms[i])
222 * In case the kernel has a bug and requests a permission
223 * between num_perms and the maximum permission number, we
224 * should audit that denial
226 for (; i < (sizeof(u32)*8); i++)
228 avd->auditdeny = result;
232 int security_mls_enabled(struct selinux_state *state)
235 struct selinux_policy *policy;
237 if (!selinux_initialized(state))
241 policy = rcu_dereference(state->policy);
242 mls_enabled = policy->policydb.mls_enabled;
248 * Return the boolean value of a constraint expression
249 * when it is applied to the specified source and target
252 * xcontext is a special beast... It is used by the validatetrans rules
253 * only. For these rules, scontext is the context before the transition,
254 * tcontext is the context after the transition, and xcontext is the context
255 * of the process performing the transition. All other callers of
256 * constraint_expr_eval should pass in NULL for xcontext.
258 static int constraint_expr_eval(struct policydb *policydb,
259 struct context *scontext,
260 struct context *tcontext,
261 struct context *xcontext,
262 struct constraint_expr *cexpr)
266 struct role_datum *r1, *r2;
267 struct mls_level *l1, *l2;
268 struct constraint_expr *e;
269 int s[CEXPR_MAXDEPTH];
272 for (e = cexpr; e; e = e->next) {
273 switch (e->expr_type) {
289 if (sp == (CEXPR_MAXDEPTH - 1))
293 val1 = scontext->user;
294 val2 = tcontext->user;
297 val1 = scontext->type;
298 val2 = tcontext->type;
301 val1 = scontext->role;
302 val2 = tcontext->role;
303 r1 = policydb->role_val_to_struct[val1 - 1];
304 r2 = policydb->role_val_to_struct[val2 - 1];
307 s[++sp] = ebitmap_get_bit(&r1->dominates,
311 s[++sp] = ebitmap_get_bit(&r2->dominates,
315 s[++sp] = (!ebitmap_get_bit(&r1->dominates,
317 !ebitmap_get_bit(&r2->dominates,
325 l1 = &(scontext->range.level[0]);
326 l2 = &(tcontext->range.level[0]);
329 l1 = &(scontext->range.level[0]);
330 l2 = &(tcontext->range.level[1]);
333 l1 = &(scontext->range.level[1]);
334 l2 = &(tcontext->range.level[0]);
337 l1 = &(scontext->range.level[1]);
338 l2 = &(tcontext->range.level[1]);
341 l1 = &(scontext->range.level[0]);
342 l2 = &(scontext->range.level[1]);
345 l1 = &(tcontext->range.level[0]);
346 l2 = &(tcontext->range.level[1]);
351 s[++sp] = mls_level_eq(l1, l2);
354 s[++sp] = !mls_level_eq(l1, l2);
357 s[++sp] = mls_level_dom(l1, l2);
360 s[++sp] = mls_level_dom(l2, l1);
363 s[++sp] = mls_level_incomp(l2, l1);
377 s[++sp] = (val1 == val2);
380 s[++sp] = (val1 != val2);
388 if (sp == (CEXPR_MAXDEPTH-1))
391 if (e->attr & CEXPR_TARGET)
393 else if (e->attr & CEXPR_XTARGET) {
400 if (e->attr & CEXPR_USER)
402 else if (e->attr & CEXPR_ROLE)
404 else if (e->attr & CEXPR_TYPE)
413 s[++sp] = ebitmap_get_bit(&e->names, val1 - 1);
416 s[++sp] = !ebitmap_get_bit(&e->names, val1 - 1);
434 * security_dump_masked_av - dumps masked permissions during
435 * security_compute_av due to RBAC, MLS/Constraint and Type bounds.
437 static int dump_masked_av_helper(void *k, void *d, void *args)
439 struct perm_datum *pdatum = d;
440 char **permission_names = args;
442 BUG_ON(pdatum->value < 1 || pdatum->value > 32);
444 permission_names[pdatum->value - 1] = (char *)k;
449 static void security_dump_masked_av(struct policydb *policydb,
450 struct context *scontext,
451 struct context *tcontext,
456 struct common_datum *common_dat;
457 struct class_datum *tclass_dat;
458 struct audit_buffer *ab;
460 char *scontext_name = NULL;
461 char *tcontext_name = NULL;
462 char *permission_names[32];
465 bool need_comma = false;
470 tclass_name = sym_name(policydb, SYM_CLASSES, tclass - 1);
471 tclass_dat = policydb->class_val_to_struct[tclass - 1];
472 common_dat = tclass_dat->comdatum;
474 /* init permission_names */
476 hashtab_map(&common_dat->permissions.table,
477 dump_masked_av_helper, permission_names) < 0)
480 if (hashtab_map(&tclass_dat->permissions.table,
481 dump_masked_av_helper, permission_names) < 0)
484 /* get scontext/tcontext in text form */
485 if (context_struct_to_string(policydb, scontext,
486 &scontext_name, &length) < 0)
489 if (context_struct_to_string(policydb, tcontext,
490 &tcontext_name, &length) < 0)
493 /* audit a message */
494 ab = audit_log_start(audit_context(),
495 GFP_ATOMIC, AUDIT_SELINUX_ERR);
499 audit_log_format(ab, "op=security_compute_av reason=%s "
500 "scontext=%s tcontext=%s tclass=%s perms=",
501 reason, scontext_name, tcontext_name, tclass_name);
503 for (index = 0; index < 32; index++) {
504 u32 mask = (1 << index);
506 if ((mask & permissions) == 0)
509 audit_log_format(ab, "%s%s",
510 need_comma ? "," : "",
511 permission_names[index]
512 ? permission_names[index] : "????");
517 /* release scontext/tcontext */
518 kfree(tcontext_name);
519 kfree(scontext_name);
525 * security_boundary_permission - drops violated permissions
526 * on boundary constraint.
528 static void type_attribute_bounds_av(struct policydb *policydb,
529 struct context *scontext,
530 struct context *tcontext,
532 struct av_decision *avd)
534 struct context lo_scontext;
535 struct context lo_tcontext, *tcontextp = tcontext;
536 struct av_decision lo_avd;
537 struct type_datum *source;
538 struct type_datum *target;
541 source = policydb->type_val_to_struct[scontext->type - 1];
547 target = policydb->type_val_to_struct[tcontext->type - 1];
550 memset(&lo_avd, 0, sizeof(lo_avd));
552 memcpy(&lo_scontext, scontext, sizeof(lo_scontext));
553 lo_scontext.type = source->bounds;
555 if (target->bounds) {
556 memcpy(&lo_tcontext, tcontext, sizeof(lo_tcontext));
557 lo_tcontext.type = target->bounds;
558 tcontextp = &lo_tcontext;
561 context_struct_compute_av(policydb, &lo_scontext,
567 masked = ~lo_avd.allowed & avd->allowed;
570 return; /* no masked permission */
572 /* mask violated permissions */
573 avd->allowed &= ~masked;
575 /* audit masked permissions */
576 security_dump_masked_av(policydb, scontext, tcontext,
577 tclass, masked, "bounds");
581 * flag which drivers have permissions
582 * only looking for ioctl based extended permssions
584 void services_compute_xperms_drivers(
585 struct extended_perms *xperms,
586 struct avtab_node *node)
590 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
591 /* if one or more driver has all permissions allowed */
592 for (i = 0; i < ARRAY_SIZE(xperms->drivers.p); i++)
593 xperms->drivers.p[i] |= node->datum.u.xperms->perms.p[i];
594 } else if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
595 /* if allowing permissions within a driver */
596 security_xperm_set(xperms->drivers.p,
597 node->datum.u.xperms->driver);
604 * Compute access vectors and extended permissions based on a context
605 * structure pair for the permissions in a particular class.
607 static void context_struct_compute_av(struct policydb *policydb,
608 struct context *scontext,
609 struct context *tcontext,
611 struct av_decision *avd,
612 struct extended_perms *xperms)
614 struct constraint_node *constraint;
615 struct role_allow *ra;
616 struct avtab_key avkey;
617 struct avtab_node *node;
618 struct class_datum *tclass_datum;
619 struct ebitmap *sattr, *tattr;
620 struct ebitmap_node *snode, *tnode;
625 avd->auditdeny = 0xffffffff;
627 memset(&xperms->drivers, 0, sizeof(xperms->drivers));
631 if (unlikely(!tclass || tclass > policydb->p_classes.nprim)) {
632 if (printk_ratelimit())
633 pr_warn("SELinux: Invalid class %hu\n", tclass);
637 tclass_datum = policydb->class_val_to_struct[tclass - 1];
640 * If a specific type enforcement rule was defined for
641 * this permission check, then use it.
643 avkey.target_class = tclass;
644 avkey.specified = AVTAB_AV | AVTAB_XPERMS;
645 sattr = &policydb->type_attr_map_array[scontext->type - 1];
646 tattr = &policydb->type_attr_map_array[tcontext->type - 1];
647 ebitmap_for_each_positive_bit(sattr, snode, i) {
648 ebitmap_for_each_positive_bit(tattr, tnode, j) {
649 avkey.source_type = i + 1;
650 avkey.target_type = j + 1;
651 for (node = avtab_search_node(&policydb->te_avtab,
654 node = avtab_search_node_next(node, avkey.specified)) {
655 if (node->key.specified == AVTAB_ALLOWED)
656 avd->allowed |= node->datum.u.data;
657 else if (node->key.specified == AVTAB_AUDITALLOW)
658 avd->auditallow |= node->datum.u.data;
659 else if (node->key.specified == AVTAB_AUDITDENY)
660 avd->auditdeny &= node->datum.u.data;
661 else if (xperms && (node->key.specified & AVTAB_XPERMS))
662 services_compute_xperms_drivers(xperms, node);
665 /* Check conditional av table for additional permissions */
666 cond_compute_av(&policydb->te_cond_avtab, &avkey,
673 * Remove any permissions prohibited by a constraint (this includes
676 constraint = tclass_datum->constraints;
678 if ((constraint->permissions & (avd->allowed)) &&
679 !constraint_expr_eval(policydb, scontext, tcontext, NULL,
681 avd->allowed &= ~(constraint->permissions);
683 constraint = constraint->next;
687 * If checking process transition permission and the
688 * role is changing, then check the (current_role, new_role)
691 if (tclass == policydb->process_class &&
692 (avd->allowed & policydb->process_trans_perms) &&
693 scontext->role != tcontext->role) {
694 for (ra = policydb->role_allow; ra; ra = ra->next) {
695 if (scontext->role == ra->role &&
696 tcontext->role == ra->new_role)
700 avd->allowed &= ~policydb->process_trans_perms;
704 * If the given source and target types have boundary
705 * constraint, lazy checks have to mask any violated
706 * permission and notice it to userspace via audit.
708 type_attribute_bounds_av(policydb, scontext, tcontext,
712 static int security_validtrans_handle_fail(struct selinux_state *state,
713 struct selinux_policy *policy,
714 struct sidtab_entry *oentry,
715 struct sidtab_entry *nentry,
716 struct sidtab_entry *tentry,
719 struct policydb *p = &policy->policydb;
720 struct sidtab *sidtab = policy->sidtab;
721 char *o = NULL, *n = NULL, *t = NULL;
722 u32 olen, nlen, tlen;
724 if (sidtab_entry_to_string(p, sidtab, oentry, &o, &olen))
726 if (sidtab_entry_to_string(p, sidtab, nentry, &n, &nlen))
728 if (sidtab_entry_to_string(p, sidtab, tentry, &t, &tlen))
730 audit_log(audit_context(), GFP_ATOMIC, AUDIT_SELINUX_ERR,
731 "op=security_validate_transition seresult=denied"
732 " oldcontext=%s newcontext=%s taskcontext=%s tclass=%s",
733 o, n, t, sym_name(p, SYM_CLASSES, tclass-1));
739 if (!enforcing_enabled(state))
744 static int security_compute_validatetrans(struct selinux_state *state,
745 u32 oldsid, u32 newsid, u32 tasksid,
746 u16 orig_tclass, bool user)
748 struct selinux_policy *policy;
749 struct policydb *policydb;
750 struct sidtab *sidtab;
751 struct sidtab_entry *oentry;
752 struct sidtab_entry *nentry;
753 struct sidtab_entry *tentry;
754 struct class_datum *tclass_datum;
755 struct constraint_node *constraint;
760 if (!selinux_initialized(state))
765 policy = rcu_dereference(state->policy);
766 policydb = &policy->policydb;
767 sidtab = policy->sidtab;
770 tclass = unmap_class(&policy->map, orig_tclass);
772 tclass = orig_tclass;
774 if (!tclass || tclass > policydb->p_classes.nprim) {
778 tclass_datum = policydb->class_val_to_struct[tclass - 1];
780 oentry = sidtab_search_entry(sidtab, oldsid);
782 pr_err("SELinux: %s: unrecognized SID %d\n",
788 nentry = sidtab_search_entry(sidtab, newsid);
790 pr_err("SELinux: %s: unrecognized SID %d\n",
796 tentry = sidtab_search_entry(sidtab, tasksid);
798 pr_err("SELinux: %s: unrecognized SID %d\n",
804 constraint = tclass_datum->validatetrans;
806 if (!constraint_expr_eval(policydb, &oentry->context,
807 &nentry->context, &tentry->context,
812 rc = security_validtrans_handle_fail(state,
820 constraint = constraint->next;
828 int security_validate_transition_user(struct selinux_state *state,
829 u32 oldsid, u32 newsid, u32 tasksid,
832 return security_compute_validatetrans(state, oldsid, newsid, tasksid,
836 int security_validate_transition(struct selinux_state *state,
837 u32 oldsid, u32 newsid, u32 tasksid,
840 return security_compute_validatetrans(state, oldsid, newsid, tasksid,
845 * security_bounded_transition - check whether the given
846 * transition is directed to bounded, or not.
847 * It returns 0, if @newsid is bounded by @oldsid.
848 * Otherwise, it returns error code.
850 * @oldsid : current security identifier
851 * @newsid : destinated security identifier
853 int security_bounded_transition(struct selinux_state *state,
854 u32 old_sid, u32 new_sid)
856 struct selinux_policy *policy;
857 struct policydb *policydb;
858 struct sidtab *sidtab;
859 struct sidtab_entry *old_entry, *new_entry;
860 struct type_datum *type;
864 if (!selinux_initialized(state))
868 policy = rcu_dereference(state->policy);
869 policydb = &policy->policydb;
870 sidtab = policy->sidtab;
873 old_entry = sidtab_search_entry(sidtab, old_sid);
875 pr_err("SELinux: %s: unrecognized SID %u\n",
881 new_entry = sidtab_search_entry(sidtab, new_sid);
883 pr_err("SELinux: %s: unrecognized SID %u\n",
889 /* type/domain unchanged */
890 if (old_entry->context.type == new_entry->context.type)
893 index = new_entry->context.type;
895 type = policydb->type_val_to_struct[index - 1];
898 /* not bounded anymore */
903 /* @newsid is bounded by @oldsid */
905 if (type->bounds == old_entry->context.type)
908 index = type->bounds;
912 char *old_name = NULL;
913 char *new_name = NULL;
916 if (!sidtab_entry_to_string(policydb, sidtab, old_entry,
917 &old_name, &length) &&
918 !sidtab_entry_to_string(policydb, sidtab, new_entry,
919 &new_name, &length)) {
920 audit_log(audit_context(),
921 GFP_ATOMIC, AUDIT_SELINUX_ERR,
922 "op=security_bounded_transition "
924 "oldcontext=%s newcontext=%s",
936 static void avd_init(struct selinux_policy *policy, struct av_decision *avd)
940 avd->auditdeny = 0xffffffff;
942 avd->seqno = policy->latest_granting;
948 void services_compute_xperms_decision(struct extended_perms_decision *xpermd,
949 struct avtab_node *node)
953 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
954 if (xpermd->driver != node->datum.u.xperms->driver)
956 } else if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
957 if (!security_xperm_test(node->datum.u.xperms->perms.p,
964 if (node->key.specified == AVTAB_XPERMS_ALLOWED) {
965 xpermd->used |= XPERMS_ALLOWED;
966 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
967 memset(xpermd->allowed->p, 0xff,
968 sizeof(xpermd->allowed->p));
970 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
971 for (i = 0; i < ARRAY_SIZE(xpermd->allowed->p); i++)
972 xpermd->allowed->p[i] |=
973 node->datum.u.xperms->perms.p[i];
975 } else if (node->key.specified == AVTAB_XPERMS_AUDITALLOW) {
976 xpermd->used |= XPERMS_AUDITALLOW;
977 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
978 memset(xpermd->auditallow->p, 0xff,
979 sizeof(xpermd->auditallow->p));
981 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
982 for (i = 0; i < ARRAY_SIZE(xpermd->auditallow->p); i++)
983 xpermd->auditallow->p[i] |=
984 node->datum.u.xperms->perms.p[i];
986 } else if (node->key.specified == AVTAB_XPERMS_DONTAUDIT) {
987 xpermd->used |= XPERMS_DONTAUDIT;
988 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
989 memset(xpermd->dontaudit->p, 0xff,
990 sizeof(xpermd->dontaudit->p));
992 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
993 for (i = 0; i < ARRAY_SIZE(xpermd->dontaudit->p); i++)
994 xpermd->dontaudit->p[i] |=
995 node->datum.u.xperms->perms.p[i];
1002 void security_compute_xperms_decision(struct selinux_state *state,
1007 struct extended_perms_decision *xpermd)
1009 struct selinux_policy *policy;
1010 struct policydb *policydb;
1011 struct sidtab *sidtab;
1013 struct context *scontext, *tcontext;
1014 struct avtab_key avkey;
1015 struct avtab_node *node;
1016 struct ebitmap *sattr, *tattr;
1017 struct ebitmap_node *snode, *tnode;
1020 xpermd->driver = driver;
1022 memset(xpermd->allowed->p, 0, sizeof(xpermd->allowed->p));
1023 memset(xpermd->auditallow->p, 0, sizeof(xpermd->auditallow->p));
1024 memset(xpermd->dontaudit->p, 0, sizeof(xpermd->dontaudit->p));
1027 if (!selinux_initialized(state))
1030 policy = rcu_dereference(state->policy);
1031 policydb = &policy->policydb;
1032 sidtab = policy->sidtab;
1034 scontext = sidtab_search(sidtab, ssid);
1036 pr_err("SELinux: %s: unrecognized SID %d\n",
1041 tcontext = sidtab_search(sidtab, tsid);
1043 pr_err("SELinux: %s: unrecognized SID %d\n",
1048 tclass = unmap_class(&policy->map, orig_tclass);
1049 if (unlikely(orig_tclass && !tclass)) {
1050 if (policydb->allow_unknown)
1056 if (unlikely(!tclass || tclass > policydb->p_classes.nprim)) {
1057 pr_warn_ratelimited("SELinux: Invalid class %hu\n", tclass);
1061 avkey.target_class = tclass;
1062 avkey.specified = AVTAB_XPERMS;
1063 sattr = &policydb->type_attr_map_array[scontext->type - 1];
1064 tattr = &policydb->type_attr_map_array[tcontext->type - 1];
1065 ebitmap_for_each_positive_bit(sattr, snode, i) {
1066 ebitmap_for_each_positive_bit(tattr, tnode, j) {
1067 avkey.source_type = i + 1;
1068 avkey.target_type = j + 1;
1069 for (node = avtab_search_node(&policydb->te_avtab,
1072 node = avtab_search_node_next(node, avkey.specified))
1073 services_compute_xperms_decision(xpermd, node);
1075 cond_compute_xperms(&policydb->te_cond_avtab,
1083 memset(xpermd->allowed->p, 0xff, sizeof(xpermd->allowed->p));
1088 * security_compute_av - Compute access vector decisions.
1089 * @ssid: source security identifier
1090 * @tsid: target security identifier
1091 * @tclass: target security class
1092 * @avd: access vector decisions
1093 * @xperms: extended permissions
1095 * Compute a set of access vector decisions based on the
1096 * SID pair (@ssid, @tsid) for the permissions in @tclass.
1098 void security_compute_av(struct selinux_state *state,
1102 struct av_decision *avd,
1103 struct extended_perms *xperms)
1105 struct selinux_policy *policy;
1106 struct policydb *policydb;
1107 struct sidtab *sidtab;
1109 struct context *scontext = NULL, *tcontext = NULL;
1112 policy = rcu_dereference(state->policy);
1113 avd_init(policy, avd);
1115 if (!selinux_initialized(state))
1118 policydb = &policy->policydb;
1119 sidtab = policy->sidtab;
1121 scontext = sidtab_search(sidtab, ssid);
1123 pr_err("SELinux: %s: unrecognized SID %d\n",
1128 /* permissive domain? */
1129 if (ebitmap_get_bit(&policydb->permissive_map, scontext->type))
1130 avd->flags |= AVD_FLAGS_PERMISSIVE;
1132 tcontext = sidtab_search(sidtab, tsid);
1134 pr_err("SELinux: %s: unrecognized SID %d\n",
1139 tclass = unmap_class(&policy->map, orig_tclass);
1140 if (unlikely(orig_tclass && !tclass)) {
1141 if (policydb->allow_unknown)
1145 context_struct_compute_av(policydb, scontext, tcontext, tclass, avd,
1147 map_decision(&policy->map, orig_tclass, avd,
1148 policydb->allow_unknown);
1153 avd->allowed = 0xffffffff;
1157 void security_compute_av_user(struct selinux_state *state,
1161 struct av_decision *avd)
1163 struct selinux_policy *policy;
1164 struct policydb *policydb;
1165 struct sidtab *sidtab;
1166 struct context *scontext = NULL, *tcontext = NULL;
1169 policy = rcu_dereference(state->policy);
1170 avd_init(policy, avd);
1171 if (!selinux_initialized(state))
1174 policydb = &policy->policydb;
1175 sidtab = policy->sidtab;
1177 scontext = sidtab_search(sidtab, ssid);
1179 pr_err("SELinux: %s: unrecognized SID %d\n",
1184 /* permissive domain? */
1185 if (ebitmap_get_bit(&policydb->permissive_map, scontext->type))
1186 avd->flags |= AVD_FLAGS_PERMISSIVE;
1188 tcontext = sidtab_search(sidtab, tsid);
1190 pr_err("SELinux: %s: unrecognized SID %d\n",
1195 if (unlikely(!tclass)) {
1196 if (policydb->allow_unknown)
1201 context_struct_compute_av(policydb, scontext, tcontext, tclass, avd,
1207 avd->allowed = 0xffffffff;
1212 * Write the security context string representation of
1213 * the context structure `context' into a dynamically
1214 * allocated string of the correct size. Set `*scontext'
1215 * to point to this string and set `*scontext_len' to
1216 * the length of the string.
1218 static int context_struct_to_string(struct policydb *p,
1219 struct context *context,
1220 char **scontext, u32 *scontext_len)
1229 *scontext_len = context->len;
1231 *scontext = kstrdup(context->str, GFP_ATOMIC);
1238 /* Compute the size of the context. */
1239 *scontext_len += strlen(sym_name(p, SYM_USERS, context->user - 1)) + 1;
1240 *scontext_len += strlen(sym_name(p, SYM_ROLES, context->role - 1)) + 1;
1241 *scontext_len += strlen(sym_name(p, SYM_TYPES, context->type - 1)) + 1;
1242 *scontext_len += mls_compute_context_len(p, context);
1247 /* Allocate space for the context; caller must free this space. */
1248 scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
1251 *scontext = scontextp;
1254 * Copy the user name, role name and type name into the context.
1256 scontextp += sprintf(scontextp, "%s:%s:%s",
1257 sym_name(p, SYM_USERS, context->user - 1),
1258 sym_name(p, SYM_ROLES, context->role - 1),
1259 sym_name(p, SYM_TYPES, context->type - 1));
1261 mls_sid_to_context(p, context, &scontextp);
1268 static int sidtab_entry_to_string(struct policydb *p,
1269 struct sidtab *sidtab,
1270 struct sidtab_entry *entry,
1271 char **scontext, u32 *scontext_len)
1273 int rc = sidtab_sid2str_get(sidtab, entry, scontext, scontext_len);
1278 rc = context_struct_to_string(p, &entry->context, scontext,
1280 if (!rc && scontext)
1281 sidtab_sid2str_put(sidtab, entry, *scontext, *scontext_len);
1285 #include "initial_sid_to_string.h"
1287 int security_sidtab_hash_stats(struct selinux_state *state, char *page)
1289 struct selinux_policy *policy;
1292 if (!selinux_initialized(state)) {
1293 pr_err("SELinux: %s: called before initial load_policy\n",
1299 policy = rcu_dereference(state->policy);
1300 rc = sidtab_hash_stats(policy->sidtab, page);
1306 const char *security_get_initial_sid_context(u32 sid)
1308 if (unlikely(sid > SECINITSID_NUM))
1310 return initial_sid_to_string[sid];
1313 static int security_sid_to_context_core(struct selinux_state *state,
1314 u32 sid, char **scontext,
1315 u32 *scontext_len, int force,
1318 struct selinux_policy *policy;
1319 struct policydb *policydb;
1320 struct sidtab *sidtab;
1321 struct sidtab_entry *entry;
1328 if (!selinux_initialized(state)) {
1329 if (sid <= SECINITSID_NUM) {
1331 const char *s = initial_sid_to_string[sid];
1335 *scontext_len = strlen(s) + 1;
1338 scontextp = kmemdup(s, *scontext_len, GFP_ATOMIC);
1341 *scontext = scontextp;
1344 pr_err("SELinux: %s: called before initial "
1345 "load_policy on unknown SID %d\n", __func__, sid);
1349 policy = rcu_dereference(state->policy);
1350 policydb = &policy->policydb;
1351 sidtab = policy->sidtab;
1354 entry = sidtab_search_entry_force(sidtab, sid);
1356 entry = sidtab_search_entry(sidtab, sid);
1358 pr_err("SELinux: %s: unrecognized SID %d\n",
1363 if (only_invalid && !entry->context.len)
1366 rc = sidtab_entry_to_string(policydb, sidtab, entry, scontext,
1376 * security_sid_to_context - Obtain a context for a given SID.
1377 * @sid: security identifier, SID
1378 * @scontext: security context
1379 * @scontext_len: length in bytes
1381 * Write the string representation of the context associated with @sid
1382 * into a dynamically allocated string of the correct size. Set @scontext
1383 * to point to this string and set @scontext_len to the length of the string.
1385 int security_sid_to_context(struct selinux_state *state,
1386 u32 sid, char **scontext, u32 *scontext_len)
1388 return security_sid_to_context_core(state, sid, scontext,
1389 scontext_len, 0, 0);
1392 int security_sid_to_context_force(struct selinux_state *state, u32 sid,
1393 char **scontext, u32 *scontext_len)
1395 return security_sid_to_context_core(state, sid, scontext,
1396 scontext_len, 1, 0);
1400 * security_sid_to_context_inval - Obtain a context for a given SID if it
1402 * @sid: security identifier, SID
1403 * @scontext: security context
1404 * @scontext_len: length in bytes
1406 * Write the string representation of the context associated with @sid
1407 * into a dynamically allocated string of the correct size, but only if the
1408 * context is invalid in the current policy. Set @scontext to point to
1409 * this string (or NULL if the context is valid) and set @scontext_len to
1410 * the length of the string (or 0 if the context is valid).
1412 int security_sid_to_context_inval(struct selinux_state *state, u32 sid,
1413 char **scontext, u32 *scontext_len)
1415 return security_sid_to_context_core(state, sid, scontext,
1416 scontext_len, 1, 1);
1420 * Caveat: Mutates scontext.
1422 static int string_to_context_struct(struct policydb *pol,
1423 struct sidtab *sidtabp,
1425 struct context *ctx,
1428 struct role_datum *role;
1429 struct type_datum *typdatum;
1430 struct user_datum *usrdatum;
1431 char *scontextp, *p, oldc;
1436 /* Parse the security context. */
1439 scontextp = (char *) scontext;
1441 /* Extract the user. */
1443 while (*p && *p != ':')
1451 usrdatum = symtab_search(&pol->p_users, scontextp);
1455 ctx->user = usrdatum->value;
1459 while (*p && *p != ':')
1467 role = symtab_search(&pol->p_roles, scontextp);
1470 ctx->role = role->value;
1474 while (*p && *p != ':')
1479 typdatum = symtab_search(&pol->p_types, scontextp);
1480 if (!typdatum || typdatum->attribute)
1483 ctx->type = typdatum->value;
1485 rc = mls_context_to_sid(pol, oldc, p, ctx, sidtabp, def_sid);
1489 /* Check the validity of the new context. */
1491 if (!policydb_context_isvalid(pol, ctx))
1496 context_destroy(ctx);
1500 static int security_context_to_sid_core(struct selinux_state *state,
1501 const char *scontext, u32 scontext_len,
1502 u32 *sid, u32 def_sid, gfp_t gfp_flags,
1505 struct selinux_policy *policy;
1506 struct policydb *policydb;
1507 struct sidtab *sidtab;
1508 char *scontext2, *str = NULL;
1509 struct context context;
1512 /* An empty security context is never valid. */
1516 /* Copy the string to allow changes and ensure a NUL terminator */
1517 scontext2 = kmemdup_nul(scontext, scontext_len, gfp_flags);
1521 if (!selinux_initialized(state)) {
1524 for (i = 1; i < SECINITSID_NUM; i++) {
1525 const char *s = initial_sid_to_string[i];
1527 if (s && !strcmp(s, scontext2)) {
1532 *sid = SECINITSID_KERNEL;
1538 /* Save another copy for storing in uninterpreted form */
1540 str = kstrdup(scontext2, gfp_flags);
1545 policy = rcu_dereference(state->policy);
1546 policydb = &policy->policydb;
1547 sidtab = policy->sidtab;
1548 rc = string_to_context_struct(policydb, sidtab, scontext2,
1550 if (rc == -EINVAL && force) {
1552 context.len = strlen(str) + 1;
1556 rc = sidtab_context_to_sid(sidtab, &context, sid);
1557 context_destroy(&context);
1567 * security_context_to_sid - Obtain a SID for a given security context.
1568 * @scontext: security context
1569 * @scontext_len: length in bytes
1570 * @sid: security identifier, SID
1571 * @gfp: context for the allocation
1573 * Obtains a SID associated with the security context that
1574 * has the string representation specified by @scontext.
1575 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1576 * memory is available, or 0 on success.
1578 int security_context_to_sid(struct selinux_state *state,
1579 const char *scontext, u32 scontext_len, u32 *sid,
1582 return security_context_to_sid_core(state, scontext, scontext_len,
1583 sid, SECSID_NULL, gfp, 0);
1586 int security_context_str_to_sid(struct selinux_state *state,
1587 const char *scontext, u32 *sid, gfp_t gfp)
1589 return security_context_to_sid(state, scontext, strlen(scontext),
1594 * security_context_to_sid_default - Obtain a SID for a given security context,
1595 * falling back to specified default if needed.
1597 * @scontext: security context
1598 * @scontext_len: length in bytes
1599 * @sid: security identifier, SID
1600 * @def_sid: default SID to assign on error
1602 * Obtains a SID associated with the security context that
1603 * has the string representation specified by @scontext.
1604 * The default SID is passed to the MLS layer to be used to allow
1605 * kernel labeling of the MLS field if the MLS field is not present
1606 * (for upgrading to MLS without full relabel).
1607 * Implicitly forces adding of the context even if it cannot be mapped yet.
1608 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1609 * memory is available, or 0 on success.
1611 int security_context_to_sid_default(struct selinux_state *state,
1612 const char *scontext, u32 scontext_len,
1613 u32 *sid, u32 def_sid, gfp_t gfp_flags)
1615 return security_context_to_sid_core(state, scontext, scontext_len,
1616 sid, def_sid, gfp_flags, 1);
1619 int security_context_to_sid_force(struct selinux_state *state,
1620 const char *scontext, u32 scontext_len,
1623 return security_context_to_sid_core(state, scontext, scontext_len,
1624 sid, SECSID_NULL, GFP_KERNEL, 1);
1627 static int compute_sid_handle_invalid_context(
1628 struct selinux_state *state,
1629 struct selinux_policy *policy,
1630 struct sidtab_entry *sentry,
1631 struct sidtab_entry *tentry,
1633 struct context *newcontext)
1635 struct policydb *policydb = &policy->policydb;
1636 struct sidtab *sidtab = policy->sidtab;
1637 char *s = NULL, *t = NULL, *n = NULL;
1638 u32 slen, tlen, nlen;
1639 struct audit_buffer *ab;
1641 if (sidtab_entry_to_string(policydb, sidtab, sentry, &s, &slen))
1643 if (sidtab_entry_to_string(policydb, sidtab, tentry, &t, &tlen))
1645 if (context_struct_to_string(policydb, newcontext, &n, &nlen))
1647 ab = audit_log_start(audit_context(), GFP_ATOMIC, AUDIT_SELINUX_ERR);
1648 audit_log_format(ab,
1649 "op=security_compute_sid invalid_context=");
1650 /* no need to record the NUL with untrusted strings */
1651 audit_log_n_untrustedstring(ab, n, nlen - 1);
1652 audit_log_format(ab, " scontext=%s tcontext=%s tclass=%s",
1653 s, t, sym_name(policydb, SYM_CLASSES, tclass-1));
1659 if (!enforcing_enabled(state))
1664 static void filename_compute_type(struct policydb *policydb,
1665 struct context *newcontext,
1666 u32 stype, u32 ttype, u16 tclass,
1667 const char *objname)
1669 struct filename_trans_key ft;
1670 struct filename_trans_datum *datum;
1673 * Most filename trans rules are going to live in specific directories
1674 * like /dev or /var/run. This bitmap will quickly skip rule searches
1675 * if the ttype does not contain any rules.
1677 if (!ebitmap_get_bit(&policydb->filename_trans_ttypes, ttype))
1684 datum = policydb_filenametr_search(policydb, &ft);
1686 if (ebitmap_get_bit(&datum->stypes, stype - 1)) {
1687 newcontext->type = datum->otype;
1690 datum = datum->next;
1694 static int security_compute_sid(struct selinux_state *state,
1699 const char *objname,
1703 struct selinux_policy *policy;
1704 struct policydb *policydb;
1705 struct sidtab *sidtab;
1706 struct class_datum *cladatum = NULL;
1707 struct context *scontext, *tcontext, newcontext;
1708 struct sidtab_entry *sentry, *tentry;
1709 struct avtab_key avkey;
1710 struct avtab_datum *avdatum;
1711 struct avtab_node *node;
1716 if (!selinux_initialized(state)) {
1717 switch (orig_tclass) {
1718 case SECCLASS_PROCESS: /* kernel value */
1728 context_init(&newcontext);
1732 policy = rcu_dereference(state->policy);
1735 tclass = unmap_class(&policy->map, orig_tclass);
1736 sock = security_is_socket_class(orig_tclass);
1738 tclass = orig_tclass;
1739 sock = security_is_socket_class(map_class(&policy->map,
1743 policydb = &policy->policydb;
1744 sidtab = policy->sidtab;
1746 sentry = sidtab_search_entry(sidtab, ssid);
1748 pr_err("SELinux: %s: unrecognized SID %d\n",
1753 tentry = sidtab_search_entry(sidtab, tsid);
1755 pr_err("SELinux: %s: unrecognized SID %d\n",
1761 scontext = &sentry->context;
1762 tcontext = &tentry->context;
1764 if (tclass && tclass <= policydb->p_classes.nprim)
1765 cladatum = policydb->class_val_to_struct[tclass - 1];
1767 /* Set the user identity. */
1768 switch (specified) {
1769 case AVTAB_TRANSITION:
1771 if (cladatum && cladatum->default_user == DEFAULT_TARGET) {
1772 newcontext.user = tcontext->user;
1774 /* notice this gets both DEFAULT_SOURCE and unset */
1775 /* Use the process user identity. */
1776 newcontext.user = scontext->user;
1780 /* Use the related object owner. */
1781 newcontext.user = tcontext->user;
1785 /* Set the role to default values. */
1786 if (cladatum && cladatum->default_role == DEFAULT_SOURCE) {
1787 newcontext.role = scontext->role;
1788 } else if (cladatum && cladatum->default_role == DEFAULT_TARGET) {
1789 newcontext.role = tcontext->role;
1791 if ((tclass == policydb->process_class) || sock)
1792 newcontext.role = scontext->role;
1794 newcontext.role = OBJECT_R_VAL;
1797 /* Set the type to default values. */
1798 if (cladatum && cladatum->default_type == DEFAULT_SOURCE) {
1799 newcontext.type = scontext->type;
1800 } else if (cladatum && cladatum->default_type == DEFAULT_TARGET) {
1801 newcontext.type = tcontext->type;
1803 if ((tclass == policydb->process_class) || sock) {
1804 /* Use the type of process. */
1805 newcontext.type = scontext->type;
1807 /* Use the type of the related object. */
1808 newcontext.type = tcontext->type;
1812 /* Look for a type transition/member/change rule. */
1813 avkey.source_type = scontext->type;
1814 avkey.target_type = tcontext->type;
1815 avkey.target_class = tclass;
1816 avkey.specified = specified;
1817 avdatum = avtab_search(&policydb->te_avtab, &avkey);
1819 /* If no permanent rule, also check for enabled conditional rules */
1821 node = avtab_search_node(&policydb->te_cond_avtab, &avkey);
1822 for (; node; node = avtab_search_node_next(node, specified)) {
1823 if (node->key.specified & AVTAB_ENABLED) {
1824 avdatum = &node->datum;
1831 /* Use the type from the type transition/member/change rule. */
1832 newcontext.type = avdatum->u.data;
1835 /* if we have a objname this is a file trans check so check those rules */
1837 filename_compute_type(policydb, &newcontext, scontext->type,
1838 tcontext->type, tclass, objname);
1840 /* Check for class-specific changes. */
1841 if (specified & AVTAB_TRANSITION) {
1842 /* Look for a role transition rule. */
1843 struct role_trans_datum *rtd;
1844 struct role_trans_key rtk = {
1845 .role = scontext->role,
1846 .type = tcontext->type,
1850 rtd = policydb_roletr_search(policydb, &rtk);
1852 newcontext.role = rtd->new_role;
1855 /* Set the MLS attributes.
1856 This is done last because it may allocate memory. */
1857 rc = mls_compute_sid(policydb, scontext, tcontext, tclass, specified,
1862 /* Check the validity of the context. */
1863 if (!policydb_context_isvalid(policydb, &newcontext)) {
1864 rc = compute_sid_handle_invalid_context(state, policy, sentry,
1870 /* Obtain the sid for the context. */
1871 rc = sidtab_context_to_sid(sidtab, &newcontext, out_sid);
1874 context_destroy(&newcontext);
1880 * security_transition_sid - Compute the SID for a new subject/object.
1881 * @ssid: source security identifier
1882 * @tsid: target security identifier
1883 * @tclass: target security class
1884 * @out_sid: security identifier for new subject/object
1886 * Compute a SID to use for labeling a new subject or object in the
1887 * class @tclass based on a SID pair (@ssid, @tsid).
1888 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1889 * if insufficient memory is available, or %0 if the new SID was
1890 * computed successfully.
1892 int security_transition_sid(struct selinux_state *state,
1893 u32 ssid, u32 tsid, u16 tclass,
1894 const struct qstr *qstr, u32 *out_sid)
1896 return security_compute_sid(state, ssid, tsid, tclass,
1898 qstr ? qstr->name : NULL, out_sid, true);
1901 int security_transition_sid_user(struct selinux_state *state,
1902 u32 ssid, u32 tsid, u16 tclass,
1903 const char *objname, u32 *out_sid)
1905 return security_compute_sid(state, ssid, tsid, tclass,
1907 objname, out_sid, false);
1911 * security_member_sid - Compute the SID for member selection.
1912 * @ssid: source security identifier
1913 * @tsid: target security identifier
1914 * @tclass: target security class
1915 * @out_sid: security identifier for selected member
1917 * Compute a SID to use when selecting a member of a polyinstantiated
1918 * object of class @tclass based on a SID pair (@ssid, @tsid).
1919 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1920 * if insufficient memory is available, or %0 if the SID was
1921 * computed successfully.
1923 int security_member_sid(struct selinux_state *state,
1929 return security_compute_sid(state, ssid, tsid, tclass,
1935 * security_change_sid - Compute the SID for object relabeling.
1936 * @ssid: source security identifier
1937 * @tsid: target security identifier
1938 * @tclass: target security class
1939 * @out_sid: security identifier for selected member
1941 * Compute a SID to use for relabeling an object of class @tclass
1942 * based on a SID pair (@ssid, @tsid).
1943 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1944 * if insufficient memory is available, or %0 if the SID was
1945 * computed successfully.
1947 int security_change_sid(struct selinux_state *state,
1953 return security_compute_sid(state,
1954 ssid, tsid, tclass, AVTAB_CHANGE, NULL,
1958 static inline int convert_context_handle_invalid_context(
1959 struct selinux_state *state,
1960 struct policydb *policydb,
1961 struct context *context)
1966 if (enforcing_enabled(state))
1969 if (!context_struct_to_string(policydb, context, &s, &len)) {
1970 pr_warn("SELinux: Context %s would be invalid if enforcing\n",
1977 struct convert_context_args {
1978 struct selinux_state *state;
1979 struct policydb *oldp;
1980 struct policydb *newp;
1984 * Convert the values in the security context
1985 * structure `oldc' from the values specified
1986 * in the policy `p->oldp' to the values specified
1987 * in the policy `p->newp', storing the new context
1988 * in `newc'. Verify that the context is valid
1989 * under the new policy.
1991 static int convert_context(struct context *oldc, struct context *newc, void *p)
1993 struct convert_context_args *args;
1994 struct ocontext *oc;
1995 struct role_datum *role;
1996 struct type_datum *typdatum;
1997 struct user_datum *usrdatum;
2005 s = kstrdup(oldc->str, GFP_KERNEL);
2009 rc = string_to_context_struct(args->newp, NULL, s,
2011 if (rc == -EINVAL) {
2013 * Retain string representation for later mapping.
2015 * IMPORTANT: We need to copy the contents of oldc->str
2016 * back into s again because string_to_context_struct()
2017 * may have garbled it.
2019 memcpy(s, oldc->str, oldc->len);
2022 newc->len = oldc->len;
2027 /* Other error condition, e.g. ENOMEM. */
2028 pr_err("SELinux: Unable to map context %s, rc = %d.\n",
2032 pr_info("SELinux: Context %s became valid (mapped).\n",
2039 /* Convert the user. */
2041 usrdatum = symtab_search(&args->newp->p_users,
2042 sym_name(args->oldp,
2043 SYM_USERS, oldc->user - 1));
2046 newc->user = usrdatum->value;
2048 /* Convert the role. */
2050 role = symtab_search(&args->newp->p_roles,
2051 sym_name(args->oldp, SYM_ROLES, oldc->role - 1));
2054 newc->role = role->value;
2056 /* Convert the type. */
2058 typdatum = symtab_search(&args->newp->p_types,
2059 sym_name(args->oldp,
2060 SYM_TYPES, oldc->type - 1));
2063 newc->type = typdatum->value;
2065 /* Convert the MLS fields if dealing with MLS policies */
2066 if (args->oldp->mls_enabled && args->newp->mls_enabled) {
2067 rc = mls_convert_context(args->oldp, args->newp, oldc, newc);
2070 } else if (!args->oldp->mls_enabled && args->newp->mls_enabled) {
2072 * Switching between non-MLS and MLS policy:
2073 * ensure that the MLS fields of the context for all
2074 * existing entries in the sidtab are filled in with a
2075 * suitable default value, likely taken from one of the
2078 oc = args->newp->ocontexts[OCON_ISID];
2079 while (oc && oc->sid[0] != SECINITSID_UNLABELED)
2083 pr_err("SELinux: unable to look up"
2084 " the initial SIDs list\n");
2087 rc = mls_range_set(newc, &oc->context[0].range);
2092 /* Check the validity of the new context. */
2093 if (!policydb_context_isvalid(args->newp, newc)) {
2094 rc = convert_context_handle_invalid_context(args->state,
2103 /* Map old representation to string and save it. */
2104 rc = context_struct_to_string(args->oldp, oldc, &s, &len);
2107 context_destroy(newc);
2110 pr_info("SELinux: Context %s became invalid (unmapped).\n",
2115 static void security_load_policycaps(struct selinux_state *state,
2116 struct selinux_policy *policy)
2120 struct ebitmap_node *node;
2122 p = &policy->policydb;
2124 for (i = 0; i < ARRAY_SIZE(state->policycap); i++)
2125 WRITE_ONCE(state->policycap[i],
2126 ebitmap_get_bit(&p->policycaps, i));
2128 for (i = 0; i < ARRAY_SIZE(selinux_policycap_names); i++)
2129 pr_info("SELinux: policy capability %s=%d\n",
2130 selinux_policycap_names[i],
2131 ebitmap_get_bit(&p->policycaps, i));
2133 ebitmap_for_each_positive_bit(&p->policycaps, node, i) {
2134 if (i >= ARRAY_SIZE(selinux_policycap_names))
2135 pr_info("SELinux: unknown policy capability %u\n",
2140 static int security_preserve_bools(struct selinux_policy *oldpolicy,
2141 struct selinux_policy *newpolicy);
2143 static void selinux_policy_free(struct selinux_policy *policy)
2148 sidtab_destroy(policy->sidtab);
2149 kfree(policy->map.mapping);
2150 policydb_destroy(&policy->policydb);
2151 kfree(policy->sidtab);
2155 static void selinux_policy_cond_free(struct selinux_policy *policy)
2157 cond_policydb_destroy_dup(&policy->policydb);
2161 void selinux_policy_cancel(struct selinux_state *state,
2162 struct selinux_policy *policy)
2164 struct selinux_policy *oldpolicy;
2166 oldpolicy = rcu_dereference_protected(state->policy,
2167 lockdep_is_held(&state->policy_mutex));
2169 sidtab_cancel_convert(oldpolicy->sidtab);
2170 selinux_policy_free(policy);
2173 static void selinux_notify_policy_change(struct selinux_state *state,
2176 /* Flush external caches and notify userspace of policy load */
2177 avc_ss_reset(state->avc, seqno);
2178 selnl_notify_policyload(seqno);
2179 selinux_status_update_policyload(state, seqno);
2180 selinux_netlbl_cache_invalidate();
2181 selinux_xfrm_notify_policyload();
2182 selinux_ima_measure_state(state);
2185 void selinux_policy_commit(struct selinux_state *state,
2186 struct selinux_policy *newpolicy)
2188 struct selinux_policy *oldpolicy;
2191 oldpolicy = rcu_dereference_protected(state->policy,
2192 lockdep_is_held(&state->policy_mutex));
2194 /* If switching between different policy types, log MLS status */
2196 if (oldpolicy->policydb.mls_enabled && !newpolicy->policydb.mls_enabled)
2197 pr_info("SELinux: Disabling MLS support...\n");
2198 else if (!oldpolicy->policydb.mls_enabled && newpolicy->policydb.mls_enabled)
2199 pr_info("SELinux: Enabling MLS support...\n");
2202 /* Set latest granting seqno for new policy. */
2204 newpolicy->latest_granting = oldpolicy->latest_granting + 1;
2206 newpolicy->latest_granting = 1;
2207 seqno = newpolicy->latest_granting;
2209 /* Install the new policy. */
2210 rcu_assign_pointer(state->policy, newpolicy);
2212 /* Load the policycaps from the new policy */
2213 security_load_policycaps(state, newpolicy);
2215 if (!selinux_initialized(state)) {
2217 * After first policy load, the security server is
2218 * marked as initialized and ready to handle requests and
2219 * any objects created prior to policy load are then labeled.
2221 selinux_mark_initialized(state);
2222 selinux_complete_init();
2225 /* Free the old policy */
2227 selinux_policy_free(oldpolicy);
2229 /* Notify others of the policy change */
2230 selinux_notify_policy_change(state, seqno);
2234 * security_load_policy - Load a security policy configuration.
2235 * @data: binary policy data
2236 * @len: length of data in bytes
2238 * Load a new set of security policy configuration data,
2239 * validate it and convert the SID table as necessary.
2240 * This function will flush the access vector cache after
2241 * loading the new policy.
2243 int security_load_policy(struct selinux_state *state, void *data, size_t len,
2244 struct selinux_policy **newpolicyp)
2246 struct selinux_policy *newpolicy, *oldpolicy;
2247 struct sidtab_convert_params convert_params;
2248 struct convert_context_args args;
2250 struct policy_file file = { data, len }, *fp = &file;
2252 newpolicy = kzalloc(sizeof(*newpolicy), GFP_KERNEL);
2256 newpolicy->sidtab = kzalloc(sizeof(*newpolicy->sidtab), GFP_KERNEL);
2257 if (!newpolicy->sidtab) {
2262 rc = policydb_read(&newpolicy->policydb, fp);
2266 newpolicy->policydb.len = len;
2267 rc = selinux_set_mapping(&newpolicy->policydb, secclass_map,
2272 rc = policydb_load_isids(&newpolicy->policydb, newpolicy->sidtab);
2274 pr_err("SELinux: unable to load the initial SIDs\n");
2279 if (!selinux_initialized(state)) {
2280 /* First policy load, so no need to preserve state from old policy */
2281 *newpolicyp = newpolicy;
2285 oldpolicy = rcu_dereference_protected(state->policy,
2286 lockdep_is_held(&state->policy_mutex));
2288 /* Preserve active boolean values from the old policy */
2289 rc = security_preserve_bools(oldpolicy, newpolicy);
2291 pr_err("SELinux: unable to preserve booleans\n");
2292 goto err_free_isids;
2296 * Convert the internal representations of contexts
2297 * in the new SID table.
2300 args.oldp = &oldpolicy->policydb;
2301 args.newp = &newpolicy->policydb;
2303 convert_params.func = convert_context;
2304 convert_params.args = &args;
2305 convert_params.target = newpolicy->sidtab;
2307 rc = sidtab_convert(oldpolicy->sidtab, &convert_params);
2309 pr_err("SELinux: unable to convert the internal"
2310 " representation of contexts in the new SID"
2312 goto err_free_isids;
2315 *newpolicyp = newpolicy;
2319 sidtab_destroy(newpolicy->sidtab);
2321 kfree(newpolicy->map.mapping);
2323 policydb_destroy(&newpolicy->policydb);
2325 kfree(newpolicy->sidtab);
2333 * security_port_sid - Obtain the SID for a port.
2334 * @protocol: protocol number
2335 * @port: port number
2336 * @out_sid: security identifier
2338 int security_port_sid(struct selinux_state *state,
2339 u8 protocol, u16 port, u32 *out_sid)
2341 struct selinux_policy *policy;
2342 struct policydb *policydb;
2343 struct sidtab *sidtab;
2347 if (!selinux_initialized(state)) {
2348 *out_sid = SECINITSID_PORT;
2353 policy = rcu_dereference(state->policy);
2354 policydb = &policy->policydb;
2355 sidtab = policy->sidtab;
2357 c = policydb->ocontexts[OCON_PORT];
2359 if (c->u.port.protocol == protocol &&
2360 c->u.port.low_port <= port &&
2361 c->u.port.high_port >= port)
2368 rc = sidtab_context_to_sid(sidtab, &c->context[0],
2373 *out_sid = c->sid[0];
2375 *out_sid = SECINITSID_PORT;
2384 * security_pkey_sid - Obtain the SID for a pkey.
2385 * @subnet_prefix: Subnet Prefix
2386 * @pkey_num: pkey number
2387 * @out_sid: security identifier
2389 int security_ib_pkey_sid(struct selinux_state *state,
2390 u64 subnet_prefix, u16 pkey_num, u32 *out_sid)
2392 struct selinux_policy *policy;
2393 struct policydb *policydb;
2394 struct sidtab *sidtab;
2398 if (!selinux_initialized(state)) {
2399 *out_sid = SECINITSID_UNLABELED;
2404 policy = rcu_dereference(state->policy);
2405 policydb = &policy->policydb;
2406 sidtab = policy->sidtab;
2408 c = policydb->ocontexts[OCON_IBPKEY];
2410 if (c->u.ibpkey.low_pkey <= pkey_num &&
2411 c->u.ibpkey.high_pkey >= pkey_num &&
2412 c->u.ibpkey.subnet_prefix == subnet_prefix)
2420 rc = sidtab_context_to_sid(sidtab,
2426 *out_sid = c->sid[0];
2428 *out_sid = SECINITSID_UNLABELED;
2436 * security_ib_endport_sid - Obtain the SID for a subnet management interface.
2437 * @dev_name: device name
2438 * @port: port number
2439 * @out_sid: security identifier
2441 int security_ib_endport_sid(struct selinux_state *state,
2442 const char *dev_name, u8 port_num, u32 *out_sid)
2444 struct selinux_policy *policy;
2445 struct policydb *policydb;
2446 struct sidtab *sidtab;
2450 if (!selinux_initialized(state)) {
2451 *out_sid = SECINITSID_UNLABELED;
2456 policy = rcu_dereference(state->policy);
2457 policydb = &policy->policydb;
2458 sidtab = policy->sidtab;
2460 c = policydb->ocontexts[OCON_IBENDPORT];
2462 if (c->u.ibendport.port == port_num &&
2463 !strncmp(c->u.ibendport.dev_name,
2465 IB_DEVICE_NAME_MAX))
2473 rc = sidtab_context_to_sid(sidtab, &c->context[0],
2478 *out_sid = c->sid[0];
2480 *out_sid = SECINITSID_UNLABELED;
2488 * security_netif_sid - Obtain the SID for a network interface.
2489 * @name: interface name
2490 * @if_sid: interface SID
2492 int security_netif_sid(struct selinux_state *state,
2493 char *name, u32 *if_sid)
2495 struct selinux_policy *policy;
2496 struct policydb *policydb;
2497 struct sidtab *sidtab;
2501 if (!selinux_initialized(state)) {
2502 *if_sid = SECINITSID_NETIF;
2507 policy = rcu_dereference(state->policy);
2508 policydb = &policy->policydb;
2509 sidtab = policy->sidtab;
2511 c = policydb->ocontexts[OCON_NETIF];
2513 if (strcmp(name, c->u.name) == 0)
2519 if (!c->sid[0] || !c->sid[1]) {
2520 rc = sidtab_context_to_sid(sidtab, &c->context[0],
2524 rc = sidtab_context_to_sid(sidtab, &c->context[1],
2529 *if_sid = c->sid[0];
2531 *if_sid = SECINITSID_NETIF;
2538 static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask)
2542 for (i = 0; i < 4; i++)
2543 if (addr[i] != (input[i] & mask[i])) {
2552 * security_node_sid - Obtain the SID for a node (host).
2553 * @domain: communication domain aka address family
2555 * @addrlen: address length in bytes
2556 * @out_sid: security identifier
2558 int security_node_sid(struct selinux_state *state,
2564 struct selinux_policy *policy;
2565 struct policydb *policydb;
2566 struct sidtab *sidtab;
2570 if (!selinux_initialized(state)) {
2571 *out_sid = SECINITSID_NODE;
2576 policy = rcu_dereference(state->policy);
2577 policydb = &policy->policydb;
2578 sidtab = policy->sidtab;
2585 if (addrlen != sizeof(u32))
2588 addr = *((u32 *)addrp);
2590 c = policydb->ocontexts[OCON_NODE];
2592 if (c->u.node.addr == (addr & c->u.node.mask))
2601 if (addrlen != sizeof(u64) * 2)
2603 c = policydb->ocontexts[OCON_NODE6];
2605 if (match_ipv6_addrmask(addrp, c->u.node6.addr,
2614 *out_sid = SECINITSID_NODE;
2620 rc = sidtab_context_to_sid(sidtab,
2626 *out_sid = c->sid[0];
2628 *out_sid = SECINITSID_NODE;
2640 * security_get_user_sids - Obtain reachable SIDs for a user.
2641 * @fromsid: starting SID
2642 * @username: username
2643 * @sids: array of reachable SIDs for user
2644 * @nel: number of elements in @sids
2646 * Generate the set of SIDs for legal security contexts
2647 * for a given user that can be reached by @fromsid.
2648 * Set *@sids to point to a dynamically allocated
2649 * array containing the set of SIDs. Set *@nel to the
2650 * number of elements in the array.
2653 int security_get_user_sids(struct selinux_state *state,
2659 struct selinux_policy *policy;
2660 struct policydb *policydb;
2661 struct sidtab *sidtab;
2662 struct context *fromcon, usercon;
2663 u32 *mysids = NULL, *mysids2, sid;
2664 u32 mynel = 0, maxnel = SIDS_NEL;
2665 struct user_datum *user;
2666 struct role_datum *role;
2667 struct ebitmap_node *rnode, *tnode;
2673 if (!selinux_initialized(state))
2677 policy = rcu_dereference(state->policy);
2678 policydb = &policy->policydb;
2679 sidtab = policy->sidtab;
2681 context_init(&usercon);
2684 fromcon = sidtab_search(sidtab, fromsid);
2689 user = symtab_search(&policydb->p_users, username);
2693 usercon.user = user->value;
2696 mysids = kcalloc(maxnel, sizeof(*mysids), GFP_ATOMIC);
2700 ebitmap_for_each_positive_bit(&user->roles, rnode, i) {
2701 role = policydb->role_val_to_struct[i];
2702 usercon.role = i + 1;
2703 ebitmap_for_each_positive_bit(&role->types, tnode, j) {
2704 usercon.type = j + 1;
2706 if (mls_setup_user_range(policydb, fromcon, user,
2710 rc = sidtab_context_to_sid(sidtab, &usercon, &sid);
2713 if (mynel < maxnel) {
2714 mysids[mynel++] = sid;
2718 mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
2721 memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
2724 mysids[mynel++] = sid;
2737 mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);
2742 for (i = 0, j = 0; i < mynel; i++) {
2743 struct av_decision dummy_avd;
2744 rc = avc_has_perm_noaudit(state,
2746 SECCLASS_PROCESS, /* kernel value */
2747 PROCESS__TRANSITION, AVC_STRICT,
2750 mysids2[j++] = mysids[i];
2762 * __security_genfs_sid - Helper to obtain a SID for a file in a filesystem
2763 * @fstype: filesystem type
2764 * @path: path from root of mount
2765 * @sclass: file security class
2766 * @sid: SID for path
2768 * Obtain a SID to use for a file in a filesystem that
2769 * cannot support xattr or use a fixed labeling behavior like
2770 * transition SIDs or task SIDs.
2772 static inline int __security_genfs_sid(struct selinux_policy *policy,
2778 struct policydb *policydb = &policy->policydb;
2779 struct sidtab *sidtab = policy->sidtab;
2782 struct genfs *genfs;
2786 while (path[0] == '/' && path[1] == '/')
2789 sclass = unmap_class(&policy->map, orig_sclass);
2790 *sid = SECINITSID_UNLABELED;
2792 for (genfs = policydb->genfs; genfs; genfs = genfs->next) {
2793 cmp = strcmp(fstype, genfs->fstype);
2802 for (c = genfs->head; c; c = c->next) {
2803 len = strlen(c->u.name);
2804 if ((!c->v.sclass || sclass == c->v.sclass) &&
2805 (strncmp(c->u.name, path, len) == 0))
2814 rc = sidtab_context_to_sid(sidtab, &c->context[0], &c->sid[0]);
2826 * security_genfs_sid - Obtain a SID for a file in a filesystem
2827 * @fstype: filesystem type
2828 * @path: path from root of mount
2829 * @sclass: file security class
2830 * @sid: SID for path
2832 * Acquire policy_rwlock before calling __security_genfs_sid() and release
2835 int security_genfs_sid(struct selinux_state *state,
2841 struct selinux_policy *policy;
2844 if (!selinux_initialized(state)) {
2845 *sid = SECINITSID_UNLABELED;
2850 policy = rcu_dereference(state->policy);
2851 retval = __security_genfs_sid(policy,
2852 fstype, path, orig_sclass, sid);
2857 int selinux_policy_genfs_sid(struct selinux_policy *policy,
2863 /* no lock required, policy is not yet accessible by other threads */
2864 return __security_genfs_sid(policy, fstype, path, orig_sclass, sid);
2868 * security_fs_use - Determine how to handle labeling for a filesystem.
2869 * @sb: superblock in question
2871 int security_fs_use(struct selinux_state *state, struct super_block *sb)
2873 struct selinux_policy *policy;
2874 struct policydb *policydb;
2875 struct sidtab *sidtab;
2878 struct superblock_security_struct *sbsec = sb->s_security;
2879 const char *fstype = sb->s_type->name;
2881 if (!selinux_initialized(state)) {
2882 sbsec->behavior = SECURITY_FS_USE_NONE;
2883 sbsec->sid = SECINITSID_UNLABELED;
2888 policy = rcu_dereference(state->policy);
2889 policydb = &policy->policydb;
2890 sidtab = policy->sidtab;
2892 c = policydb->ocontexts[OCON_FSUSE];
2894 if (strcmp(fstype, c->u.name) == 0)
2900 sbsec->behavior = c->v.behavior;
2902 rc = sidtab_context_to_sid(sidtab, &c->context[0],
2907 sbsec->sid = c->sid[0];
2909 rc = __security_genfs_sid(policy, fstype, "/",
2910 SECCLASS_DIR, &sbsec->sid);
2912 sbsec->behavior = SECURITY_FS_USE_NONE;
2915 sbsec->behavior = SECURITY_FS_USE_GENFS;
2924 int security_get_bools(struct selinux_policy *policy,
2925 u32 *len, char ***names, int **values)
2927 struct policydb *policydb;
2931 policydb = &policy->policydb;
2937 *len = policydb->p_bools.nprim;
2942 *names = kcalloc(*len, sizeof(char *), GFP_ATOMIC);
2947 *values = kcalloc(*len, sizeof(int), GFP_ATOMIC);
2951 for (i = 0; i < *len; i++) {
2952 (*values)[i] = policydb->bool_val_to_struct[i]->state;
2955 (*names)[i] = kstrdup(sym_name(policydb, SYM_BOOLS, i),
2965 for (i = 0; i < *len; i++)
2977 int security_set_bools(struct selinux_state *state, u32 len, int *values)
2979 struct selinux_policy *newpolicy, *oldpolicy;
2983 if (!selinux_initialized(state))
2986 oldpolicy = rcu_dereference_protected(state->policy,
2987 lockdep_is_held(&state->policy_mutex));
2989 /* Consistency check on number of booleans, should never fail */
2990 if (WARN_ON(len != oldpolicy->policydb.p_bools.nprim))
2993 newpolicy = kmemdup(oldpolicy, sizeof(*newpolicy), GFP_KERNEL);
2998 * Deep copy only the parts of the policydb that might be
2999 * modified as a result of changing booleans.
3001 rc = cond_policydb_dup(&newpolicy->policydb, &oldpolicy->policydb);
3007 /* Update the boolean states in the copy */
3008 for (i = 0; i < len; i++) {
3009 int new_state = !!values[i];
3010 int old_state = newpolicy->policydb.bool_val_to_struct[i]->state;
3012 if (new_state != old_state) {
3013 audit_log(audit_context(), GFP_ATOMIC,
3014 AUDIT_MAC_CONFIG_CHANGE,
3015 "bool=%s val=%d old_val=%d auid=%u ses=%u",
3016 sym_name(&newpolicy->policydb, SYM_BOOLS, i),
3019 from_kuid(&init_user_ns, audit_get_loginuid(current)),
3020 audit_get_sessionid(current));
3021 newpolicy->policydb.bool_val_to_struct[i]->state = new_state;
3025 /* Re-evaluate the conditional rules in the copy */
3026 evaluate_cond_nodes(&newpolicy->policydb);
3028 /* Set latest granting seqno for new policy */
3029 newpolicy->latest_granting = oldpolicy->latest_granting + 1;
3030 seqno = newpolicy->latest_granting;
3032 /* Install the new policy */
3033 rcu_assign_pointer(state->policy, newpolicy);
3036 * Free the conditional portions of the old policydb
3037 * that were copied for the new policy, and the oldpolicy
3038 * structure itself but not what it references.
3041 selinux_policy_cond_free(oldpolicy);
3043 /* Notify others of the policy change */
3044 selinux_notify_policy_change(state, seqno);
3048 int security_get_bool_value(struct selinux_state *state,
3051 struct selinux_policy *policy;
3052 struct policydb *policydb;
3056 if (!selinux_initialized(state))
3060 policy = rcu_dereference(state->policy);
3061 policydb = &policy->policydb;
3064 len = policydb->p_bools.nprim;
3068 rc = policydb->bool_val_to_struct[index]->state;
3074 static int security_preserve_bools(struct selinux_policy *oldpolicy,
3075 struct selinux_policy *newpolicy)
3077 int rc, *bvalues = NULL;
3078 char **bnames = NULL;
3079 struct cond_bool_datum *booldatum;
3082 rc = security_get_bools(oldpolicy, &nbools, &bnames, &bvalues);
3085 for (i = 0; i < nbools; i++) {
3086 booldatum = symtab_search(&newpolicy->policydb.p_bools,
3089 booldatum->state = bvalues[i];
3091 evaluate_cond_nodes(&newpolicy->policydb);
3095 for (i = 0; i < nbools; i++)
3104 * security_sid_mls_copy() - computes a new sid based on the given
3105 * sid and the mls portion of mls_sid.
3107 int security_sid_mls_copy(struct selinux_state *state,
3108 u32 sid, u32 mls_sid, u32 *new_sid)
3110 struct selinux_policy *policy;
3111 struct policydb *policydb;
3112 struct sidtab *sidtab;
3113 struct context *context1;
3114 struct context *context2;
3115 struct context newcon;
3121 if (!selinux_initialized(state)) {
3126 context_init(&newcon);
3129 policy = rcu_dereference(state->policy);
3130 policydb = &policy->policydb;
3131 sidtab = policy->sidtab;
3133 if (!policydb->mls_enabled) {
3139 context1 = sidtab_search(sidtab, sid);
3141 pr_err("SELinux: %s: unrecognized SID %d\n",
3147 context2 = sidtab_search(sidtab, mls_sid);
3149 pr_err("SELinux: %s: unrecognized SID %d\n",
3154 newcon.user = context1->user;
3155 newcon.role = context1->role;
3156 newcon.type = context1->type;
3157 rc = mls_context_cpy(&newcon, context2);
3161 /* Check the validity of the new context. */
3162 if (!policydb_context_isvalid(policydb, &newcon)) {
3163 rc = convert_context_handle_invalid_context(state, policydb,
3166 if (!context_struct_to_string(policydb, &newcon, &s,
3168 struct audit_buffer *ab;
3170 ab = audit_log_start(audit_context(),
3173 audit_log_format(ab,
3174 "op=security_sid_mls_copy invalid_context=");
3175 /* don't record NUL with untrusted strings */
3176 audit_log_n_untrustedstring(ab, s, len - 1);
3183 rc = sidtab_context_to_sid(sidtab, &newcon, new_sid);
3186 context_destroy(&newcon);
3192 * security_net_peersid_resolve - Compare and resolve two network peer SIDs
3193 * @nlbl_sid: NetLabel SID
3194 * @nlbl_type: NetLabel labeling protocol type
3195 * @xfrm_sid: XFRM SID
3198 * Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be
3199 * resolved into a single SID it is returned via @peer_sid and the function
3200 * returns zero. Otherwise @peer_sid is set to SECSID_NULL and the function
3201 * returns a negative value. A table summarizing the behavior is below:
3203 * | function return | @sid
3204 * ------------------------------+-----------------+-----------------
3205 * no peer labels | 0 | SECSID_NULL
3206 * single peer label | 0 | <peer_label>
3207 * multiple, consistent labels | 0 | <peer_label>
3208 * multiple, inconsistent labels | -<errno> | SECSID_NULL
3211 int security_net_peersid_resolve(struct selinux_state *state,
3212 u32 nlbl_sid, u32 nlbl_type,
3216 struct selinux_policy *policy;
3217 struct policydb *policydb;
3218 struct sidtab *sidtab;
3220 struct context *nlbl_ctx;
3221 struct context *xfrm_ctx;
3223 *peer_sid = SECSID_NULL;
3225 /* handle the common (which also happens to be the set of easy) cases
3226 * right away, these two if statements catch everything involving a
3227 * single or absent peer SID/label */
3228 if (xfrm_sid == SECSID_NULL) {
3229 *peer_sid = nlbl_sid;
3232 /* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a "fallback" label
3233 * and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label
3235 if (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) {
3236 *peer_sid = xfrm_sid;
3240 if (!selinux_initialized(state))
3244 policy = rcu_dereference(state->policy);
3245 policydb = &policy->policydb;
3246 sidtab = policy->sidtab;
3249 * We don't need to check initialized here since the only way both
3250 * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the
3251 * security server was initialized and state->initialized was true.
3253 if (!policydb->mls_enabled) {
3259 nlbl_ctx = sidtab_search(sidtab, nlbl_sid);
3261 pr_err("SELinux: %s: unrecognized SID %d\n",
3262 __func__, nlbl_sid);
3266 xfrm_ctx = sidtab_search(sidtab, xfrm_sid);
3268 pr_err("SELinux: %s: unrecognized SID %d\n",
3269 __func__, xfrm_sid);
3272 rc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES);
3276 /* at present NetLabel SIDs/labels really only carry MLS
3277 * information so if the MLS portion of the NetLabel SID
3278 * matches the MLS portion of the labeled XFRM SID/label
3279 * then pass along the XFRM SID as it is the most
3281 *peer_sid = xfrm_sid;
3287 static int get_classes_callback(void *k, void *d, void *args)
3289 struct class_datum *datum = d;
3290 char *name = k, **classes = args;
3291 int value = datum->value - 1;
3293 classes[value] = kstrdup(name, GFP_ATOMIC);
3294 if (!classes[value])
3300 int security_get_classes(struct selinux_policy *policy,
3301 char ***classes, int *nclasses)
3303 struct policydb *policydb;
3306 policydb = &policy->policydb;
3309 *nclasses = policydb->p_classes.nprim;
3310 *classes = kcalloc(*nclasses, sizeof(**classes), GFP_ATOMIC);
3314 rc = hashtab_map(&policydb->p_classes.table, get_classes_callback,
3318 for (i = 0; i < *nclasses; i++)
3319 kfree((*classes)[i]);
3327 static int get_permissions_callback(void *k, void *d, void *args)
3329 struct perm_datum *datum = d;
3330 char *name = k, **perms = args;
3331 int value = datum->value - 1;
3333 perms[value] = kstrdup(name, GFP_ATOMIC);
3340 int security_get_permissions(struct selinux_policy *policy,
3341 char *class, char ***perms, int *nperms)
3343 struct policydb *policydb;
3345 struct class_datum *match;
3347 policydb = &policy->policydb;
3350 match = symtab_search(&policydb->p_classes, class);
3352 pr_err("SELinux: %s: unrecognized class %s\n",
3358 *nperms = match->permissions.nprim;
3359 *perms = kcalloc(*nperms, sizeof(**perms), GFP_ATOMIC);
3363 if (match->comdatum) {
3364 rc = hashtab_map(&match->comdatum->permissions.table,
3365 get_permissions_callback, *perms);
3370 rc = hashtab_map(&match->permissions.table, get_permissions_callback,
3379 for (i = 0; i < *nperms; i++)
3385 int security_get_reject_unknown(struct selinux_state *state)
3387 struct selinux_policy *policy;
3390 if (!selinux_initialized(state))
3394 policy = rcu_dereference(state->policy);
3395 value = policy->policydb.reject_unknown;
3400 int security_get_allow_unknown(struct selinux_state *state)
3402 struct selinux_policy *policy;
3405 if (!selinux_initialized(state))
3409 policy = rcu_dereference(state->policy);
3410 value = policy->policydb.allow_unknown;
3416 * security_policycap_supported - Check for a specific policy capability
3417 * @req_cap: capability
3420 * This function queries the currently loaded policy to see if it supports the
3421 * capability specified by @req_cap. Returns true (1) if the capability is
3422 * supported, false (0) if it isn't supported.
3425 int security_policycap_supported(struct selinux_state *state,
3426 unsigned int req_cap)
3428 struct selinux_policy *policy;
3431 if (!selinux_initialized(state))
3435 policy = rcu_dereference(state->policy);
3436 rc = ebitmap_get_bit(&policy->policydb.policycaps, req_cap);
3442 struct selinux_audit_rule {
3444 struct context au_ctxt;
3447 void selinux_audit_rule_free(void *vrule)
3449 struct selinux_audit_rule *rule = vrule;
3452 context_destroy(&rule->au_ctxt);
3457 int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule)
3459 struct selinux_state *state = &selinux_state;
3460 struct selinux_policy *policy;
3461 struct policydb *policydb;
3462 struct selinux_audit_rule *tmprule;
3463 struct role_datum *roledatum;
3464 struct type_datum *typedatum;
3465 struct user_datum *userdatum;
3466 struct selinux_audit_rule **rule = (struct selinux_audit_rule **)vrule;
3471 if (!selinux_initialized(state))
3475 case AUDIT_SUBJ_USER:
3476 case AUDIT_SUBJ_ROLE:
3477 case AUDIT_SUBJ_TYPE:
3478 case AUDIT_OBJ_USER:
3479 case AUDIT_OBJ_ROLE:
3480 case AUDIT_OBJ_TYPE:
3481 /* only 'equals' and 'not equals' fit user, role, and type */
3482 if (op != Audit_equal && op != Audit_not_equal)
3485 case AUDIT_SUBJ_SEN:
3486 case AUDIT_SUBJ_CLR:
3487 case AUDIT_OBJ_LEV_LOW:
3488 case AUDIT_OBJ_LEV_HIGH:
3489 /* we do not allow a range, indicated by the presence of '-' */
3490 if (strchr(rulestr, '-'))
3494 /* only the above fields are valid */
3498 tmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL);
3502 context_init(&tmprule->au_ctxt);
3505 policy = rcu_dereference(state->policy);
3506 policydb = &policy->policydb;
3508 tmprule->au_seqno = policy->latest_granting;
3511 case AUDIT_SUBJ_USER:
3512 case AUDIT_OBJ_USER:
3514 userdatum = symtab_search(&policydb->p_users, rulestr);
3517 tmprule->au_ctxt.user = userdatum->value;
3519 case AUDIT_SUBJ_ROLE:
3520 case AUDIT_OBJ_ROLE:
3522 roledatum = symtab_search(&policydb->p_roles, rulestr);
3525 tmprule->au_ctxt.role = roledatum->value;
3527 case AUDIT_SUBJ_TYPE:
3528 case AUDIT_OBJ_TYPE:
3530 typedatum = symtab_search(&policydb->p_types, rulestr);
3533 tmprule->au_ctxt.type = typedatum->value;
3535 case AUDIT_SUBJ_SEN:
3536 case AUDIT_SUBJ_CLR:
3537 case AUDIT_OBJ_LEV_LOW:
3538 case AUDIT_OBJ_LEV_HIGH:
3539 rc = mls_from_string(policydb, rulestr, &tmprule->au_ctxt,
3550 selinux_audit_rule_free(tmprule);
3559 /* Check to see if the rule contains any selinux fields */
3560 int selinux_audit_rule_known(struct audit_krule *rule)
3564 for (i = 0; i < rule->field_count; i++) {
3565 struct audit_field *f = &rule->fields[i];
3567 case AUDIT_SUBJ_USER:
3568 case AUDIT_SUBJ_ROLE:
3569 case AUDIT_SUBJ_TYPE:
3570 case AUDIT_SUBJ_SEN:
3571 case AUDIT_SUBJ_CLR:
3572 case AUDIT_OBJ_USER:
3573 case AUDIT_OBJ_ROLE:
3574 case AUDIT_OBJ_TYPE:
3575 case AUDIT_OBJ_LEV_LOW:
3576 case AUDIT_OBJ_LEV_HIGH:
3584 int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule)
3586 struct selinux_state *state = &selinux_state;
3587 struct selinux_policy *policy;
3588 struct context *ctxt;
3589 struct mls_level *level;
3590 struct selinux_audit_rule *rule = vrule;
3593 if (unlikely(!rule)) {
3594 WARN_ONCE(1, "selinux_audit_rule_match: missing rule\n");
3598 if (!selinux_initialized(state))
3603 policy = rcu_dereference(state->policy);
3605 if (rule->au_seqno < policy->latest_granting) {
3610 ctxt = sidtab_search(policy->sidtab, sid);
3611 if (unlikely(!ctxt)) {
3612 WARN_ONCE(1, "selinux_audit_rule_match: unrecognized SID %d\n",
3618 /* a field/op pair that is not caught here will simply fall through
3621 case AUDIT_SUBJ_USER:
3622 case AUDIT_OBJ_USER:
3625 match = (ctxt->user == rule->au_ctxt.user);
3627 case Audit_not_equal:
3628 match = (ctxt->user != rule->au_ctxt.user);
3632 case AUDIT_SUBJ_ROLE:
3633 case AUDIT_OBJ_ROLE:
3636 match = (ctxt->role == rule->au_ctxt.role);
3638 case Audit_not_equal:
3639 match = (ctxt->role != rule->au_ctxt.role);
3643 case AUDIT_SUBJ_TYPE:
3644 case AUDIT_OBJ_TYPE:
3647 match = (ctxt->type == rule->au_ctxt.type);
3649 case Audit_not_equal:
3650 match = (ctxt->type != rule->au_ctxt.type);
3654 case AUDIT_SUBJ_SEN:
3655 case AUDIT_SUBJ_CLR:
3656 case AUDIT_OBJ_LEV_LOW:
3657 case AUDIT_OBJ_LEV_HIGH:
3658 level = ((field == AUDIT_SUBJ_SEN ||
3659 field == AUDIT_OBJ_LEV_LOW) ?
3660 &ctxt->range.level[0] : &ctxt->range.level[1]);
3663 match = mls_level_eq(&rule->au_ctxt.range.level[0],
3666 case Audit_not_equal:
3667 match = !mls_level_eq(&rule->au_ctxt.range.level[0],
3671 match = (mls_level_dom(&rule->au_ctxt.range.level[0],
3673 !mls_level_eq(&rule->au_ctxt.range.level[0],
3677 match = mls_level_dom(&rule->au_ctxt.range.level[0],
3681 match = (mls_level_dom(level,
3682 &rule->au_ctxt.range.level[0]) &&
3683 !mls_level_eq(level,
3684 &rule->au_ctxt.range.level[0]));
3687 match = mls_level_dom(level,
3688 &rule->au_ctxt.range.level[0]);
3698 static int aurule_avc_callback(u32 event)
3700 if (event == AVC_CALLBACK_RESET)
3701 return audit_update_lsm_rules();
3705 static int __init aurule_init(void)
3709 err = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET);
3711 panic("avc_add_callback() failed, error %d\n", err);
3715 __initcall(aurule_init);
3717 #ifdef CONFIG_NETLABEL
3719 * security_netlbl_cache_add - Add an entry to the NetLabel cache
3720 * @secattr: the NetLabel packet security attributes
3721 * @sid: the SELinux SID
3724 * Attempt to cache the context in @ctx, which was derived from the packet in
3725 * @skb, in the NetLabel subsystem cache. This function assumes @secattr has
3726 * already been initialized.
3729 static void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr,
3734 sid_cache = kmalloc(sizeof(*sid_cache), GFP_ATOMIC);
3735 if (sid_cache == NULL)
3737 secattr->cache = netlbl_secattr_cache_alloc(GFP_ATOMIC);
3738 if (secattr->cache == NULL) {
3744 secattr->cache->free = kfree;
3745 secattr->cache->data = sid_cache;
3746 secattr->flags |= NETLBL_SECATTR_CACHE;
3750 * security_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID
3751 * @secattr: the NetLabel packet security attributes
3752 * @sid: the SELinux SID
3755 * Convert the given NetLabel security attributes in @secattr into a
3756 * SELinux SID. If the @secattr field does not contain a full SELinux
3757 * SID/context then use SECINITSID_NETMSG as the foundation. If possible the
3758 * 'cache' field of @secattr is set and the CACHE flag is set; this is to
3759 * allow the @secattr to be used by NetLabel to cache the secattr to SID
3760 * conversion for future lookups. Returns zero on success, negative values on
3764 int security_netlbl_secattr_to_sid(struct selinux_state *state,
3765 struct netlbl_lsm_secattr *secattr,
3768 struct selinux_policy *policy;
3769 struct policydb *policydb;
3770 struct sidtab *sidtab;
3772 struct context *ctx;
3773 struct context ctx_new;
3775 if (!selinux_initialized(state)) {
3781 policy = rcu_dereference(state->policy);
3782 policydb = &policy->policydb;
3783 sidtab = policy->sidtab;
3785 if (secattr->flags & NETLBL_SECATTR_CACHE)
3786 *sid = *(u32 *)secattr->cache->data;
3787 else if (secattr->flags & NETLBL_SECATTR_SECID)
3788 *sid = secattr->attr.secid;
3789 else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) {
3791 ctx = sidtab_search(sidtab, SECINITSID_NETMSG);
3795 context_init(&ctx_new);
3796 ctx_new.user = ctx->user;
3797 ctx_new.role = ctx->role;
3798 ctx_new.type = ctx->type;
3799 mls_import_netlbl_lvl(policydb, &ctx_new, secattr);
3800 if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
3801 rc = mls_import_netlbl_cat(policydb, &ctx_new, secattr);
3806 if (!mls_context_isvalid(policydb, &ctx_new))
3809 rc = sidtab_context_to_sid(sidtab, &ctx_new, sid);
3813 security_netlbl_cache_add(secattr, *sid);
3815 ebitmap_destroy(&ctx_new.range.level[0].cat);
3822 ebitmap_destroy(&ctx_new.range.level[0].cat);
3829 * security_netlbl_sid_to_secattr - Convert a SELinux SID to a NetLabel secattr
3830 * @sid: the SELinux SID
3831 * @secattr: the NetLabel packet security attributes
3834 * Convert the given SELinux SID in @sid into a NetLabel security attribute.
3835 * Returns zero on success, negative values on failure.
3838 int security_netlbl_sid_to_secattr(struct selinux_state *state,
3839 u32 sid, struct netlbl_lsm_secattr *secattr)
3841 struct selinux_policy *policy;
3842 struct policydb *policydb;
3844 struct context *ctx;
3846 if (!selinux_initialized(state))
3850 policy = rcu_dereference(state->policy);
3851 policydb = &policy->policydb;
3854 ctx = sidtab_search(policy->sidtab, sid);
3859 secattr->domain = kstrdup(sym_name(policydb, SYM_TYPES, ctx->type - 1),
3861 if (secattr->domain == NULL)
3864 secattr->attr.secid = sid;
3865 secattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID;
3866 mls_export_netlbl_lvl(policydb, ctx, secattr);
3867 rc = mls_export_netlbl_cat(policydb, ctx, secattr);
3872 #endif /* CONFIG_NETLABEL */
3875 * __security_read_policy - read the policy.
3876 * @policy: SELinux policy
3877 * @data: binary policy data
3878 * @len: length of data in bytes
3881 static int __security_read_policy(struct selinux_policy *policy,
3882 void *data, size_t *len)
3885 struct policy_file fp;
3890 rc = policydb_write(&policy->policydb, &fp);
3894 *len = (unsigned long)fp.data - (unsigned long)data;
3899 * security_read_policy - read the policy.
3900 * @state: selinux_state
3901 * @data: binary policy data
3902 * @len: length of data in bytes
3905 int security_read_policy(struct selinux_state *state,
3906 void **data, size_t *len)
3908 struct selinux_policy *policy;
3910 policy = rcu_dereference_protected(
3911 state->policy, lockdep_is_held(&state->policy_mutex));
3915 *len = policy->policydb.len;
3916 *data = vmalloc_user(*len);
3920 return __security_read_policy(policy, *data, len);
3924 * security_read_state_kernel - read the policy.
3925 * @state: selinux_state
3926 * @data: binary policy data
3927 * @len: length of data in bytes
3929 * Allocates kernel memory for reading SELinux policy.
3930 * This function is for internal use only and should not
3931 * be used for returning data to user space.
3933 * This function must be called with policy_mutex held.
3935 int security_read_state_kernel(struct selinux_state *state,
3936 void **data, size_t *len)
3938 struct selinux_policy *policy;
3940 policy = rcu_dereference_protected(
3941 state->policy, lockdep_is_held(&state->policy_mutex));
3945 *len = policy->policydb.len;
3946 *data = vmalloc(*len);
3950 return __security_read_policy(policy, *data, len);