1 // SPDX-License-Identifier: GPL-2.0-only
3 * Implementation of the security services.
5 * Authors : Stephen Smalley, <stephen.smalley.work@gmail.com>
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 selinux_policy_convert_data {
72 struct convert_context_args args;
73 struct sidtab_convert_params sidtab_params;
76 /* Forward declaration. */
77 static int context_struct_to_string(struct policydb *policydb,
78 struct context *context,
82 static int sidtab_entry_to_string(struct policydb *policydb,
83 struct sidtab *sidtab,
84 struct sidtab_entry *entry,
88 static void context_struct_compute_av(struct policydb *policydb,
89 struct context *scontext,
90 struct context *tcontext,
92 struct av_decision *avd,
93 struct extended_perms *xperms);
95 static int selinux_set_mapping(struct policydb *pol,
96 const struct security_class_mapping *map,
97 struct selinux_map *out_map)
100 bool print_unknown_handle = false;
102 /* Find number of classes in the input mapping */
109 /* Allocate space for the class records, plus one for class zero */
110 out_map->mapping = kcalloc(++i, sizeof(*out_map->mapping), GFP_ATOMIC);
111 if (!out_map->mapping)
114 /* Store the raw class and permission values */
116 while (map[j].name) {
117 const struct security_class_mapping *p_in = map + (j++);
118 struct selinux_mapping *p_out = out_map->mapping + j;
121 /* An empty class string skips ahead */
122 if (!strcmp(p_in->name, "")) {
123 p_out->num_perms = 0;
127 p_out->value = string_to_security_class(pol, p_in->name);
129 pr_info("SELinux: Class %s not defined in policy.\n",
131 if (pol->reject_unknown)
133 p_out->num_perms = 0;
134 print_unknown_handle = true;
139 while (p_in->perms[k]) {
140 /* An empty permission string skips ahead */
141 if (!*p_in->perms[k]) {
145 p_out->perms[k] = string_to_av_perm(pol, p_out->value,
147 if (!p_out->perms[k]) {
148 pr_info("SELinux: Permission %s in class %s not defined in policy.\n",
149 p_in->perms[k], p_in->name);
150 if (pol->reject_unknown)
152 print_unknown_handle = true;
157 p_out->num_perms = k;
160 if (print_unknown_handle)
161 pr_info("SELinux: the above unknown classes and permissions will be %s\n",
162 pol->allow_unknown ? "allowed" : "denied");
167 kfree(out_map->mapping);
168 out_map->mapping = NULL;
173 * Get real, policy values from mapped values
176 static u16 unmap_class(struct selinux_map *map, u16 tclass)
178 if (tclass < map->size)
179 return map->mapping[tclass].value;
185 * Get kernel value for class from its policy value
187 static u16 map_class(struct selinux_map *map, u16 pol_value)
191 for (i = 1; i < map->size; i++) {
192 if (map->mapping[i].value == pol_value)
196 return SECCLASS_NULL;
199 static void map_decision(struct selinux_map *map,
200 u16 tclass, struct av_decision *avd,
203 if (tclass < map->size) {
204 struct selinux_mapping *mapping = &map->mapping[tclass];
205 unsigned int i, n = mapping->num_perms;
208 for (i = 0, result = 0; i < n; i++) {
209 if (avd->allowed & mapping->perms[i])
211 if (allow_unknown && !mapping->perms[i])
214 avd->allowed = result;
216 for (i = 0, result = 0; i < n; i++)
217 if (avd->auditallow & mapping->perms[i])
219 avd->auditallow = result;
221 for (i = 0, result = 0; i < n; i++) {
222 if (avd->auditdeny & mapping->perms[i])
224 if (!allow_unknown && !mapping->perms[i])
228 * In case the kernel has a bug and requests a permission
229 * between num_perms and the maximum permission number, we
230 * should audit that denial
232 for (; i < (sizeof(u32)*8); i++)
234 avd->auditdeny = result;
238 int security_mls_enabled(void)
241 struct selinux_policy *policy;
243 if (!selinux_initialized())
247 policy = rcu_dereference(selinux_state.policy);
248 mls_enabled = policy->policydb.mls_enabled;
254 * Return the boolean value of a constraint expression
255 * when it is applied to the specified source and target
258 * xcontext is a special beast... It is used by the validatetrans rules
259 * only. For these rules, scontext is the context before the transition,
260 * tcontext is the context after the transition, and xcontext is the context
261 * of the process performing the transition. All other callers of
262 * constraint_expr_eval should pass in NULL for xcontext.
264 static int constraint_expr_eval(struct policydb *policydb,
265 struct context *scontext,
266 struct context *tcontext,
267 struct context *xcontext,
268 struct constraint_expr *cexpr)
272 struct role_datum *r1, *r2;
273 struct mls_level *l1, *l2;
274 struct constraint_expr *e;
275 int s[CEXPR_MAXDEPTH];
278 for (e = cexpr; e; e = e->next) {
279 switch (e->expr_type) {
295 if (sp == (CEXPR_MAXDEPTH - 1))
299 val1 = scontext->user;
300 val2 = tcontext->user;
303 val1 = scontext->type;
304 val2 = tcontext->type;
307 val1 = scontext->role;
308 val2 = tcontext->role;
309 r1 = policydb->role_val_to_struct[val1 - 1];
310 r2 = policydb->role_val_to_struct[val2 - 1];
313 s[++sp] = ebitmap_get_bit(&r1->dominates,
317 s[++sp] = ebitmap_get_bit(&r2->dominates,
321 s[++sp] = (!ebitmap_get_bit(&r1->dominates,
323 !ebitmap_get_bit(&r2->dominates,
331 l1 = &(scontext->range.level[0]);
332 l2 = &(tcontext->range.level[0]);
335 l1 = &(scontext->range.level[0]);
336 l2 = &(tcontext->range.level[1]);
339 l1 = &(scontext->range.level[1]);
340 l2 = &(tcontext->range.level[0]);
343 l1 = &(scontext->range.level[1]);
344 l2 = &(tcontext->range.level[1]);
347 l1 = &(scontext->range.level[0]);
348 l2 = &(scontext->range.level[1]);
351 l1 = &(tcontext->range.level[0]);
352 l2 = &(tcontext->range.level[1]);
357 s[++sp] = mls_level_eq(l1, l2);
360 s[++sp] = !mls_level_eq(l1, l2);
363 s[++sp] = mls_level_dom(l1, l2);
366 s[++sp] = mls_level_dom(l2, l1);
369 s[++sp] = mls_level_incomp(l2, l1);
383 s[++sp] = (val1 == val2);
386 s[++sp] = (val1 != val2);
394 if (sp == (CEXPR_MAXDEPTH-1))
397 if (e->attr & CEXPR_TARGET)
399 else if (e->attr & CEXPR_XTARGET) {
406 if (e->attr & CEXPR_USER)
408 else if (e->attr & CEXPR_ROLE)
410 else if (e->attr & CEXPR_TYPE)
419 s[++sp] = ebitmap_get_bit(&e->names, val1 - 1);
422 s[++sp] = !ebitmap_get_bit(&e->names, val1 - 1);
440 * security_dump_masked_av - dumps masked permissions during
441 * security_compute_av due to RBAC, MLS/Constraint and Type bounds.
443 static int dump_masked_av_helper(void *k, void *d, void *args)
445 struct perm_datum *pdatum = d;
446 char **permission_names = args;
448 BUG_ON(pdatum->value < 1 || pdatum->value > 32);
450 permission_names[pdatum->value - 1] = (char *)k;
455 static void security_dump_masked_av(struct policydb *policydb,
456 struct context *scontext,
457 struct context *tcontext,
462 struct common_datum *common_dat;
463 struct class_datum *tclass_dat;
464 struct audit_buffer *ab;
466 char *scontext_name = NULL;
467 char *tcontext_name = NULL;
468 char *permission_names[32];
471 bool need_comma = false;
476 tclass_name = sym_name(policydb, SYM_CLASSES, tclass - 1);
477 tclass_dat = policydb->class_val_to_struct[tclass - 1];
478 common_dat = tclass_dat->comdatum;
480 /* init permission_names */
482 hashtab_map(&common_dat->permissions.table,
483 dump_masked_av_helper, permission_names) < 0)
486 if (hashtab_map(&tclass_dat->permissions.table,
487 dump_masked_av_helper, permission_names) < 0)
490 /* get scontext/tcontext in text form */
491 if (context_struct_to_string(policydb, scontext,
492 &scontext_name, &length) < 0)
495 if (context_struct_to_string(policydb, tcontext,
496 &tcontext_name, &length) < 0)
499 /* audit a message */
500 ab = audit_log_start(audit_context(),
501 GFP_ATOMIC, AUDIT_SELINUX_ERR);
505 audit_log_format(ab, "op=security_compute_av reason=%s "
506 "scontext=%s tcontext=%s tclass=%s perms=",
507 reason, scontext_name, tcontext_name, tclass_name);
509 for (index = 0; index < 32; index++) {
510 u32 mask = (1 << index);
512 if ((mask & permissions) == 0)
515 audit_log_format(ab, "%s%s",
516 need_comma ? "," : "",
517 permission_names[index]
518 ? permission_names[index] : "????");
523 /* release scontext/tcontext */
524 kfree(tcontext_name);
525 kfree(scontext_name);
529 * security_boundary_permission - drops violated permissions
530 * on boundary constraint.
532 static void type_attribute_bounds_av(struct policydb *policydb,
533 struct context *scontext,
534 struct context *tcontext,
536 struct av_decision *avd)
538 struct context lo_scontext;
539 struct context lo_tcontext, *tcontextp = tcontext;
540 struct av_decision lo_avd;
541 struct type_datum *source;
542 struct type_datum *target;
545 source = policydb->type_val_to_struct[scontext->type - 1];
551 target = policydb->type_val_to_struct[tcontext->type - 1];
554 memset(&lo_avd, 0, sizeof(lo_avd));
556 memcpy(&lo_scontext, scontext, sizeof(lo_scontext));
557 lo_scontext.type = source->bounds;
559 if (target->bounds) {
560 memcpy(&lo_tcontext, tcontext, sizeof(lo_tcontext));
561 lo_tcontext.type = target->bounds;
562 tcontextp = &lo_tcontext;
565 context_struct_compute_av(policydb, &lo_scontext,
571 masked = ~lo_avd.allowed & avd->allowed;
574 return; /* no masked permission */
576 /* mask violated permissions */
577 avd->allowed &= ~masked;
579 /* audit masked permissions */
580 security_dump_masked_av(policydb, scontext, tcontext,
581 tclass, masked, "bounds");
585 * flag which drivers have permissions
586 * only looking for ioctl based extended permissions
588 void services_compute_xperms_drivers(
589 struct extended_perms *xperms,
590 struct avtab_node *node)
594 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
595 /* if one or more driver has all permissions allowed */
596 for (i = 0; i < ARRAY_SIZE(xperms->drivers.p); i++)
597 xperms->drivers.p[i] |= node->datum.u.xperms->perms.p[i];
598 } else if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
599 /* if allowing permissions within a driver */
600 security_xperm_set(xperms->drivers.p,
601 node->datum.u.xperms->driver);
608 * Compute access vectors and extended permissions based on a context
609 * structure pair for the permissions in a particular class.
611 static void context_struct_compute_av(struct policydb *policydb,
612 struct context *scontext,
613 struct context *tcontext,
615 struct av_decision *avd,
616 struct extended_perms *xperms)
618 struct constraint_node *constraint;
619 struct role_allow *ra;
620 struct avtab_key avkey;
621 struct avtab_node *node;
622 struct class_datum *tclass_datum;
623 struct ebitmap *sattr, *tattr;
624 struct ebitmap_node *snode, *tnode;
629 avd->auditdeny = 0xffffffff;
631 memset(&xperms->drivers, 0, sizeof(xperms->drivers));
635 if (unlikely(!tclass || tclass > policydb->p_classes.nprim)) {
636 if (printk_ratelimit())
637 pr_warn("SELinux: Invalid class %hu\n", tclass);
641 tclass_datum = policydb->class_val_to_struct[tclass - 1];
644 * If a specific type enforcement rule was defined for
645 * this permission check, then use it.
647 avkey.target_class = tclass;
648 avkey.specified = AVTAB_AV | AVTAB_XPERMS;
649 sattr = &policydb->type_attr_map_array[scontext->type - 1];
650 tattr = &policydb->type_attr_map_array[tcontext->type - 1];
651 ebitmap_for_each_positive_bit(sattr, snode, i) {
652 ebitmap_for_each_positive_bit(tattr, tnode, j) {
653 avkey.source_type = i + 1;
654 avkey.target_type = j + 1;
655 for (node = avtab_search_node(&policydb->te_avtab,
658 node = avtab_search_node_next(node, avkey.specified)) {
659 if (node->key.specified == AVTAB_ALLOWED)
660 avd->allowed |= node->datum.u.data;
661 else if (node->key.specified == AVTAB_AUDITALLOW)
662 avd->auditallow |= node->datum.u.data;
663 else if (node->key.specified == AVTAB_AUDITDENY)
664 avd->auditdeny &= node->datum.u.data;
665 else if (xperms && (node->key.specified & AVTAB_XPERMS))
666 services_compute_xperms_drivers(xperms, node);
669 /* Check conditional av table for additional permissions */
670 cond_compute_av(&policydb->te_cond_avtab, &avkey,
677 * Remove any permissions prohibited by a constraint (this includes
680 constraint = tclass_datum->constraints;
682 if ((constraint->permissions & (avd->allowed)) &&
683 !constraint_expr_eval(policydb, scontext, tcontext, NULL,
685 avd->allowed &= ~(constraint->permissions);
687 constraint = constraint->next;
691 * If checking process transition permission and the
692 * role is changing, then check the (current_role, new_role)
695 if (tclass == policydb->process_class &&
696 (avd->allowed & policydb->process_trans_perms) &&
697 scontext->role != tcontext->role) {
698 for (ra = policydb->role_allow; ra; ra = ra->next) {
699 if (scontext->role == ra->role &&
700 tcontext->role == ra->new_role)
704 avd->allowed &= ~policydb->process_trans_perms;
708 * If the given source and target types have boundary
709 * constraint, lazy checks have to mask any violated
710 * permission and notice it to userspace via audit.
712 type_attribute_bounds_av(policydb, scontext, tcontext,
716 static int security_validtrans_handle_fail(struct selinux_policy *policy,
717 struct sidtab_entry *oentry,
718 struct sidtab_entry *nentry,
719 struct sidtab_entry *tentry,
722 struct policydb *p = &policy->policydb;
723 struct sidtab *sidtab = policy->sidtab;
724 char *o = NULL, *n = NULL, *t = NULL;
725 u32 olen, nlen, tlen;
727 if (sidtab_entry_to_string(p, sidtab, oentry, &o, &olen))
729 if (sidtab_entry_to_string(p, sidtab, nentry, &n, &nlen))
731 if (sidtab_entry_to_string(p, sidtab, tentry, &t, &tlen))
733 audit_log(audit_context(), GFP_ATOMIC, AUDIT_SELINUX_ERR,
734 "op=security_validate_transition seresult=denied"
735 " oldcontext=%s newcontext=%s taskcontext=%s tclass=%s",
736 o, n, t, sym_name(p, SYM_CLASSES, tclass-1));
742 if (!enforcing_enabled())
747 static int security_compute_validatetrans(u32 oldsid, u32 newsid, u32 tasksid,
748 u16 orig_tclass, bool user)
750 struct selinux_policy *policy;
751 struct policydb *policydb;
752 struct sidtab *sidtab;
753 struct sidtab_entry *oentry;
754 struct sidtab_entry *nentry;
755 struct sidtab_entry *tentry;
756 struct class_datum *tclass_datum;
757 struct constraint_node *constraint;
762 if (!selinux_initialized())
767 policy = rcu_dereference(selinux_state.policy);
768 policydb = &policy->policydb;
769 sidtab = policy->sidtab;
772 tclass = unmap_class(&policy->map, orig_tclass);
774 tclass = orig_tclass;
776 if (!tclass || tclass > policydb->p_classes.nprim) {
780 tclass_datum = policydb->class_val_to_struct[tclass - 1];
782 oentry = sidtab_search_entry(sidtab, oldsid);
784 pr_err("SELinux: %s: unrecognized SID %d\n",
790 nentry = sidtab_search_entry(sidtab, newsid);
792 pr_err("SELinux: %s: unrecognized SID %d\n",
798 tentry = sidtab_search_entry(sidtab, tasksid);
800 pr_err("SELinux: %s: unrecognized SID %d\n",
806 constraint = tclass_datum->validatetrans;
808 if (!constraint_expr_eval(policydb, &oentry->context,
809 &nentry->context, &tentry->context,
814 rc = security_validtrans_handle_fail(policy,
821 constraint = constraint->next;
829 int security_validate_transition_user(u32 oldsid, u32 newsid, u32 tasksid,
832 return security_compute_validatetrans(oldsid, newsid, tasksid,
836 int security_validate_transition(u32 oldsid, u32 newsid, u32 tasksid,
839 return security_compute_validatetrans(oldsid, newsid, tasksid,
844 * security_bounded_transition - check whether the given
845 * transition is directed to bounded, or not.
846 * It returns 0, if @newsid is bounded by @oldsid.
847 * Otherwise, it returns error code.
849 * @oldsid : current security identifier
850 * @newsid : destinated security identifier
852 int security_bounded_transition(u32 old_sid, u32 new_sid)
854 struct selinux_policy *policy;
855 struct policydb *policydb;
856 struct sidtab *sidtab;
857 struct sidtab_entry *old_entry, *new_entry;
858 struct type_datum *type;
862 if (!selinux_initialized())
866 policy = rcu_dereference(selinux_state.policy);
867 policydb = &policy->policydb;
868 sidtab = policy->sidtab;
871 old_entry = sidtab_search_entry(sidtab, old_sid);
873 pr_err("SELinux: %s: unrecognized SID %u\n",
879 new_entry = sidtab_search_entry(sidtab, new_sid);
881 pr_err("SELinux: %s: unrecognized SID %u\n",
887 /* type/domain unchanged */
888 if (old_entry->context.type == new_entry->context.type)
891 index = new_entry->context.type;
893 type = policydb->type_val_to_struct[index - 1];
896 /* not bounded anymore */
901 /* @newsid is bounded by @oldsid */
903 if (type->bounds == old_entry->context.type)
906 index = type->bounds;
910 char *old_name = NULL;
911 char *new_name = NULL;
914 if (!sidtab_entry_to_string(policydb, sidtab, old_entry,
915 &old_name, &length) &&
916 !sidtab_entry_to_string(policydb, sidtab, new_entry,
917 &new_name, &length)) {
918 audit_log(audit_context(),
919 GFP_ATOMIC, AUDIT_SELINUX_ERR,
920 "op=security_bounded_transition "
922 "oldcontext=%s newcontext=%s",
934 static void avd_init(struct selinux_policy *policy, struct av_decision *avd)
938 avd->auditdeny = 0xffffffff;
940 avd->seqno = policy->latest_granting;
946 void services_compute_xperms_decision(struct extended_perms_decision *xpermd,
947 struct avtab_node *node)
951 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
952 if (xpermd->driver != node->datum.u.xperms->driver)
954 } else if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
955 if (!security_xperm_test(node->datum.u.xperms->perms.p,
962 if (node->key.specified == AVTAB_XPERMS_ALLOWED) {
963 xpermd->used |= XPERMS_ALLOWED;
964 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
965 memset(xpermd->allowed->p, 0xff,
966 sizeof(xpermd->allowed->p));
968 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
969 for (i = 0; i < ARRAY_SIZE(xpermd->allowed->p); i++)
970 xpermd->allowed->p[i] |=
971 node->datum.u.xperms->perms.p[i];
973 } else if (node->key.specified == AVTAB_XPERMS_AUDITALLOW) {
974 xpermd->used |= XPERMS_AUDITALLOW;
975 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
976 memset(xpermd->auditallow->p, 0xff,
977 sizeof(xpermd->auditallow->p));
979 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
980 for (i = 0; i < ARRAY_SIZE(xpermd->auditallow->p); i++)
981 xpermd->auditallow->p[i] |=
982 node->datum.u.xperms->perms.p[i];
984 } else if (node->key.specified == AVTAB_XPERMS_DONTAUDIT) {
985 xpermd->used |= XPERMS_DONTAUDIT;
986 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
987 memset(xpermd->dontaudit->p, 0xff,
988 sizeof(xpermd->dontaudit->p));
990 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
991 for (i = 0; i < ARRAY_SIZE(xpermd->dontaudit->p); i++)
992 xpermd->dontaudit->p[i] |=
993 node->datum.u.xperms->perms.p[i];
1000 void security_compute_xperms_decision(u32 ssid,
1004 struct extended_perms_decision *xpermd)
1006 struct selinux_policy *policy;
1007 struct policydb *policydb;
1008 struct sidtab *sidtab;
1010 struct context *scontext, *tcontext;
1011 struct avtab_key avkey;
1012 struct avtab_node *node;
1013 struct ebitmap *sattr, *tattr;
1014 struct ebitmap_node *snode, *tnode;
1017 xpermd->driver = driver;
1019 memset(xpermd->allowed->p, 0, sizeof(xpermd->allowed->p));
1020 memset(xpermd->auditallow->p, 0, sizeof(xpermd->auditallow->p));
1021 memset(xpermd->dontaudit->p, 0, sizeof(xpermd->dontaudit->p));
1024 if (!selinux_initialized())
1027 policy = rcu_dereference(selinux_state.policy);
1028 policydb = &policy->policydb;
1029 sidtab = policy->sidtab;
1031 scontext = sidtab_search(sidtab, ssid);
1033 pr_err("SELinux: %s: unrecognized SID %d\n",
1038 tcontext = sidtab_search(sidtab, tsid);
1040 pr_err("SELinux: %s: unrecognized SID %d\n",
1045 tclass = unmap_class(&policy->map, orig_tclass);
1046 if (unlikely(orig_tclass && !tclass)) {
1047 if (policydb->allow_unknown)
1053 if (unlikely(!tclass || tclass > policydb->p_classes.nprim)) {
1054 pr_warn_ratelimited("SELinux: Invalid class %hu\n", tclass);
1058 avkey.target_class = tclass;
1059 avkey.specified = AVTAB_XPERMS;
1060 sattr = &policydb->type_attr_map_array[scontext->type - 1];
1061 tattr = &policydb->type_attr_map_array[tcontext->type - 1];
1062 ebitmap_for_each_positive_bit(sattr, snode, i) {
1063 ebitmap_for_each_positive_bit(tattr, tnode, j) {
1064 avkey.source_type = i + 1;
1065 avkey.target_type = j + 1;
1066 for (node = avtab_search_node(&policydb->te_avtab,
1069 node = avtab_search_node_next(node, avkey.specified))
1070 services_compute_xperms_decision(xpermd, node);
1072 cond_compute_xperms(&policydb->te_cond_avtab,
1080 memset(xpermd->allowed->p, 0xff, sizeof(xpermd->allowed->p));
1085 * security_compute_av - Compute access vector decisions.
1086 * @ssid: source security identifier
1087 * @tsid: target security identifier
1088 * @orig_tclass: target security class
1089 * @avd: access vector decisions
1090 * @xperms: extended permissions
1092 * Compute a set of access vector decisions based on the
1093 * SID pair (@ssid, @tsid) for the permissions in @tclass.
1095 void security_compute_av(u32 ssid,
1098 struct av_decision *avd,
1099 struct extended_perms *xperms)
1101 struct selinux_policy *policy;
1102 struct policydb *policydb;
1103 struct sidtab *sidtab;
1105 struct context *scontext = NULL, *tcontext = NULL;
1108 policy = rcu_dereference(selinux_state.policy);
1109 avd_init(policy, avd);
1111 if (!selinux_initialized())
1114 policydb = &policy->policydb;
1115 sidtab = policy->sidtab;
1117 scontext = sidtab_search(sidtab, ssid);
1119 pr_err("SELinux: %s: unrecognized SID %d\n",
1124 /* permissive domain? */
1125 if (ebitmap_get_bit(&policydb->permissive_map, scontext->type))
1126 avd->flags |= AVD_FLAGS_PERMISSIVE;
1128 tcontext = sidtab_search(sidtab, tsid);
1130 pr_err("SELinux: %s: unrecognized SID %d\n",
1135 tclass = unmap_class(&policy->map, orig_tclass);
1136 if (unlikely(orig_tclass && !tclass)) {
1137 if (policydb->allow_unknown)
1141 context_struct_compute_av(policydb, scontext, tcontext, tclass, avd,
1143 map_decision(&policy->map, orig_tclass, avd,
1144 policydb->allow_unknown);
1149 avd->allowed = 0xffffffff;
1153 void security_compute_av_user(u32 ssid,
1156 struct av_decision *avd)
1158 struct selinux_policy *policy;
1159 struct policydb *policydb;
1160 struct sidtab *sidtab;
1161 struct context *scontext = NULL, *tcontext = NULL;
1164 policy = rcu_dereference(selinux_state.policy);
1165 avd_init(policy, avd);
1166 if (!selinux_initialized())
1169 policydb = &policy->policydb;
1170 sidtab = policy->sidtab;
1172 scontext = sidtab_search(sidtab, ssid);
1174 pr_err("SELinux: %s: unrecognized SID %d\n",
1179 /* permissive domain? */
1180 if (ebitmap_get_bit(&policydb->permissive_map, scontext->type))
1181 avd->flags |= AVD_FLAGS_PERMISSIVE;
1183 tcontext = sidtab_search(sidtab, tsid);
1185 pr_err("SELinux: %s: unrecognized SID %d\n",
1190 if (unlikely(!tclass)) {
1191 if (policydb->allow_unknown)
1196 context_struct_compute_av(policydb, scontext, tcontext, tclass, avd,
1202 avd->allowed = 0xffffffff;
1207 * Write the security context string representation of
1208 * the context structure `context' into a dynamically
1209 * allocated string of the correct size. Set `*scontext'
1210 * to point to this string and set `*scontext_len' to
1211 * the length of the string.
1213 static int context_struct_to_string(struct policydb *p,
1214 struct context *context,
1215 char **scontext, u32 *scontext_len)
1224 *scontext_len = context->len;
1226 *scontext = kstrdup(context->str, GFP_ATOMIC);
1233 /* Compute the size of the context. */
1234 *scontext_len += strlen(sym_name(p, SYM_USERS, context->user - 1)) + 1;
1235 *scontext_len += strlen(sym_name(p, SYM_ROLES, context->role - 1)) + 1;
1236 *scontext_len += strlen(sym_name(p, SYM_TYPES, context->type - 1)) + 1;
1237 *scontext_len += mls_compute_context_len(p, context);
1242 /* Allocate space for the context; caller must free this space. */
1243 scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
1246 *scontext = scontextp;
1249 * Copy the user name, role name and type name into the context.
1251 scontextp += sprintf(scontextp, "%s:%s:%s",
1252 sym_name(p, SYM_USERS, context->user - 1),
1253 sym_name(p, SYM_ROLES, context->role - 1),
1254 sym_name(p, SYM_TYPES, context->type - 1));
1256 mls_sid_to_context(p, context, &scontextp);
1263 static int sidtab_entry_to_string(struct policydb *p,
1264 struct sidtab *sidtab,
1265 struct sidtab_entry *entry,
1266 char **scontext, u32 *scontext_len)
1268 int rc = sidtab_sid2str_get(sidtab, entry, scontext, scontext_len);
1273 rc = context_struct_to_string(p, &entry->context, scontext,
1275 if (!rc && scontext)
1276 sidtab_sid2str_put(sidtab, entry, *scontext, *scontext_len);
1280 #include "initial_sid_to_string.h"
1282 int security_sidtab_hash_stats(char *page)
1284 struct selinux_policy *policy;
1287 if (!selinux_initialized()) {
1288 pr_err("SELinux: %s: called before initial load_policy\n",
1294 policy = rcu_dereference(selinux_state.policy);
1295 rc = sidtab_hash_stats(policy->sidtab, page);
1301 const char *security_get_initial_sid_context(u32 sid)
1303 if (unlikely(sid > SECINITSID_NUM))
1305 return initial_sid_to_string[sid];
1308 static int security_sid_to_context_core(u32 sid, char **scontext,
1309 u32 *scontext_len, int force,
1312 struct selinux_policy *policy;
1313 struct policydb *policydb;
1314 struct sidtab *sidtab;
1315 struct sidtab_entry *entry;
1322 if (!selinux_initialized()) {
1323 if (sid <= SECINITSID_NUM) {
1325 const char *s = initial_sid_to_string[sid];
1329 *scontext_len = strlen(s) + 1;
1332 scontextp = kmemdup(s, *scontext_len, GFP_ATOMIC);
1335 *scontext = scontextp;
1338 pr_err("SELinux: %s: called before initial "
1339 "load_policy on unknown SID %d\n", __func__, sid);
1343 policy = rcu_dereference(selinux_state.policy);
1344 policydb = &policy->policydb;
1345 sidtab = policy->sidtab;
1348 entry = sidtab_search_entry_force(sidtab, sid);
1350 entry = sidtab_search_entry(sidtab, sid);
1352 pr_err("SELinux: %s: unrecognized SID %d\n",
1357 if (only_invalid && !entry->context.len)
1360 rc = sidtab_entry_to_string(policydb, sidtab, entry, scontext,
1370 * security_sid_to_context - Obtain a context for a given SID.
1371 * @sid: security identifier, SID
1372 * @scontext: security context
1373 * @scontext_len: length in bytes
1375 * Write the string representation of the context associated with @sid
1376 * into a dynamically allocated string of the correct size. Set @scontext
1377 * to point to this string and set @scontext_len to the length of the string.
1379 int security_sid_to_context(u32 sid, char **scontext, u32 *scontext_len)
1381 return security_sid_to_context_core(sid, scontext,
1382 scontext_len, 0, 0);
1385 int security_sid_to_context_force(u32 sid,
1386 char **scontext, u32 *scontext_len)
1388 return security_sid_to_context_core(sid, scontext,
1389 scontext_len, 1, 0);
1393 * security_sid_to_context_inval - Obtain a context for a given SID if it
1395 * @sid: security identifier, SID
1396 * @scontext: security context
1397 * @scontext_len: length in bytes
1399 * Write the string representation of the context associated with @sid
1400 * into a dynamically allocated string of the correct size, but only if the
1401 * context is invalid in the current policy. Set @scontext to point to
1402 * this string (or NULL if the context is valid) and set @scontext_len to
1403 * the length of the string (or 0 if the context is valid).
1405 int security_sid_to_context_inval(u32 sid,
1406 char **scontext, u32 *scontext_len)
1408 return security_sid_to_context_core(sid, scontext,
1409 scontext_len, 1, 1);
1413 * Caveat: Mutates scontext.
1415 static int string_to_context_struct(struct policydb *pol,
1416 struct sidtab *sidtabp,
1418 struct context *ctx,
1421 struct role_datum *role;
1422 struct type_datum *typdatum;
1423 struct user_datum *usrdatum;
1424 char *scontextp, *p, oldc;
1429 /* Parse the security context. */
1432 scontextp = scontext;
1434 /* Extract the user. */
1436 while (*p && *p != ':')
1444 usrdatum = symtab_search(&pol->p_users, scontextp);
1448 ctx->user = usrdatum->value;
1452 while (*p && *p != ':')
1460 role = symtab_search(&pol->p_roles, scontextp);
1463 ctx->role = role->value;
1467 while (*p && *p != ':')
1472 typdatum = symtab_search(&pol->p_types, scontextp);
1473 if (!typdatum || typdatum->attribute)
1476 ctx->type = typdatum->value;
1478 rc = mls_context_to_sid(pol, oldc, p, ctx, sidtabp, def_sid);
1482 /* Check the validity of the new context. */
1484 if (!policydb_context_isvalid(pol, ctx))
1489 context_destroy(ctx);
1493 static int security_context_to_sid_core(const char *scontext, u32 scontext_len,
1494 u32 *sid, u32 def_sid, gfp_t gfp_flags,
1497 struct selinux_policy *policy;
1498 struct policydb *policydb;
1499 struct sidtab *sidtab;
1500 char *scontext2, *str = NULL;
1501 struct context context;
1504 /* An empty security context is never valid. */
1508 /* Copy the string to allow changes and ensure a NUL terminator */
1509 scontext2 = kmemdup_nul(scontext, scontext_len, gfp_flags);
1513 if (!selinux_initialized()) {
1516 for (i = 1; i < SECINITSID_NUM; i++) {
1517 const char *s = initial_sid_to_string[i];
1519 if (s && !strcmp(s, scontext2)) {
1524 *sid = SECINITSID_KERNEL;
1530 /* Save another copy for storing in uninterpreted form */
1532 str = kstrdup(scontext2, gfp_flags);
1538 policy = rcu_dereference(selinux_state.policy);
1539 policydb = &policy->policydb;
1540 sidtab = policy->sidtab;
1541 rc = string_to_context_struct(policydb, sidtab, scontext2,
1543 if (rc == -EINVAL && force) {
1545 context.len = strlen(str) + 1;
1549 rc = sidtab_context_to_sid(sidtab, &context, sid);
1550 if (rc == -ESTALE) {
1556 context_destroy(&context);
1559 context_destroy(&context);
1569 * security_context_to_sid - Obtain a SID for a given security context.
1570 * @scontext: security context
1571 * @scontext_len: length in bytes
1572 * @sid: security identifier, SID
1573 * @gfp: context for the allocation
1575 * Obtains a SID associated with the security context that
1576 * has the string representation specified by @scontext.
1577 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1578 * memory is available, or 0 on success.
1580 int security_context_to_sid(const char *scontext, u32 scontext_len, u32 *sid,
1583 return security_context_to_sid_core(scontext, scontext_len,
1584 sid, SECSID_NULL, gfp, 0);
1587 int security_context_str_to_sid(const char *scontext, u32 *sid, gfp_t gfp)
1589 return security_context_to_sid(scontext, strlen(scontext),
1594 * security_context_to_sid_default - Obtain a SID for a given security context,
1595 * falling back to specified default if needed.
1597 * @scontext: security context
1598 * @scontext_len: length in bytes
1599 * @sid: security identifier, SID
1600 * @def_sid: default SID to assign on error
1601 * @gfp_flags: the allocator get-free-page (GFP) flags
1603 * Obtains a SID associated with the security context that
1604 * has the string representation specified by @scontext.
1605 * The default SID is passed to the MLS layer to be used to allow
1606 * kernel labeling of the MLS field if the MLS field is not present
1607 * (for upgrading to MLS without full relabel).
1608 * Implicitly forces adding of the context even if it cannot be mapped yet.
1609 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1610 * memory is available, or 0 on success.
1612 int security_context_to_sid_default(const char *scontext, u32 scontext_len,
1613 u32 *sid, u32 def_sid, gfp_t gfp_flags)
1615 return security_context_to_sid_core(scontext, scontext_len,
1616 sid, def_sid, gfp_flags, 1);
1619 int security_context_to_sid_force(const char *scontext, u32 scontext_len,
1622 return security_context_to_sid_core(scontext, scontext_len,
1623 sid, SECSID_NULL, GFP_KERNEL, 1);
1626 static int compute_sid_handle_invalid_context(
1627 struct selinux_policy *policy,
1628 struct sidtab_entry *sentry,
1629 struct sidtab_entry *tentry,
1631 struct context *newcontext)
1633 struct policydb *policydb = &policy->policydb;
1634 struct sidtab *sidtab = policy->sidtab;
1635 char *s = NULL, *t = NULL, *n = NULL;
1636 u32 slen, tlen, nlen;
1637 struct audit_buffer *ab;
1639 if (sidtab_entry_to_string(policydb, sidtab, sentry, &s, &slen))
1641 if (sidtab_entry_to_string(policydb, sidtab, tentry, &t, &tlen))
1643 if (context_struct_to_string(policydb, newcontext, &n, &nlen))
1645 ab = audit_log_start(audit_context(), GFP_ATOMIC, AUDIT_SELINUX_ERR);
1648 audit_log_format(ab,
1649 "op=security_compute_sid invalid_context=");
1650 /* no need to record the NUL with untrusted strings */
1651 audit_log_n_untrustedstring(ab, n, nlen - 1);
1652 audit_log_format(ab, " scontext=%s tcontext=%s tclass=%s",
1653 s, t, sym_name(policydb, SYM_CLASSES, tclass-1));
1659 if (!enforcing_enabled())
1664 static void filename_compute_type(struct policydb *policydb,
1665 struct context *newcontext,
1666 u32 stype, u32 ttype, u16 tclass,
1667 const char *objname)
1669 struct filename_trans_key ft;
1670 struct filename_trans_datum *datum;
1673 * Most filename trans rules are going to live in specific directories
1674 * like /dev or /var/run. This bitmap will quickly skip rule searches
1675 * if the ttype does not contain any rules.
1677 if (!ebitmap_get_bit(&policydb->filename_trans_ttypes, ttype))
1684 datum = policydb_filenametr_search(policydb, &ft);
1686 if (ebitmap_get_bit(&datum->stypes, stype - 1)) {
1687 newcontext->type = datum->otype;
1690 datum = datum->next;
1694 static int security_compute_sid(u32 ssid,
1698 const char *objname,
1702 struct selinux_policy *policy;
1703 struct policydb *policydb;
1704 struct sidtab *sidtab;
1705 struct class_datum *cladatum;
1706 struct context *scontext, *tcontext, newcontext;
1707 struct sidtab_entry *sentry, *tentry;
1708 struct avtab_key avkey;
1709 struct avtab_node *avnode, *node;
1714 if (!selinux_initialized()) {
1715 switch (orig_tclass) {
1716 case SECCLASS_PROCESS: /* kernel value */
1728 context_init(&newcontext);
1732 policy = rcu_dereference(selinux_state.policy);
1735 tclass = unmap_class(&policy->map, orig_tclass);
1736 sock = security_is_socket_class(orig_tclass);
1738 tclass = orig_tclass;
1739 sock = security_is_socket_class(map_class(&policy->map,
1743 policydb = &policy->policydb;
1744 sidtab = policy->sidtab;
1746 sentry = sidtab_search_entry(sidtab, ssid);
1748 pr_err("SELinux: %s: unrecognized SID %d\n",
1753 tentry = sidtab_search_entry(sidtab, tsid);
1755 pr_err("SELinux: %s: unrecognized SID %d\n",
1761 scontext = &sentry->context;
1762 tcontext = &tentry->context;
1764 if (tclass && tclass <= policydb->p_classes.nprim)
1765 cladatum = policydb->class_val_to_struct[tclass - 1];
1767 /* Set the user identity. */
1768 switch (specified) {
1769 case AVTAB_TRANSITION:
1771 if (cladatum && cladatum->default_user == DEFAULT_TARGET) {
1772 newcontext.user = tcontext->user;
1774 /* notice this gets both DEFAULT_SOURCE and unset */
1775 /* Use the process user identity. */
1776 newcontext.user = scontext->user;
1780 /* Use the related object owner. */
1781 newcontext.user = tcontext->user;
1785 /* Set the role to default values. */
1786 if (cladatum && cladatum->default_role == DEFAULT_SOURCE) {
1787 newcontext.role = scontext->role;
1788 } else if (cladatum && cladatum->default_role == DEFAULT_TARGET) {
1789 newcontext.role = tcontext->role;
1791 if ((tclass == policydb->process_class) || sock)
1792 newcontext.role = scontext->role;
1794 newcontext.role = OBJECT_R_VAL;
1797 /* Set the type to default values. */
1798 if (cladatum && cladatum->default_type == DEFAULT_SOURCE) {
1799 newcontext.type = scontext->type;
1800 } else if (cladatum && cladatum->default_type == DEFAULT_TARGET) {
1801 newcontext.type = tcontext->type;
1803 if ((tclass == policydb->process_class) || sock) {
1804 /* Use the type of process. */
1805 newcontext.type = scontext->type;
1807 /* Use the type of the related object. */
1808 newcontext.type = tcontext->type;
1812 /* Look for a type transition/member/change rule. */
1813 avkey.source_type = scontext->type;
1814 avkey.target_type = tcontext->type;
1815 avkey.target_class = tclass;
1816 avkey.specified = specified;
1817 avnode = avtab_search_node(&policydb->te_avtab, &avkey);
1819 /* If no permanent rule, also check for enabled conditional rules */
1821 node = avtab_search_node(&policydb->te_cond_avtab, &avkey);
1822 for (; node; node = avtab_search_node_next(node, specified)) {
1823 if (node->key.specified & AVTAB_ENABLED) {
1831 /* Use the type from the type transition/member/change rule. */
1832 newcontext.type = avnode->datum.u.data;
1835 /* if we have a objname this is a file trans check so check those rules */
1837 filename_compute_type(policydb, &newcontext, scontext->type,
1838 tcontext->type, tclass, objname);
1840 /* Check for class-specific changes. */
1841 if (specified & AVTAB_TRANSITION) {
1842 /* Look for a role transition rule. */
1843 struct role_trans_datum *rtd;
1844 struct role_trans_key rtk = {
1845 .role = scontext->role,
1846 .type = tcontext->type,
1850 rtd = policydb_roletr_search(policydb, &rtk);
1852 newcontext.role = rtd->new_role;
1855 /* Set the MLS attributes.
1856 This is done last because it may allocate memory. */
1857 rc = mls_compute_sid(policydb, scontext, tcontext, tclass, specified,
1862 /* Check the validity of the context. */
1863 if (!policydb_context_isvalid(policydb, &newcontext)) {
1864 rc = compute_sid_handle_invalid_context(policy, sentry,
1870 /* Obtain the sid for the context. */
1871 rc = sidtab_context_to_sid(sidtab, &newcontext, out_sid);
1872 if (rc == -ESTALE) {
1874 context_destroy(&newcontext);
1879 context_destroy(&newcontext);
1885 * security_transition_sid - Compute the SID for a new subject/object.
1886 * @ssid: source security identifier
1887 * @tsid: target security identifier
1888 * @tclass: target security class
1889 * @qstr: object name
1890 * @out_sid: security identifier for new subject/object
1892 * Compute a SID to use for labeling a new subject or object in the
1893 * class @tclass based on a SID pair (@ssid, @tsid).
1894 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1895 * if insufficient memory is available, or %0 if the new SID was
1896 * computed successfully.
1898 int security_transition_sid(u32 ssid, u32 tsid, u16 tclass,
1899 const struct qstr *qstr, u32 *out_sid)
1901 return security_compute_sid(ssid, tsid, tclass,
1903 qstr ? qstr->name : NULL, out_sid, true);
1906 int security_transition_sid_user(u32 ssid, u32 tsid, u16 tclass,
1907 const char *objname, u32 *out_sid)
1909 return security_compute_sid(ssid, tsid, tclass,
1911 objname, out_sid, false);
1915 * security_member_sid - Compute the SID for member selection.
1916 * @ssid: source security identifier
1917 * @tsid: target security identifier
1918 * @tclass: target security class
1919 * @out_sid: security identifier for selected member
1921 * Compute a SID to use when selecting a member of a polyinstantiated
1922 * object of class @tclass based on a SID pair (@ssid, @tsid).
1923 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1924 * if insufficient memory is available, or %0 if the SID was
1925 * computed successfully.
1927 int security_member_sid(u32 ssid,
1932 return security_compute_sid(ssid, tsid, tclass,
1938 * security_change_sid - Compute the SID for object relabeling.
1939 * @ssid: source security identifier
1940 * @tsid: target security identifier
1941 * @tclass: target security class
1942 * @out_sid: security identifier for selected member
1944 * Compute a SID to use for relabeling an object of class @tclass
1945 * based on a SID pair (@ssid, @tsid).
1946 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1947 * if insufficient memory is available, or %0 if the SID was
1948 * computed successfully.
1950 int security_change_sid(u32 ssid,
1955 return security_compute_sid(ssid, tsid, tclass, AVTAB_CHANGE, NULL,
1959 static inline int convert_context_handle_invalid_context(
1960 struct policydb *policydb,
1961 struct context *context)
1966 if (enforcing_enabled())
1969 if (!context_struct_to_string(policydb, context, &s, &len)) {
1970 pr_warn("SELinux: Context %s would be invalid if enforcing\n",
1978 * services_convert_context - Convert a security context across policies.
1979 * @args: populated convert_context_args struct
1980 * @oldc: original context
1981 * @newc: converted context
1982 * @gfp_flags: allocation flags
1984 * Convert the values in the security context structure @oldc from the values
1985 * specified in the policy @args->oldp to the values specified in the policy
1986 * @args->newp, storing the new context in @newc, and verifying that the
1987 * context is valid under the new policy.
1989 int services_convert_context(struct convert_context_args *args,
1990 struct context *oldc, struct context *newc,
1993 struct ocontext *oc;
1994 struct role_datum *role;
1995 struct type_datum *typdatum;
1996 struct user_datum *usrdatum;
2002 s = kstrdup(oldc->str, gfp_flags);
2006 rc = string_to_context_struct(args->newp, NULL, s, newc, SECSID_NULL);
2007 if (rc == -EINVAL) {
2009 * Retain string representation for later mapping.
2011 * IMPORTANT: We need to copy the contents of oldc->str
2012 * back into s again because string_to_context_struct()
2013 * may have garbled it.
2015 memcpy(s, oldc->str, oldc->len);
2018 newc->len = oldc->len;
2023 /* Other error condition, e.g. ENOMEM. */
2024 pr_err("SELinux: Unable to map context %s, rc = %d.\n",
2028 pr_info("SELinux: Context %s became valid (mapped).\n",
2035 /* Convert the user. */
2036 usrdatum = symtab_search(&args->newp->p_users,
2037 sym_name(args->oldp, SYM_USERS, oldc->user - 1));
2040 newc->user = usrdatum->value;
2042 /* Convert the role. */
2043 role = symtab_search(&args->newp->p_roles,
2044 sym_name(args->oldp, SYM_ROLES, oldc->role - 1));
2047 newc->role = role->value;
2049 /* Convert the type. */
2050 typdatum = symtab_search(&args->newp->p_types,
2051 sym_name(args->oldp, SYM_TYPES, oldc->type - 1));
2054 newc->type = typdatum->value;
2056 /* Convert the MLS fields if dealing with MLS policies */
2057 if (args->oldp->mls_enabled && args->newp->mls_enabled) {
2058 rc = mls_convert_context(args->oldp, args->newp, oldc, newc);
2061 } else if (!args->oldp->mls_enabled && args->newp->mls_enabled) {
2063 * Switching between non-MLS and MLS policy:
2064 * ensure that the MLS fields of the context for all
2065 * existing entries in the sidtab are filled in with a
2066 * suitable default value, likely taken from one of the
2069 oc = args->newp->ocontexts[OCON_ISID];
2070 while (oc && oc->sid[0] != SECINITSID_UNLABELED)
2073 pr_err("SELinux: unable to look up"
2074 " the initial SIDs list\n");
2077 rc = mls_range_set(newc, &oc->context[0].range);
2082 /* Check the validity of the new context. */
2083 if (!policydb_context_isvalid(args->newp, newc)) {
2084 rc = convert_context_handle_invalid_context(args->oldp, oldc);
2091 /* Map old representation to string and save it. */
2092 rc = context_struct_to_string(args->oldp, oldc, &s, &len);
2095 context_destroy(newc);
2098 pr_info("SELinux: Context %s became invalid (unmapped).\n",
2103 static void security_load_policycaps(struct selinux_policy *policy)
2107 struct ebitmap_node *node;
2109 p = &policy->policydb;
2111 for (i = 0; i < ARRAY_SIZE(selinux_state.policycap); i++)
2112 WRITE_ONCE(selinux_state.policycap[i],
2113 ebitmap_get_bit(&p->policycaps, i));
2115 for (i = 0; i < ARRAY_SIZE(selinux_policycap_names); i++)
2116 pr_info("SELinux: policy capability %s=%d\n",
2117 selinux_policycap_names[i],
2118 ebitmap_get_bit(&p->policycaps, i));
2120 ebitmap_for_each_positive_bit(&p->policycaps, node, i) {
2121 if (i >= ARRAY_SIZE(selinux_policycap_names))
2122 pr_info("SELinux: unknown policy capability %u\n",
2127 static int security_preserve_bools(struct selinux_policy *oldpolicy,
2128 struct selinux_policy *newpolicy);
2130 static void selinux_policy_free(struct selinux_policy *policy)
2135 sidtab_destroy(policy->sidtab);
2136 kfree(policy->map.mapping);
2137 policydb_destroy(&policy->policydb);
2138 kfree(policy->sidtab);
2142 static void selinux_policy_cond_free(struct selinux_policy *policy)
2144 cond_policydb_destroy_dup(&policy->policydb);
2148 void selinux_policy_cancel(struct selinux_load_state *load_state)
2150 struct selinux_state *state = &selinux_state;
2151 struct selinux_policy *oldpolicy;
2153 oldpolicy = rcu_dereference_protected(state->policy,
2154 lockdep_is_held(&state->policy_mutex));
2156 sidtab_cancel_convert(oldpolicy->sidtab);
2157 selinux_policy_free(load_state->policy);
2158 kfree(load_state->convert_data);
2161 static void selinux_notify_policy_change(u32 seqno)
2163 /* Flush external caches and notify userspace of policy load */
2164 avc_ss_reset(seqno);
2165 selnl_notify_policyload(seqno);
2166 selinux_status_update_policyload(seqno);
2167 selinux_netlbl_cache_invalidate();
2168 selinux_xfrm_notify_policyload();
2169 selinux_ima_measure_state_locked();
2172 void selinux_policy_commit(struct selinux_load_state *load_state)
2174 struct selinux_state *state = &selinux_state;
2175 struct selinux_policy *oldpolicy, *newpolicy = load_state->policy;
2176 unsigned long flags;
2179 oldpolicy = rcu_dereference_protected(state->policy,
2180 lockdep_is_held(&state->policy_mutex));
2182 /* If switching between different policy types, log MLS status */
2184 if (oldpolicy->policydb.mls_enabled && !newpolicy->policydb.mls_enabled)
2185 pr_info("SELinux: Disabling MLS support...\n");
2186 else if (!oldpolicy->policydb.mls_enabled && newpolicy->policydb.mls_enabled)
2187 pr_info("SELinux: Enabling MLS support...\n");
2190 /* Set latest granting seqno for new policy. */
2192 newpolicy->latest_granting = oldpolicy->latest_granting + 1;
2194 newpolicy->latest_granting = 1;
2195 seqno = newpolicy->latest_granting;
2197 /* Install the new policy. */
2199 sidtab_freeze_begin(oldpolicy->sidtab, &flags);
2200 rcu_assign_pointer(state->policy, newpolicy);
2201 sidtab_freeze_end(oldpolicy->sidtab, &flags);
2203 rcu_assign_pointer(state->policy, newpolicy);
2206 /* Load the policycaps from the new policy */
2207 security_load_policycaps(newpolicy);
2209 if (!selinux_initialized()) {
2211 * After first policy load, the security server is
2212 * marked as initialized and ready to handle requests and
2213 * any objects created prior to policy load are then labeled.
2215 selinux_mark_initialized();
2216 selinux_complete_init();
2219 /* Free the old policy */
2221 selinux_policy_free(oldpolicy);
2222 kfree(load_state->convert_data);
2224 /* Notify others of the policy change */
2225 selinux_notify_policy_change(seqno);
2229 * security_load_policy - Load a security policy configuration.
2230 * @data: binary policy data
2231 * @len: length of data in bytes
2232 * @load_state: policy load state
2234 * Load a new set of security policy configuration data,
2235 * validate it and convert the SID table as necessary.
2236 * This function will flush the access vector cache after
2237 * loading the new policy.
2239 int security_load_policy(void *data, size_t len,
2240 struct selinux_load_state *load_state)
2242 struct selinux_state *state = &selinux_state;
2243 struct selinux_policy *newpolicy, *oldpolicy;
2244 struct selinux_policy_convert_data *convert_data;
2246 struct policy_file file = { data, len }, *fp = &file;
2248 newpolicy = kzalloc(sizeof(*newpolicy), GFP_KERNEL);
2252 newpolicy->sidtab = kzalloc(sizeof(*newpolicy->sidtab), GFP_KERNEL);
2253 if (!newpolicy->sidtab) {
2258 rc = policydb_read(&newpolicy->policydb, fp);
2262 newpolicy->policydb.len = len;
2263 rc = selinux_set_mapping(&newpolicy->policydb, secclass_map,
2268 rc = policydb_load_isids(&newpolicy->policydb, newpolicy->sidtab);
2270 pr_err("SELinux: unable to load the initial SIDs\n");
2274 if (!selinux_initialized()) {
2275 /* First policy load, so no need to preserve state from old policy */
2276 load_state->policy = newpolicy;
2277 load_state->convert_data = NULL;
2281 oldpolicy = rcu_dereference_protected(state->policy,
2282 lockdep_is_held(&state->policy_mutex));
2284 /* Preserve active boolean values from the old policy */
2285 rc = security_preserve_bools(oldpolicy, newpolicy);
2287 pr_err("SELinux: unable to preserve booleans\n");
2288 goto err_free_isids;
2292 * Convert the internal representations of contexts
2293 * in the new SID table.
2296 convert_data = kmalloc(sizeof(*convert_data), GFP_KERNEL);
2297 if (!convert_data) {
2299 goto err_free_isids;
2302 convert_data->args.oldp = &oldpolicy->policydb;
2303 convert_data->args.newp = &newpolicy->policydb;
2305 convert_data->sidtab_params.args = &convert_data->args;
2306 convert_data->sidtab_params.target = newpolicy->sidtab;
2308 rc = sidtab_convert(oldpolicy->sidtab, &convert_data->sidtab_params);
2310 pr_err("SELinux: unable to convert the internal"
2311 " representation of contexts in the new SID"
2313 goto err_free_convert_data;
2316 load_state->policy = newpolicy;
2317 load_state->convert_data = convert_data;
2320 err_free_convert_data:
2321 kfree(convert_data);
2323 sidtab_destroy(newpolicy->sidtab);
2325 kfree(newpolicy->map.mapping);
2327 policydb_destroy(&newpolicy->policydb);
2329 kfree(newpolicy->sidtab);
2337 * ocontext_to_sid - Helper to safely get sid for an ocontext
2338 * @sidtab: SID table
2339 * @c: ocontext structure
2340 * @index: index of the context entry (0 or 1)
2341 * @out_sid: pointer to the resulting SID value
2343 * For all ocontexts except OCON_ISID the SID fields are populated
2344 * on-demand when needed. Since updating the SID value is an SMP-sensitive
2345 * operation, this helper must be used to do that safely.
2347 * WARNING: This function may return -ESTALE, indicating that the caller
2348 * must retry the operation after re-acquiring the policy pointer!
2350 static int ocontext_to_sid(struct sidtab *sidtab, struct ocontext *c,
2351 size_t index, u32 *out_sid)
2356 /* Ensure the associated sidtab entry is visible to this thread. */
2357 sid = smp_load_acquire(&c->sid[index]);
2359 rc = sidtab_context_to_sid(sidtab, &c->context[index], &sid);
2364 * Ensure the new sidtab entry is visible to other threads
2365 * when they see the SID.
2367 smp_store_release(&c->sid[index], sid);
2374 * security_port_sid - Obtain the SID for a port.
2375 * @protocol: protocol number
2376 * @port: port number
2377 * @out_sid: security identifier
2379 int security_port_sid(u8 protocol, u16 port, u32 *out_sid)
2381 struct selinux_policy *policy;
2382 struct policydb *policydb;
2383 struct sidtab *sidtab;
2387 if (!selinux_initialized()) {
2388 *out_sid = SECINITSID_PORT;
2395 policy = rcu_dereference(selinux_state.policy);
2396 policydb = &policy->policydb;
2397 sidtab = policy->sidtab;
2399 c = policydb->ocontexts[OCON_PORT];
2401 if (c->u.port.protocol == protocol &&
2402 c->u.port.low_port <= port &&
2403 c->u.port.high_port >= port)
2409 rc = ocontext_to_sid(sidtab, c, 0, out_sid);
2410 if (rc == -ESTALE) {
2417 *out_sid = SECINITSID_PORT;
2426 * security_ib_pkey_sid - Obtain the SID for a pkey.
2427 * @subnet_prefix: Subnet Prefix
2428 * @pkey_num: pkey number
2429 * @out_sid: security identifier
2431 int security_ib_pkey_sid(u64 subnet_prefix, u16 pkey_num, u32 *out_sid)
2433 struct selinux_policy *policy;
2434 struct policydb *policydb;
2435 struct sidtab *sidtab;
2439 if (!selinux_initialized()) {
2440 *out_sid = SECINITSID_UNLABELED;
2447 policy = rcu_dereference(selinux_state.policy);
2448 policydb = &policy->policydb;
2449 sidtab = policy->sidtab;
2451 c = policydb->ocontexts[OCON_IBPKEY];
2453 if (c->u.ibpkey.low_pkey <= pkey_num &&
2454 c->u.ibpkey.high_pkey >= pkey_num &&
2455 c->u.ibpkey.subnet_prefix == subnet_prefix)
2462 rc = ocontext_to_sid(sidtab, c, 0, out_sid);
2463 if (rc == -ESTALE) {
2470 *out_sid = SECINITSID_UNLABELED;
2478 * security_ib_endport_sid - Obtain the SID for a subnet management interface.
2479 * @dev_name: device name
2480 * @port_num: port number
2481 * @out_sid: security identifier
2483 int security_ib_endport_sid(const char *dev_name, u8 port_num, u32 *out_sid)
2485 struct selinux_policy *policy;
2486 struct policydb *policydb;
2487 struct sidtab *sidtab;
2491 if (!selinux_initialized()) {
2492 *out_sid = SECINITSID_UNLABELED;
2499 policy = rcu_dereference(selinux_state.policy);
2500 policydb = &policy->policydb;
2501 sidtab = policy->sidtab;
2503 c = policydb->ocontexts[OCON_IBENDPORT];
2505 if (c->u.ibendport.port == port_num &&
2506 !strncmp(c->u.ibendport.dev_name,
2508 IB_DEVICE_NAME_MAX))
2515 rc = ocontext_to_sid(sidtab, c, 0, out_sid);
2516 if (rc == -ESTALE) {
2523 *out_sid = SECINITSID_UNLABELED;
2531 * security_netif_sid - Obtain the SID for a network interface.
2532 * @name: interface name
2533 * @if_sid: interface SID
2535 int security_netif_sid(char *name, u32 *if_sid)
2537 struct selinux_policy *policy;
2538 struct policydb *policydb;
2539 struct sidtab *sidtab;
2543 if (!selinux_initialized()) {
2544 *if_sid = SECINITSID_NETIF;
2551 policy = rcu_dereference(selinux_state.policy);
2552 policydb = &policy->policydb;
2553 sidtab = policy->sidtab;
2555 c = policydb->ocontexts[OCON_NETIF];
2557 if (strcmp(name, c->u.name) == 0)
2563 rc = ocontext_to_sid(sidtab, c, 0, if_sid);
2564 if (rc == -ESTALE) {
2571 *if_sid = SECINITSID_NETIF;
2578 static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask)
2582 for (i = 0; i < 4; i++)
2583 if (addr[i] != (input[i] & mask[i])) {
2592 * security_node_sid - Obtain the SID for a node (host).
2593 * @domain: communication domain aka address family
2595 * @addrlen: address length in bytes
2596 * @out_sid: security identifier
2598 int security_node_sid(u16 domain,
2603 struct selinux_policy *policy;
2604 struct policydb *policydb;
2605 struct sidtab *sidtab;
2609 if (!selinux_initialized()) {
2610 *out_sid = SECINITSID_NODE;
2616 policy = rcu_dereference(selinux_state.policy);
2617 policydb = &policy->policydb;
2618 sidtab = policy->sidtab;
2625 if (addrlen != sizeof(u32))
2628 addr = *((u32 *)addrp);
2630 c = policydb->ocontexts[OCON_NODE];
2632 if (c->u.node.addr == (addr & c->u.node.mask))
2641 if (addrlen != sizeof(u64) * 2)
2643 c = policydb->ocontexts[OCON_NODE6];
2645 if (match_ipv6_addrmask(addrp, c->u.node6.addr,
2654 *out_sid = SECINITSID_NODE;
2659 rc = ocontext_to_sid(sidtab, c, 0, out_sid);
2660 if (rc == -ESTALE) {
2667 *out_sid = SECINITSID_NODE;
2679 * security_get_user_sids - Obtain reachable SIDs for a user.
2680 * @fromsid: starting SID
2681 * @username: username
2682 * @sids: array of reachable SIDs for user
2683 * @nel: number of elements in @sids
2685 * Generate the set of SIDs for legal security contexts
2686 * for a given user that can be reached by @fromsid.
2687 * Set *@sids to point to a dynamically allocated
2688 * array containing the set of SIDs. Set *@nel to the
2689 * number of elements in the array.
2692 int security_get_user_sids(u32 fromsid,
2697 struct selinux_policy *policy;
2698 struct policydb *policydb;
2699 struct sidtab *sidtab;
2700 struct context *fromcon, usercon;
2701 u32 *mysids = NULL, *mysids2, sid;
2702 u32 i, j, mynel, maxnel = SIDS_NEL;
2703 struct user_datum *user;
2704 struct role_datum *role;
2705 struct ebitmap_node *rnode, *tnode;
2711 if (!selinux_initialized())
2714 mysids = kcalloc(maxnel, sizeof(*mysids), GFP_KERNEL);
2721 policy = rcu_dereference(selinux_state.policy);
2722 policydb = &policy->policydb;
2723 sidtab = policy->sidtab;
2725 context_init(&usercon);
2728 fromcon = sidtab_search(sidtab, fromsid);
2733 user = symtab_search(&policydb->p_users, username);
2737 usercon.user = user->value;
2739 ebitmap_for_each_positive_bit(&user->roles, rnode, i) {
2740 role = policydb->role_val_to_struct[i];
2741 usercon.role = i + 1;
2742 ebitmap_for_each_positive_bit(&role->types, tnode, j) {
2743 usercon.type = j + 1;
2745 if (mls_setup_user_range(policydb, fromcon, user,
2749 rc = sidtab_context_to_sid(sidtab, &usercon, &sid);
2750 if (rc == -ESTALE) {
2756 if (mynel < maxnel) {
2757 mysids[mynel++] = sid;
2761 mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
2764 memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
2767 mysids[mynel++] = sid;
2780 mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);
2785 for (i = 0, j = 0; i < mynel; i++) {
2786 struct av_decision dummy_avd;
2787 rc = avc_has_perm_noaudit(fromsid, mysids[i],
2788 SECCLASS_PROCESS, /* kernel value */
2789 PROCESS__TRANSITION, AVC_STRICT,
2792 mysids2[j++] = mysids[i];
2802 * __security_genfs_sid - Helper to obtain a SID for a file in a filesystem
2804 * @fstype: filesystem type
2805 * @path: path from root of mount
2806 * @orig_sclass: file security class
2807 * @sid: SID for path
2809 * Obtain a SID to use for a file in a filesystem that
2810 * cannot support xattr or use a fixed labeling behavior like
2811 * transition SIDs or task SIDs.
2813 * WARNING: This function may return -ESTALE, indicating that the caller
2814 * must retry the operation after re-acquiring the policy pointer!
2816 static inline int __security_genfs_sid(struct selinux_policy *policy,
2822 struct policydb *policydb = &policy->policydb;
2823 struct sidtab *sidtab = policy->sidtab;
2825 struct genfs *genfs;
2829 while (path[0] == '/' && path[1] == '/')
2832 sclass = unmap_class(&policy->map, orig_sclass);
2833 *sid = SECINITSID_UNLABELED;
2835 for (genfs = policydb->genfs; genfs; genfs = genfs->next) {
2836 cmp = strcmp(fstype, genfs->fstype);
2844 for (c = genfs->head; c; c = c->next) {
2845 size_t len = strlen(c->u.name);
2846 if ((!c->v.sclass || sclass == c->v.sclass) &&
2847 (strncmp(c->u.name, path, len) == 0))
2854 return ocontext_to_sid(sidtab, c, 0, sid);
2858 * security_genfs_sid - Obtain a SID for a file in a filesystem
2859 * @fstype: filesystem type
2860 * @path: path from root of mount
2861 * @orig_sclass: file security class
2862 * @sid: SID for path
2864 * Acquire policy_rwlock before calling __security_genfs_sid() and release
2867 int security_genfs_sid(const char *fstype,
2872 struct selinux_policy *policy;
2875 if (!selinux_initialized()) {
2876 *sid = SECINITSID_UNLABELED;
2882 policy = rcu_dereference(selinux_state.policy);
2883 retval = __security_genfs_sid(policy, fstype, path,
2886 } while (retval == -ESTALE);
2890 int selinux_policy_genfs_sid(struct selinux_policy *policy,
2896 /* no lock required, policy is not yet accessible by other threads */
2897 return __security_genfs_sid(policy, fstype, path, orig_sclass, sid);
2901 * security_fs_use - Determine how to handle labeling for a filesystem.
2902 * @sb: superblock in question
2904 int security_fs_use(struct super_block *sb)
2906 struct selinux_policy *policy;
2907 struct policydb *policydb;
2908 struct sidtab *sidtab;
2911 struct superblock_security_struct *sbsec = selinux_superblock(sb);
2912 const char *fstype = sb->s_type->name;
2914 if (!selinux_initialized()) {
2915 sbsec->behavior = SECURITY_FS_USE_NONE;
2916 sbsec->sid = SECINITSID_UNLABELED;
2922 policy = rcu_dereference(selinux_state.policy);
2923 policydb = &policy->policydb;
2924 sidtab = policy->sidtab;
2926 c = policydb->ocontexts[OCON_FSUSE];
2928 if (strcmp(fstype, c->u.name) == 0)
2934 sbsec->behavior = c->v.behavior;
2935 rc = ocontext_to_sid(sidtab, c, 0, &sbsec->sid);
2936 if (rc == -ESTALE) {
2943 rc = __security_genfs_sid(policy, fstype, "/",
2944 SECCLASS_DIR, &sbsec->sid);
2945 if (rc == -ESTALE) {
2950 sbsec->behavior = SECURITY_FS_USE_NONE;
2953 sbsec->behavior = SECURITY_FS_USE_GENFS;
2962 int security_get_bools(struct selinux_policy *policy,
2963 u32 *len, char ***names, int **values)
2965 struct policydb *policydb;
2969 policydb = &policy->policydb;
2975 *len = policydb->p_bools.nprim;
2980 *names = kcalloc(*len, sizeof(char *), GFP_ATOMIC);
2985 *values = kcalloc(*len, sizeof(int), GFP_ATOMIC);
2989 for (i = 0; i < *len; i++) {
2990 (*values)[i] = policydb->bool_val_to_struct[i]->state;
2993 (*names)[i] = kstrdup(sym_name(policydb, SYM_BOOLS, i),
3003 for (i = 0; i < *len; i++)
3015 int security_set_bools(u32 len, int *values)
3017 struct selinux_state *state = &selinux_state;
3018 struct selinux_policy *newpolicy, *oldpolicy;
3022 if (!selinux_initialized())
3025 oldpolicy = rcu_dereference_protected(state->policy,
3026 lockdep_is_held(&state->policy_mutex));
3028 /* Consistency check on number of booleans, should never fail */
3029 if (WARN_ON(len != oldpolicy->policydb.p_bools.nprim))
3032 newpolicy = kmemdup(oldpolicy, sizeof(*newpolicy), GFP_KERNEL);
3037 * Deep copy only the parts of the policydb that might be
3038 * modified as a result of changing booleans.
3040 rc = cond_policydb_dup(&newpolicy->policydb, &oldpolicy->policydb);
3046 /* Update the boolean states in the copy */
3047 for (i = 0; i < len; i++) {
3048 int new_state = !!values[i];
3049 int old_state = newpolicy->policydb.bool_val_to_struct[i]->state;
3051 if (new_state != old_state) {
3052 audit_log(audit_context(), GFP_ATOMIC,
3053 AUDIT_MAC_CONFIG_CHANGE,
3054 "bool=%s val=%d old_val=%d auid=%u ses=%u",
3055 sym_name(&newpolicy->policydb, SYM_BOOLS, i),
3058 from_kuid(&init_user_ns, audit_get_loginuid(current)),
3059 audit_get_sessionid(current));
3060 newpolicy->policydb.bool_val_to_struct[i]->state = new_state;
3064 /* Re-evaluate the conditional rules in the copy */
3065 evaluate_cond_nodes(&newpolicy->policydb);
3067 /* Set latest granting seqno for new policy */
3068 newpolicy->latest_granting = oldpolicy->latest_granting + 1;
3069 seqno = newpolicy->latest_granting;
3071 /* Install the new policy */
3072 rcu_assign_pointer(state->policy, newpolicy);
3075 * Free the conditional portions of the old policydb
3076 * that were copied for the new policy, and the oldpolicy
3077 * structure itself but not what it references.
3080 selinux_policy_cond_free(oldpolicy);
3082 /* Notify others of the policy change */
3083 selinux_notify_policy_change(seqno);
3087 int security_get_bool_value(u32 index)
3089 struct selinux_policy *policy;
3090 struct policydb *policydb;
3094 if (!selinux_initialized())
3098 policy = rcu_dereference(selinux_state.policy);
3099 policydb = &policy->policydb;
3102 len = policydb->p_bools.nprim;
3106 rc = policydb->bool_val_to_struct[index]->state;
3112 static int security_preserve_bools(struct selinux_policy *oldpolicy,
3113 struct selinux_policy *newpolicy)
3115 int rc, *bvalues = NULL;
3116 char **bnames = NULL;
3117 struct cond_bool_datum *booldatum;
3120 rc = security_get_bools(oldpolicy, &nbools, &bnames, &bvalues);
3123 for (i = 0; i < nbools; i++) {
3124 booldatum = symtab_search(&newpolicy->policydb.p_bools,
3127 booldatum->state = bvalues[i];
3129 evaluate_cond_nodes(&newpolicy->policydb);
3133 for (i = 0; i < nbools; i++)
3142 * security_sid_mls_copy() - computes a new sid based on the given
3143 * sid and the mls portion of mls_sid.
3145 int security_sid_mls_copy(u32 sid, u32 mls_sid, u32 *new_sid)
3147 struct selinux_policy *policy;
3148 struct policydb *policydb;
3149 struct sidtab *sidtab;
3150 struct context *context1;
3151 struct context *context2;
3152 struct context newcon;
3157 if (!selinux_initialized()) {
3164 context_init(&newcon);
3167 policy = rcu_dereference(selinux_state.policy);
3168 policydb = &policy->policydb;
3169 sidtab = policy->sidtab;
3171 if (!policydb->mls_enabled) {
3177 context1 = sidtab_search(sidtab, sid);
3179 pr_err("SELinux: %s: unrecognized SID %d\n",
3185 context2 = sidtab_search(sidtab, mls_sid);
3187 pr_err("SELinux: %s: unrecognized SID %d\n",
3192 newcon.user = context1->user;
3193 newcon.role = context1->role;
3194 newcon.type = context1->type;
3195 rc = mls_context_cpy(&newcon, context2);
3199 /* Check the validity of the new context. */
3200 if (!policydb_context_isvalid(policydb, &newcon)) {
3201 rc = convert_context_handle_invalid_context(policydb,
3204 if (!context_struct_to_string(policydb, &newcon, &s,
3206 struct audit_buffer *ab;
3208 ab = audit_log_start(audit_context(),
3211 audit_log_format(ab,
3212 "op=security_sid_mls_copy invalid_context=");
3213 /* don't record NUL with untrusted strings */
3214 audit_log_n_untrustedstring(ab, s, len - 1);
3221 rc = sidtab_context_to_sid(sidtab, &newcon, new_sid);
3222 if (rc == -ESTALE) {
3224 context_destroy(&newcon);
3229 context_destroy(&newcon);
3234 * security_net_peersid_resolve - Compare and resolve two network peer SIDs
3235 * @nlbl_sid: NetLabel SID
3236 * @nlbl_type: NetLabel labeling protocol type
3237 * @xfrm_sid: XFRM SID
3238 * @peer_sid: network peer sid
3241 * Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be
3242 * resolved into a single SID it is returned via @peer_sid and the function
3243 * returns zero. Otherwise @peer_sid is set to SECSID_NULL and the function
3244 * returns a negative value. A table summarizing the behavior is below:
3246 * | function return | @sid
3247 * ------------------------------+-----------------+-----------------
3248 * no peer labels | 0 | SECSID_NULL
3249 * single peer label | 0 | <peer_label>
3250 * multiple, consistent labels | 0 | <peer_label>
3251 * multiple, inconsistent labels | -<errno> | SECSID_NULL
3254 int security_net_peersid_resolve(u32 nlbl_sid, u32 nlbl_type,
3258 struct selinux_policy *policy;
3259 struct policydb *policydb;
3260 struct sidtab *sidtab;
3262 struct context *nlbl_ctx;
3263 struct context *xfrm_ctx;
3265 *peer_sid = SECSID_NULL;
3267 /* handle the common (which also happens to be the set of easy) cases
3268 * right away, these two if statements catch everything involving a
3269 * single or absent peer SID/label */
3270 if (xfrm_sid == SECSID_NULL) {
3271 *peer_sid = nlbl_sid;
3274 /* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a "fallback" label
3275 * and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label
3277 if (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) {
3278 *peer_sid = xfrm_sid;
3282 if (!selinux_initialized())
3286 policy = rcu_dereference(selinux_state.policy);
3287 policydb = &policy->policydb;
3288 sidtab = policy->sidtab;
3291 * We don't need to check initialized here since the only way both
3292 * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the
3293 * security server was initialized and state->initialized was true.
3295 if (!policydb->mls_enabled) {
3301 nlbl_ctx = sidtab_search(sidtab, nlbl_sid);
3303 pr_err("SELinux: %s: unrecognized SID %d\n",
3304 __func__, nlbl_sid);
3308 xfrm_ctx = sidtab_search(sidtab, xfrm_sid);
3310 pr_err("SELinux: %s: unrecognized SID %d\n",
3311 __func__, xfrm_sid);
3314 rc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES);
3318 /* at present NetLabel SIDs/labels really only carry MLS
3319 * information so if the MLS portion of the NetLabel SID
3320 * matches the MLS portion of the labeled XFRM SID/label
3321 * then pass along the XFRM SID as it is the most
3323 *peer_sid = xfrm_sid;
3329 static int get_classes_callback(void *k, void *d, void *args)
3331 struct class_datum *datum = d;
3332 char *name = k, **classes = args;
3333 u32 value = datum->value - 1;
3335 classes[value] = kstrdup(name, GFP_ATOMIC);
3336 if (!classes[value])
3342 int security_get_classes(struct selinux_policy *policy,
3343 char ***classes, u32 *nclasses)
3345 struct policydb *policydb;
3348 policydb = &policy->policydb;
3351 *nclasses = policydb->p_classes.nprim;
3352 *classes = kcalloc(*nclasses, sizeof(**classes), GFP_ATOMIC);
3356 rc = hashtab_map(&policydb->p_classes.table, get_classes_callback,
3361 for (i = 0; i < *nclasses; i++)
3362 kfree((*classes)[i]);
3370 static int get_permissions_callback(void *k, void *d, void *args)
3372 struct perm_datum *datum = d;
3373 char *name = k, **perms = args;
3374 u32 value = datum->value - 1;
3376 perms[value] = kstrdup(name, GFP_ATOMIC);
3383 int security_get_permissions(struct selinux_policy *policy,
3384 const char *class, char ***perms, u32 *nperms)
3386 struct policydb *policydb;
3389 struct class_datum *match;
3391 policydb = &policy->policydb;
3394 match = symtab_search(&policydb->p_classes, class);
3396 pr_err("SELinux: %s: unrecognized class %s\n",
3402 *nperms = match->permissions.nprim;
3403 *perms = kcalloc(*nperms, sizeof(**perms), GFP_ATOMIC);
3407 if (match->comdatum) {
3408 rc = hashtab_map(&match->comdatum->permissions.table,
3409 get_permissions_callback, *perms);
3414 rc = hashtab_map(&match->permissions.table, get_permissions_callback,
3423 for (i = 0; i < *nperms; i++)
3429 int security_get_reject_unknown(void)
3431 struct selinux_policy *policy;
3434 if (!selinux_initialized())
3438 policy = rcu_dereference(selinux_state.policy);
3439 value = policy->policydb.reject_unknown;
3444 int security_get_allow_unknown(void)
3446 struct selinux_policy *policy;
3449 if (!selinux_initialized())
3453 policy = rcu_dereference(selinux_state.policy);
3454 value = policy->policydb.allow_unknown;
3460 * security_policycap_supported - Check for a specific policy capability
3461 * @req_cap: capability
3464 * This function queries the currently loaded policy to see if it supports the
3465 * capability specified by @req_cap. Returns true (1) if the capability is
3466 * supported, false (0) if it isn't supported.
3469 int security_policycap_supported(unsigned int req_cap)
3471 struct selinux_policy *policy;
3474 if (!selinux_initialized())
3478 policy = rcu_dereference(selinux_state.policy);
3479 rc = ebitmap_get_bit(&policy->policydb.policycaps, req_cap);
3485 struct selinux_audit_rule {
3487 struct context au_ctxt;
3490 void selinux_audit_rule_free(void *vrule)
3492 struct selinux_audit_rule *rule = vrule;
3495 context_destroy(&rule->au_ctxt);
3500 int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule)
3502 struct selinux_state *state = &selinux_state;
3503 struct selinux_policy *policy;
3504 struct policydb *policydb;
3505 struct selinux_audit_rule *tmprule;
3506 struct role_datum *roledatum;
3507 struct type_datum *typedatum;
3508 struct user_datum *userdatum;
3509 struct selinux_audit_rule **rule = (struct selinux_audit_rule **)vrule;
3514 if (!selinux_initialized())
3518 case AUDIT_SUBJ_USER:
3519 case AUDIT_SUBJ_ROLE:
3520 case AUDIT_SUBJ_TYPE:
3521 case AUDIT_OBJ_USER:
3522 case AUDIT_OBJ_ROLE:
3523 case AUDIT_OBJ_TYPE:
3524 /* only 'equals' and 'not equals' fit user, role, and type */
3525 if (op != Audit_equal && op != Audit_not_equal)
3528 case AUDIT_SUBJ_SEN:
3529 case AUDIT_SUBJ_CLR:
3530 case AUDIT_OBJ_LEV_LOW:
3531 case AUDIT_OBJ_LEV_HIGH:
3532 /* we do not allow a range, indicated by the presence of '-' */
3533 if (strchr(rulestr, '-'))
3537 /* only the above fields are valid */
3541 tmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL);
3544 context_init(&tmprule->au_ctxt);
3547 policy = rcu_dereference(state->policy);
3548 policydb = &policy->policydb;
3549 tmprule->au_seqno = policy->latest_granting;
3551 case AUDIT_SUBJ_USER:
3552 case AUDIT_OBJ_USER:
3553 userdatum = symtab_search(&policydb->p_users, rulestr);
3558 tmprule->au_ctxt.user = userdatum->value;
3560 case AUDIT_SUBJ_ROLE:
3561 case AUDIT_OBJ_ROLE:
3562 roledatum = symtab_search(&policydb->p_roles, rulestr);
3567 tmprule->au_ctxt.role = roledatum->value;
3569 case AUDIT_SUBJ_TYPE:
3570 case AUDIT_OBJ_TYPE:
3571 typedatum = symtab_search(&policydb->p_types, rulestr);
3576 tmprule->au_ctxt.type = typedatum->value;
3578 case AUDIT_SUBJ_SEN:
3579 case AUDIT_SUBJ_CLR:
3580 case AUDIT_OBJ_LEV_LOW:
3581 case AUDIT_OBJ_LEV_HIGH:
3582 rc = mls_from_string(policydb, rulestr, &tmprule->au_ctxt,
3595 selinux_audit_rule_free(tmprule);
3600 /* Check to see if the rule contains any selinux fields */
3601 int selinux_audit_rule_known(struct audit_krule *rule)
3605 for (i = 0; i < rule->field_count; i++) {
3606 struct audit_field *f = &rule->fields[i];
3608 case AUDIT_SUBJ_USER:
3609 case AUDIT_SUBJ_ROLE:
3610 case AUDIT_SUBJ_TYPE:
3611 case AUDIT_SUBJ_SEN:
3612 case AUDIT_SUBJ_CLR:
3613 case AUDIT_OBJ_USER:
3614 case AUDIT_OBJ_ROLE:
3615 case AUDIT_OBJ_TYPE:
3616 case AUDIT_OBJ_LEV_LOW:
3617 case AUDIT_OBJ_LEV_HIGH:
3625 int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule)
3627 struct selinux_state *state = &selinux_state;
3628 struct selinux_policy *policy;
3629 struct context *ctxt;
3630 struct mls_level *level;
3631 struct selinux_audit_rule *rule = vrule;
3634 if (unlikely(!rule)) {
3635 WARN_ONCE(1, "selinux_audit_rule_match: missing rule\n");
3639 if (!selinux_initialized())
3644 policy = rcu_dereference(state->policy);
3646 if (rule->au_seqno < policy->latest_granting) {
3651 ctxt = sidtab_search(policy->sidtab, sid);
3652 if (unlikely(!ctxt)) {
3653 WARN_ONCE(1, "selinux_audit_rule_match: unrecognized SID %d\n",
3659 /* a field/op pair that is not caught here will simply fall through
3662 case AUDIT_SUBJ_USER:
3663 case AUDIT_OBJ_USER:
3666 match = (ctxt->user == rule->au_ctxt.user);
3668 case Audit_not_equal:
3669 match = (ctxt->user != rule->au_ctxt.user);
3673 case AUDIT_SUBJ_ROLE:
3674 case AUDIT_OBJ_ROLE:
3677 match = (ctxt->role == rule->au_ctxt.role);
3679 case Audit_not_equal:
3680 match = (ctxt->role != rule->au_ctxt.role);
3684 case AUDIT_SUBJ_TYPE:
3685 case AUDIT_OBJ_TYPE:
3688 match = (ctxt->type == rule->au_ctxt.type);
3690 case Audit_not_equal:
3691 match = (ctxt->type != rule->au_ctxt.type);
3695 case AUDIT_SUBJ_SEN:
3696 case AUDIT_SUBJ_CLR:
3697 case AUDIT_OBJ_LEV_LOW:
3698 case AUDIT_OBJ_LEV_HIGH:
3699 level = ((field == AUDIT_SUBJ_SEN ||
3700 field == AUDIT_OBJ_LEV_LOW) ?
3701 &ctxt->range.level[0] : &ctxt->range.level[1]);
3704 match = mls_level_eq(&rule->au_ctxt.range.level[0],
3707 case Audit_not_equal:
3708 match = !mls_level_eq(&rule->au_ctxt.range.level[0],
3712 match = (mls_level_dom(&rule->au_ctxt.range.level[0],
3714 !mls_level_eq(&rule->au_ctxt.range.level[0],
3718 match = mls_level_dom(&rule->au_ctxt.range.level[0],
3722 match = (mls_level_dom(level,
3723 &rule->au_ctxt.range.level[0]) &&
3724 !mls_level_eq(level,
3725 &rule->au_ctxt.range.level[0]));
3728 match = mls_level_dom(level,
3729 &rule->au_ctxt.range.level[0]);
3739 static int aurule_avc_callback(u32 event)
3741 if (event == AVC_CALLBACK_RESET)
3742 return audit_update_lsm_rules();
3746 static int __init aurule_init(void)
3750 err = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET);
3752 panic("avc_add_callback() failed, error %d\n", err);
3756 __initcall(aurule_init);
3758 #ifdef CONFIG_NETLABEL
3760 * security_netlbl_cache_add - Add an entry to the NetLabel cache
3761 * @secattr: the NetLabel packet security attributes
3762 * @sid: the SELinux SID
3765 * Attempt to cache the context in @ctx, which was derived from the packet in
3766 * @skb, in the NetLabel subsystem cache. This function assumes @secattr has
3767 * already been initialized.
3770 static void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr,
3775 sid_cache = kmalloc(sizeof(*sid_cache), GFP_ATOMIC);
3776 if (sid_cache == NULL)
3778 secattr->cache = netlbl_secattr_cache_alloc(GFP_ATOMIC);
3779 if (secattr->cache == NULL) {
3785 secattr->cache->free = kfree;
3786 secattr->cache->data = sid_cache;
3787 secattr->flags |= NETLBL_SECATTR_CACHE;
3791 * security_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID
3792 * @secattr: the NetLabel packet security attributes
3793 * @sid: the SELinux SID
3796 * Convert the given NetLabel security attributes in @secattr into a
3797 * SELinux SID. If the @secattr field does not contain a full SELinux
3798 * SID/context then use SECINITSID_NETMSG as the foundation. If possible the
3799 * 'cache' field of @secattr is set and the CACHE flag is set; this is to
3800 * allow the @secattr to be used by NetLabel to cache the secattr to SID
3801 * conversion for future lookups. Returns zero on success, negative values on
3805 int security_netlbl_secattr_to_sid(struct netlbl_lsm_secattr *secattr,
3808 struct selinux_policy *policy;
3809 struct policydb *policydb;
3810 struct sidtab *sidtab;
3812 struct context *ctx;
3813 struct context ctx_new;
3815 if (!selinux_initialized()) {
3823 policy = rcu_dereference(selinux_state.policy);
3824 policydb = &policy->policydb;
3825 sidtab = policy->sidtab;
3827 if (secattr->flags & NETLBL_SECATTR_CACHE)
3828 *sid = *(u32 *)secattr->cache->data;
3829 else if (secattr->flags & NETLBL_SECATTR_SECID)
3830 *sid = secattr->attr.secid;
3831 else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) {
3833 ctx = sidtab_search(sidtab, SECINITSID_NETMSG);
3837 context_init(&ctx_new);
3838 ctx_new.user = ctx->user;
3839 ctx_new.role = ctx->role;
3840 ctx_new.type = ctx->type;
3841 mls_import_netlbl_lvl(policydb, &ctx_new, secattr);
3842 if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
3843 rc = mls_import_netlbl_cat(policydb, &ctx_new, secattr);
3848 if (!mls_context_isvalid(policydb, &ctx_new)) {
3849 ebitmap_destroy(&ctx_new.range.level[0].cat);
3853 rc = sidtab_context_to_sid(sidtab, &ctx_new, sid);
3854 ebitmap_destroy(&ctx_new.range.level[0].cat);
3855 if (rc == -ESTALE) {
3862 security_netlbl_cache_add(secattr, *sid);
3872 * security_netlbl_sid_to_secattr - Convert a SELinux SID to a NetLabel secattr
3873 * @sid: the SELinux SID
3874 * @secattr: the NetLabel packet security attributes
3877 * Convert the given SELinux SID in @sid into a NetLabel security attribute.
3878 * Returns zero on success, negative values on failure.
3881 int security_netlbl_sid_to_secattr(u32 sid, struct netlbl_lsm_secattr *secattr)
3883 struct selinux_policy *policy;
3884 struct policydb *policydb;
3886 struct context *ctx;
3888 if (!selinux_initialized())
3892 policy = rcu_dereference(selinux_state.policy);
3893 policydb = &policy->policydb;
3896 ctx = sidtab_search(policy->sidtab, sid);
3901 secattr->domain = kstrdup(sym_name(policydb, SYM_TYPES, ctx->type - 1),
3903 if (secattr->domain == NULL)
3906 secattr->attr.secid = sid;
3907 secattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID;
3908 mls_export_netlbl_lvl(policydb, ctx, secattr);
3909 rc = mls_export_netlbl_cat(policydb, ctx, secattr);
3914 #endif /* CONFIG_NETLABEL */
3917 * __security_read_policy - read the policy.
3918 * @policy: SELinux policy
3919 * @data: binary policy data
3920 * @len: length of data in bytes
3923 static int __security_read_policy(struct selinux_policy *policy,
3924 void *data, size_t *len)
3927 struct policy_file fp;
3932 rc = policydb_write(&policy->policydb, &fp);
3936 *len = (unsigned long)fp.data - (unsigned long)data;
3941 * security_read_policy - read the policy.
3942 * @data: binary policy data
3943 * @len: length of data in bytes
3946 int security_read_policy(void **data, size_t *len)
3948 struct selinux_state *state = &selinux_state;
3949 struct selinux_policy *policy;
3951 policy = rcu_dereference_protected(
3952 state->policy, lockdep_is_held(&state->policy_mutex));
3956 *len = policy->policydb.len;
3957 *data = vmalloc_user(*len);
3961 return __security_read_policy(policy, *data, len);
3965 * security_read_state_kernel - read the policy.
3966 * @data: binary policy data
3967 * @len: length of data in bytes
3969 * Allocates kernel memory for reading SELinux policy.
3970 * This function is for internal use only and should not
3971 * be used for returning data to user space.
3973 * This function must be called with policy_mutex held.
3975 int security_read_state_kernel(void **data, size_t *len)
3978 struct selinux_state *state = &selinux_state;
3979 struct selinux_policy *policy;
3981 policy = rcu_dereference_protected(
3982 state->policy, lockdep_is_held(&state->policy_mutex));
3986 *len = policy->policydb.len;
3987 *data = vmalloc(*len);
3991 err = __security_read_policy(policy, *data, len);