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 struct convert_context_args {
71 struct selinux_state *state;
72 struct policydb *oldp;
73 struct policydb *newp;
76 struct selinux_policy_convert_data {
77 struct convert_context_args args;
78 struct sidtab_convert_params sidtab_params;
81 /* Forward declaration. */
82 static int context_struct_to_string(struct policydb *policydb,
83 struct context *context,
87 static int sidtab_entry_to_string(struct policydb *policydb,
88 struct sidtab *sidtab,
89 struct sidtab_entry *entry,
93 static void context_struct_compute_av(struct policydb *policydb,
94 struct context *scontext,
95 struct context *tcontext,
97 struct av_decision *avd,
98 struct extended_perms *xperms);
100 static int selinux_set_mapping(struct policydb *pol,
101 struct security_class_mapping *map,
102 struct selinux_map *out_map)
106 bool print_unknown_handle = false;
108 /* Find number of classes in the input mapping */
115 /* Allocate space for the class records, plus one for class zero */
116 out_map->mapping = kcalloc(++i, sizeof(*out_map->mapping), GFP_ATOMIC);
117 if (!out_map->mapping)
120 /* Store the raw class and permission values */
122 while (map[j].name) {
123 struct security_class_mapping *p_in = map + (j++);
124 struct selinux_mapping *p_out = out_map->mapping + j;
126 /* An empty class string skips ahead */
127 if (!strcmp(p_in->name, "")) {
128 p_out->num_perms = 0;
132 p_out->value = string_to_security_class(pol, p_in->name);
134 pr_info("SELinux: Class %s not defined in policy.\n",
136 if (pol->reject_unknown)
138 p_out->num_perms = 0;
139 print_unknown_handle = true;
144 while (p_in->perms[k]) {
145 /* An empty permission string skips ahead */
146 if (!*p_in->perms[k]) {
150 p_out->perms[k] = string_to_av_perm(pol, p_out->value,
152 if (!p_out->perms[k]) {
153 pr_info("SELinux: Permission %s in class %s not defined in policy.\n",
154 p_in->perms[k], p_in->name);
155 if (pol->reject_unknown)
157 print_unknown_handle = true;
162 p_out->num_perms = k;
165 if (print_unknown_handle)
166 pr_info("SELinux: the above unknown classes and permissions will be %s\n",
167 pol->allow_unknown ? "allowed" : "denied");
172 kfree(out_map->mapping);
173 out_map->mapping = NULL;
178 * Get real, policy values from mapped values
181 static u16 unmap_class(struct selinux_map *map, u16 tclass)
183 if (tclass < map->size)
184 return map->mapping[tclass].value;
190 * Get kernel value for class from its policy value
192 static u16 map_class(struct selinux_map *map, u16 pol_value)
196 for (i = 1; i < map->size; i++) {
197 if (map->mapping[i].value == pol_value)
201 return SECCLASS_NULL;
204 static void map_decision(struct selinux_map *map,
205 u16 tclass, struct av_decision *avd,
208 if (tclass < map->size) {
209 struct selinux_mapping *mapping = &map->mapping[tclass];
210 unsigned int i, n = mapping->num_perms;
213 for (i = 0, result = 0; i < n; i++) {
214 if (avd->allowed & mapping->perms[i])
216 if (allow_unknown && !mapping->perms[i])
219 avd->allowed = result;
221 for (i = 0, result = 0; i < n; i++)
222 if (avd->auditallow & mapping->perms[i])
224 avd->auditallow = result;
226 for (i = 0, result = 0; i < n; i++) {
227 if (avd->auditdeny & mapping->perms[i])
229 if (!allow_unknown && !mapping->perms[i])
233 * In case the kernel has a bug and requests a permission
234 * between num_perms and the maximum permission number, we
235 * should audit that denial
237 for (; i < (sizeof(u32)*8); i++)
239 avd->auditdeny = result;
243 int security_mls_enabled(struct selinux_state *state)
246 struct selinux_policy *policy;
248 if (!selinux_initialized(state))
252 policy = rcu_dereference(state->policy);
253 mls_enabled = policy->policydb.mls_enabled;
259 * Return the boolean value of a constraint expression
260 * when it is applied to the specified source and target
263 * xcontext is a special beast... It is used by the validatetrans rules
264 * only. For these rules, scontext is the context before the transition,
265 * tcontext is the context after the transition, and xcontext is the context
266 * of the process performing the transition. All other callers of
267 * constraint_expr_eval should pass in NULL for xcontext.
269 static int constraint_expr_eval(struct policydb *policydb,
270 struct context *scontext,
271 struct context *tcontext,
272 struct context *xcontext,
273 struct constraint_expr *cexpr)
277 struct role_datum *r1, *r2;
278 struct mls_level *l1, *l2;
279 struct constraint_expr *e;
280 int s[CEXPR_MAXDEPTH];
283 for (e = cexpr; e; e = e->next) {
284 switch (e->expr_type) {
300 if (sp == (CEXPR_MAXDEPTH - 1))
304 val1 = scontext->user;
305 val2 = tcontext->user;
308 val1 = scontext->type;
309 val2 = tcontext->type;
312 val1 = scontext->role;
313 val2 = tcontext->role;
314 r1 = policydb->role_val_to_struct[val1 - 1];
315 r2 = policydb->role_val_to_struct[val2 - 1];
318 s[++sp] = ebitmap_get_bit(&r1->dominates,
322 s[++sp] = ebitmap_get_bit(&r2->dominates,
326 s[++sp] = (!ebitmap_get_bit(&r1->dominates,
328 !ebitmap_get_bit(&r2->dominates,
336 l1 = &(scontext->range.level[0]);
337 l2 = &(tcontext->range.level[0]);
340 l1 = &(scontext->range.level[0]);
341 l2 = &(tcontext->range.level[1]);
344 l1 = &(scontext->range.level[1]);
345 l2 = &(tcontext->range.level[0]);
348 l1 = &(scontext->range.level[1]);
349 l2 = &(tcontext->range.level[1]);
352 l1 = &(scontext->range.level[0]);
353 l2 = &(scontext->range.level[1]);
356 l1 = &(tcontext->range.level[0]);
357 l2 = &(tcontext->range.level[1]);
362 s[++sp] = mls_level_eq(l1, l2);
365 s[++sp] = !mls_level_eq(l1, l2);
368 s[++sp] = mls_level_dom(l1, l2);
371 s[++sp] = mls_level_dom(l2, l1);
374 s[++sp] = mls_level_incomp(l2, l1);
388 s[++sp] = (val1 == val2);
391 s[++sp] = (val1 != val2);
399 if (sp == (CEXPR_MAXDEPTH-1))
402 if (e->attr & CEXPR_TARGET)
404 else if (e->attr & CEXPR_XTARGET) {
411 if (e->attr & CEXPR_USER)
413 else if (e->attr & CEXPR_ROLE)
415 else if (e->attr & CEXPR_TYPE)
424 s[++sp] = ebitmap_get_bit(&e->names, val1 - 1);
427 s[++sp] = !ebitmap_get_bit(&e->names, val1 - 1);
445 * security_dump_masked_av - dumps masked permissions during
446 * security_compute_av due to RBAC, MLS/Constraint and Type bounds.
448 static int dump_masked_av_helper(void *k, void *d, void *args)
450 struct perm_datum *pdatum = d;
451 char **permission_names = args;
453 BUG_ON(pdatum->value < 1 || pdatum->value > 32);
455 permission_names[pdatum->value - 1] = (char *)k;
460 static void security_dump_masked_av(struct policydb *policydb,
461 struct context *scontext,
462 struct context *tcontext,
467 struct common_datum *common_dat;
468 struct class_datum *tclass_dat;
469 struct audit_buffer *ab;
471 char *scontext_name = NULL;
472 char *tcontext_name = NULL;
473 char *permission_names[32];
476 bool need_comma = false;
481 tclass_name = sym_name(policydb, SYM_CLASSES, tclass - 1);
482 tclass_dat = policydb->class_val_to_struct[tclass - 1];
483 common_dat = tclass_dat->comdatum;
485 /* init permission_names */
487 hashtab_map(&common_dat->permissions.table,
488 dump_masked_av_helper, permission_names) < 0)
491 if (hashtab_map(&tclass_dat->permissions.table,
492 dump_masked_av_helper, permission_names) < 0)
495 /* get scontext/tcontext in text form */
496 if (context_struct_to_string(policydb, scontext,
497 &scontext_name, &length) < 0)
500 if (context_struct_to_string(policydb, tcontext,
501 &tcontext_name, &length) < 0)
504 /* audit a message */
505 ab = audit_log_start(audit_context(),
506 GFP_ATOMIC, AUDIT_SELINUX_ERR);
510 audit_log_format(ab, "op=security_compute_av reason=%s "
511 "scontext=%s tcontext=%s tclass=%s perms=",
512 reason, scontext_name, tcontext_name, tclass_name);
514 for (index = 0; index < 32; index++) {
515 u32 mask = (1 << index);
517 if ((mask & permissions) == 0)
520 audit_log_format(ab, "%s%s",
521 need_comma ? "," : "",
522 permission_names[index]
523 ? permission_names[index] : "????");
528 /* release scontext/tcontext */
529 kfree(tcontext_name);
530 kfree(scontext_name);
536 * security_boundary_permission - drops violated permissions
537 * on boundary constraint.
539 static void type_attribute_bounds_av(struct policydb *policydb,
540 struct context *scontext,
541 struct context *tcontext,
543 struct av_decision *avd)
545 struct context lo_scontext;
546 struct context lo_tcontext, *tcontextp = tcontext;
547 struct av_decision lo_avd;
548 struct type_datum *source;
549 struct type_datum *target;
552 source = policydb->type_val_to_struct[scontext->type - 1];
558 target = policydb->type_val_to_struct[tcontext->type - 1];
561 memset(&lo_avd, 0, sizeof(lo_avd));
563 memcpy(&lo_scontext, scontext, sizeof(lo_scontext));
564 lo_scontext.type = source->bounds;
566 if (target->bounds) {
567 memcpy(&lo_tcontext, tcontext, sizeof(lo_tcontext));
568 lo_tcontext.type = target->bounds;
569 tcontextp = &lo_tcontext;
572 context_struct_compute_av(policydb, &lo_scontext,
578 masked = ~lo_avd.allowed & avd->allowed;
581 return; /* no masked permission */
583 /* mask violated permissions */
584 avd->allowed &= ~masked;
586 /* audit masked permissions */
587 security_dump_masked_av(policydb, scontext, tcontext,
588 tclass, masked, "bounds");
592 * flag which drivers have permissions
593 * only looking for ioctl based extended permssions
595 void services_compute_xperms_drivers(
596 struct extended_perms *xperms,
597 struct avtab_node *node)
601 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
602 /* if one or more driver has all permissions allowed */
603 for (i = 0; i < ARRAY_SIZE(xperms->drivers.p); i++)
604 xperms->drivers.p[i] |= node->datum.u.xperms->perms.p[i];
605 } else if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
606 /* if allowing permissions within a driver */
607 security_xperm_set(xperms->drivers.p,
608 node->datum.u.xperms->driver);
615 * Compute access vectors and extended permissions based on a context
616 * structure pair for the permissions in a particular class.
618 static void context_struct_compute_av(struct policydb *policydb,
619 struct context *scontext,
620 struct context *tcontext,
622 struct av_decision *avd,
623 struct extended_perms *xperms)
625 struct constraint_node *constraint;
626 struct role_allow *ra;
627 struct avtab_key avkey;
628 struct avtab_node *node;
629 struct class_datum *tclass_datum;
630 struct ebitmap *sattr, *tattr;
631 struct ebitmap_node *snode, *tnode;
636 avd->auditdeny = 0xffffffff;
638 memset(&xperms->drivers, 0, sizeof(xperms->drivers));
642 if (unlikely(!tclass || tclass > policydb->p_classes.nprim)) {
643 if (printk_ratelimit())
644 pr_warn("SELinux: Invalid class %hu\n", tclass);
648 tclass_datum = policydb->class_val_to_struct[tclass - 1];
651 * If a specific type enforcement rule was defined for
652 * this permission check, then use it.
654 avkey.target_class = tclass;
655 avkey.specified = AVTAB_AV | AVTAB_XPERMS;
656 sattr = &policydb->type_attr_map_array[scontext->type - 1];
657 tattr = &policydb->type_attr_map_array[tcontext->type - 1];
658 ebitmap_for_each_positive_bit(sattr, snode, i) {
659 ebitmap_for_each_positive_bit(tattr, tnode, j) {
660 avkey.source_type = i + 1;
661 avkey.target_type = j + 1;
662 for (node = avtab_search_node(&policydb->te_avtab,
665 node = avtab_search_node_next(node, avkey.specified)) {
666 if (node->key.specified == AVTAB_ALLOWED)
667 avd->allowed |= node->datum.u.data;
668 else if (node->key.specified == AVTAB_AUDITALLOW)
669 avd->auditallow |= node->datum.u.data;
670 else if (node->key.specified == AVTAB_AUDITDENY)
671 avd->auditdeny &= node->datum.u.data;
672 else if (xperms && (node->key.specified & AVTAB_XPERMS))
673 services_compute_xperms_drivers(xperms, node);
676 /* Check conditional av table for additional permissions */
677 cond_compute_av(&policydb->te_cond_avtab, &avkey,
684 * Remove any permissions prohibited by a constraint (this includes
687 constraint = tclass_datum->constraints;
689 if ((constraint->permissions & (avd->allowed)) &&
690 !constraint_expr_eval(policydb, scontext, tcontext, NULL,
692 avd->allowed &= ~(constraint->permissions);
694 constraint = constraint->next;
698 * If checking process transition permission and the
699 * role is changing, then check the (current_role, new_role)
702 if (tclass == policydb->process_class &&
703 (avd->allowed & policydb->process_trans_perms) &&
704 scontext->role != tcontext->role) {
705 for (ra = policydb->role_allow; ra; ra = ra->next) {
706 if (scontext->role == ra->role &&
707 tcontext->role == ra->new_role)
711 avd->allowed &= ~policydb->process_trans_perms;
715 * If the given source and target types have boundary
716 * constraint, lazy checks have to mask any violated
717 * permission and notice it to userspace via audit.
719 type_attribute_bounds_av(policydb, scontext, tcontext,
723 static int security_validtrans_handle_fail(struct selinux_state *state,
724 struct selinux_policy *policy,
725 struct sidtab_entry *oentry,
726 struct sidtab_entry *nentry,
727 struct sidtab_entry *tentry,
730 struct policydb *p = &policy->policydb;
731 struct sidtab *sidtab = policy->sidtab;
732 char *o = NULL, *n = NULL, *t = NULL;
733 u32 olen, nlen, tlen;
735 if (sidtab_entry_to_string(p, sidtab, oentry, &o, &olen))
737 if (sidtab_entry_to_string(p, sidtab, nentry, &n, &nlen))
739 if (sidtab_entry_to_string(p, sidtab, tentry, &t, &tlen))
741 audit_log(audit_context(), GFP_ATOMIC, AUDIT_SELINUX_ERR,
742 "op=security_validate_transition seresult=denied"
743 " oldcontext=%s newcontext=%s taskcontext=%s tclass=%s",
744 o, n, t, sym_name(p, SYM_CLASSES, tclass-1));
750 if (!enforcing_enabled(state))
755 static int security_compute_validatetrans(struct selinux_state *state,
756 u32 oldsid, u32 newsid, u32 tasksid,
757 u16 orig_tclass, bool user)
759 struct selinux_policy *policy;
760 struct policydb *policydb;
761 struct sidtab *sidtab;
762 struct sidtab_entry *oentry;
763 struct sidtab_entry *nentry;
764 struct sidtab_entry *tentry;
765 struct class_datum *tclass_datum;
766 struct constraint_node *constraint;
771 if (!selinux_initialized(state))
776 policy = rcu_dereference(state->policy);
777 policydb = &policy->policydb;
778 sidtab = policy->sidtab;
781 tclass = unmap_class(&policy->map, orig_tclass);
783 tclass = orig_tclass;
785 if (!tclass || tclass > policydb->p_classes.nprim) {
789 tclass_datum = policydb->class_val_to_struct[tclass - 1];
791 oentry = sidtab_search_entry(sidtab, oldsid);
793 pr_err("SELinux: %s: unrecognized SID %d\n",
799 nentry = sidtab_search_entry(sidtab, newsid);
801 pr_err("SELinux: %s: unrecognized SID %d\n",
807 tentry = sidtab_search_entry(sidtab, tasksid);
809 pr_err("SELinux: %s: unrecognized SID %d\n",
815 constraint = tclass_datum->validatetrans;
817 if (!constraint_expr_eval(policydb, &oentry->context,
818 &nentry->context, &tentry->context,
823 rc = security_validtrans_handle_fail(state,
831 constraint = constraint->next;
839 int security_validate_transition_user(struct selinux_state *state,
840 u32 oldsid, u32 newsid, u32 tasksid,
843 return security_compute_validatetrans(state, oldsid, newsid, tasksid,
847 int security_validate_transition(struct selinux_state *state,
848 u32 oldsid, u32 newsid, u32 tasksid,
851 return security_compute_validatetrans(state, oldsid, newsid, tasksid,
856 * security_bounded_transition - check whether the given
857 * transition is directed to bounded, or not.
858 * It returns 0, if @newsid is bounded by @oldsid.
859 * Otherwise, it returns error code.
861 * @oldsid : current security identifier
862 * @newsid : destinated security identifier
864 int security_bounded_transition(struct selinux_state *state,
865 u32 old_sid, u32 new_sid)
867 struct selinux_policy *policy;
868 struct policydb *policydb;
869 struct sidtab *sidtab;
870 struct sidtab_entry *old_entry, *new_entry;
871 struct type_datum *type;
875 if (!selinux_initialized(state))
879 policy = rcu_dereference(state->policy);
880 policydb = &policy->policydb;
881 sidtab = policy->sidtab;
884 old_entry = sidtab_search_entry(sidtab, old_sid);
886 pr_err("SELinux: %s: unrecognized SID %u\n",
892 new_entry = sidtab_search_entry(sidtab, new_sid);
894 pr_err("SELinux: %s: unrecognized SID %u\n",
900 /* type/domain unchanged */
901 if (old_entry->context.type == new_entry->context.type)
904 index = new_entry->context.type;
906 type = policydb->type_val_to_struct[index - 1];
909 /* not bounded anymore */
914 /* @newsid is bounded by @oldsid */
916 if (type->bounds == old_entry->context.type)
919 index = type->bounds;
923 char *old_name = NULL;
924 char *new_name = NULL;
927 if (!sidtab_entry_to_string(policydb, sidtab, old_entry,
928 &old_name, &length) &&
929 !sidtab_entry_to_string(policydb, sidtab, new_entry,
930 &new_name, &length)) {
931 audit_log(audit_context(),
932 GFP_ATOMIC, AUDIT_SELINUX_ERR,
933 "op=security_bounded_transition "
935 "oldcontext=%s newcontext=%s",
947 static void avd_init(struct selinux_policy *policy, struct av_decision *avd)
951 avd->auditdeny = 0xffffffff;
953 avd->seqno = policy->latest_granting;
959 void services_compute_xperms_decision(struct extended_perms_decision *xpermd,
960 struct avtab_node *node)
964 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
965 if (xpermd->driver != node->datum.u.xperms->driver)
967 } else if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
968 if (!security_xperm_test(node->datum.u.xperms->perms.p,
975 if (node->key.specified == AVTAB_XPERMS_ALLOWED) {
976 xpermd->used |= XPERMS_ALLOWED;
977 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
978 memset(xpermd->allowed->p, 0xff,
979 sizeof(xpermd->allowed->p));
981 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
982 for (i = 0; i < ARRAY_SIZE(xpermd->allowed->p); i++)
983 xpermd->allowed->p[i] |=
984 node->datum.u.xperms->perms.p[i];
986 } else if (node->key.specified == AVTAB_XPERMS_AUDITALLOW) {
987 xpermd->used |= XPERMS_AUDITALLOW;
988 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
989 memset(xpermd->auditallow->p, 0xff,
990 sizeof(xpermd->auditallow->p));
992 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
993 for (i = 0; i < ARRAY_SIZE(xpermd->auditallow->p); i++)
994 xpermd->auditallow->p[i] |=
995 node->datum.u.xperms->perms.p[i];
997 } else if (node->key.specified == AVTAB_XPERMS_DONTAUDIT) {
998 xpermd->used |= XPERMS_DONTAUDIT;
999 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
1000 memset(xpermd->dontaudit->p, 0xff,
1001 sizeof(xpermd->dontaudit->p));
1003 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
1004 for (i = 0; i < ARRAY_SIZE(xpermd->dontaudit->p); i++)
1005 xpermd->dontaudit->p[i] |=
1006 node->datum.u.xperms->perms.p[i];
1013 void security_compute_xperms_decision(struct selinux_state *state,
1018 struct extended_perms_decision *xpermd)
1020 struct selinux_policy *policy;
1021 struct policydb *policydb;
1022 struct sidtab *sidtab;
1024 struct context *scontext, *tcontext;
1025 struct avtab_key avkey;
1026 struct avtab_node *node;
1027 struct ebitmap *sattr, *tattr;
1028 struct ebitmap_node *snode, *tnode;
1031 xpermd->driver = driver;
1033 memset(xpermd->allowed->p, 0, sizeof(xpermd->allowed->p));
1034 memset(xpermd->auditallow->p, 0, sizeof(xpermd->auditallow->p));
1035 memset(xpermd->dontaudit->p, 0, sizeof(xpermd->dontaudit->p));
1038 if (!selinux_initialized(state))
1041 policy = rcu_dereference(state->policy);
1042 policydb = &policy->policydb;
1043 sidtab = policy->sidtab;
1045 scontext = sidtab_search(sidtab, ssid);
1047 pr_err("SELinux: %s: unrecognized SID %d\n",
1052 tcontext = sidtab_search(sidtab, tsid);
1054 pr_err("SELinux: %s: unrecognized SID %d\n",
1059 tclass = unmap_class(&policy->map, orig_tclass);
1060 if (unlikely(orig_tclass && !tclass)) {
1061 if (policydb->allow_unknown)
1067 if (unlikely(!tclass || tclass > policydb->p_classes.nprim)) {
1068 pr_warn_ratelimited("SELinux: Invalid class %hu\n", tclass);
1072 avkey.target_class = tclass;
1073 avkey.specified = AVTAB_XPERMS;
1074 sattr = &policydb->type_attr_map_array[scontext->type - 1];
1075 tattr = &policydb->type_attr_map_array[tcontext->type - 1];
1076 ebitmap_for_each_positive_bit(sattr, snode, i) {
1077 ebitmap_for_each_positive_bit(tattr, tnode, j) {
1078 avkey.source_type = i + 1;
1079 avkey.target_type = j + 1;
1080 for (node = avtab_search_node(&policydb->te_avtab,
1083 node = avtab_search_node_next(node, avkey.specified))
1084 services_compute_xperms_decision(xpermd, node);
1086 cond_compute_xperms(&policydb->te_cond_avtab,
1094 memset(xpermd->allowed->p, 0xff, sizeof(xpermd->allowed->p));
1099 * security_compute_av - Compute access vector decisions.
1100 * @ssid: source security identifier
1101 * @tsid: target security identifier
1102 * @tclass: target security class
1103 * @avd: access vector decisions
1104 * @xperms: extended permissions
1106 * Compute a set of access vector decisions based on the
1107 * SID pair (@ssid, @tsid) for the permissions in @tclass.
1109 void security_compute_av(struct selinux_state *state,
1113 struct av_decision *avd,
1114 struct extended_perms *xperms)
1116 struct selinux_policy *policy;
1117 struct policydb *policydb;
1118 struct sidtab *sidtab;
1120 struct context *scontext = NULL, *tcontext = NULL;
1123 policy = rcu_dereference(state->policy);
1124 avd_init(policy, avd);
1126 if (!selinux_initialized(state))
1129 policydb = &policy->policydb;
1130 sidtab = policy->sidtab;
1132 scontext = sidtab_search(sidtab, ssid);
1134 pr_err("SELinux: %s: unrecognized SID %d\n",
1139 /* permissive domain? */
1140 if (ebitmap_get_bit(&policydb->permissive_map, scontext->type))
1141 avd->flags |= AVD_FLAGS_PERMISSIVE;
1143 tcontext = sidtab_search(sidtab, tsid);
1145 pr_err("SELinux: %s: unrecognized SID %d\n",
1150 tclass = unmap_class(&policy->map, orig_tclass);
1151 if (unlikely(orig_tclass && !tclass)) {
1152 if (policydb->allow_unknown)
1156 context_struct_compute_av(policydb, scontext, tcontext, tclass, avd,
1158 map_decision(&policy->map, orig_tclass, avd,
1159 policydb->allow_unknown);
1164 avd->allowed = 0xffffffff;
1168 void security_compute_av_user(struct selinux_state *state,
1172 struct av_decision *avd)
1174 struct selinux_policy *policy;
1175 struct policydb *policydb;
1176 struct sidtab *sidtab;
1177 struct context *scontext = NULL, *tcontext = NULL;
1180 policy = rcu_dereference(state->policy);
1181 avd_init(policy, avd);
1182 if (!selinux_initialized(state))
1185 policydb = &policy->policydb;
1186 sidtab = policy->sidtab;
1188 scontext = sidtab_search(sidtab, ssid);
1190 pr_err("SELinux: %s: unrecognized SID %d\n",
1195 /* permissive domain? */
1196 if (ebitmap_get_bit(&policydb->permissive_map, scontext->type))
1197 avd->flags |= AVD_FLAGS_PERMISSIVE;
1199 tcontext = sidtab_search(sidtab, tsid);
1201 pr_err("SELinux: %s: unrecognized SID %d\n",
1206 if (unlikely(!tclass)) {
1207 if (policydb->allow_unknown)
1212 context_struct_compute_av(policydb, scontext, tcontext, tclass, avd,
1218 avd->allowed = 0xffffffff;
1223 * Write the security context string representation of
1224 * the context structure `context' into a dynamically
1225 * allocated string of the correct size. Set `*scontext'
1226 * to point to this string and set `*scontext_len' to
1227 * the length of the string.
1229 static int context_struct_to_string(struct policydb *p,
1230 struct context *context,
1231 char **scontext, u32 *scontext_len)
1240 *scontext_len = context->len;
1242 *scontext = kstrdup(context->str, GFP_ATOMIC);
1249 /* Compute the size of the context. */
1250 *scontext_len += strlen(sym_name(p, SYM_USERS, context->user - 1)) + 1;
1251 *scontext_len += strlen(sym_name(p, SYM_ROLES, context->role - 1)) + 1;
1252 *scontext_len += strlen(sym_name(p, SYM_TYPES, context->type - 1)) + 1;
1253 *scontext_len += mls_compute_context_len(p, context);
1258 /* Allocate space for the context; caller must free this space. */
1259 scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
1262 *scontext = scontextp;
1265 * Copy the user name, role name and type name into the context.
1267 scontextp += sprintf(scontextp, "%s:%s:%s",
1268 sym_name(p, SYM_USERS, context->user - 1),
1269 sym_name(p, SYM_ROLES, context->role - 1),
1270 sym_name(p, SYM_TYPES, context->type - 1));
1272 mls_sid_to_context(p, context, &scontextp);
1279 static int sidtab_entry_to_string(struct policydb *p,
1280 struct sidtab *sidtab,
1281 struct sidtab_entry *entry,
1282 char **scontext, u32 *scontext_len)
1284 int rc = sidtab_sid2str_get(sidtab, entry, scontext, scontext_len);
1289 rc = context_struct_to_string(p, &entry->context, scontext,
1291 if (!rc && scontext)
1292 sidtab_sid2str_put(sidtab, entry, *scontext, *scontext_len);
1296 #include "initial_sid_to_string.h"
1298 int security_sidtab_hash_stats(struct selinux_state *state, char *page)
1300 struct selinux_policy *policy;
1303 if (!selinux_initialized(state)) {
1304 pr_err("SELinux: %s: called before initial load_policy\n",
1310 policy = rcu_dereference(state->policy);
1311 rc = sidtab_hash_stats(policy->sidtab, page);
1317 const char *security_get_initial_sid_context(u32 sid)
1319 if (unlikely(sid > SECINITSID_NUM))
1321 return initial_sid_to_string[sid];
1324 static int security_sid_to_context_core(struct selinux_state *state,
1325 u32 sid, char **scontext,
1326 u32 *scontext_len, int force,
1329 struct selinux_policy *policy;
1330 struct policydb *policydb;
1331 struct sidtab *sidtab;
1332 struct sidtab_entry *entry;
1339 if (!selinux_initialized(state)) {
1340 if (sid <= SECINITSID_NUM) {
1342 const char *s = initial_sid_to_string[sid];
1346 *scontext_len = strlen(s) + 1;
1349 scontextp = kmemdup(s, *scontext_len, GFP_ATOMIC);
1352 *scontext = scontextp;
1355 pr_err("SELinux: %s: called before initial "
1356 "load_policy on unknown SID %d\n", __func__, sid);
1360 policy = rcu_dereference(state->policy);
1361 policydb = &policy->policydb;
1362 sidtab = policy->sidtab;
1365 entry = sidtab_search_entry_force(sidtab, sid);
1367 entry = sidtab_search_entry(sidtab, sid);
1369 pr_err("SELinux: %s: unrecognized SID %d\n",
1374 if (only_invalid && !entry->context.len)
1377 rc = sidtab_entry_to_string(policydb, sidtab, entry, scontext,
1387 * security_sid_to_context - Obtain a context for a given SID.
1388 * @sid: security identifier, SID
1389 * @scontext: security context
1390 * @scontext_len: length in bytes
1392 * Write the string representation of the context associated with @sid
1393 * into a dynamically allocated string of the correct size. Set @scontext
1394 * to point to this string and set @scontext_len to the length of the string.
1396 int security_sid_to_context(struct selinux_state *state,
1397 u32 sid, char **scontext, u32 *scontext_len)
1399 return security_sid_to_context_core(state, sid, scontext,
1400 scontext_len, 0, 0);
1403 int security_sid_to_context_force(struct selinux_state *state, u32 sid,
1404 char **scontext, u32 *scontext_len)
1406 return security_sid_to_context_core(state, sid, scontext,
1407 scontext_len, 1, 0);
1411 * security_sid_to_context_inval - Obtain a context for a given SID if it
1413 * @sid: security identifier, SID
1414 * @scontext: security context
1415 * @scontext_len: length in bytes
1417 * Write the string representation of the context associated with @sid
1418 * into a dynamically allocated string of the correct size, but only if the
1419 * context is invalid in the current policy. Set @scontext to point to
1420 * this string (or NULL if the context is valid) and set @scontext_len to
1421 * the length of the string (or 0 if the context is valid).
1423 int security_sid_to_context_inval(struct selinux_state *state, u32 sid,
1424 char **scontext, u32 *scontext_len)
1426 return security_sid_to_context_core(state, sid, scontext,
1427 scontext_len, 1, 1);
1431 * Caveat: Mutates scontext.
1433 static int string_to_context_struct(struct policydb *pol,
1434 struct sidtab *sidtabp,
1436 struct context *ctx,
1439 struct role_datum *role;
1440 struct type_datum *typdatum;
1441 struct user_datum *usrdatum;
1442 char *scontextp, *p, oldc;
1447 /* Parse the security context. */
1450 scontextp = (char *) scontext;
1452 /* Extract the user. */
1454 while (*p && *p != ':')
1462 usrdatum = symtab_search(&pol->p_users, scontextp);
1466 ctx->user = usrdatum->value;
1470 while (*p && *p != ':')
1478 role = symtab_search(&pol->p_roles, scontextp);
1481 ctx->role = role->value;
1485 while (*p && *p != ':')
1490 typdatum = symtab_search(&pol->p_types, scontextp);
1491 if (!typdatum || typdatum->attribute)
1494 ctx->type = typdatum->value;
1496 rc = mls_context_to_sid(pol, oldc, p, ctx, sidtabp, def_sid);
1500 /* Check the validity of the new context. */
1502 if (!policydb_context_isvalid(pol, ctx))
1507 context_destroy(ctx);
1511 static int security_context_to_sid_core(struct selinux_state *state,
1512 const char *scontext, u32 scontext_len,
1513 u32 *sid, u32 def_sid, gfp_t gfp_flags,
1516 struct selinux_policy *policy;
1517 struct policydb *policydb;
1518 struct sidtab *sidtab;
1519 char *scontext2, *str = NULL;
1520 struct context context;
1523 /* An empty security context is never valid. */
1527 /* Copy the string to allow changes and ensure a NUL terminator */
1528 scontext2 = kmemdup_nul(scontext, scontext_len, gfp_flags);
1532 if (!selinux_initialized(state)) {
1535 for (i = 1; i < SECINITSID_NUM; i++) {
1536 const char *s = initial_sid_to_string[i];
1538 if (s && !strcmp(s, scontext2)) {
1543 *sid = SECINITSID_KERNEL;
1549 /* Save another copy for storing in uninterpreted form */
1551 str = kstrdup(scontext2, gfp_flags);
1557 policy = rcu_dereference(state->policy);
1558 policydb = &policy->policydb;
1559 sidtab = policy->sidtab;
1560 rc = string_to_context_struct(policydb, sidtab, scontext2,
1562 if (rc == -EINVAL && force) {
1564 context.len = strlen(str) + 1;
1568 rc = sidtab_context_to_sid(sidtab, &context, sid);
1569 if (rc == -ESTALE) {
1575 context_destroy(&context);
1578 context_destroy(&context);
1588 * security_context_to_sid - Obtain a SID for a given security context.
1589 * @scontext: security context
1590 * @scontext_len: length in bytes
1591 * @sid: security identifier, SID
1592 * @gfp: context for the allocation
1594 * Obtains a SID associated with the security context that
1595 * has the string representation specified by @scontext.
1596 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1597 * memory is available, or 0 on success.
1599 int security_context_to_sid(struct selinux_state *state,
1600 const char *scontext, u32 scontext_len, u32 *sid,
1603 return security_context_to_sid_core(state, scontext, scontext_len,
1604 sid, SECSID_NULL, gfp, 0);
1607 int security_context_str_to_sid(struct selinux_state *state,
1608 const char *scontext, u32 *sid, gfp_t gfp)
1610 return security_context_to_sid(state, scontext, strlen(scontext),
1615 * security_context_to_sid_default - Obtain a SID for a given security context,
1616 * falling back to specified default if needed.
1618 * @scontext: security context
1619 * @scontext_len: length in bytes
1620 * @sid: security identifier, SID
1621 * @def_sid: default SID to assign on error
1623 * Obtains a SID associated with the security context that
1624 * has the string representation specified by @scontext.
1625 * The default SID is passed to the MLS layer to be used to allow
1626 * kernel labeling of the MLS field if the MLS field is not present
1627 * (for upgrading to MLS without full relabel).
1628 * Implicitly forces adding of the context even if it cannot be mapped yet.
1629 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1630 * memory is available, or 0 on success.
1632 int security_context_to_sid_default(struct selinux_state *state,
1633 const char *scontext, u32 scontext_len,
1634 u32 *sid, u32 def_sid, gfp_t gfp_flags)
1636 return security_context_to_sid_core(state, scontext, scontext_len,
1637 sid, def_sid, gfp_flags, 1);
1640 int security_context_to_sid_force(struct selinux_state *state,
1641 const char *scontext, u32 scontext_len,
1644 return security_context_to_sid_core(state, scontext, scontext_len,
1645 sid, SECSID_NULL, GFP_KERNEL, 1);
1648 static int compute_sid_handle_invalid_context(
1649 struct selinux_state *state,
1650 struct selinux_policy *policy,
1651 struct sidtab_entry *sentry,
1652 struct sidtab_entry *tentry,
1654 struct context *newcontext)
1656 struct policydb *policydb = &policy->policydb;
1657 struct sidtab *sidtab = policy->sidtab;
1658 char *s = NULL, *t = NULL, *n = NULL;
1659 u32 slen, tlen, nlen;
1660 struct audit_buffer *ab;
1662 if (sidtab_entry_to_string(policydb, sidtab, sentry, &s, &slen))
1664 if (sidtab_entry_to_string(policydb, sidtab, tentry, &t, &tlen))
1666 if (context_struct_to_string(policydb, newcontext, &n, &nlen))
1668 ab = audit_log_start(audit_context(), GFP_ATOMIC, AUDIT_SELINUX_ERR);
1669 audit_log_format(ab,
1670 "op=security_compute_sid invalid_context=");
1671 /* no need to record the NUL with untrusted strings */
1672 audit_log_n_untrustedstring(ab, n, nlen - 1);
1673 audit_log_format(ab, " scontext=%s tcontext=%s tclass=%s",
1674 s, t, sym_name(policydb, SYM_CLASSES, tclass-1));
1680 if (!enforcing_enabled(state))
1685 static void filename_compute_type(struct policydb *policydb,
1686 struct context *newcontext,
1687 u32 stype, u32 ttype, u16 tclass,
1688 const char *objname)
1690 struct filename_trans_key ft;
1691 struct filename_trans_datum *datum;
1694 * Most filename trans rules are going to live in specific directories
1695 * like /dev or /var/run. This bitmap will quickly skip rule searches
1696 * if the ttype does not contain any rules.
1698 if (!ebitmap_get_bit(&policydb->filename_trans_ttypes, ttype))
1705 datum = policydb_filenametr_search(policydb, &ft);
1707 if (ebitmap_get_bit(&datum->stypes, stype - 1)) {
1708 newcontext->type = datum->otype;
1711 datum = datum->next;
1715 static int security_compute_sid(struct selinux_state *state,
1720 const char *objname,
1724 struct selinux_policy *policy;
1725 struct policydb *policydb;
1726 struct sidtab *sidtab;
1727 struct class_datum *cladatum;
1728 struct context *scontext, *tcontext, newcontext;
1729 struct sidtab_entry *sentry, *tentry;
1730 struct avtab_key avkey;
1731 struct avtab_datum *avdatum;
1732 struct avtab_node *node;
1737 if (!selinux_initialized(state)) {
1738 switch (orig_tclass) {
1739 case SECCLASS_PROCESS: /* kernel value */
1751 context_init(&newcontext);
1755 policy = rcu_dereference(state->policy);
1758 tclass = unmap_class(&policy->map, orig_tclass);
1759 sock = security_is_socket_class(orig_tclass);
1761 tclass = orig_tclass;
1762 sock = security_is_socket_class(map_class(&policy->map,
1766 policydb = &policy->policydb;
1767 sidtab = policy->sidtab;
1769 sentry = sidtab_search_entry(sidtab, ssid);
1771 pr_err("SELinux: %s: unrecognized SID %d\n",
1776 tentry = sidtab_search_entry(sidtab, tsid);
1778 pr_err("SELinux: %s: unrecognized SID %d\n",
1784 scontext = &sentry->context;
1785 tcontext = &tentry->context;
1787 if (tclass && tclass <= policydb->p_classes.nprim)
1788 cladatum = policydb->class_val_to_struct[tclass - 1];
1790 /* Set the user identity. */
1791 switch (specified) {
1792 case AVTAB_TRANSITION:
1794 if (cladatum && cladatum->default_user == DEFAULT_TARGET) {
1795 newcontext.user = tcontext->user;
1797 /* notice this gets both DEFAULT_SOURCE and unset */
1798 /* Use the process user identity. */
1799 newcontext.user = scontext->user;
1803 /* Use the related object owner. */
1804 newcontext.user = tcontext->user;
1808 /* Set the role to default values. */
1809 if (cladatum && cladatum->default_role == DEFAULT_SOURCE) {
1810 newcontext.role = scontext->role;
1811 } else if (cladatum && cladatum->default_role == DEFAULT_TARGET) {
1812 newcontext.role = tcontext->role;
1814 if ((tclass == policydb->process_class) || sock)
1815 newcontext.role = scontext->role;
1817 newcontext.role = OBJECT_R_VAL;
1820 /* Set the type to default values. */
1821 if (cladatum && cladatum->default_type == DEFAULT_SOURCE) {
1822 newcontext.type = scontext->type;
1823 } else if (cladatum && cladatum->default_type == DEFAULT_TARGET) {
1824 newcontext.type = tcontext->type;
1826 if ((tclass == policydb->process_class) || sock) {
1827 /* Use the type of process. */
1828 newcontext.type = scontext->type;
1830 /* Use the type of the related object. */
1831 newcontext.type = tcontext->type;
1835 /* Look for a type transition/member/change rule. */
1836 avkey.source_type = scontext->type;
1837 avkey.target_type = tcontext->type;
1838 avkey.target_class = tclass;
1839 avkey.specified = specified;
1840 avdatum = avtab_search(&policydb->te_avtab, &avkey);
1842 /* If no permanent rule, also check for enabled conditional rules */
1844 node = avtab_search_node(&policydb->te_cond_avtab, &avkey);
1845 for (; node; node = avtab_search_node_next(node, specified)) {
1846 if (node->key.specified & AVTAB_ENABLED) {
1847 avdatum = &node->datum;
1854 /* Use the type from the type transition/member/change rule. */
1855 newcontext.type = avdatum->u.data;
1858 /* if we have a objname this is a file trans check so check those rules */
1860 filename_compute_type(policydb, &newcontext, scontext->type,
1861 tcontext->type, tclass, objname);
1863 /* Check for class-specific changes. */
1864 if (specified & AVTAB_TRANSITION) {
1865 /* Look for a role transition rule. */
1866 struct role_trans_datum *rtd;
1867 struct role_trans_key rtk = {
1868 .role = scontext->role,
1869 .type = tcontext->type,
1873 rtd = policydb_roletr_search(policydb, &rtk);
1875 newcontext.role = rtd->new_role;
1878 /* Set the MLS attributes.
1879 This is done last because it may allocate memory. */
1880 rc = mls_compute_sid(policydb, scontext, tcontext, tclass, specified,
1885 /* Check the validity of the context. */
1886 if (!policydb_context_isvalid(policydb, &newcontext)) {
1887 rc = compute_sid_handle_invalid_context(state, policy, sentry,
1893 /* Obtain the sid for the context. */
1894 rc = sidtab_context_to_sid(sidtab, &newcontext, out_sid);
1895 if (rc == -ESTALE) {
1897 context_destroy(&newcontext);
1902 context_destroy(&newcontext);
1908 * security_transition_sid - Compute the SID for a new subject/object.
1909 * @ssid: source security identifier
1910 * @tsid: target security identifier
1911 * @tclass: target security class
1912 * @out_sid: security identifier for new subject/object
1914 * Compute a SID to use for labeling a new subject or object in the
1915 * class @tclass based on a SID pair (@ssid, @tsid).
1916 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1917 * if insufficient memory is available, or %0 if the new SID was
1918 * computed successfully.
1920 int security_transition_sid(struct selinux_state *state,
1921 u32 ssid, u32 tsid, u16 tclass,
1922 const struct qstr *qstr, u32 *out_sid)
1924 return security_compute_sid(state, ssid, tsid, tclass,
1926 qstr ? qstr->name : NULL, out_sid, true);
1929 int security_transition_sid_user(struct selinux_state *state,
1930 u32 ssid, u32 tsid, u16 tclass,
1931 const char *objname, u32 *out_sid)
1933 return security_compute_sid(state, ssid, tsid, tclass,
1935 objname, out_sid, false);
1939 * security_member_sid - Compute the SID for member selection.
1940 * @ssid: source security identifier
1941 * @tsid: target security identifier
1942 * @tclass: target security class
1943 * @out_sid: security identifier for selected member
1945 * Compute a SID to use when selecting a member of a polyinstantiated
1946 * object of class @tclass based on a SID pair (@ssid, @tsid).
1947 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1948 * if insufficient memory is available, or %0 if the SID was
1949 * computed successfully.
1951 int security_member_sid(struct selinux_state *state,
1957 return security_compute_sid(state, ssid, tsid, tclass,
1963 * security_change_sid - Compute the SID for object relabeling.
1964 * @ssid: source security identifier
1965 * @tsid: target security identifier
1966 * @tclass: target security class
1967 * @out_sid: security identifier for selected member
1969 * Compute a SID to use for relabeling an object of class @tclass
1970 * based on a SID pair (@ssid, @tsid).
1971 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1972 * if insufficient memory is available, or %0 if the SID was
1973 * computed successfully.
1975 int security_change_sid(struct selinux_state *state,
1981 return security_compute_sid(state,
1982 ssid, tsid, tclass, AVTAB_CHANGE, NULL,
1986 static inline int convert_context_handle_invalid_context(
1987 struct selinux_state *state,
1988 struct policydb *policydb,
1989 struct context *context)
1994 if (enforcing_enabled(state))
1997 if (!context_struct_to_string(policydb, context, &s, &len)) {
1998 pr_warn("SELinux: Context %s would be invalid if enforcing\n",
2006 * Convert the values in the security context
2007 * structure `oldc' from the values specified
2008 * in the policy `p->oldp' to the values specified
2009 * in the policy `p->newp', storing the new context
2010 * in `newc'. Verify that the context is valid
2011 * under the new policy.
2013 static int convert_context(struct context *oldc, struct context *newc, void *p)
2015 struct convert_context_args *args;
2016 struct ocontext *oc;
2017 struct role_datum *role;
2018 struct type_datum *typdatum;
2019 struct user_datum *usrdatum;
2027 s = kstrdup(oldc->str, GFP_KERNEL);
2031 rc = string_to_context_struct(args->newp, NULL, s,
2033 if (rc == -EINVAL) {
2035 * Retain string representation for later mapping.
2037 * IMPORTANT: We need to copy the contents of oldc->str
2038 * back into s again because string_to_context_struct()
2039 * may have garbled it.
2041 memcpy(s, oldc->str, oldc->len);
2044 newc->len = oldc->len;
2049 /* Other error condition, e.g. ENOMEM. */
2050 pr_err("SELinux: Unable to map context %s, rc = %d.\n",
2054 pr_info("SELinux: Context %s became valid (mapped).\n",
2061 /* Convert the user. */
2063 usrdatum = symtab_search(&args->newp->p_users,
2064 sym_name(args->oldp,
2065 SYM_USERS, oldc->user - 1));
2068 newc->user = usrdatum->value;
2070 /* Convert the role. */
2072 role = symtab_search(&args->newp->p_roles,
2073 sym_name(args->oldp, SYM_ROLES, oldc->role - 1));
2076 newc->role = role->value;
2078 /* Convert the type. */
2080 typdatum = symtab_search(&args->newp->p_types,
2081 sym_name(args->oldp,
2082 SYM_TYPES, oldc->type - 1));
2085 newc->type = typdatum->value;
2087 /* Convert the MLS fields if dealing with MLS policies */
2088 if (args->oldp->mls_enabled && args->newp->mls_enabled) {
2089 rc = mls_convert_context(args->oldp, args->newp, oldc, newc);
2092 } else if (!args->oldp->mls_enabled && args->newp->mls_enabled) {
2094 * Switching between non-MLS and MLS policy:
2095 * ensure that the MLS fields of the context for all
2096 * existing entries in the sidtab are filled in with a
2097 * suitable default value, likely taken from one of the
2100 oc = args->newp->ocontexts[OCON_ISID];
2101 while (oc && oc->sid[0] != SECINITSID_UNLABELED)
2105 pr_err("SELinux: unable to look up"
2106 " the initial SIDs list\n");
2109 rc = mls_range_set(newc, &oc->context[0].range);
2114 /* Check the validity of the new context. */
2115 if (!policydb_context_isvalid(args->newp, newc)) {
2116 rc = convert_context_handle_invalid_context(args->state,
2125 /* Map old representation to string and save it. */
2126 rc = context_struct_to_string(args->oldp, oldc, &s, &len);
2129 context_destroy(newc);
2132 pr_info("SELinux: Context %s became invalid (unmapped).\n",
2137 static void security_load_policycaps(struct selinux_state *state,
2138 struct selinux_policy *policy)
2142 struct ebitmap_node *node;
2144 p = &policy->policydb;
2146 for (i = 0; i < ARRAY_SIZE(state->policycap); i++)
2147 WRITE_ONCE(state->policycap[i],
2148 ebitmap_get_bit(&p->policycaps, i));
2150 for (i = 0; i < ARRAY_SIZE(selinux_policycap_names); i++)
2151 pr_info("SELinux: policy capability %s=%d\n",
2152 selinux_policycap_names[i],
2153 ebitmap_get_bit(&p->policycaps, i));
2155 ebitmap_for_each_positive_bit(&p->policycaps, node, i) {
2156 if (i >= ARRAY_SIZE(selinux_policycap_names))
2157 pr_info("SELinux: unknown policy capability %u\n",
2162 static int security_preserve_bools(struct selinux_policy *oldpolicy,
2163 struct selinux_policy *newpolicy);
2165 static void selinux_policy_free(struct selinux_policy *policy)
2170 sidtab_destroy(policy->sidtab);
2171 kfree(policy->map.mapping);
2172 policydb_destroy(&policy->policydb);
2173 kfree(policy->sidtab);
2177 static void selinux_policy_cond_free(struct selinux_policy *policy)
2179 cond_policydb_destroy_dup(&policy->policydb);
2183 void selinux_policy_cancel(struct selinux_state *state,
2184 struct selinux_load_state *load_state)
2186 struct selinux_policy *oldpolicy;
2188 oldpolicy = rcu_dereference_protected(state->policy,
2189 lockdep_is_held(&state->policy_mutex));
2191 sidtab_cancel_convert(oldpolicy->sidtab);
2192 selinux_policy_free(load_state->policy);
2193 kfree(load_state->convert_data);
2196 static void selinux_notify_policy_change(struct selinux_state *state,
2199 /* Flush external caches and notify userspace of policy load */
2200 avc_ss_reset(state->avc, seqno);
2201 selnl_notify_policyload(seqno);
2202 selinux_status_update_policyload(state, seqno);
2203 selinux_netlbl_cache_invalidate();
2204 selinux_xfrm_notify_policyload();
2205 selinux_ima_measure_state_locked(state);
2208 void selinux_policy_commit(struct selinux_state *state,
2209 struct selinux_load_state *load_state)
2211 struct selinux_policy *oldpolicy, *newpolicy = load_state->policy;
2212 unsigned long flags;
2215 oldpolicy = rcu_dereference_protected(state->policy,
2216 lockdep_is_held(&state->policy_mutex));
2218 /* If switching between different policy types, log MLS status */
2220 if (oldpolicy->policydb.mls_enabled && !newpolicy->policydb.mls_enabled)
2221 pr_info("SELinux: Disabling MLS support...\n");
2222 else if (!oldpolicy->policydb.mls_enabled && newpolicy->policydb.mls_enabled)
2223 pr_info("SELinux: Enabling MLS support...\n");
2226 /* Set latest granting seqno for new policy. */
2228 newpolicy->latest_granting = oldpolicy->latest_granting + 1;
2230 newpolicy->latest_granting = 1;
2231 seqno = newpolicy->latest_granting;
2233 /* Install the new policy. */
2235 sidtab_freeze_begin(oldpolicy->sidtab, &flags);
2236 rcu_assign_pointer(state->policy, newpolicy);
2237 sidtab_freeze_end(oldpolicy->sidtab, &flags);
2239 rcu_assign_pointer(state->policy, newpolicy);
2242 /* Load the policycaps from the new policy */
2243 security_load_policycaps(state, newpolicy);
2245 if (!selinux_initialized(state)) {
2247 * After first policy load, the security server is
2248 * marked as initialized and ready to handle requests and
2249 * any objects created prior to policy load are then labeled.
2251 selinux_mark_initialized(state);
2252 selinux_complete_init();
2255 /* Free the old policy */
2257 selinux_policy_free(oldpolicy);
2258 kfree(load_state->convert_data);
2260 /* Notify others of the policy change */
2261 selinux_notify_policy_change(state, seqno);
2265 * security_load_policy - Load a security policy configuration.
2266 * @data: binary policy data
2267 * @len: length of data in bytes
2269 * Load a new set of security policy configuration data,
2270 * validate it and convert the SID table as necessary.
2271 * This function will flush the access vector cache after
2272 * loading the new policy.
2274 int security_load_policy(struct selinux_state *state, void *data, size_t len,
2275 struct selinux_load_state *load_state)
2277 struct selinux_policy *newpolicy, *oldpolicy;
2278 struct selinux_policy_convert_data *convert_data;
2280 struct policy_file file = { data, len }, *fp = &file;
2282 newpolicy = kzalloc(sizeof(*newpolicy), GFP_KERNEL);
2286 newpolicy->sidtab = kzalloc(sizeof(*newpolicy->sidtab), GFP_KERNEL);
2287 if (!newpolicy->sidtab) {
2292 rc = policydb_read(&newpolicy->policydb, fp);
2296 newpolicy->policydb.len = len;
2297 rc = selinux_set_mapping(&newpolicy->policydb, secclass_map,
2302 rc = policydb_load_isids(&newpolicy->policydb, newpolicy->sidtab);
2304 pr_err("SELinux: unable to load the initial SIDs\n");
2308 if (!selinux_initialized(state)) {
2309 /* First policy load, so no need to preserve state from old policy */
2310 load_state->policy = newpolicy;
2311 load_state->convert_data = NULL;
2315 oldpolicy = rcu_dereference_protected(state->policy,
2316 lockdep_is_held(&state->policy_mutex));
2318 /* Preserve active boolean values from the old policy */
2319 rc = security_preserve_bools(oldpolicy, newpolicy);
2321 pr_err("SELinux: unable to preserve booleans\n");
2322 goto err_free_isids;
2325 convert_data = kmalloc(sizeof(*convert_data), GFP_KERNEL);
2326 if (!convert_data) {
2328 goto err_free_isids;
2332 * Convert the internal representations of contexts
2333 * in the new SID table.
2335 convert_data->args.state = state;
2336 convert_data->args.oldp = &oldpolicy->policydb;
2337 convert_data->args.newp = &newpolicy->policydb;
2339 convert_data->sidtab_params.func = convert_context;
2340 convert_data->sidtab_params.args = &convert_data->args;
2341 convert_data->sidtab_params.target = newpolicy->sidtab;
2343 rc = sidtab_convert(oldpolicy->sidtab, &convert_data->sidtab_params);
2345 pr_err("SELinux: unable to convert the internal"
2346 " representation of contexts in the new SID"
2348 goto err_free_convert_data;
2351 load_state->policy = newpolicy;
2352 load_state->convert_data = convert_data;
2355 err_free_convert_data:
2356 kfree(convert_data);
2358 sidtab_destroy(newpolicy->sidtab);
2360 kfree(newpolicy->map.mapping);
2362 policydb_destroy(&newpolicy->policydb);
2364 kfree(newpolicy->sidtab);
2372 * security_port_sid - Obtain the SID for a port.
2373 * @protocol: protocol number
2374 * @port: port number
2375 * @out_sid: security identifier
2377 int security_port_sid(struct selinux_state *state,
2378 u8 protocol, u16 port, u32 *out_sid)
2380 struct selinux_policy *policy;
2381 struct policydb *policydb;
2382 struct sidtab *sidtab;
2386 if (!selinux_initialized(state)) {
2387 *out_sid = SECINITSID_PORT;
2394 policy = rcu_dereference(state->policy);
2395 policydb = &policy->policydb;
2396 sidtab = policy->sidtab;
2398 c = policydb->ocontexts[OCON_PORT];
2400 if (c->u.port.protocol == protocol &&
2401 c->u.port.low_port <= port &&
2402 c->u.port.high_port >= port)
2409 rc = sidtab_context_to_sid(sidtab, &c->context[0],
2411 if (rc == -ESTALE) {
2418 *out_sid = c->sid[0];
2420 *out_sid = SECINITSID_PORT;
2429 * security_pkey_sid - Obtain the SID for a pkey.
2430 * @subnet_prefix: Subnet Prefix
2431 * @pkey_num: pkey number
2432 * @out_sid: security identifier
2434 int security_ib_pkey_sid(struct selinux_state *state,
2435 u64 subnet_prefix, u16 pkey_num, u32 *out_sid)
2437 struct selinux_policy *policy;
2438 struct policydb *policydb;
2439 struct sidtab *sidtab;
2443 if (!selinux_initialized(state)) {
2444 *out_sid = SECINITSID_UNLABELED;
2451 policy = rcu_dereference(state->policy);
2452 policydb = &policy->policydb;
2453 sidtab = policy->sidtab;
2455 c = policydb->ocontexts[OCON_IBPKEY];
2457 if (c->u.ibpkey.low_pkey <= pkey_num &&
2458 c->u.ibpkey.high_pkey >= pkey_num &&
2459 c->u.ibpkey.subnet_prefix == subnet_prefix)
2467 rc = sidtab_context_to_sid(sidtab,
2470 if (rc == -ESTALE) {
2477 *out_sid = c->sid[0];
2479 *out_sid = SECINITSID_UNLABELED;
2487 * security_ib_endport_sid - Obtain the SID for a subnet management interface.
2488 * @dev_name: device name
2489 * @port: port number
2490 * @out_sid: security identifier
2492 int security_ib_endport_sid(struct selinux_state *state,
2493 const char *dev_name, u8 port_num, u32 *out_sid)
2495 struct selinux_policy *policy;
2496 struct policydb *policydb;
2497 struct sidtab *sidtab;
2501 if (!selinux_initialized(state)) {
2502 *out_sid = SECINITSID_UNLABELED;
2509 policy = rcu_dereference(state->policy);
2510 policydb = &policy->policydb;
2511 sidtab = policy->sidtab;
2513 c = policydb->ocontexts[OCON_IBENDPORT];
2515 if (c->u.ibendport.port == port_num &&
2516 !strncmp(c->u.ibendport.dev_name,
2518 IB_DEVICE_NAME_MAX))
2526 rc = sidtab_context_to_sid(sidtab, &c->context[0],
2528 if (rc == -ESTALE) {
2535 *out_sid = c->sid[0];
2537 *out_sid = SECINITSID_UNLABELED;
2545 * security_netif_sid - Obtain the SID for a network interface.
2546 * @name: interface name
2547 * @if_sid: interface SID
2549 int security_netif_sid(struct selinux_state *state,
2550 char *name, u32 *if_sid)
2552 struct selinux_policy *policy;
2553 struct policydb *policydb;
2554 struct sidtab *sidtab;
2558 if (!selinux_initialized(state)) {
2559 *if_sid = SECINITSID_NETIF;
2566 policy = rcu_dereference(state->policy);
2567 policydb = &policy->policydb;
2568 sidtab = policy->sidtab;
2570 c = policydb->ocontexts[OCON_NETIF];
2572 if (strcmp(name, c->u.name) == 0)
2578 if (!c->sid[0] || !c->sid[1]) {
2579 rc = sidtab_context_to_sid(sidtab, &c->context[0],
2581 if (rc == -ESTALE) {
2587 rc = sidtab_context_to_sid(sidtab, &c->context[1],
2589 if (rc == -ESTALE) {
2596 *if_sid = c->sid[0];
2598 *if_sid = SECINITSID_NETIF;
2605 static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask)
2609 for (i = 0; i < 4; i++)
2610 if (addr[i] != (input[i] & mask[i])) {
2619 * security_node_sid - Obtain the SID for a node (host).
2620 * @domain: communication domain aka address family
2622 * @addrlen: address length in bytes
2623 * @out_sid: security identifier
2625 int security_node_sid(struct selinux_state *state,
2631 struct selinux_policy *policy;
2632 struct policydb *policydb;
2633 struct sidtab *sidtab;
2637 if (!selinux_initialized(state)) {
2638 *out_sid = SECINITSID_NODE;
2644 policy = rcu_dereference(state->policy);
2645 policydb = &policy->policydb;
2646 sidtab = policy->sidtab;
2653 if (addrlen != sizeof(u32))
2656 addr = *((u32 *)addrp);
2658 c = policydb->ocontexts[OCON_NODE];
2660 if (c->u.node.addr == (addr & c->u.node.mask))
2669 if (addrlen != sizeof(u64) * 2)
2671 c = policydb->ocontexts[OCON_NODE6];
2673 if (match_ipv6_addrmask(addrp, c->u.node6.addr,
2682 *out_sid = SECINITSID_NODE;
2688 rc = sidtab_context_to_sid(sidtab,
2691 if (rc == -ESTALE) {
2698 *out_sid = c->sid[0];
2700 *out_sid = SECINITSID_NODE;
2712 * security_get_user_sids - Obtain reachable SIDs for a user.
2713 * @fromsid: starting SID
2714 * @username: username
2715 * @sids: array of reachable SIDs for user
2716 * @nel: number of elements in @sids
2718 * Generate the set of SIDs for legal security contexts
2719 * for a given user that can be reached by @fromsid.
2720 * Set *@sids to point to a dynamically allocated
2721 * array containing the set of SIDs. Set *@nel to the
2722 * number of elements in the array.
2725 int security_get_user_sids(struct selinux_state *state,
2731 struct selinux_policy *policy;
2732 struct policydb *policydb;
2733 struct sidtab *sidtab;
2734 struct context *fromcon, usercon;
2735 u32 *mysids = NULL, *mysids2, sid;
2736 u32 i, j, mynel, maxnel = SIDS_NEL;
2737 struct user_datum *user;
2738 struct role_datum *role;
2739 struct ebitmap_node *rnode, *tnode;
2745 if (!selinux_initialized(state))
2748 mysids = kcalloc(maxnel, sizeof(*mysids), GFP_KERNEL);
2755 policy = rcu_dereference(state->policy);
2756 policydb = &policy->policydb;
2757 sidtab = policy->sidtab;
2759 context_init(&usercon);
2762 fromcon = sidtab_search(sidtab, fromsid);
2767 user = symtab_search(&policydb->p_users, username);
2771 usercon.user = user->value;
2773 ebitmap_for_each_positive_bit(&user->roles, rnode, i) {
2774 role = policydb->role_val_to_struct[i];
2775 usercon.role = i + 1;
2776 ebitmap_for_each_positive_bit(&role->types, tnode, j) {
2777 usercon.type = j + 1;
2779 if (mls_setup_user_range(policydb, fromcon, user,
2783 rc = sidtab_context_to_sid(sidtab, &usercon, &sid);
2784 if (rc == -ESTALE) {
2790 if (mynel < maxnel) {
2791 mysids[mynel++] = sid;
2795 mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
2798 memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
2801 mysids[mynel++] = sid;
2814 mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);
2819 for (i = 0, j = 0; i < mynel; i++) {
2820 struct av_decision dummy_avd;
2821 rc = avc_has_perm_noaudit(state,
2823 SECCLASS_PROCESS, /* kernel value */
2824 PROCESS__TRANSITION, AVC_STRICT,
2827 mysids2[j++] = mysids[i];
2837 * __security_genfs_sid - Helper to obtain a SID for a file in a filesystem
2838 * @fstype: filesystem type
2839 * @path: path from root of mount
2840 * @sclass: file security class
2841 * @sid: SID for path
2843 * Obtain a SID to use for a file in a filesystem that
2844 * cannot support xattr or use a fixed labeling behavior like
2845 * transition SIDs or task SIDs.
2847 * WARNING: This function may return -ESTALE, indicating that the caller
2848 * must retry the operation after re-acquiring the policy pointer!
2850 static inline int __security_genfs_sid(struct selinux_policy *policy,
2856 struct policydb *policydb = &policy->policydb;
2857 struct sidtab *sidtab = policy->sidtab;
2860 struct genfs *genfs;
2864 while (path[0] == '/' && path[1] == '/')
2867 sclass = unmap_class(&policy->map, orig_sclass);
2868 *sid = SECINITSID_UNLABELED;
2870 for (genfs = policydb->genfs; genfs; genfs = genfs->next) {
2871 cmp = strcmp(fstype, genfs->fstype);
2880 for (c = genfs->head; c; c = c->next) {
2881 len = strlen(c->u.name);
2882 if ((!c->v.sclass || sclass == c->v.sclass) &&
2883 (strncmp(c->u.name, path, len) == 0))
2892 rc = sidtab_context_to_sid(sidtab, &c->context[0], &c->sid[0]);
2904 * security_genfs_sid - Obtain a SID for a file in a filesystem
2905 * @fstype: filesystem type
2906 * @path: path from root of mount
2907 * @sclass: file security class
2908 * @sid: SID for path
2910 * Acquire policy_rwlock before calling __security_genfs_sid() and release
2913 int security_genfs_sid(struct selinux_state *state,
2919 struct selinux_policy *policy;
2922 if (!selinux_initialized(state)) {
2923 *sid = SECINITSID_UNLABELED;
2929 policy = rcu_dereference(state->policy);
2930 retval = __security_genfs_sid(policy, fstype, path,
2933 } while (retval == -ESTALE);
2937 int selinux_policy_genfs_sid(struct selinux_policy *policy,
2943 /* no lock required, policy is not yet accessible by other threads */
2944 return __security_genfs_sid(policy, fstype, path, orig_sclass, sid);
2948 * security_fs_use - Determine how to handle labeling for a filesystem.
2949 * @sb: superblock in question
2951 int security_fs_use(struct selinux_state *state, struct super_block *sb)
2953 struct selinux_policy *policy;
2954 struct policydb *policydb;
2955 struct sidtab *sidtab;
2958 struct superblock_security_struct *sbsec = sb->s_security;
2959 const char *fstype = sb->s_type->name;
2961 if (!selinux_initialized(state)) {
2962 sbsec->behavior = SECURITY_FS_USE_NONE;
2963 sbsec->sid = SECINITSID_UNLABELED;
2970 policy = rcu_dereference(state->policy);
2971 policydb = &policy->policydb;
2972 sidtab = policy->sidtab;
2974 c = policydb->ocontexts[OCON_FSUSE];
2976 if (strcmp(fstype, c->u.name) == 0)
2982 sbsec->behavior = c->v.behavior;
2984 rc = sidtab_context_to_sid(sidtab, &c->context[0],
2986 if (rc == -ESTALE) {
2993 sbsec->sid = c->sid[0];
2995 rc = __security_genfs_sid(policy, fstype, "/",
2996 SECCLASS_DIR, &sbsec->sid);
2997 if (rc == -ESTALE) {
3002 sbsec->behavior = SECURITY_FS_USE_NONE;
3005 sbsec->behavior = SECURITY_FS_USE_GENFS;
3014 int security_get_bools(struct selinux_policy *policy,
3015 u32 *len, char ***names, int **values)
3017 struct policydb *policydb;
3021 policydb = &policy->policydb;
3027 *len = policydb->p_bools.nprim;
3032 *names = kcalloc(*len, sizeof(char *), GFP_ATOMIC);
3037 *values = kcalloc(*len, sizeof(int), GFP_ATOMIC);
3041 for (i = 0; i < *len; i++) {
3042 (*values)[i] = policydb->bool_val_to_struct[i]->state;
3045 (*names)[i] = kstrdup(sym_name(policydb, SYM_BOOLS, i),
3055 for (i = 0; i < *len; i++)
3067 int security_set_bools(struct selinux_state *state, u32 len, int *values)
3069 struct selinux_policy *newpolicy, *oldpolicy;
3073 if (!selinux_initialized(state))
3076 oldpolicy = rcu_dereference_protected(state->policy,
3077 lockdep_is_held(&state->policy_mutex));
3079 /* Consistency check on number of booleans, should never fail */
3080 if (WARN_ON(len != oldpolicy->policydb.p_bools.nprim))
3083 newpolicy = kmemdup(oldpolicy, sizeof(*newpolicy), GFP_KERNEL);
3088 * Deep copy only the parts of the policydb that might be
3089 * modified as a result of changing booleans.
3091 rc = cond_policydb_dup(&newpolicy->policydb, &oldpolicy->policydb);
3097 /* Update the boolean states in the copy */
3098 for (i = 0; i < len; i++) {
3099 int new_state = !!values[i];
3100 int old_state = newpolicy->policydb.bool_val_to_struct[i]->state;
3102 if (new_state != old_state) {
3103 audit_log(audit_context(), GFP_ATOMIC,
3104 AUDIT_MAC_CONFIG_CHANGE,
3105 "bool=%s val=%d old_val=%d auid=%u ses=%u",
3106 sym_name(&newpolicy->policydb, SYM_BOOLS, i),
3109 from_kuid(&init_user_ns, audit_get_loginuid(current)),
3110 audit_get_sessionid(current));
3111 newpolicy->policydb.bool_val_to_struct[i]->state = new_state;
3115 /* Re-evaluate the conditional rules in the copy */
3116 evaluate_cond_nodes(&newpolicy->policydb);
3118 /* Set latest granting seqno for new policy */
3119 newpolicy->latest_granting = oldpolicy->latest_granting + 1;
3120 seqno = newpolicy->latest_granting;
3122 /* Install the new policy */
3123 rcu_assign_pointer(state->policy, newpolicy);
3126 * Free the conditional portions of the old policydb
3127 * that were copied for the new policy, and the oldpolicy
3128 * structure itself but not what it references.
3131 selinux_policy_cond_free(oldpolicy);
3133 /* Notify others of the policy change */
3134 selinux_notify_policy_change(state, seqno);
3138 int security_get_bool_value(struct selinux_state *state,
3141 struct selinux_policy *policy;
3142 struct policydb *policydb;
3146 if (!selinux_initialized(state))
3150 policy = rcu_dereference(state->policy);
3151 policydb = &policy->policydb;
3154 len = policydb->p_bools.nprim;
3158 rc = policydb->bool_val_to_struct[index]->state;
3164 static int security_preserve_bools(struct selinux_policy *oldpolicy,
3165 struct selinux_policy *newpolicy)
3167 int rc, *bvalues = NULL;
3168 char **bnames = NULL;
3169 struct cond_bool_datum *booldatum;
3172 rc = security_get_bools(oldpolicy, &nbools, &bnames, &bvalues);
3175 for (i = 0; i < nbools; i++) {
3176 booldatum = symtab_search(&newpolicy->policydb.p_bools,
3179 booldatum->state = bvalues[i];
3181 evaluate_cond_nodes(&newpolicy->policydb);
3185 for (i = 0; i < nbools; i++)
3194 * security_sid_mls_copy() - computes a new sid based on the given
3195 * sid and the mls portion of mls_sid.
3197 int security_sid_mls_copy(struct selinux_state *state,
3198 u32 sid, u32 mls_sid, u32 *new_sid)
3200 struct selinux_policy *policy;
3201 struct policydb *policydb;
3202 struct sidtab *sidtab;
3203 struct context *context1;
3204 struct context *context2;
3205 struct context newcon;
3210 if (!selinux_initialized(state)) {
3217 context_init(&newcon);
3220 policy = rcu_dereference(state->policy);
3221 policydb = &policy->policydb;
3222 sidtab = policy->sidtab;
3224 if (!policydb->mls_enabled) {
3230 context1 = sidtab_search(sidtab, sid);
3232 pr_err("SELinux: %s: unrecognized SID %d\n",
3238 context2 = sidtab_search(sidtab, mls_sid);
3240 pr_err("SELinux: %s: unrecognized SID %d\n",
3245 newcon.user = context1->user;
3246 newcon.role = context1->role;
3247 newcon.type = context1->type;
3248 rc = mls_context_cpy(&newcon, context2);
3252 /* Check the validity of the new context. */
3253 if (!policydb_context_isvalid(policydb, &newcon)) {
3254 rc = convert_context_handle_invalid_context(state, policydb,
3257 if (!context_struct_to_string(policydb, &newcon, &s,
3259 struct audit_buffer *ab;
3261 ab = audit_log_start(audit_context(),
3264 audit_log_format(ab,
3265 "op=security_sid_mls_copy invalid_context=");
3266 /* don't record NUL with untrusted strings */
3267 audit_log_n_untrustedstring(ab, s, len - 1);
3274 rc = sidtab_context_to_sid(sidtab, &newcon, new_sid);
3275 if (rc == -ESTALE) {
3277 context_destroy(&newcon);
3282 context_destroy(&newcon);
3287 * security_net_peersid_resolve - Compare and resolve two network peer SIDs
3288 * @nlbl_sid: NetLabel SID
3289 * @nlbl_type: NetLabel labeling protocol type
3290 * @xfrm_sid: XFRM SID
3293 * Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be
3294 * resolved into a single SID it is returned via @peer_sid and the function
3295 * returns zero. Otherwise @peer_sid is set to SECSID_NULL and the function
3296 * returns a negative value. A table summarizing the behavior is below:
3298 * | function return | @sid
3299 * ------------------------------+-----------------+-----------------
3300 * no peer labels | 0 | SECSID_NULL
3301 * single peer label | 0 | <peer_label>
3302 * multiple, consistent labels | 0 | <peer_label>
3303 * multiple, inconsistent labels | -<errno> | SECSID_NULL
3306 int security_net_peersid_resolve(struct selinux_state *state,
3307 u32 nlbl_sid, u32 nlbl_type,
3311 struct selinux_policy *policy;
3312 struct policydb *policydb;
3313 struct sidtab *sidtab;
3315 struct context *nlbl_ctx;
3316 struct context *xfrm_ctx;
3318 *peer_sid = SECSID_NULL;
3320 /* handle the common (which also happens to be the set of easy) cases
3321 * right away, these two if statements catch everything involving a
3322 * single or absent peer SID/label */
3323 if (xfrm_sid == SECSID_NULL) {
3324 *peer_sid = nlbl_sid;
3327 /* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a "fallback" label
3328 * and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label
3330 if (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) {
3331 *peer_sid = xfrm_sid;
3335 if (!selinux_initialized(state))
3339 policy = rcu_dereference(state->policy);
3340 policydb = &policy->policydb;
3341 sidtab = policy->sidtab;
3344 * We don't need to check initialized here since the only way both
3345 * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the
3346 * security server was initialized and state->initialized was true.
3348 if (!policydb->mls_enabled) {
3354 nlbl_ctx = sidtab_search(sidtab, nlbl_sid);
3356 pr_err("SELinux: %s: unrecognized SID %d\n",
3357 __func__, nlbl_sid);
3361 xfrm_ctx = sidtab_search(sidtab, xfrm_sid);
3363 pr_err("SELinux: %s: unrecognized SID %d\n",
3364 __func__, xfrm_sid);
3367 rc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES);
3371 /* at present NetLabel SIDs/labels really only carry MLS
3372 * information so if the MLS portion of the NetLabel SID
3373 * matches the MLS portion of the labeled XFRM SID/label
3374 * then pass along the XFRM SID as it is the most
3376 *peer_sid = xfrm_sid;
3382 static int get_classes_callback(void *k, void *d, void *args)
3384 struct class_datum *datum = d;
3385 char *name = k, **classes = args;
3386 int value = datum->value - 1;
3388 classes[value] = kstrdup(name, GFP_ATOMIC);
3389 if (!classes[value])
3395 int security_get_classes(struct selinux_policy *policy,
3396 char ***classes, int *nclasses)
3398 struct policydb *policydb;
3401 policydb = &policy->policydb;
3404 *nclasses = policydb->p_classes.nprim;
3405 *classes = kcalloc(*nclasses, sizeof(**classes), GFP_ATOMIC);
3409 rc = hashtab_map(&policydb->p_classes.table, get_classes_callback,
3413 for (i = 0; i < *nclasses; i++)
3414 kfree((*classes)[i]);
3422 static int get_permissions_callback(void *k, void *d, void *args)
3424 struct perm_datum *datum = d;
3425 char *name = k, **perms = args;
3426 int value = datum->value - 1;
3428 perms[value] = kstrdup(name, GFP_ATOMIC);
3435 int security_get_permissions(struct selinux_policy *policy,
3436 char *class, char ***perms, int *nperms)
3438 struct policydb *policydb;
3440 struct class_datum *match;
3442 policydb = &policy->policydb;
3445 match = symtab_search(&policydb->p_classes, class);
3447 pr_err("SELinux: %s: unrecognized class %s\n",
3453 *nperms = match->permissions.nprim;
3454 *perms = kcalloc(*nperms, sizeof(**perms), GFP_ATOMIC);
3458 if (match->comdatum) {
3459 rc = hashtab_map(&match->comdatum->permissions.table,
3460 get_permissions_callback, *perms);
3465 rc = hashtab_map(&match->permissions.table, get_permissions_callback,
3474 for (i = 0; i < *nperms; i++)
3480 int security_get_reject_unknown(struct selinux_state *state)
3482 struct selinux_policy *policy;
3485 if (!selinux_initialized(state))
3489 policy = rcu_dereference(state->policy);
3490 value = policy->policydb.reject_unknown;
3495 int security_get_allow_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.allow_unknown;
3511 * security_policycap_supported - Check for a specific policy capability
3512 * @req_cap: capability
3515 * This function queries the currently loaded policy to see if it supports the
3516 * capability specified by @req_cap. Returns true (1) if the capability is
3517 * supported, false (0) if it isn't supported.
3520 int security_policycap_supported(struct selinux_state *state,
3521 unsigned int req_cap)
3523 struct selinux_policy *policy;
3526 if (!selinux_initialized(state))
3530 policy = rcu_dereference(state->policy);
3531 rc = ebitmap_get_bit(&policy->policydb.policycaps, req_cap);
3537 struct selinux_audit_rule {
3539 struct context au_ctxt;
3542 void selinux_audit_rule_free(void *vrule)
3544 struct selinux_audit_rule *rule = vrule;
3547 context_destroy(&rule->au_ctxt);
3552 int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule)
3554 struct selinux_state *state = &selinux_state;
3555 struct selinux_policy *policy;
3556 struct policydb *policydb;
3557 struct selinux_audit_rule *tmprule;
3558 struct role_datum *roledatum;
3559 struct type_datum *typedatum;
3560 struct user_datum *userdatum;
3561 struct selinux_audit_rule **rule = (struct selinux_audit_rule **)vrule;
3566 if (!selinux_initialized(state))
3570 case AUDIT_SUBJ_USER:
3571 case AUDIT_SUBJ_ROLE:
3572 case AUDIT_SUBJ_TYPE:
3573 case AUDIT_OBJ_USER:
3574 case AUDIT_OBJ_ROLE:
3575 case AUDIT_OBJ_TYPE:
3576 /* only 'equals' and 'not equals' fit user, role, and type */
3577 if (op != Audit_equal && op != Audit_not_equal)
3580 case AUDIT_SUBJ_SEN:
3581 case AUDIT_SUBJ_CLR:
3582 case AUDIT_OBJ_LEV_LOW:
3583 case AUDIT_OBJ_LEV_HIGH:
3584 /* we do not allow a range, indicated by the presence of '-' */
3585 if (strchr(rulestr, '-'))
3589 /* only the above fields are valid */
3593 tmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL);
3597 context_init(&tmprule->au_ctxt);
3600 policy = rcu_dereference(state->policy);
3601 policydb = &policy->policydb;
3603 tmprule->au_seqno = policy->latest_granting;
3606 case AUDIT_SUBJ_USER:
3607 case AUDIT_OBJ_USER:
3609 userdatum = symtab_search(&policydb->p_users, rulestr);
3612 tmprule->au_ctxt.user = userdatum->value;
3614 case AUDIT_SUBJ_ROLE:
3615 case AUDIT_OBJ_ROLE:
3617 roledatum = symtab_search(&policydb->p_roles, rulestr);
3620 tmprule->au_ctxt.role = roledatum->value;
3622 case AUDIT_SUBJ_TYPE:
3623 case AUDIT_OBJ_TYPE:
3625 typedatum = symtab_search(&policydb->p_types, rulestr);
3628 tmprule->au_ctxt.type = typedatum->value;
3630 case AUDIT_SUBJ_SEN:
3631 case AUDIT_SUBJ_CLR:
3632 case AUDIT_OBJ_LEV_LOW:
3633 case AUDIT_OBJ_LEV_HIGH:
3634 rc = mls_from_string(policydb, rulestr, &tmprule->au_ctxt,
3645 selinux_audit_rule_free(tmprule);
3654 /* Check to see if the rule contains any selinux fields */
3655 int selinux_audit_rule_known(struct audit_krule *rule)
3659 for (i = 0; i < rule->field_count; i++) {
3660 struct audit_field *f = &rule->fields[i];
3662 case AUDIT_SUBJ_USER:
3663 case AUDIT_SUBJ_ROLE:
3664 case AUDIT_SUBJ_TYPE:
3665 case AUDIT_SUBJ_SEN:
3666 case AUDIT_SUBJ_CLR:
3667 case AUDIT_OBJ_USER:
3668 case AUDIT_OBJ_ROLE:
3669 case AUDIT_OBJ_TYPE:
3670 case AUDIT_OBJ_LEV_LOW:
3671 case AUDIT_OBJ_LEV_HIGH:
3679 int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule)
3681 struct selinux_state *state = &selinux_state;
3682 struct selinux_policy *policy;
3683 struct context *ctxt;
3684 struct mls_level *level;
3685 struct selinux_audit_rule *rule = vrule;
3688 if (unlikely(!rule)) {
3689 WARN_ONCE(1, "selinux_audit_rule_match: missing rule\n");
3693 if (!selinux_initialized(state))
3698 policy = rcu_dereference(state->policy);
3700 if (rule->au_seqno < policy->latest_granting) {
3705 ctxt = sidtab_search(policy->sidtab, sid);
3706 if (unlikely(!ctxt)) {
3707 WARN_ONCE(1, "selinux_audit_rule_match: unrecognized SID %d\n",
3713 /* a field/op pair that is not caught here will simply fall through
3716 case AUDIT_SUBJ_USER:
3717 case AUDIT_OBJ_USER:
3720 match = (ctxt->user == rule->au_ctxt.user);
3722 case Audit_not_equal:
3723 match = (ctxt->user != rule->au_ctxt.user);
3727 case AUDIT_SUBJ_ROLE:
3728 case AUDIT_OBJ_ROLE:
3731 match = (ctxt->role == rule->au_ctxt.role);
3733 case Audit_not_equal:
3734 match = (ctxt->role != rule->au_ctxt.role);
3738 case AUDIT_SUBJ_TYPE:
3739 case AUDIT_OBJ_TYPE:
3742 match = (ctxt->type == rule->au_ctxt.type);
3744 case Audit_not_equal:
3745 match = (ctxt->type != rule->au_ctxt.type);
3749 case AUDIT_SUBJ_SEN:
3750 case AUDIT_SUBJ_CLR:
3751 case AUDIT_OBJ_LEV_LOW:
3752 case AUDIT_OBJ_LEV_HIGH:
3753 level = ((field == AUDIT_SUBJ_SEN ||
3754 field == AUDIT_OBJ_LEV_LOW) ?
3755 &ctxt->range.level[0] : &ctxt->range.level[1]);
3758 match = mls_level_eq(&rule->au_ctxt.range.level[0],
3761 case Audit_not_equal:
3762 match = !mls_level_eq(&rule->au_ctxt.range.level[0],
3766 match = (mls_level_dom(&rule->au_ctxt.range.level[0],
3768 !mls_level_eq(&rule->au_ctxt.range.level[0],
3772 match = mls_level_dom(&rule->au_ctxt.range.level[0],
3776 match = (mls_level_dom(level,
3777 &rule->au_ctxt.range.level[0]) &&
3778 !mls_level_eq(level,
3779 &rule->au_ctxt.range.level[0]));
3782 match = mls_level_dom(level,
3783 &rule->au_ctxt.range.level[0]);
3793 static int aurule_avc_callback(u32 event)
3795 if (event == AVC_CALLBACK_RESET)
3796 return audit_update_lsm_rules();
3800 static int __init aurule_init(void)
3804 err = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET);
3806 panic("avc_add_callback() failed, error %d\n", err);
3810 __initcall(aurule_init);
3812 #ifdef CONFIG_NETLABEL
3814 * security_netlbl_cache_add - Add an entry to the NetLabel cache
3815 * @secattr: the NetLabel packet security attributes
3816 * @sid: the SELinux SID
3819 * Attempt to cache the context in @ctx, which was derived from the packet in
3820 * @skb, in the NetLabel subsystem cache. This function assumes @secattr has
3821 * already been initialized.
3824 static void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr,
3829 sid_cache = kmalloc(sizeof(*sid_cache), GFP_ATOMIC);
3830 if (sid_cache == NULL)
3832 secattr->cache = netlbl_secattr_cache_alloc(GFP_ATOMIC);
3833 if (secattr->cache == NULL) {
3839 secattr->cache->free = kfree;
3840 secattr->cache->data = sid_cache;
3841 secattr->flags |= NETLBL_SECATTR_CACHE;
3845 * security_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID
3846 * @secattr: the NetLabel packet security attributes
3847 * @sid: the SELinux SID
3850 * Convert the given NetLabel security attributes in @secattr into a
3851 * SELinux SID. If the @secattr field does not contain a full SELinux
3852 * SID/context then use SECINITSID_NETMSG as the foundation. If possible the
3853 * 'cache' field of @secattr is set and the CACHE flag is set; this is to
3854 * allow the @secattr to be used by NetLabel to cache the secattr to SID
3855 * conversion for future lookups. Returns zero on success, negative values on
3859 int security_netlbl_secattr_to_sid(struct selinux_state *state,
3860 struct netlbl_lsm_secattr *secattr,
3863 struct selinux_policy *policy;
3864 struct policydb *policydb;
3865 struct sidtab *sidtab;
3867 struct context *ctx;
3868 struct context ctx_new;
3870 if (!selinux_initialized(state)) {
3878 policy = rcu_dereference(state->policy);
3879 policydb = &policy->policydb;
3880 sidtab = policy->sidtab;
3882 if (secattr->flags & NETLBL_SECATTR_CACHE)
3883 *sid = *(u32 *)secattr->cache->data;
3884 else if (secattr->flags & NETLBL_SECATTR_SECID)
3885 *sid = secattr->attr.secid;
3886 else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) {
3888 ctx = sidtab_search(sidtab, SECINITSID_NETMSG);
3892 context_init(&ctx_new);
3893 ctx_new.user = ctx->user;
3894 ctx_new.role = ctx->role;
3895 ctx_new.type = ctx->type;
3896 mls_import_netlbl_lvl(policydb, &ctx_new, secattr);
3897 if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
3898 rc = mls_import_netlbl_cat(policydb, &ctx_new, secattr);
3903 if (!mls_context_isvalid(policydb, &ctx_new)) {
3904 ebitmap_destroy(&ctx_new.range.level[0].cat);
3908 rc = sidtab_context_to_sid(sidtab, &ctx_new, sid);
3909 ebitmap_destroy(&ctx_new.range.level[0].cat);
3910 if (rc == -ESTALE) {
3917 security_netlbl_cache_add(secattr, *sid);
3927 * security_netlbl_sid_to_secattr - Convert a SELinux SID to a NetLabel secattr
3928 * @sid: the SELinux SID
3929 * @secattr: the NetLabel packet security attributes
3932 * Convert the given SELinux SID in @sid into a NetLabel security attribute.
3933 * Returns zero on success, negative values on failure.
3936 int security_netlbl_sid_to_secattr(struct selinux_state *state,
3937 u32 sid, struct netlbl_lsm_secattr *secattr)
3939 struct selinux_policy *policy;
3940 struct policydb *policydb;
3942 struct context *ctx;
3944 if (!selinux_initialized(state))
3948 policy = rcu_dereference(state->policy);
3949 policydb = &policy->policydb;
3952 ctx = sidtab_search(policy->sidtab, sid);
3957 secattr->domain = kstrdup(sym_name(policydb, SYM_TYPES, ctx->type - 1),
3959 if (secattr->domain == NULL)
3962 secattr->attr.secid = sid;
3963 secattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID;
3964 mls_export_netlbl_lvl(policydb, ctx, secattr);
3965 rc = mls_export_netlbl_cat(policydb, ctx, secattr);
3970 #endif /* CONFIG_NETLABEL */
3973 * __security_read_policy - read the policy.
3974 * @policy: SELinux policy
3975 * @data: binary policy data
3976 * @len: length of data in bytes
3979 static int __security_read_policy(struct selinux_policy *policy,
3980 void *data, size_t *len)
3983 struct policy_file fp;
3988 rc = policydb_write(&policy->policydb, &fp);
3992 *len = (unsigned long)fp.data - (unsigned long)data;
3997 * security_read_policy - read the policy.
3998 * @state: selinux_state
3999 * @data: binary policy data
4000 * @len: length of data in bytes
4003 int security_read_policy(struct selinux_state *state,
4004 void **data, size_t *len)
4006 struct selinux_policy *policy;
4008 policy = rcu_dereference_protected(
4009 state->policy, lockdep_is_held(&state->policy_mutex));
4013 *len = policy->policydb.len;
4014 *data = vmalloc_user(*len);
4018 return __security_read_policy(policy, *data, len);
4022 * security_read_state_kernel - read the policy.
4023 * @state: selinux_state
4024 * @data: binary policy data
4025 * @len: length of data in bytes
4027 * Allocates kernel memory for reading SELinux policy.
4028 * This function is for internal use only and should not
4029 * be used for returning data to user space.
4031 * This function must be called with policy_mutex held.
4033 int security_read_state_kernel(struct selinux_state *state,
4034 void **data, size_t *len)
4036 struct selinux_policy *policy;
4038 policy = rcu_dereference_protected(
4039 state->policy, lockdep_is_held(&state->policy_mutex));
4043 *len = policy->policydb.len;
4044 *data = vmalloc(*len);
4048 return __security_read_policy(policy, *data, len);