1 // SPDX-License-Identifier: GPL-2.0-only
3 * Implementation of the security services.
5 * Authors : Stephen Smalley, <sds@tycho.nsa.gov>
6 * James Morris <jmorris@redhat.com>
8 * Updated: Trusted Computer Solutions, Inc. <dgoeddel@trustedcs.com>
10 * Support for enhanced MLS infrastructure.
11 * Support for context based audit filters.
13 * Updated: Frank Mayer <mayerf@tresys.com> and Karl MacMillan <kmacmillan@tresys.com>
15 * Added conditional policy language extensions
17 * Updated: Hewlett-Packard <paul@paul-moore.com>
19 * Added support for NetLabel
20 * Added support for the policy capability bitmap
22 * Updated: Chad Sellers <csellers@tresys.com>
24 * Added validation of kernel classes and permissions
26 * Updated: KaiGai Kohei <kaigai@ak.jp.nec.com>
28 * Added support for bounds domain and audit messaged on masked permissions
30 * Updated: Guido Trentalancia <guido@trentalancia.com>
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
38 * Copyright (C) 2003 Red Hat, Inc., James Morris <jmorris@redhat.com>
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 <linux/lsm_hooks.h>
51 #include <net/netlabel.h>
61 #include "conditional.h"
68 #include "policycap_names.h"
71 struct convert_context_args {
72 struct selinux_state *state;
73 struct policydb *oldp;
74 struct policydb *newp;
77 struct selinux_policy_convert_data {
78 struct convert_context_args args;
79 struct sidtab_convert_params sidtab_params;
82 /* Forward declaration. */
83 static int context_struct_to_string(struct policydb *policydb,
84 struct context *context,
88 static int sidtab_entry_to_string(struct policydb *policydb,
89 struct sidtab *sidtab,
90 struct sidtab_entry *entry,
94 static void context_struct_compute_av(struct policydb *policydb,
95 struct context *scontext,
96 struct context *tcontext,
98 struct av_decision *avd,
99 struct extended_perms *xperms);
101 static int selinux_set_mapping(struct policydb *pol,
102 struct security_class_mapping *map,
103 struct selinux_map *out_map)
107 bool print_unknown_handle = false;
109 /* Find number of classes in the input mapping */
116 /* Allocate space for the class records, plus one for class zero */
117 out_map->mapping = kcalloc(++i, sizeof(*out_map->mapping), GFP_ATOMIC);
118 if (!out_map->mapping)
121 /* Store the raw class and permission values */
123 while (map[j].name) {
124 struct security_class_mapping *p_in = map + (j++);
125 struct selinux_mapping *p_out = out_map->mapping + j;
127 /* An empty class string skips ahead */
128 if (!strcmp(p_in->name, "")) {
129 p_out->num_perms = 0;
133 p_out->value = string_to_security_class(pol, p_in->name);
135 pr_info("SELinux: Class %s not defined in policy.\n",
137 if (pol->reject_unknown)
139 p_out->num_perms = 0;
140 print_unknown_handle = true;
145 while (p_in->perms[k]) {
146 /* An empty permission string skips ahead */
147 if (!*p_in->perms[k]) {
151 p_out->perms[k] = string_to_av_perm(pol, p_out->value,
153 if (!p_out->perms[k]) {
154 pr_info("SELinux: Permission %s in class %s not defined in policy.\n",
155 p_in->perms[k], p_in->name);
156 if (pol->reject_unknown)
158 print_unknown_handle = true;
163 p_out->num_perms = k;
166 if (print_unknown_handle)
167 pr_info("SELinux: the above unknown classes and permissions will be %s\n",
168 pol->allow_unknown ? "allowed" : "denied");
173 kfree(out_map->mapping);
174 out_map->mapping = NULL;
179 * Get real, policy values from mapped values
182 static u16 unmap_class(struct selinux_map *map, u16 tclass)
184 if (tclass < map->size)
185 return map->mapping[tclass].value;
191 * Get kernel value for class from its policy value
193 static u16 map_class(struct selinux_map *map, u16 pol_value)
197 for (i = 1; i < map->size; i++) {
198 if (map->mapping[i].value == pol_value)
202 return SECCLASS_NULL;
205 static void map_decision(struct selinux_map *map,
206 u16 tclass, struct av_decision *avd,
209 if (tclass < map->size) {
210 struct selinux_mapping *mapping = &map->mapping[tclass];
211 unsigned int i, n = mapping->num_perms;
214 for (i = 0, result = 0; i < n; i++) {
215 if (avd->allowed & mapping->perms[i])
217 if (allow_unknown && !mapping->perms[i])
220 avd->allowed = result;
222 for (i = 0, result = 0; i < n; i++)
223 if (avd->auditallow & mapping->perms[i])
225 avd->auditallow = result;
227 for (i = 0, result = 0; i < n; i++) {
228 if (avd->auditdeny & mapping->perms[i])
230 if (!allow_unknown && !mapping->perms[i])
234 * In case the kernel has a bug and requests a permission
235 * between num_perms and the maximum permission number, we
236 * should audit that denial
238 for (; i < (sizeof(u32)*8); i++)
240 avd->auditdeny = result;
244 int security_mls_enabled(struct selinux_state *state)
247 struct selinux_policy *policy;
249 if (!selinux_initialized(state))
253 policy = rcu_dereference(state->policy);
254 mls_enabled = policy->policydb.mls_enabled;
260 * Return the boolean value of a constraint expression
261 * when it is applied to the specified source and target
264 * xcontext is a special beast... It is used by the validatetrans rules
265 * only. For these rules, scontext is the context before the transition,
266 * tcontext is the context after the transition, and xcontext is the context
267 * of the process performing the transition. All other callers of
268 * constraint_expr_eval should pass in NULL for xcontext.
270 static int constraint_expr_eval(struct policydb *policydb,
271 struct context *scontext,
272 struct context *tcontext,
273 struct context *xcontext,
274 struct constraint_expr *cexpr)
278 struct role_datum *r1, *r2;
279 struct mls_level *l1, *l2;
280 struct constraint_expr *e;
281 int s[CEXPR_MAXDEPTH];
284 for (e = cexpr; e; e = e->next) {
285 switch (e->expr_type) {
301 if (sp == (CEXPR_MAXDEPTH - 1))
305 val1 = scontext->user;
306 val2 = tcontext->user;
309 val1 = scontext->type;
310 val2 = tcontext->type;
313 val1 = scontext->role;
314 val2 = tcontext->role;
315 r1 = policydb->role_val_to_struct[val1 - 1];
316 r2 = policydb->role_val_to_struct[val2 - 1];
319 s[++sp] = ebitmap_get_bit(&r1->dominates,
323 s[++sp] = ebitmap_get_bit(&r2->dominates,
327 s[++sp] = (!ebitmap_get_bit(&r1->dominates,
329 !ebitmap_get_bit(&r2->dominates,
337 l1 = &(scontext->range.level[0]);
338 l2 = &(tcontext->range.level[0]);
341 l1 = &(scontext->range.level[0]);
342 l2 = &(tcontext->range.level[1]);
345 l1 = &(scontext->range.level[1]);
346 l2 = &(tcontext->range.level[0]);
349 l1 = &(scontext->range.level[1]);
350 l2 = &(tcontext->range.level[1]);
353 l1 = &(scontext->range.level[0]);
354 l2 = &(scontext->range.level[1]);
357 l1 = &(tcontext->range.level[0]);
358 l2 = &(tcontext->range.level[1]);
363 s[++sp] = mls_level_eq(l1, l2);
366 s[++sp] = !mls_level_eq(l1, l2);
369 s[++sp] = mls_level_dom(l1, l2);
372 s[++sp] = mls_level_dom(l2, l1);
375 s[++sp] = mls_level_incomp(l2, l1);
389 s[++sp] = (val1 == val2);
392 s[++sp] = (val1 != val2);
400 if (sp == (CEXPR_MAXDEPTH-1))
403 if (e->attr & CEXPR_TARGET)
405 else if (e->attr & CEXPR_XTARGET) {
412 if (e->attr & CEXPR_USER)
414 else if (e->attr & CEXPR_ROLE)
416 else if (e->attr & CEXPR_TYPE)
425 s[++sp] = ebitmap_get_bit(&e->names, val1 - 1);
428 s[++sp] = !ebitmap_get_bit(&e->names, val1 - 1);
446 * security_dump_masked_av - dumps masked permissions during
447 * security_compute_av due to RBAC, MLS/Constraint and Type bounds.
449 static int dump_masked_av_helper(void *k, void *d, void *args)
451 struct perm_datum *pdatum = d;
452 char **permission_names = args;
454 BUG_ON(pdatum->value < 1 || pdatum->value > 32);
456 permission_names[pdatum->value - 1] = (char *)k;
461 static void security_dump_masked_av(struct policydb *policydb,
462 struct context *scontext,
463 struct context *tcontext,
468 struct common_datum *common_dat;
469 struct class_datum *tclass_dat;
470 struct audit_buffer *ab;
472 char *scontext_name = NULL;
473 char *tcontext_name = NULL;
474 char *permission_names[32];
477 bool need_comma = false;
482 tclass_name = sym_name(policydb, SYM_CLASSES, tclass - 1);
483 tclass_dat = policydb->class_val_to_struct[tclass - 1];
484 common_dat = tclass_dat->comdatum;
486 /* init permission_names */
488 hashtab_map(&common_dat->permissions.table,
489 dump_masked_av_helper, permission_names) < 0)
492 if (hashtab_map(&tclass_dat->permissions.table,
493 dump_masked_av_helper, permission_names) < 0)
496 /* get scontext/tcontext in text form */
497 if (context_struct_to_string(policydb, scontext,
498 &scontext_name, &length) < 0)
501 if (context_struct_to_string(policydb, tcontext,
502 &tcontext_name, &length) < 0)
505 /* audit a message */
506 ab = audit_log_start(audit_context(),
507 GFP_ATOMIC, AUDIT_SELINUX_ERR);
511 audit_log_format(ab, "op=security_compute_av reason=%s "
512 "scontext=%s tcontext=%s tclass=%s perms=",
513 reason, scontext_name, tcontext_name, tclass_name);
515 for (index = 0; index < 32; index++) {
516 u32 mask = (1 << index);
518 if ((mask & permissions) == 0)
521 audit_log_format(ab, "%s%s",
522 need_comma ? "," : "",
523 permission_names[index]
524 ? permission_names[index] : "????");
529 /* release scontext/tcontext */
530 kfree(tcontext_name);
531 kfree(scontext_name);
537 * security_boundary_permission - drops violated permissions
538 * on boundary constraint.
540 static void type_attribute_bounds_av(struct policydb *policydb,
541 struct context *scontext,
542 struct context *tcontext,
544 struct av_decision *avd)
546 struct context lo_scontext;
547 struct context lo_tcontext, *tcontextp = tcontext;
548 struct av_decision lo_avd;
549 struct type_datum *source;
550 struct type_datum *target;
553 source = policydb->type_val_to_struct[scontext->type - 1];
559 target = policydb->type_val_to_struct[tcontext->type - 1];
562 memset(&lo_avd, 0, sizeof(lo_avd));
564 memcpy(&lo_scontext, scontext, sizeof(lo_scontext));
565 lo_scontext.type = source->bounds;
567 if (target->bounds) {
568 memcpy(&lo_tcontext, tcontext, sizeof(lo_tcontext));
569 lo_tcontext.type = target->bounds;
570 tcontextp = &lo_tcontext;
573 context_struct_compute_av(policydb, &lo_scontext,
579 masked = ~lo_avd.allowed & avd->allowed;
582 return; /* no masked permission */
584 /* mask violated permissions */
585 avd->allowed &= ~masked;
587 /* audit masked permissions */
588 security_dump_masked_av(policydb, scontext, tcontext,
589 tclass, masked, "bounds");
593 * flag which drivers have permissions
594 * only looking for ioctl based extended permssions
596 void services_compute_xperms_drivers(
597 struct extended_perms *xperms,
598 struct avtab_node *node)
602 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
603 /* if one or more driver has all permissions allowed */
604 for (i = 0; i < ARRAY_SIZE(xperms->drivers.p); i++)
605 xperms->drivers.p[i] |= node->datum.u.xperms->perms.p[i];
606 } else if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
607 /* if allowing permissions within a driver */
608 security_xperm_set(xperms->drivers.p,
609 node->datum.u.xperms->driver);
616 * Compute access vectors and extended permissions based on a context
617 * structure pair for the permissions in a particular class.
619 static void context_struct_compute_av(struct policydb *policydb,
620 struct context *scontext,
621 struct context *tcontext,
623 struct av_decision *avd,
624 struct extended_perms *xperms)
626 struct constraint_node *constraint;
627 struct role_allow *ra;
628 struct avtab_key avkey;
629 struct avtab_node *node;
630 struct class_datum *tclass_datum;
631 struct ebitmap *sattr, *tattr;
632 struct ebitmap_node *snode, *tnode;
637 avd->auditdeny = 0xffffffff;
639 memset(&xperms->drivers, 0, sizeof(xperms->drivers));
643 if (unlikely(!tclass || tclass > policydb->p_classes.nprim)) {
644 if (printk_ratelimit())
645 pr_warn("SELinux: Invalid class %hu\n", tclass);
649 tclass_datum = policydb->class_val_to_struct[tclass - 1];
652 * If a specific type enforcement rule was defined for
653 * this permission check, then use it.
655 avkey.target_class = tclass;
656 avkey.specified = AVTAB_AV | AVTAB_XPERMS;
657 sattr = &policydb->type_attr_map_array[scontext->type - 1];
658 tattr = &policydb->type_attr_map_array[tcontext->type - 1];
659 ebitmap_for_each_positive_bit(sattr, snode, i) {
660 ebitmap_for_each_positive_bit(tattr, tnode, j) {
661 avkey.source_type = i + 1;
662 avkey.target_type = j + 1;
663 for (node = avtab_search_node(&policydb->te_avtab,
666 node = avtab_search_node_next(node, avkey.specified)) {
667 if (node->key.specified == AVTAB_ALLOWED)
668 avd->allowed |= node->datum.u.data;
669 else if (node->key.specified == AVTAB_AUDITALLOW)
670 avd->auditallow |= node->datum.u.data;
671 else if (node->key.specified == AVTAB_AUDITDENY)
672 avd->auditdeny &= node->datum.u.data;
673 else if (xperms && (node->key.specified & AVTAB_XPERMS))
674 services_compute_xperms_drivers(xperms, node);
677 /* Check conditional av table for additional permissions */
678 cond_compute_av(&policydb->te_cond_avtab, &avkey,
685 * Remove any permissions prohibited by a constraint (this includes
688 constraint = tclass_datum->constraints;
690 if ((constraint->permissions & (avd->allowed)) &&
691 !constraint_expr_eval(policydb, scontext, tcontext, NULL,
693 avd->allowed &= ~(constraint->permissions);
695 constraint = constraint->next;
699 * If checking process transition permission and the
700 * role is changing, then check the (current_role, new_role)
703 if (tclass == policydb->process_class &&
704 (avd->allowed & policydb->process_trans_perms) &&
705 scontext->role != tcontext->role) {
706 for (ra = policydb->role_allow; ra; ra = ra->next) {
707 if (scontext->role == ra->role &&
708 tcontext->role == ra->new_role)
712 avd->allowed &= ~policydb->process_trans_perms;
716 * If the given source and target types have boundary
717 * constraint, lazy checks have to mask any violated
718 * permission and notice it to userspace via audit.
720 type_attribute_bounds_av(policydb, scontext, tcontext,
724 static int security_validtrans_handle_fail(struct selinux_state *state,
725 struct selinux_policy *policy,
726 struct sidtab_entry *oentry,
727 struct sidtab_entry *nentry,
728 struct sidtab_entry *tentry,
731 struct policydb *p = &policy->policydb;
732 struct sidtab *sidtab = policy->sidtab;
733 char *o = NULL, *n = NULL, *t = NULL;
734 u32 olen, nlen, tlen;
736 if (sidtab_entry_to_string(p, sidtab, oentry, &o, &olen))
738 if (sidtab_entry_to_string(p, sidtab, nentry, &n, &nlen))
740 if (sidtab_entry_to_string(p, sidtab, tentry, &t, &tlen))
742 audit_log(audit_context(), GFP_ATOMIC, AUDIT_SELINUX_ERR,
743 "op=security_validate_transition seresult=denied"
744 " oldcontext=%s newcontext=%s taskcontext=%s tclass=%s",
745 o, n, t, sym_name(p, SYM_CLASSES, tclass-1));
751 if (!enforcing_enabled(state))
756 static int security_compute_validatetrans(struct selinux_state *state,
757 u32 oldsid, u32 newsid, u32 tasksid,
758 u16 orig_tclass, bool user)
760 struct selinux_policy *policy;
761 struct policydb *policydb;
762 struct sidtab *sidtab;
763 struct sidtab_entry *oentry;
764 struct sidtab_entry *nentry;
765 struct sidtab_entry *tentry;
766 struct class_datum *tclass_datum;
767 struct constraint_node *constraint;
772 if (!selinux_initialized(state))
777 policy = rcu_dereference(state->policy);
778 policydb = &policy->policydb;
779 sidtab = policy->sidtab;
782 tclass = unmap_class(&policy->map, orig_tclass);
784 tclass = orig_tclass;
786 if (!tclass || tclass > policydb->p_classes.nprim) {
790 tclass_datum = policydb->class_val_to_struct[tclass - 1];
792 oentry = sidtab_search_entry(sidtab, oldsid);
794 pr_err("SELinux: %s: unrecognized SID %d\n",
800 nentry = sidtab_search_entry(sidtab, newsid);
802 pr_err("SELinux: %s: unrecognized SID %d\n",
808 tentry = sidtab_search_entry(sidtab, tasksid);
810 pr_err("SELinux: %s: unrecognized SID %d\n",
816 constraint = tclass_datum->validatetrans;
818 if (!constraint_expr_eval(policydb, &oentry->context,
819 &nentry->context, &tentry->context,
824 rc = security_validtrans_handle_fail(state,
832 constraint = constraint->next;
840 int security_validate_transition_user(struct selinux_state *state,
841 u32 oldsid, u32 newsid, u32 tasksid,
844 return security_compute_validatetrans(state, oldsid, newsid, tasksid,
848 int security_validate_transition(struct selinux_state *state,
849 u32 oldsid, u32 newsid, u32 tasksid,
852 return security_compute_validatetrans(state, oldsid, newsid, tasksid,
857 * security_bounded_transition - check whether the given
858 * transition is directed to bounded, or not.
859 * It returns 0, if @newsid is bounded by @oldsid.
860 * Otherwise, it returns error code.
862 * @state: SELinux state
863 * @oldsid : current security identifier
864 * @newsid : destinated security identifier
866 int security_bounded_transition(struct selinux_state *state,
867 u32 old_sid, u32 new_sid)
869 struct selinux_policy *policy;
870 struct policydb *policydb;
871 struct sidtab *sidtab;
872 struct sidtab_entry *old_entry, *new_entry;
873 struct type_datum *type;
877 if (!selinux_initialized(state))
881 policy = rcu_dereference(state->policy);
882 policydb = &policy->policydb;
883 sidtab = policy->sidtab;
886 old_entry = sidtab_search_entry(sidtab, old_sid);
888 pr_err("SELinux: %s: unrecognized SID %u\n",
894 new_entry = sidtab_search_entry(sidtab, new_sid);
896 pr_err("SELinux: %s: unrecognized SID %u\n",
902 /* type/domain unchanged */
903 if (old_entry->context.type == new_entry->context.type)
906 index = new_entry->context.type;
908 type = policydb->type_val_to_struct[index - 1];
911 /* not bounded anymore */
916 /* @newsid is bounded by @oldsid */
918 if (type->bounds == old_entry->context.type)
921 index = type->bounds;
925 char *old_name = NULL;
926 char *new_name = NULL;
929 if (!sidtab_entry_to_string(policydb, sidtab, old_entry,
930 &old_name, &length) &&
931 !sidtab_entry_to_string(policydb, sidtab, new_entry,
932 &new_name, &length)) {
933 audit_log(audit_context(),
934 GFP_ATOMIC, AUDIT_SELINUX_ERR,
935 "op=security_bounded_transition "
937 "oldcontext=%s newcontext=%s",
949 static void avd_init(struct selinux_policy *policy, struct av_decision *avd)
953 avd->auditdeny = 0xffffffff;
955 avd->seqno = policy->latest_granting;
961 void services_compute_xperms_decision(struct extended_perms_decision *xpermd,
962 struct avtab_node *node)
966 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
967 if (xpermd->driver != node->datum.u.xperms->driver)
969 } else if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
970 if (!security_xperm_test(node->datum.u.xperms->perms.p,
977 if (node->key.specified == AVTAB_XPERMS_ALLOWED) {
978 xpermd->used |= XPERMS_ALLOWED;
979 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
980 memset(xpermd->allowed->p, 0xff,
981 sizeof(xpermd->allowed->p));
983 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
984 for (i = 0; i < ARRAY_SIZE(xpermd->allowed->p); i++)
985 xpermd->allowed->p[i] |=
986 node->datum.u.xperms->perms.p[i];
988 } else if (node->key.specified == AVTAB_XPERMS_AUDITALLOW) {
989 xpermd->used |= XPERMS_AUDITALLOW;
990 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
991 memset(xpermd->auditallow->p, 0xff,
992 sizeof(xpermd->auditallow->p));
994 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
995 for (i = 0; i < ARRAY_SIZE(xpermd->auditallow->p); i++)
996 xpermd->auditallow->p[i] |=
997 node->datum.u.xperms->perms.p[i];
999 } else if (node->key.specified == AVTAB_XPERMS_DONTAUDIT) {
1000 xpermd->used |= XPERMS_DONTAUDIT;
1001 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
1002 memset(xpermd->dontaudit->p, 0xff,
1003 sizeof(xpermd->dontaudit->p));
1005 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
1006 for (i = 0; i < ARRAY_SIZE(xpermd->dontaudit->p); i++)
1007 xpermd->dontaudit->p[i] |=
1008 node->datum.u.xperms->perms.p[i];
1015 void security_compute_xperms_decision(struct selinux_state *state,
1020 struct extended_perms_decision *xpermd)
1022 struct selinux_policy *policy;
1023 struct policydb *policydb;
1024 struct sidtab *sidtab;
1026 struct context *scontext, *tcontext;
1027 struct avtab_key avkey;
1028 struct avtab_node *node;
1029 struct ebitmap *sattr, *tattr;
1030 struct ebitmap_node *snode, *tnode;
1033 xpermd->driver = driver;
1035 memset(xpermd->allowed->p, 0, sizeof(xpermd->allowed->p));
1036 memset(xpermd->auditallow->p, 0, sizeof(xpermd->auditallow->p));
1037 memset(xpermd->dontaudit->p, 0, sizeof(xpermd->dontaudit->p));
1040 if (!selinux_initialized(state))
1043 policy = rcu_dereference(state->policy);
1044 policydb = &policy->policydb;
1045 sidtab = policy->sidtab;
1047 scontext = sidtab_search(sidtab, ssid);
1049 pr_err("SELinux: %s: unrecognized SID %d\n",
1054 tcontext = sidtab_search(sidtab, tsid);
1056 pr_err("SELinux: %s: unrecognized SID %d\n",
1061 tclass = unmap_class(&policy->map, orig_tclass);
1062 if (unlikely(orig_tclass && !tclass)) {
1063 if (policydb->allow_unknown)
1069 if (unlikely(!tclass || tclass > policydb->p_classes.nprim)) {
1070 pr_warn_ratelimited("SELinux: Invalid class %hu\n", tclass);
1074 avkey.target_class = tclass;
1075 avkey.specified = AVTAB_XPERMS;
1076 sattr = &policydb->type_attr_map_array[scontext->type - 1];
1077 tattr = &policydb->type_attr_map_array[tcontext->type - 1];
1078 ebitmap_for_each_positive_bit(sattr, snode, i) {
1079 ebitmap_for_each_positive_bit(tattr, tnode, j) {
1080 avkey.source_type = i + 1;
1081 avkey.target_type = j + 1;
1082 for (node = avtab_search_node(&policydb->te_avtab,
1085 node = avtab_search_node_next(node, avkey.specified))
1086 services_compute_xperms_decision(xpermd, node);
1088 cond_compute_xperms(&policydb->te_cond_avtab,
1096 memset(xpermd->allowed->p, 0xff, sizeof(xpermd->allowed->p));
1101 * security_compute_av - Compute access vector decisions.
1102 * @state: SELinux state
1103 * @ssid: source security identifier
1104 * @tsid: target security identifier
1105 * @tclass: target security class
1106 * @avd: access vector decisions
1107 * @xperms: extended permissions
1109 * Compute a set of access vector decisions based on the
1110 * SID pair (@ssid, @tsid) for the permissions in @tclass.
1112 void security_compute_av(struct selinux_state *state,
1116 struct av_decision *avd,
1117 struct extended_perms *xperms)
1119 struct selinux_policy *policy;
1120 struct policydb *policydb;
1121 struct sidtab *sidtab;
1123 struct context *scontext = NULL, *tcontext = NULL;
1126 policy = rcu_dereference(state->policy);
1127 avd_init(policy, avd);
1129 if (!selinux_initialized(state))
1132 policydb = &policy->policydb;
1133 sidtab = policy->sidtab;
1135 scontext = sidtab_search(sidtab, ssid);
1137 pr_err("SELinux: %s: unrecognized SID %d\n",
1142 /* permissive domain? */
1143 if (ebitmap_get_bit(&policydb->permissive_map, scontext->type))
1144 avd->flags |= AVD_FLAGS_PERMISSIVE;
1146 tcontext = sidtab_search(sidtab, tsid);
1148 pr_err("SELinux: %s: unrecognized SID %d\n",
1153 tclass = unmap_class(&policy->map, orig_tclass);
1154 if (unlikely(orig_tclass && !tclass)) {
1155 if (policydb->allow_unknown)
1159 context_struct_compute_av(policydb, scontext, tcontext, tclass, avd,
1161 map_decision(&policy->map, orig_tclass, avd,
1162 policydb->allow_unknown);
1167 avd->allowed = 0xffffffff;
1171 void security_compute_av_user(struct selinux_state *state,
1175 struct av_decision *avd)
1177 struct selinux_policy *policy;
1178 struct policydb *policydb;
1179 struct sidtab *sidtab;
1180 struct context *scontext = NULL, *tcontext = NULL;
1183 policy = rcu_dereference(state->policy);
1184 avd_init(policy, avd);
1185 if (!selinux_initialized(state))
1188 policydb = &policy->policydb;
1189 sidtab = policy->sidtab;
1191 scontext = sidtab_search(sidtab, ssid);
1193 pr_err("SELinux: %s: unrecognized SID %d\n",
1198 /* permissive domain? */
1199 if (ebitmap_get_bit(&policydb->permissive_map, scontext->type))
1200 avd->flags |= AVD_FLAGS_PERMISSIVE;
1202 tcontext = sidtab_search(sidtab, tsid);
1204 pr_err("SELinux: %s: unrecognized SID %d\n",
1209 if (unlikely(!tclass)) {
1210 if (policydb->allow_unknown)
1215 context_struct_compute_av(policydb, scontext, tcontext, tclass, avd,
1221 avd->allowed = 0xffffffff;
1226 * Write the security context string representation of
1227 * the context structure `context' into a dynamically
1228 * allocated string of the correct size. Set `*scontext'
1229 * to point to this string and set `*scontext_len' to
1230 * the length of the string.
1232 static int context_struct_to_string(struct policydb *p,
1233 struct context *context,
1234 char **scontext, u32 *scontext_len)
1243 *scontext_len = context->len;
1245 *scontext = kstrdup(context->str, GFP_ATOMIC);
1252 /* Compute the size of the context. */
1253 *scontext_len += strlen(sym_name(p, SYM_USERS, context->user - 1)) + 1;
1254 *scontext_len += strlen(sym_name(p, SYM_ROLES, context->role - 1)) + 1;
1255 *scontext_len += strlen(sym_name(p, SYM_TYPES, context->type - 1)) + 1;
1256 *scontext_len += mls_compute_context_len(p, context);
1261 /* Allocate space for the context; caller must free this space. */
1262 scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
1265 *scontext = scontextp;
1268 * Copy the user name, role name and type name into the context.
1270 scontextp += sprintf(scontextp, "%s:%s:%s",
1271 sym_name(p, SYM_USERS, context->user - 1),
1272 sym_name(p, SYM_ROLES, context->role - 1),
1273 sym_name(p, SYM_TYPES, context->type - 1));
1275 mls_sid_to_context(p, context, &scontextp);
1282 static int sidtab_entry_to_string(struct policydb *p,
1283 struct sidtab *sidtab,
1284 struct sidtab_entry *entry,
1285 char **scontext, u32 *scontext_len)
1287 int rc = sidtab_sid2str_get(sidtab, entry, scontext, scontext_len);
1292 rc = context_struct_to_string(p, &entry->context, scontext,
1294 if (!rc && scontext)
1295 sidtab_sid2str_put(sidtab, entry, *scontext, *scontext_len);
1299 #include "initial_sid_to_string.h"
1301 int security_sidtab_hash_stats(struct selinux_state *state, char *page)
1303 struct selinux_policy *policy;
1306 if (!selinux_initialized(state)) {
1307 pr_err("SELinux: %s: called before initial load_policy\n",
1313 policy = rcu_dereference(state->policy);
1314 rc = sidtab_hash_stats(policy->sidtab, page);
1320 const char *security_get_initial_sid_context(u32 sid)
1322 if (unlikely(sid > SECINITSID_NUM))
1324 return initial_sid_to_string[sid];
1327 static int security_sid_to_context_core(struct selinux_state *state,
1328 u32 sid, char **scontext,
1329 u32 *scontext_len, int force,
1332 struct selinux_policy *policy;
1333 struct policydb *policydb;
1334 struct sidtab *sidtab;
1335 struct sidtab_entry *entry;
1342 if (!selinux_initialized(state)) {
1343 if (sid <= SECINITSID_NUM) {
1345 const char *s = initial_sid_to_string[sid];
1349 *scontext_len = strlen(s) + 1;
1352 scontextp = kmemdup(s, *scontext_len, GFP_ATOMIC);
1355 *scontext = scontextp;
1358 pr_err("SELinux: %s: called before initial "
1359 "load_policy on unknown SID %d\n", __func__, sid);
1363 policy = rcu_dereference(state->policy);
1364 policydb = &policy->policydb;
1365 sidtab = policy->sidtab;
1368 entry = sidtab_search_entry_force(sidtab, sid);
1370 entry = sidtab_search_entry(sidtab, sid);
1372 pr_err("SELinux: %s: unrecognized SID %d\n",
1377 if (only_invalid && !entry->context.len)
1380 rc = sidtab_entry_to_string(policydb, sidtab, entry, scontext,
1390 * security_sid_to_context - Obtain a context for a given SID.
1391 * @state: SELinux state
1392 * @sid: security identifier, SID
1393 * @scontext: security context
1394 * @scontext_len: length in bytes
1396 * Write the string representation of the context associated with @sid
1397 * into a dynamically allocated string of the correct size. Set @scontext
1398 * to point to this string and set @scontext_len to the length of the string.
1400 int security_sid_to_context(struct selinux_state *state,
1401 u32 sid, char **scontext, u32 *scontext_len)
1403 return security_sid_to_context_core(state, sid, scontext,
1404 scontext_len, 0, 0);
1407 int security_sid_to_context_force(struct selinux_state *state, u32 sid,
1408 char **scontext, u32 *scontext_len)
1410 return security_sid_to_context_core(state, sid, scontext,
1411 scontext_len, 1, 0);
1415 * security_sid_to_context_inval - Obtain a context for a given SID if it
1417 * @state: SELinux state
1418 * @sid: security identifier, SID
1419 * @scontext: security context
1420 * @scontext_len: length in bytes
1422 * Write the string representation of the context associated with @sid
1423 * into a dynamically allocated string of the correct size, but only if the
1424 * context is invalid in the current policy. Set @scontext to point to
1425 * this string (or NULL if the context is valid) and set @scontext_len to
1426 * the length of the string (or 0 if the context is valid).
1428 int security_sid_to_context_inval(struct selinux_state *state, u32 sid,
1429 char **scontext, u32 *scontext_len)
1431 return security_sid_to_context_core(state, sid, scontext,
1432 scontext_len, 1, 1);
1436 * Caveat: Mutates scontext.
1438 static int string_to_context_struct(struct policydb *pol,
1439 struct sidtab *sidtabp,
1441 struct context *ctx,
1444 struct role_datum *role;
1445 struct type_datum *typdatum;
1446 struct user_datum *usrdatum;
1447 char *scontextp, *p, oldc;
1452 /* Parse the security context. */
1455 scontextp = (char *) scontext;
1457 /* Extract the user. */
1459 while (*p && *p != ':')
1467 usrdatum = symtab_search(&pol->p_users, scontextp);
1471 ctx->user = usrdatum->value;
1475 while (*p && *p != ':')
1483 role = symtab_search(&pol->p_roles, scontextp);
1486 ctx->role = role->value;
1490 while (*p && *p != ':')
1495 typdatum = symtab_search(&pol->p_types, scontextp);
1496 if (!typdatum || typdatum->attribute)
1499 ctx->type = typdatum->value;
1501 rc = mls_context_to_sid(pol, oldc, p, ctx, sidtabp, def_sid);
1505 /* Check the validity of the new context. */
1507 if (!policydb_context_isvalid(pol, ctx))
1512 context_destroy(ctx);
1516 static int security_context_to_sid_core(struct selinux_state *state,
1517 const char *scontext, u32 scontext_len,
1518 u32 *sid, u32 def_sid, gfp_t gfp_flags,
1521 struct selinux_policy *policy;
1522 struct policydb *policydb;
1523 struct sidtab *sidtab;
1524 char *scontext2, *str = NULL;
1525 struct context context;
1528 /* An empty security context is never valid. */
1532 /* Copy the string to allow changes and ensure a NUL terminator */
1533 scontext2 = kmemdup_nul(scontext, scontext_len, gfp_flags);
1537 if (!selinux_initialized(state)) {
1540 for (i = 1; i < SECINITSID_NUM; i++) {
1541 const char *s = initial_sid_to_string[i];
1543 if (s && !strcmp(s, scontext2)) {
1548 *sid = SECINITSID_KERNEL;
1554 /* Save another copy for storing in uninterpreted form */
1556 str = kstrdup(scontext2, gfp_flags);
1562 policy = rcu_dereference(state->policy);
1563 policydb = &policy->policydb;
1564 sidtab = policy->sidtab;
1565 rc = string_to_context_struct(policydb, sidtab, scontext2,
1567 if (rc == -EINVAL && force) {
1569 context.len = strlen(str) + 1;
1573 rc = sidtab_context_to_sid(sidtab, &context, sid);
1574 if (rc == -ESTALE) {
1580 context_destroy(&context);
1583 context_destroy(&context);
1593 * security_context_to_sid - Obtain a SID for a given security context.
1594 * @state: SELinux state
1595 * @scontext: security context
1596 * @scontext_len: length in bytes
1597 * @sid: security identifier, SID
1598 * @gfp: context for the allocation
1600 * Obtains a SID associated with the security context that
1601 * has the string representation specified by @scontext.
1602 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1603 * memory is available, or 0 on success.
1605 int security_context_to_sid(struct selinux_state *state,
1606 const char *scontext, u32 scontext_len, u32 *sid,
1609 return security_context_to_sid_core(state, scontext, scontext_len,
1610 sid, SECSID_NULL, gfp, 0);
1613 int security_context_str_to_sid(struct selinux_state *state,
1614 const char *scontext, u32 *sid, gfp_t gfp)
1616 return security_context_to_sid(state, scontext, strlen(scontext),
1621 * security_context_to_sid_default - Obtain a SID for a given security context,
1622 * falling back to specified default if needed.
1624 * @state: SELinux state
1625 * @scontext: security context
1626 * @scontext_len: length in bytes
1627 * @sid: security identifier, SID
1628 * @def_sid: default SID to assign on error
1630 * Obtains a SID associated with the security context that
1631 * has the string representation specified by @scontext.
1632 * The default SID is passed to the MLS layer to be used to allow
1633 * kernel labeling of the MLS field if the MLS field is not present
1634 * (for upgrading to MLS without full relabel).
1635 * Implicitly forces adding of the context even if it cannot be mapped yet.
1636 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1637 * memory is available, or 0 on success.
1639 int security_context_to_sid_default(struct selinux_state *state,
1640 const char *scontext, u32 scontext_len,
1641 u32 *sid, u32 def_sid, gfp_t gfp_flags)
1643 return security_context_to_sid_core(state, scontext, scontext_len,
1644 sid, def_sid, gfp_flags, 1);
1647 int security_context_to_sid_force(struct selinux_state *state,
1648 const char *scontext, u32 scontext_len,
1651 return security_context_to_sid_core(state, scontext, scontext_len,
1652 sid, SECSID_NULL, GFP_KERNEL, 1);
1655 static int compute_sid_handle_invalid_context(
1656 struct selinux_state *state,
1657 struct selinux_policy *policy,
1658 struct sidtab_entry *sentry,
1659 struct sidtab_entry *tentry,
1661 struct context *newcontext)
1663 struct policydb *policydb = &policy->policydb;
1664 struct sidtab *sidtab = policy->sidtab;
1665 char *s = NULL, *t = NULL, *n = NULL;
1666 u32 slen, tlen, nlen;
1667 struct audit_buffer *ab;
1669 if (sidtab_entry_to_string(policydb, sidtab, sentry, &s, &slen))
1671 if (sidtab_entry_to_string(policydb, sidtab, tentry, &t, &tlen))
1673 if (context_struct_to_string(policydb, newcontext, &n, &nlen))
1675 ab = audit_log_start(audit_context(), GFP_ATOMIC, AUDIT_SELINUX_ERR);
1676 audit_log_format(ab,
1677 "op=security_compute_sid invalid_context=");
1678 /* no need to record the NUL with untrusted strings */
1679 audit_log_n_untrustedstring(ab, n, nlen - 1);
1680 audit_log_format(ab, " scontext=%s tcontext=%s tclass=%s",
1681 s, t, sym_name(policydb, SYM_CLASSES, tclass-1));
1687 if (!enforcing_enabled(state))
1692 static void filename_compute_type(struct policydb *policydb,
1693 struct context *newcontext,
1694 u32 stype, u32 ttype, u16 tclass,
1695 const char *objname)
1697 struct filename_trans_key ft;
1698 struct filename_trans_datum *datum;
1701 * Most filename trans rules are going to live in specific directories
1702 * like /dev or /var/run. This bitmap will quickly skip rule searches
1703 * if the ttype does not contain any rules.
1705 if (!ebitmap_get_bit(&policydb->filename_trans_ttypes, ttype))
1712 datum = policydb_filenametr_search(policydb, &ft);
1714 if (ebitmap_get_bit(&datum->stypes, stype - 1)) {
1715 newcontext->type = datum->otype;
1718 datum = datum->next;
1722 static int security_compute_sid(struct selinux_state *state,
1727 const char *objname,
1731 struct selinux_policy *policy;
1732 struct policydb *policydb;
1733 struct sidtab *sidtab;
1734 struct class_datum *cladatum;
1735 struct context *scontext, *tcontext, newcontext;
1736 struct sidtab_entry *sentry, *tentry;
1737 struct avtab_key avkey;
1738 struct avtab_datum *avdatum;
1739 struct avtab_node *node;
1744 if (!selinux_initialized(state)) {
1745 switch (orig_tclass) {
1746 case SECCLASS_PROCESS: /* kernel value */
1758 context_init(&newcontext);
1762 policy = rcu_dereference(state->policy);
1765 tclass = unmap_class(&policy->map, orig_tclass);
1766 sock = security_is_socket_class(orig_tclass);
1768 tclass = orig_tclass;
1769 sock = security_is_socket_class(map_class(&policy->map,
1773 policydb = &policy->policydb;
1774 sidtab = policy->sidtab;
1776 sentry = sidtab_search_entry(sidtab, ssid);
1778 pr_err("SELinux: %s: unrecognized SID %d\n",
1783 tentry = sidtab_search_entry(sidtab, tsid);
1785 pr_err("SELinux: %s: unrecognized SID %d\n",
1791 scontext = &sentry->context;
1792 tcontext = &tentry->context;
1794 if (tclass && tclass <= policydb->p_classes.nprim)
1795 cladatum = policydb->class_val_to_struct[tclass - 1];
1797 /* Set the user identity. */
1798 switch (specified) {
1799 case AVTAB_TRANSITION:
1801 if (cladatum && cladatum->default_user == DEFAULT_TARGET) {
1802 newcontext.user = tcontext->user;
1804 /* notice this gets both DEFAULT_SOURCE and unset */
1805 /* Use the process user identity. */
1806 newcontext.user = scontext->user;
1810 /* Use the related object owner. */
1811 newcontext.user = tcontext->user;
1815 /* Set the role to default values. */
1816 if (cladatum && cladatum->default_role == DEFAULT_SOURCE) {
1817 newcontext.role = scontext->role;
1818 } else if (cladatum && cladatum->default_role == DEFAULT_TARGET) {
1819 newcontext.role = tcontext->role;
1821 if ((tclass == policydb->process_class) || sock)
1822 newcontext.role = scontext->role;
1824 newcontext.role = OBJECT_R_VAL;
1827 /* Set the type to default values. */
1828 if (cladatum && cladatum->default_type == DEFAULT_SOURCE) {
1829 newcontext.type = scontext->type;
1830 } else if (cladatum && cladatum->default_type == DEFAULT_TARGET) {
1831 newcontext.type = tcontext->type;
1833 if ((tclass == policydb->process_class) || sock) {
1834 /* Use the type of process. */
1835 newcontext.type = scontext->type;
1837 /* Use the type of the related object. */
1838 newcontext.type = tcontext->type;
1842 /* Look for a type transition/member/change rule. */
1843 avkey.source_type = scontext->type;
1844 avkey.target_type = tcontext->type;
1845 avkey.target_class = tclass;
1846 avkey.specified = specified;
1847 avdatum = avtab_search(&policydb->te_avtab, &avkey);
1849 /* If no permanent rule, also check for enabled conditional rules */
1851 node = avtab_search_node(&policydb->te_cond_avtab, &avkey);
1852 for (; node; node = avtab_search_node_next(node, specified)) {
1853 if (node->key.specified & AVTAB_ENABLED) {
1854 avdatum = &node->datum;
1861 /* Use the type from the type transition/member/change rule. */
1862 newcontext.type = avdatum->u.data;
1865 /* if we have a objname this is a file trans check so check those rules */
1867 filename_compute_type(policydb, &newcontext, scontext->type,
1868 tcontext->type, tclass, objname);
1870 /* Check for class-specific changes. */
1871 if (specified & AVTAB_TRANSITION) {
1872 /* Look for a role transition rule. */
1873 struct role_trans_datum *rtd;
1874 struct role_trans_key rtk = {
1875 .role = scontext->role,
1876 .type = tcontext->type,
1880 rtd = policydb_roletr_search(policydb, &rtk);
1882 newcontext.role = rtd->new_role;
1885 /* Set the MLS attributes.
1886 This is done last because it may allocate memory. */
1887 rc = mls_compute_sid(policydb, scontext, tcontext, tclass, specified,
1892 /* Check the validity of the context. */
1893 if (!policydb_context_isvalid(policydb, &newcontext)) {
1894 rc = compute_sid_handle_invalid_context(state, policy, sentry,
1900 /* Obtain the sid for the context. */
1901 rc = sidtab_context_to_sid(sidtab, &newcontext, out_sid);
1902 if (rc == -ESTALE) {
1904 context_destroy(&newcontext);
1909 context_destroy(&newcontext);
1915 * security_transition_sid - Compute the SID for a new subject/object.
1916 * @state: SELinux state
1917 * @ssid: source security identifier
1918 * @tsid: target security identifier
1919 * @tclass: target security class
1920 * @out_sid: security identifier for new subject/object
1922 * Compute a SID to use for labeling a new subject or object in the
1923 * class @tclass based on a SID pair (@ssid, @tsid).
1924 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1925 * if insufficient memory is available, or %0 if the new SID was
1926 * computed successfully.
1928 int security_transition_sid(struct selinux_state *state,
1929 u32 ssid, u32 tsid, u16 tclass,
1930 const struct qstr *qstr, u32 *out_sid)
1932 return security_compute_sid(state, ssid, tsid, tclass,
1934 qstr ? qstr->name : NULL, out_sid, true);
1937 int security_transition_sid_user(struct selinux_state *state,
1938 u32 ssid, u32 tsid, u16 tclass,
1939 const char *objname, u32 *out_sid)
1941 return security_compute_sid(state, ssid, tsid, tclass,
1943 objname, out_sid, false);
1947 * security_member_sid - Compute the SID for member selection.
1948 * @ssid: source security identifier
1949 * @tsid: target security identifier
1950 * @tclass: target security class
1951 * @out_sid: security identifier for selected member
1953 * Compute a SID to use when selecting a member of a polyinstantiated
1954 * object of class @tclass based on a SID pair (@ssid, @tsid).
1955 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1956 * if insufficient memory is available, or %0 if the SID was
1957 * computed successfully.
1959 int security_member_sid(struct selinux_state *state,
1965 return security_compute_sid(state, ssid, tsid, tclass,
1971 * security_change_sid - Compute the SID for object relabeling.
1972 * @state: SELinux state
1973 * @ssid: source security identifier
1974 * @tsid: target security identifier
1975 * @tclass: target security class
1976 * @out_sid: security identifier for selected member
1978 * Compute a SID to use for relabeling an object of class @tclass
1979 * based on a SID pair (@ssid, @tsid).
1980 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1981 * if insufficient memory is available, or %0 if the SID was
1982 * computed successfully.
1984 int security_change_sid(struct selinux_state *state,
1990 return security_compute_sid(state,
1991 ssid, tsid, tclass, AVTAB_CHANGE, NULL,
1995 static inline int convert_context_handle_invalid_context(
1996 struct selinux_state *state,
1997 struct policydb *policydb,
1998 struct context *context)
2003 if (enforcing_enabled(state))
2006 if (!context_struct_to_string(policydb, context, &s, &len)) {
2007 pr_warn("SELinux: Context %s would be invalid if enforcing\n",
2015 * Convert the values in the security context
2016 * structure `oldc' from the values specified
2017 * in the policy `p->oldp' to the values specified
2018 * in the policy `p->newp', storing the new context
2019 * in `newc'. Verify that the context is valid
2020 * under the new policy.
2022 static int convert_context(struct context *oldc, struct context *newc, void *p)
2024 struct convert_context_args *args;
2025 struct ocontext *oc;
2026 struct role_datum *role;
2027 struct type_datum *typdatum;
2028 struct user_datum *usrdatum;
2036 s = kstrdup(oldc->str, GFP_KERNEL);
2040 rc = string_to_context_struct(args->newp, NULL, s,
2042 if (rc == -EINVAL) {
2044 * Retain string representation for later mapping.
2046 * IMPORTANT: We need to copy the contents of oldc->str
2047 * back into s again because string_to_context_struct()
2048 * may have garbled it.
2050 memcpy(s, oldc->str, oldc->len);
2053 newc->len = oldc->len;
2058 /* Other error condition, e.g. ENOMEM. */
2059 pr_err("SELinux: Unable to map context %s, rc = %d.\n",
2063 pr_info("SELinux: Context %s became valid (mapped).\n",
2070 /* Convert the user. */
2071 usrdatum = symtab_search(&args->newp->p_users,
2072 sym_name(args->oldp,
2073 SYM_USERS, oldc->user - 1));
2076 newc->user = usrdatum->value;
2078 /* Convert the role. */
2079 role = symtab_search(&args->newp->p_roles,
2080 sym_name(args->oldp, SYM_ROLES, oldc->role - 1));
2083 newc->role = role->value;
2085 /* Convert the type. */
2086 typdatum = symtab_search(&args->newp->p_types,
2087 sym_name(args->oldp,
2088 SYM_TYPES, oldc->type - 1));
2091 newc->type = typdatum->value;
2093 /* Convert the MLS fields if dealing with MLS policies */
2094 if (args->oldp->mls_enabled && args->newp->mls_enabled) {
2095 rc = mls_convert_context(args->oldp, args->newp, oldc, newc);
2098 } else if (!args->oldp->mls_enabled && args->newp->mls_enabled) {
2100 * Switching between non-MLS and MLS policy:
2101 * ensure that the MLS fields of the context for all
2102 * existing entries in the sidtab are filled in with a
2103 * suitable default value, likely taken from one of the
2106 oc = args->newp->ocontexts[OCON_ISID];
2107 while (oc && oc->sid[0] != SECINITSID_UNLABELED)
2110 pr_err("SELinux: unable to look up"
2111 " the initial SIDs list\n");
2114 rc = mls_range_set(newc, &oc->context[0].range);
2119 /* Check the validity of the new context. */
2120 if (!policydb_context_isvalid(args->newp, newc)) {
2121 rc = convert_context_handle_invalid_context(args->state,
2130 /* Map old representation to string and save it. */
2131 rc = context_struct_to_string(args->oldp, oldc, &s, &len);
2134 context_destroy(newc);
2137 pr_info("SELinux: Context %s became invalid (unmapped).\n",
2142 static void security_load_policycaps(struct selinux_state *state,
2143 struct selinux_policy *policy)
2147 struct ebitmap_node *node;
2149 p = &policy->policydb;
2151 for (i = 0; i < ARRAY_SIZE(state->policycap); i++)
2152 WRITE_ONCE(state->policycap[i],
2153 ebitmap_get_bit(&p->policycaps, i));
2155 for (i = 0; i < ARRAY_SIZE(selinux_policycap_names); i++)
2156 pr_info("SELinux: policy capability %s=%d\n",
2157 selinux_policycap_names[i],
2158 ebitmap_get_bit(&p->policycaps, i));
2160 ebitmap_for_each_positive_bit(&p->policycaps, node, i) {
2161 if (i >= ARRAY_SIZE(selinux_policycap_names))
2162 pr_info("SELinux: unknown policy capability %u\n",
2167 static int security_preserve_bools(struct selinux_policy *oldpolicy,
2168 struct selinux_policy *newpolicy);
2170 static void selinux_policy_free(struct selinux_policy *policy)
2175 sidtab_destroy(policy->sidtab);
2176 kfree(policy->map.mapping);
2177 policydb_destroy(&policy->policydb);
2178 kfree(policy->sidtab);
2182 static void selinux_policy_cond_free(struct selinux_policy *policy)
2184 cond_policydb_destroy_dup(&policy->policydb);
2188 void selinux_policy_cancel(struct selinux_state *state,
2189 struct selinux_load_state *load_state)
2191 struct selinux_policy *oldpolicy;
2193 oldpolicy = rcu_dereference_protected(state->policy,
2194 lockdep_is_held(&state->policy_mutex));
2196 sidtab_cancel_convert(oldpolicy->sidtab);
2197 selinux_policy_free(load_state->policy);
2198 kfree(load_state->convert_data);
2201 static void selinux_notify_policy_change(struct selinux_state *state,
2204 /* Flush external caches and notify userspace of policy load */
2205 avc_ss_reset(state->avc, seqno);
2206 selnl_notify_policyload(seqno);
2207 selinux_status_update_policyload(state, seqno);
2208 selinux_netlbl_cache_invalidate();
2209 selinux_xfrm_notify_policyload();
2210 selinux_ima_measure_state_locked(state);
2213 void selinux_policy_commit(struct selinux_state *state,
2214 struct selinux_load_state *load_state)
2216 struct selinux_policy *oldpolicy, *newpolicy = load_state->policy;
2217 unsigned long flags;
2220 oldpolicy = rcu_dereference_protected(state->policy,
2221 lockdep_is_held(&state->policy_mutex));
2223 /* If switching between different policy types, log MLS status */
2225 if (oldpolicy->policydb.mls_enabled && !newpolicy->policydb.mls_enabled)
2226 pr_info("SELinux: Disabling MLS support...\n");
2227 else if (!oldpolicy->policydb.mls_enabled && newpolicy->policydb.mls_enabled)
2228 pr_info("SELinux: Enabling MLS support...\n");
2231 /* Set latest granting seqno for new policy. */
2233 newpolicy->latest_granting = oldpolicy->latest_granting + 1;
2235 newpolicy->latest_granting = 1;
2236 seqno = newpolicy->latest_granting;
2238 /* Install the new policy. */
2240 sidtab_freeze_begin(oldpolicy->sidtab, &flags);
2241 rcu_assign_pointer(state->policy, newpolicy);
2242 sidtab_freeze_end(oldpolicy->sidtab, &flags);
2244 rcu_assign_pointer(state->policy, newpolicy);
2247 /* Load the policycaps from the new policy */
2248 security_load_policycaps(state, newpolicy);
2250 if (!selinux_initialized(state)) {
2252 * After first policy load, the security server is
2253 * marked as initialized and ready to handle requests and
2254 * any objects created prior to policy load are then labeled.
2256 selinux_mark_initialized(state);
2257 selinux_complete_init();
2260 /* Free the old policy */
2262 selinux_policy_free(oldpolicy);
2263 kfree(load_state->convert_data);
2265 /* Notify others of the policy change */
2266 selinux_notify_policy_change(state, seqno);
2270 * security_load_policy - Load a security policy configuration.
2271 * @state: SELinux state
2272 * @data: binary policy data
2273 * @len: length of data in bytes
2275 * Load a new set of security policy configuration data,
2276 * validate it and convert the SID table as necessary.
2277 * This function will flush the access vector cache after
2278 * loading the new policy.
2280 int security_load_policy(struct selinux_state *state, void *data, size_t len,
2281 struct selinux_load_state *load_state)
2283 struct selinux_policy *newpolicy, *oldpolicy;
2284 struct selinux_policy_convert_data *convert_data;
2286 struct policy_file file = { data, len }, *fp = &file;
2288 newpolicy = kzalloc(sizeof(*newpolicy), GFP_KERNEL);
2292 newpolicy->sidtab = kzalloc(sizeof(*newpolicy->sidtab), GFP_KERNEL);
2293 if (!newpolicy->sidtab) {
2298 rc = policydb_read(&newpolicy->policydb, fp);
2302 newpolicy->policydb.len = len;
2303 rc = selinux_set_mapping(&newpolicy->policydb, secclass_map,
2308 rc = policydb_load_isids(&newpolicy->policydb, newpolicy->sidtab);
2310 pr_err("SELinux: unable to load the initial SIDs\n");
2314 if (!selinux_initialized(state)) {
2315 /* First policy load, so no need to preserve state from old policy */
2316 load_state->policy = newpolicy;
2317 load_state->convert_data = NULL;
2321 oldpolicy = rcu_dereference_protected(state->policy,
2322 lockdep_is_held(&state->policy_mutex));
2324 /* Preserve active boolean values from the old policy */
2325 rc = security_preserve_bools(oldpolicy, newpolicy);
2327 pr_err("SELinux: unable to preserve booleans\n");
2328 goto err_free_isids;
2331 convert_data = kmalloc(sizeof(*convert_data), GFP_KERNEL);
2332 if (!convert_data) {
2334 goto err_free_isids;
2338 * Convert the internal representations of contexts
2339 * in the new SID table.
2341 convert_data->args.state = state;
2342 convert_data->args.oldp = &oldpolicy->policydb;
2343 convert_data->args.newp = &newpolicy->policydb;
2345 convert_data->sidtab_params.func = convert_context;
2346 convert_data->sidtab_params.args = &convert_data->args;
2347 convert_data->sidtab_params.target = newpolicy->sidtab;
2349 rc = sidtab_convert(oldpolicy->sidtab, &convert_data->sidtab_params);
2351 pr_err("SELinux: unable to convert the internal"
2352 " representation of contexts in the new SID"
2354 goto err_free_convert_data;
2357 load_state->policy = newpolicy;
2358 load_state->convert_data = convert_data;
2361 err_free_convert_data:
2362 kfree(convert_data);
2364 sidtab_destroy(newpolicy->sidtab);
2366 kfree(newpolicy->map.mapping);
2368 policydb_destroy(&newpolicy->policydb);
2370 kfree(newpolicy->sidtab);
2378 * security_port_sid - Obtain the SID for a port.
2379 * @state: SELinux state
2380 * @protocol: protocol number
2381 * @port: port number
2382 * @out_sid: security identifier
2384 int security_port_sid(struct selinux_state *state,
2385 u8 protocol, u16 port, u32 *out_sid)
2387 struct selinux_policy *policy;
2388 struct policydb *policydb;
2389 struct sidtab *sidtab;
2393 if (!selinux_initialized(state)) {
2394 *out_sid = SECINITSID_PORT;
2401 policy = rcu_dereference(state->policy);
2402 policydb = &policy->policydb;
2403 sidtab = policy->sidtab;
2405 c = policydb->ocontexts[OCON_PORT];
2407 if (c->u.port.protocol == protocol &&
2408 c->u.port.low_port <= port &&
2409 c->u.port.high_port >= port)
2416 rc = sidtab_context_to_sid(sidtab, &c->context[0],
2418 if (rc == -ESTALE) {
2425 *out_sid = c->sid[0];
2427 *out_sid = SECINITSID_PORT;
2436 * security_ib_pkey_sid - Obtain the SID for a pkey.
2437 * @state: SELinux state
2438 * @subnet_prefix: Subnet Prefix
2439 * @pkey_num: pkey number
2440 * @out_sid: security identifier
2442 int security_ib_pkey_sid(struct selinux_state *state,
2443 u64 subnet_prefix, u16 pkey_num, u32 *out_sid)
2445 struct selinux_policy *policy;
2446 struct policydb *policydb;
2447 struct sidtab *sidtab;
2451 if (!selinux_initialized(state)) {
2452 *out_sid = SECINITSID_UNLABELED;
2459 policy = rcu_dereference(state->policy);
2460 policydb = &policy->policydb;
2461 sidtab = policy->sidtab;
2463 c = policydb->ocontexts[OCON_IBPKEY];
2465 if (c->u.ibpkey.low_pkey <= pkey_num &&
2466 c->u.ibpkey.high_pkey >= pkey_num &&
2467 c->u.ibpkey.subnet_prefix == subnet_prefix)
2475 rc = sidtab_context_to_sid(sidtab,
2478 if (rc == -ESTALE) {
2485 *out_sid = c->sid[0];
2487 *out_sid = SECINITSID_UNLABELED;
2495 * security_ib_endport_sid - Obtain the SID for a subnet management interface.
2496 * @state: SELinux state
2497 * @dev_name: device name
2498 * @port: port number
2499 * @out_sid: security identifier
2501 int security_ib_endport_sid(struct selinux_state *state,
2502 const char *dev_name, u8 port_num, u32 *out_sid)
2504 struct selinux_policy *policy;
2505 struct policydb *policydb;
2506 struct sidtab *sidtab;
2510 if (!selinux_initialized(state)) {
2511 *out_sid = SECINITSID_UNLABELED;
2518 policy = rcu_dereference(state->policy);
2519 policydb = &policy->policydb;
2520 sidtab = policy->sidtab;
2522 c = policydb->ocontexts[OCON_IBENDPORT];
2524 if (c->u.ibendport.port == port_num &&
2525 !strncmp(c->u.ibendport.dev_name,
2527 IB_DEVICE_NAME_MAX))
2535 rc = sidtab_context_to_sid(sidtab, &c->context[0],
2537 if (rc == -ESTALE) {
2544 *out_sid = c->sid[0];
2546 *out_sid = SECINITSID_UNLABELED;
2554 * security_netif_sid - Obtain the SID for a network interface.
2555 * @state: SELinux state
2556 * @name: interface name
2557 * @if_sid: interface SID
2559 int security_netif_sid(struct selinux_state *state,
2560 char *name, u32 *if_sid)
2562 struct selinux_policy *policy;
2563 struct policydb *policydb;
2564 struct sidtab *sidtab;
2568 if (!selinux_initialized(state)) {
2569 *if_sid = SECINITSID_NETIF;
2576 policy = rcu_dereference(state->policy);
2577 policydb = &policy->policydb;
2578 sidtab = policy->sidtab;
2580 c = policydb->ocontexts[OCON_NETIF];
2582 if (strcmp(name, c->u.name) == 0)
2588 if (!c->sid[0] || !c->sid[1]) {
2589 rc = sidtab_context_to_sid(sidtab, &c->context[0],
2591 if (rc == -ESTALE) {
2597 rc = sidtab_context_to_sid(sidtab, &c->context[1],
2599 if (rc == -ESTALE) {
2606 *if_sid = c->sid[0];
2608 *if_sid = SECINITSID_NETIF;
2615 static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask)
2619 for (i = 0; i < 4; i++)
2620 if (addr[i] != (input[i] & mask[i])) {
2629 * security_node_sid - Obtain the SID for a node (host).
2630 * @state: SELinux state
2631 * @domain: communication domain aka address family
2633 * @addrlen: address length in bytes
2634 * @out_sid: security identifier
2636 int security_node_sid(struct selinux_state *state,
2642 struct selinux_policy *policy;
2643 struct policydb *policydb;
2644 struct sidtab *sidtab;
2648 if (!selinux_initialized(state)) {
2649 *out_sid = SECINITSID_NODE;
2655 policy = rcu_dereference(state->policy);
2656 policydb = &policy->policydb;
2657 sidtab = policy->sidtab;
2664 if (addrlen != sizeof(u32))
2667 addr = *((u32 *)addrp);
2669 c = policydb->ocontexts[OCON_NODE];
2671 if (c->u.node.addr == (addr & c->u.node.mask))
2680 if (addrlen != sizeof(u64) * 2)
2682 c = policydb->ocontexts[OCON_NODE6];
2684 if (match_ipv6_addrmask(addrp, c->u.node6.addr,
2693 *out_sid = SECINITSID_NODE;
2699 rc = sidtab_context_to_sid(sidtab,
2702 if (rc == -ESTALE) {
2709 *out_sid = c->sid[0];
2711 *out_sid = SECINITSID_NODE;
2723 * security_get_user_sids - Obtain reachable SIDs for a user.
2724 * @state: SELinux state
2725 * @fromsid: starting SID
2726 * @username: username
2727 * @sids: array of reachable SIDs for user
2728 * @nel: number of elements in @sids
2730 * Generate the set of SIDs for legal security contexts
2731 * for a given user that can be reached by @fromsid.
2732 * Set *@sids to point to a dynamically allocated
2733 * array containing the set of SIDs. Set *@nel to the
2734 * number of elements in the array.
2737 int security_get_user_sids(struct selinux_state *state,
2743 struct selinux_policy *policy;
2744 struct policydb *policydb;
2745 struct sidtab *sidtab;
2746 struct context *fromcon, usercon;
2747 u32 *mysids = NULL, *mysids2, sid;
2748 u32 i, j, mynel, maxnel = SIDS_NEL;
2749 struct user_datum *user;
2750 struct role_datum *role;
2751 struct ebitmap_node *rnode, *tnode;
2757 if (!selinux_initialized(state))
2760 mysids = kcalloc(maxnel, sizeof(*mysids), GFP_KERNEL);
2767 policy = rcu_dereference(state->policy);
2768 policydb = &policy->policydb;
2769 sidtab = policy->sidtab;
2771 context_init(&usercon);
2774 fromcon = sidtab_search(sidtab, fromsid);
2779 user = symtab_search(&policydb->p_users, username);
2783 usercon.user = user->value;
2785 ebitmap_for_each_positive_bit(&user->roles, rnode, i) {
2786 role = policydb->role_val_to_struct[i];
2787 usercon.role = i + 1;
2788 ebitmap_for_each_positive_bit(&role->types, tnode, j) {
2789 usercon.type = j + 1;
2791 if (mls_setup_user_range(policydb, fromcon, user,
2795 rc = sidtab_context_to_sid(sidtab, &usercon, &sid);
2796 if (rc == -ESTALE) {
2802 if (mynel < maxnel) {
2803 mysids[mynel++] = sid;
2807 mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
2810 memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
2813 mysids[mynel++] = sid;
2826 mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);
2831 for (i = 0, j = 0; i < mynel; i++) {
2832 struct av_decision dummy_avd;
2833 rc = avc_has_perm_noaudit(state,
2835 SECCLASS_PROCESS, /* kernel value */
2836 PROCESS__TRANSITION, AVC_STRICT,
2839 mysids2[j++] = mysids[i];
2849 * __security_genfs_sid - Helper to obtain a SID for a file in a filesystem
2850 * @fstype: filesystem type
2851 * @path: path from root of mount
2852 * @sclass: file security class
2853 * @sid: SID for path
2855 * Obtain a SID to use for a file in a filesystem that
2856 * cannot support xattr or use a fixed labeling behavior like
2857 * transition SIDs or task SIDs.
2859 * WARNING: This function may return -ESTALE, indicating that the caller
2860 * must retry the operation after re-acquiring the policy pointer!
2862 static inline int __security_genfs_sid(struct selinux_policy *policy,
2868 struct policydb *policydb = &policy->policydb;
2869 struct sidtab *sidtab = policy->sidtab;
2872 struct genfs *genfs;
2876 while (path[0] == '/' && path[1] == '/')
2879 sclass = unmap_class(&policy->map, orig_sclass);
2880 *sid = SECINITSID_UNLABELED;
2882 for (genfs = policydb->genfs; genfs; genfs = genfs->next) {
2883 cmp = strcmp(fstype, genfs->fstype);
2892 for (c = genfs->head; c; c = c->next) {
2893 len = strlen(c->u.name);
2894 if ((!c->v.sclass || sclass == c->v.sclass) &&
2895 (strncmp(c->u.name, path, len) == 0))
2904 rc = sidtab_context_to_sid(sidtab, &c->context[0], &c->sid[0]);
2916 * security_genfs_sid - Obtain a SID for a file in a filesystem
2917 * @state: SELinux state
2918 * @fstype: filesystem type
2919 * @path: path from root of mount
2920 * @sclass: file security class
2921 * @sid: SID for path
2923 * Acquire policy_rwlock before calling __security_genfs_sid() and release
2926 int security_genfs_sid(struct selinux_state *state,
2932 struct selinux_policy *policy;
2935 if (!selinux_initialized(state)) {
2936 *sid = SECINITSID_UNLABELED;
2942 policy = rcu_dereference(state->policy);
2943 retval = __security_genfs_sid(policy, fstype, path,
2946 } while (retval == -ESTALE);
2950 int selinux_policy_genfs_sid(struct selinux_policy *policy,
2956 /* no lock required, policy is not yet accessible by other threads */
2957 return __security_genfs_sid(policy, fstype, path, orig_sclass, sid);
2961 * security_fs_use - Determine how to handle labeling for a filesystem.
2962 * @state: SELinux state
2963 * @sb: superblock in question
2965 int security_fs_use(struct selinux_state *state, struct super_block *sb)
2967 struct selinux_policy *policy;
2968 struct policydb *policydb;
2969 struct sidtab *sidtab;
2972 struct superblock_security_struct *sbsec = selinux_superblock(sb);
2973 const char *fstype = sb->s_type->name;
2975 if (!selinux_initialized(state)) {
2976 sbsec->behavior = SECURITY_FS_USE_NONE;
2977 sbsec->sid = SECINITSID_UNLABELED;
2984 policy = rcu_dereference(state->policy);
2985 policydb = &policy->policydb;
2986 sidtab = policy->sidtab;
2988 c = policydb->ocontexts[OCON_FSUSE];
2990 if (strcmp(fstype, c->u.name) == 0)
2996 sbsec->behavior = c->v.behavior;
2998 rc = sidtab_context_to_sid(sidtab, &c->context[0],
3000 if (rc == -ESTALE) {
3007 sbsec->sid = c->sid[0];
3009 rc = __security_genfs_sid(policy, fstype, "/",
3010 SECCLASS_DIR, &sbsec->sid);
3011 if (rc == -ESTALE) {
3016 sbsec->behavior = SECURITY_FS_USE_NONE;
3019 sbsec->behavior = SECURITY_FS_USE_GENFS;
3028 int security_get_bools(struct selinux_policy *policy,
3029 u32 *len, char ***names, int **values)
3031 struct policydb *policydb;
3035 policydb = &policy->policydb;
3041 *len = policydb->p_bools.nprim;
3046 *names = kcalloc(*len, sizeof(char *), GFP_ATOMIC);
3051 *values = kcalloc(*len, sizeof(int), GFP_ATOMIC);
3055 for (i = 0; i < *len; i++) {
3056 (*values)[i] = policydb->bool_val_to_struct[i]->state;
3059 (*names)[i] = kstrdup(sym_name(policydb, SYM_BOOLS, i),
3069 for (i = 0; i < *len; i++)
3081 int security_set_bools(struct selinux_state *state, u32 len, int *values)
3083 struct selinux_policy *newpolicy, *oldpolicy;
3087 if (!selinux_initialized(state))
3090 oldpolicy = rcu_dereference_protected(state->policy,
3091 lockdep_is_held(&state->policy_mutex));
3093 /* Consistency check on number of booleans, should never fail */
3094 if (WARN_ON(len != oldpolicy->policydb.p_bools.nprim))
3097 newpolicy = kmemdup(oldpolicy, sizeof(*newpolicy), GFP_KERNEL);
3102 * Deep copy only the parts of the policydb that might be
3103 * modified as a result of changing booleans.
3105 rc = cond_policydb_dup(&newpolicy->policydb, &oldpolicy->policydb);
3111 /* Update the boolean states in the copy */
3112 for (i = 0; i < len; i++) {
3113 int new_state = !!values[i];
3114 int old_state = newpolicy->policydb.bool_val_to_struct[i]->state;
3116 if (new_state != old_state) {
3117 audit_log(audit_context(), GFP_ATOMIC,
3118 AUDIT_MAC_CONFIG_CHANGE,
3119 "bool=%s val=%d old_val=%d auid=%u ses=%u",
3120 sym_name(&newpolicy->policydb, SYM_BOOLS, i),
3123 from_kuid(&init_user_ns, audit_get_loginuid(current)),
3124 audit_get_sessionid(current));
3125 newpolicy->policydb.bool_val_to_struct[i]->state = new_state;
3129 /* Re-evaluate the conditional rules in the copy */
3130 evaluate_cond_nodes(&newpolicy->policydb);
3132 /* Set latest granting seqno for new policy */
3133 newpolicy->latest_granting = oldpolicy->latest_granting + 1;
3134 seqno = newpolicy->latest_granting;
3136 /* Install the new policy */
3137 rcu_assign_pointer(state->policy, newpolicy);
3140 * Free the conditional portions of the old policydb
3141 * that were copied for the new policy, and the oldpolicy
3142 * structure itself but not what it references.
3145 selinux_policy_cond_free(oldpolicy);
3147 /* Notify others of the policy change */
3148 selinux_notify_policy_change(state, seqno);
3152 int security_get_bool_value(struct selinux_state *state,
3155 struct selinux_policy *policy;
3156 struct policydb *policydb;
3160 if (!selinux_initialized(state))
3164 policy = rcu_dereference(state->policy);
3165 policydb = &policy->policydb;
3168 len = policydb->p_bools.nprim;
3172 rc = policydb->bool_val_to_struct[index]->state;
3178 static int security_preserve_bools(struct selinux_policy *oldpolicy,
3179 struct selinux_policy *newpolicy)
3181 int rc, *bvalues = NULL;
3182 char **bnames = NULL;
3183 struct cond_bool_datum *booldatum;
3186 rc = security_get_bools(oldpolicy, &nbools, &bnames, &bvalues);
3189 for (i = 0; i < nbools; i++) {
3190 booldatum = symtab_search(&newpolicy->policydb.p_bools,
3193 booldatum->state = bvalues[i];
3195 evaluate_cond_nodes(&newpolicy->policydb);
3199 for (i = 0; i < nbools; i++)
3208 * security_sid_mls_copy() - computes a new sid based on the given
3209 * sid and the mls portion of mls_sid.
3211 int security_sid_mls_copy(struct selinux_state *state,
3212 u32 sid, u32 mls_sid, u32 *new_sid)
3214 struct selinux_policy *policy;
3215 struct policydb *policydb;
3216 struct sidtab *sidtab;
3217 struct context *context1;
3218 struct context *context2;
3219 struct context newcon;
3224 if (!selinux_initialized(state)) {
3231 context_init(&newcon);
3234 policy = rcu_dereference(state->policy);
3235 policydb = &policy->policydb;
3236 sidtab = policy->sidtab;
3238 if (!policydb->mls_enabled) {
3244 context1 = sidtab_search(sidtab, sid);
3246 pr_err("SELinux: %s: unrecognized SID %d\n",
3252 context2 = sidtab_search(sidtab, mls_sid);
3254 pr_err("SELinux: %s: unrecognized SID %d\n",
3259 newcon.user = context1->user;
3260 newcon.role = context1->role;
3261 newcon.type = context1->type;
3262 rc = mls_context_cpy(&newcon, context2);
3266 /* Check the validity of the new context. */
3267 if (!policydb_context_isvalid(policydb, &newcon)) {
3268 rc = convert_context_handle_invalid_context(state, policydb,
3271 if (!context_struct_to_string(policydb, &newcon, &s,
3273 struct audit_buffer *ab;
3275 ab = audit_log_start(audit_context(),
3278 audit_log_format(ab,
3279 "op=security_sid_mls_copy invalid_context=");
3280 /* don't record NUL with untrusted strings */
3281 audit_log_n_untrustedstring(ab, s, len - 1);
3288 rc = sidtab_context_to_sid(sidtab, &newcon, new_sid);
3289 if (rc == -ESTALE) {
3291 context_destroy(&newcon);
3296 context_destroy(&newcon);
3301 * security_net_peersid_resolve - Compare and resolve two network peer SIDs
3302 * @state: SELinux state
3303 * @nlbl_sid: NetLabel SID
3304 * @nlbl_type: NetLabel labeling protocol type
3305 * @xfrm_sid: XFRM SID
3308 * Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be
3309 * resolved into a single SID it is returned via @peer_sid and the function
3310 * returns zero. Otherwise @peer_sid is set to SECSID_NULL and the function
3311 * returns a negative value. A table summarizing the behavior is below:
3313 * | function return | @sid
3314 * ------------------------------+-----------------+-----------------
3315 * no peer labels | 0 | SECSID_NULL
3316 * single peer label | 0 | <peer_label>
3317 * multiple, consistent labels | 0 | <peer_label>
3318 * multiple, inconsistent labels | -<errno> | SECSID_NULL
3321 int security_net_peersid_resolve(struct selinux_state *state,
3322 u32 nlbl_sid, u32 nlbl_type,
3326 struct selinux_policy *policy;
3327 struct policydb *policydb;
3328 struct sidtab *sidtab;
3330 struct context *nlbl_ctx;
3331 struct context *xfrm_ctx;
3333 *peer_sid = SECSID_NULL;
3335 /* handle the common (which also happens to be the set of easy) cases
3336 * right away, these two if statements catch everything involving a
3337 * single or absent peer SID/label */
3338 if (xfrm_sid == SECSID_NULL) {
3339 *peer_sid = nlbl_sid;
3342 /* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a "fallback" label
3343 * and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label
3345 if (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) {
3346 *peer_sid = xfrm_sid;
3350 if (!selinux_initialized(state))
3354 policy = rcu_dereference(state->policy);
3355 policydb = &policy->policydb;
3356 sidtab = policy->sidtab;
3359 * We don't need to check initialized here since the only way both
3360 * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the
3361 * security server was initialized and state->initialized was true.
3363 if (!policydb->mls_enabled) {
3369 nlbl_ctx = sidtab_search(sidtab, nlbl_sid);
3371 pr_err("SELinux: %s: unrecognized SID %d\n",
3372 __func__, nlbl_sid);
3376 xfrm_ctx = sidtab_search(sidtab, xfrm_sid);
3378 pr_err("SELinux: %s: unrecognized SID %d\n",
3379 __func__, xfrm_sid);
3382 rc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES);
3386 /* at present NetLabel SIDs/labels really only carry MLS
3387 * information so if the MLS portion of the NetLabel SID
3388 * matches the MLS portion of the labeled XFRM SID/label
3389 * then pass along the XFRM SID as it is the most
3391 *peer_sid = xfrm_sid;
3397 static int get_classes_callback(void *k, void *d, void *args)
3399 struct class_datum *datum = d;
3400 char *name = k, **classes = args;
3401 int value = datum->value - 1;
3403 classes[value] = kstrdup(name, GFP_ATOMIC);
3404 if (!classes[value])
3410 int security_get_classes(struct selinux_policy *policy,
3411 char ***classes, int *nclasses)
3413 struct policydb *policydb;
3416 policydb = &policy->policydb;
3419 *nclasses = policydb->p_classes.nprim;
3420 *classes = kcalloc(*nclasses, sizeof(**classes), GFP_ATOMIC);
3424 rc = hashtab_map(&policydb->p_classes.table, get_classes_callback,
3428 for (i = 0; i < *nclasses; i++)
3429 kfree((*classes)[i]);
3437 static int get_permissions_callback(void *k, void *d, void *args)
3439 struct perm_datum *datum = d;
3440 char *name = k, **perms = args;
3441 int value = datum->value - 1;
3443 perms[value] = kstrdup(name, GFP_ATOMIC);
3450 int security_get_permissions(struct selinux_policy *policy,
3451 char *class, char ***perms, int *nperms)
3453 struct policydb *policydb;
3455 struct class_datum *match;
3457 policydb = &policy->policydb;
3460 match = symtab_search(&policydb->p_classes, class);
3462 pr_err("SELinux: %s: unrecognized class %s\n",
3468 *nperms = match->permissions.nprim;
3469 *perms = kcalloc(*nperms, sizeof(**perms), GFP_ATOMIC);
3473 if (match->comdatum) {
3474 rc = hashtab_map(&match->comdatum->permissions.table,
3475 get_permissions_callback, *perms);
3480 rc = hashtab_map(&match->permissions.table, get_permissions_callback,
3489 for (i = 0; i < *nperms; i++)
3495 int security_get_reject_unknown(struct selinux_state *state)
3497 struct selinux_policy *policy;
3500 if (!selinux_initialized(state))
3504 policy = rcu_dereference(state->policy);
3505 value = policy->policydb.reject_unknown;
3510 int security_get_allow_unknown(struct selinux_state *state)
3512 struct selinux_policy *policy;
3515 if (!selinux_initialized(state))
3519 policy = rcu_dereference(state->policy);
3520 value = policy->policydb.allow_unknown;
3526 * security_policycap_supported - Check for a specific policy capability
3527 * @state: SELinux state
3528 * @req_cap: capability
3531 * This function queries the currently loaded policy to see if it supports the
3532 * capability specified by @req_cap. Returns true (1) if the capability is
3533 * supported, false (0) if it isn't supported.
3536 int security_policycap_supported(struct selinux_state *state,
3537 unsigned int req_cap)
3539 struct selinux_policy *policy;
3542 if (!selinux_initialized(state))
3546 policy = rcu_dereference(state->policy);
3547 rc = ebitmap_get_bit(&policy->policydb.policycaps, req_cap);
3553 struct selinux_audit_rule {
3555 struct context au_ctxt;
3558 void selinux_audit_rule_free(void *vrule)
3560 struct selinux_audit_rule *rule = vrule;
3563 context_destroy(&rule->au_ctxt);
3568 int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule)
3570 struct selinux_state *state = &selinux_state;
3571 struct selinux_policy *policy;
3572 struct policydb *policydb;
3573 struct selinux_audit_rule *tmprule;
3574 struct role_datum *roledatum;
3575 struct type_datum *typedatum;
3576 struct user_datum *userdatum;
3577 struct selinux_audit_rule **rule = (struct selinux_audit_rule **)vrule;
3582 if (!selinux_initialized(state))
3586 case AUDIT_SUBJ_USER:
3587 case AUDIT_SUBJ_ROLE:
3588 case AUDIT_SUBJ_TYPE:
3589 case AUDIT_OBJ_USER:
3590 case AUDIT_OBJ_ROLE:
3591 case AUDIT_OBJ_TYPE:
3592 /* only 'equals' and 'not equals' fit user, role, and type */
3593 if (op != Audit_equal && op != Audit_not_equal)
3596 case AUDIT_SUBJ_SEN:
3597 case AUDIT_SUBJ_CLR:
3598 case AUDIT_OBJ_LEV_LOW:
3599 case AUDIT_OBJ_LEV_HIGH:
3600 /* we do not allow a range, indicated by the presence of '-' */
3601 if (strchr(rulestr, '-'))
3605 /* only the above fields are valid */
3609 tmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL);
3613 context_init(&tmprule->au_ctxt);
3616 policy = rcu_dereference(state->policy);
3617 policydb = &policy->policydb;
3619 tmprule->au_seqno = policy->latest_granting;
3622 case AUDIT_SUBJ_USER:
3623 case AUDIT_OBJ_USER:
3625 userdatum = symtab_search(&policydb->p_users, rulestr);
3628 tmprule->au_ctxt.user = userdatum->value;
3630 case AUDIT_SUBJ_ROLE:
3631 case AUDIT_OBJ_ROLE:
3633 roledatum = symtab_search(&policydb->p_roles, rulestr);
3636 tmprule->au_ctxt.role = roledatum->value;
3638 case AUDIT_SUBJ_TYPE:
3639 case AUDIT_OBJ_TYPE:
3641 typedatum = symtab_search(&policydb->p_types, rulestr);
3644 tmprule->au_ctxt.type = typedatum->value;
3646 case AUDIT_SUBJ_SEN:
3647 case AUDIT_SUBJ_CLR:
3648 case AUDIT_OBJ_LEV_LOW:
3649 case AUDIT_OBJ_LEV_HIGH:
3650 rc = mls_from_string(policydb, rulestr, &tmprule->au_ctxt,
3661 selinux_audit_rule_free(tmprule);
3670 /* Check to see if the rule contains any selinux fields */
3671 int selinux_audit_rule_known(struct audit_krule *rule)
3675 for (i = 0; i < rule->field_count; i++) {
3676 struct audit_field *f = &rule->fields[i];
3678 case AUDIT_SUBJ_USER:
3679 case AUDIT_SUBJ_ROLE:
3680 case AUDIT_SUBJ_TYPE:
3681 case AUDIT_SUBJ_SEN:
3682 case AUDIT_SUBJ_CLR:
3683 case AUDIT_OBJ_USER:
3684 case AUDIT_OBJ_ROLE:
3685 case AUDIT_OBJ_TYPE:
3686 case AUDIT_OBJ_LEV_LOW:
3687 case AUDIT_OBJ_LEV_HIGH:
3695 int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule)
3697 struct selinux_state *state = &selinux_state;
3698 struct selinux_policy *policy;
3699 struct context *ctxt;
3700 struct mls_level *level;
3701 struct selinux_audit_rule *rule = vrule;
3704 if (unlikely(!rule)) {
3705 WARN_ONCE(1, "selinux_audit_rule_match: missing rule\n");
3709 if (!selinux_initialized(state))
3714 policy = rcu_dereference(state->policy);
3716 if (rule->au_seqno < policy->latest_granting) {
3721 ctxt = sidtab_search(policy->sidtab, sid);
3722 if (unlikely(!ctxt)) {
3723 WARN_ONCE(1, "selinux_audit_rule_match: unrecognized SID %d\n",
3729 /* a field/op pair that is not caught here will simply fall through
3732 case AUDIT_SUBJ_USER:
3733 case AUDIT_OBJ_USER:
3736 match = (ctxt->user == rule->au_ctxt.user);
3738 case Audit_not_equal:
3739 match = (ctxt->user != rule->au_ctxt.user);
3743 case AUDIT_SUBJ_ROLE:
3744 case AUDIT_OBJ_ROLE:
3747 match = (ctxt->role == rule->au_ctxt.role);
3749 case Audit_not_equal:
3750 match = (ctxt->role != rule->au_ctxt.role);
3754 case AUDIT_SUBJ_TYPE:
3755 case AUDIT_OBJ_TYPE:
3758 match = (ctxt->type == rule->au_ctxt.type);
3760 case Audit_not_equal:
3761 match = (ctxt->type != rule->au_ctxt.type);
3765 case AUDIT_SUBJ_SEN:
3766 case AUDIT_SUBJ_CLR:
3767 case AUDIT_OBJ_LEV_LOW:
3768 case AUDIT_OBJ_LEV_HIGH:
3769 level = ((field == AUDIT_SUBJ_SEN ||
3770 field == AUDIT_OBJ_LEV_LOW) ?
3771 &ctxt->range.level[0] : &ctxt->range.level[1]);
3774 match = mls_level_eq(&rule->au_ctxt.range.level[0],
3777 case Audit_not_equal:
3778 match = !mls_level_eq(&rule->au_ctxt.range.level[0],
3782 match = (mls_level_dom(&rule->au_ctxt.range.level[0],
3784 !mls_level_eq(&rule->au_ctxt.range.level[0],
3788 match = mls_level_dom(&rule->au_ctxt.range.level[0],
3792 match = (mls_level_dom(level,
3793 &rule->au_ctxt.range.level[0]) &&
3794 !mls_level_eq(level,
3795 &rule->au_ctxt.range.level[0]));
3798 match = mls_level_dom(level,
3799 &rule->au_ctxt.range.level[0]);
3809 static int aurule_avc_callback(u32 event)
3811 if (event == AVC_CALLBACK_RESET)
3812 return audit_update_lsm_rules();
3816 static int __init aurule_init(void)
3820 err = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET);
3822 panic("avc_add_callback() failed, error %d\n", err);
3826 __initcall(aurule_init);
3828 #ifdef CONFIG_NETLABEL
3830 * security_netlbl_cache_add - Add an entry to the NetLabel cache
3831 * @secattr: the NetLabel packet security attributes
3832 * @sid: the SELinux SID
3835 * Attempt to cache the context in @ctx, which was derived from the packet in
3836 * @skb, in the NetLabel subsystem cache. This function assumes @secattr has
3837 * already been initialized.
3840 static void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr,
3845 sid_cache = kmalloc(sizeof(*sid_cache), GFP_ATOMIC);
3846 if (sid_cache == NULL)
3848 secattr->cache = netlbl_secattr_cache_alloc(GFP_ATOMIC);
3849 if (secattr->cache == NULL) {
3855 secattr->cache->free = kfree;
3856 secattr->cache->data = sid_cache;
3857 secattr->flags |= NETLBL_SECATTR_CACHE;
3861 * security_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID
3862 * @state: SELinux state
3863 * @secattr: the NetLabel packet security attributes
3864 * @sid: the SELinux SID
3867 * Convert the given NetLabel security attributes in @secattr into a
3868 * SELinux SID. If the @secattr field does not contain a full SELinux
3869 * SID/context then use SECINITSID_NETMSG as the foundation. If possible the
3870 * 'cache' field of @secattr is set and the CACHE flag is set; this is to
3871 * allow the @secattr to be used by NetLabel to cache the secattr to SID
3872 * conversion for future lookups. Returns zero on success, negative values on
3876 int security_netlbl_secattr_to_sid(struct selinux_state *state,
3877 struct netlbl_lsm_secattr *secattr,
3880 struct selinux_policy *policy;
3881 struct policydb *policydb;
3882 struct sidtab *sidtab;
3884 struct context *ctx;
3885 struct context ctx_new;
3887 if (!selinux_initialized(state)) {
3895 policy = rcu_dereference(state->policy);
3896 policydb = &policy->policydb;
3897 sidtab = policy->sidtab;
3899 if (secattr->flags & NETLBL_SECATTR_CACHE)
3900 *sid = *(u32 *)secattr->cache->data;
3901 else if (secattr->flags & NETLBL_SECATTR_SECID)
3902 *sid = secattr->attr.secid;
3903 else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) {
3905 ctx = sidtab_search(sidtab, SECINITSID_NETMSG);
3909 context_init(&ctx_new);
3910 ctx_new.user = ctx->user;
3911 ctx_new.role = ctx->role;
3912 ctx_new.type = ctx->type;
3913 mls_import_netlbl_lvl(policydb, &ctx_new, secattr);
3914 if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
3915 rc = mls_import_netlbl_cat(policydb, &ctx_new, secattr);
3920 if (!mls_context_isvalid(policydb, &ctx_new)) {
3921 ebitmap_destroy(&ctx_new.range.level[0].cat);
3925 rc = sidtab_context_to_sid(sidtab, &ctx_new, sid);
3926 ebitmap_destroy(&ctx_new.range.level[0].cat);
3927 if (rc == -ESTALE) {
3934 security_netlbl_cache_add(secattr, *sid);
3944 * security_netlbl_sid_to_secattr - Convert a SELinux SID to a NetLabel secattr
3945 * @state: SELinux state
3946 * @sid: the SELinux SID
3947 * @secattr: the NetLabel packet security attributes
3950 * Convert the given SELinux SID in @sid into a NetLabel security attribute.
3951 * Returns zero on success, negative values on failure.
3954 int security_netlbl_sid_to_secattr(struct selinux_state *state,
3955 u32 sid, struct netlbl_lsm_secattr *secattr)
3957 struct selinux_policy *policy;
3958 struct policydb *policydb;
3960 struct context *ctx;
3962 if (!selinux_initialized(state))
3966 policy = rcu_dereference(state->policy);
3967 policydb = &policy->policydb;
3970 ctx = sidtab_search(policy->sidtab, sid);
3975 secattr->domain = kstrdup(sym_name(policydb, SYM_TYPES, ctx->type - 1),
3977 if (secattr->domain == NULL)
3980 secattr->attr.secid = sid;
3981 secattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID;
3982 mls_export_netlbl_lvl(policydb, ctx, secattr);
3983 rc = mls_export_netlbl_cat(policydb, ctx, secattr);
3988 #endif /* CONFIG_NETLABEL */
3991 * __security_read_policy - read the policy.
3992 * @policy: SELinux policy
3993 * @data: binary policy data
3994 * @len: length of data in bytes
3997 static int __security_read_policy(struct selinux_policy *policy,
3998 void *data, size_t *len)
4001 struct policy_file fp;
4006 rc = policydb_write(&policy->policydb, &fp);
4010 *len = (unsigned long)fp.data - (unsigned long)data;
4015 * security_read_policy - read the policy.
4016 * @state: selinux_state
4017 * @data: binary policy data
4018 * @len: length of data in bytes
4021 int security_read_policy(struct selinux_state *state,
4022 void **data, size_t *len)
4024 struct selinux_policy *policy;
4026 policy = rcu_dereference_protected(
4027 state->policy, lockdep_is_held(&state->policy_mutex));
4031 *len = policy->policydb.len;
4032 *data = vmalloc_user(*len);
4036 return __security_read_policy(policy, *data, len);
4040 * security_read_state_kernel - read the policy.
4041 * @state: selinux_state
4042 * @data: binary policy data
4043 * @len: length of data in bytes
4045 * Allocates kernel memory for reading SELinux policy.
4046 * This function is for internal use only and should not
4047 * be used for returning data to user space.
4049 * This function must be called with policy_mutex held.
4051 int security_read_state_kernel(struct selinux_state *state,
4052 void **data, size_t *len)
4054 struct selinux_policy *policy;
4056 policy = rcu_dereference_protected(
4057 state->policy, lockdep_is_held(&state->policy_mutex));
4061 *len = policy->policydb.len;
4062 *data = vmalloc(*len);
4066 return __security_read_policy(policy, *data, len);