1 // SPDX-License-Identifier: GPL-2.0-only
3 * Implementation of the security services.
5 * Authors : Stephen Smalley, <sds@tycho.nsa.gov>
6 * James Morris <jmorris@redhat.com>
8 * Updated: Trusted Computer Solutions, Inc. <dgoeddel@trustedcs.com>
10 * Support for enhanced MLS infrastructure.
11 * Support for context based audit filters.
13 * Updated: Frank Mayer <mayerf@tresys.com> and Karl MacMillan <kmacmillan@tresys.com>
15 * Added conditional policy language extensions
17 * Updated: Hewlett-Packard <paul@paul-moore.com>
19 * Added support for NetLabel
20 * Added support for the policy capability bitmap
22 * Updated: Chad Sellers <csellers@tresys.com>
24 * Added validation of kernel classes and permissions
26 * Updated: KaiGai Kohei <kaigai@ak.jp.nec.com>
28 * Added support for bounds domain and audit messaged on masked permissions
30 * Updated: Guido Trentalancia <guido@trentalancia.com>
32 * Added support for runtime switching of the policy type
34 * Copyright (C) 2008, 2009 NEC Corporation
35 * Copyright (C) 2006, 2007 Hewlett-Packard Development Company, L.P.
36 * Copyright (C) 2004-2006 Trusted Computer Solutions, Inc.
37 * Copyright (C) 2003 - 2004, 2006 Tresys Technology, LLC
38 * Copyright (C) 2003 Red Hat, Inc., James Morris <jmorris@redhat.com>
40 #include <linux/kernel.h>
41 #include <linux/slab.h>
42 #include <linux/string.h>
43 #include <linux/spinlock.h>
44 #include <linux/rcupdate.h>
45 #include <linux/errno.h>
47 #include <linux/sched.h>
48 #include <linux/audit.h>
49 #include <linux/vmalloc.h>
50 #include <linux/lsm_hooks.h>
51 #include <net/netlabel.h>
61 #include "conditional.h"
68 #include "policycap_names.h"
71 struct convert_context_args {
72 struct selinux_state *state;
73 struct policydb *oldp;
74 struct policydb *newp;
77 struct selinux_policy_convert_data {
78 struct convert_context_args args;
79 struct sidtab_convert_params sidtab_params;
82 /* Forward declaration. */
83 static int context_struct_to_string(struct policydb *policydb,
84 struct context *context,
88 static int sidtab_entry_to_string(struct policydb *policydb,
89 struct sidtab *sidtab,
90 struct sidtab_entry *entry,
94 static void context_struct_compute_av(struct policydb *policydb,
95 struct context *scontext,
96 struct context *tcontext,
98 struct av_decision *avd,
99 struct extended_perms *xperms);
101 static int selinux_set_mapping(struct policydb *pol,
102 struct security_class_mapping *map,
103 struct selinux_map *out_map)
107 bool print_unknown_handle = false;
109 /* Find number of classes in the input mapping */
116 /* Allocate space for the class records, plus one for class zero */
117 out_map->mapping = kcalloc(++i, sizeof(*out_map->mapping), GFP_ATOMIC);
118 if (!out_map->mapping)
121 /* Store the raw class and permission values */
123 while (map[j].name) {
124 struct security_class_mapping *p_in = map + (j++);
125 struct selinux_mapping *p_out = out_map->mapping + j;
127 /* An empty class string skips ahead */
128 if (!strcmp(p_in->name, "")) {
129 p_out->num_perms = 0;
133 p_out->value = string_to_security_class(pol, p_in->name);
135 pr_info("SELinux: Class %s not defined in policy.\n",
137 if (pol->reject_unknown)
139 p_out->num_perms = 0;
140 print_unknown_handle = true;
145 while (p_in->perms[k]) {
146 /* An empty permission string skips ahead */
147 if (!*p_in->perms[k]) {
151 p_out->perms[k] = string_to_av_perm(pol, p_out->value,
153 if (!p_out->perms[k]) {
154 pr_info("SELinux: Permission %s in class %s not defined in policy.\n",
155 p_in->perms[k], p_in->name);
156 if (pol->reject_unknown)
158 print_unknown_handle = true;
163 p_out->num_perms = k;
166 if (print_unknown_handle)
167 pr_info("SELinux: the above unknown classes and permissions will be %s\n",
168 pol->allow_unknown ? "allowed" : "denied");
173 kfree(out_map->mapping);
174 out_map->mapping = NULL;
179 * Get real, policy values from mapped values
182 static u16 unmap_class(struct selinux_map *map, u16 tclass)
184 if (tclass < map->size)
185 return map->mapping[tclass].value;
191 * Get kernel value for class from its policy value
193 static u16 map_class(struct selinux_map *map, u16 pol_value)
197 for (i = 1; i < map->size; i++) {
198 if (map->mapping[i].value == pol_value)
202 return SECCLASS_NULL;
205 static void map_decision(struct selinux_map *map,
206 u16 tclass, struct av_decision *avd,
209 if (tclass < map->size) {
210 struct selinux_mapping *mapping = &map->mapping[tclass];
211 unsigned int i, n = mapping->num_perms;
214 for (i = 0, result = 0; i < n; i++) {
215 if (avd->allowed & mapping->perms[i])
217 if (allow_unknown && !mapping->perms[i])
220 avd->allowed = result;
222 for (i = 0, result = 0; i < n; i++)
223 if (avd->auditallow & mapping->perms[i])
225 avd->auditallow = result;
227 for (i = 0, result = 0; i < n; i++) {
228 if (avd->auditdeny & mapping->perms[i])
230 if (!allow_unknown && !mapping->perms[i])
234 * In case the kernel has a bug and requests a permission
235 * between num_perms and the maximum permission number, we
236 * should audit that denial
238 for (; i < (sizeof(u32)*8); i++)
240 avd->auditdeny = result;
244 int security_mls_enabled(struct selinux_state *state)
247 struct selinux_policy *policy;
249 if (!selinux_initialized(state))
253 policy = rcu_dereference(state->policy);
254 mls_enabled = policy->policydb.mls_enabled;
260 * Return the boolean value of a constraint expression
261 * when it is applied to the specified source and target
264 * xcontext is a special beast... It is used by the validatetrans rules
265 * only. For these rules, scontext is the context before the transition,
266 * tcontext is the context after the transition, and xcontext is the context
267 * of the process performing the transition. All other callers of
268 * constraint_expr_eval should pass in NULL for xcontext.
270 static int constraint_expr_eval(struct policydb *policydb,
271 struct context *scontext,
272 struct context *tcontext,
273 struct context *xcontext,
274 struct constraint_expr *cexpr)
278 struct role_datum *r1, *r2;
279 struct mls_level *l1, *l2;
280 struct constraint_expr *e;
281 int s[CEXPR_MAXDEPTH];
284 for (e = cexpr; e; e = e->next) {
285 switch (e->expr_type) {
301 if (sp == (CEXPR_MAXDEPTH - 1))
305 val1 = scontext->user;
306 val2 = tcontext->user;
309 val1 = scontext->type;
310 val2 = tcontext->type;
313 val1 = scontext->role;
314 val2 = tcontext->role;
315 r1 = policydb->role_val_to_struct[val1 - 1];
316 r2 = policydb->role_val_to_struct[val2 - 1];
319 s[++sp] = ebitmap_get_bit(&r1->dominates,
323 s[++sp] = ebitmap_get_bit(&r2->dominates,
327 s[++sp] = (!ebitmap_get_bit(&r1->dominates,
329 !ebitmap_get_bit(&r2->dominates,
337 l1 = &(scontext->range.level[0]);
338 l2 = &(tcontext->range.level[0]);
341 l1 = &(scontext->range.level[0]);
342 l2 = &(tcontext->range.level[1]);
345 l1 = &(scontext->range.level[1]);
346 l2 = &(tcontext->range.level[0]);
349 l1 = &(scontext->range.level[1]);
350 l2 = &(tcontext->range.level[1]);
353 l1 = &(scontext->range.level[0]);
354 l2 = &(scontext->range.level[1]);
357 l1 = &(tcontext->range.level[0]);
358 l2 = &(tcontext->range.level[1]);
363 s[++sp] = mls_level_eq(l1, l2);
366 s[++sp] = !mls_level_eq(l1, l2);
369 s[++sp] = mls_level_dom(l1, l2);
372 s[++sp] = mls_level_dom(l2, l1);
375 s[++sp] = mls_level_incomp(l2, l1);
389 s[++sp] = (val1 == val2);
392 s[++sp] = (val1 != val2);
400 if (sp == (CEXPR_MAXDEPTH-1))
403 if (e->attr & CEXPR_TARGET)
405 else if (e->attr & CEXPR_XTARGET) {
412 if (e->attr & CEXPR_USER)
414 else if (e->attr & CEXPR_ROLE)
416 else if (e->attr & CEXPR_TYPE)
425 s[++sp] = ebitmap_get_bit(&e->names, val1 - 1);
428 s[++sp] = !ebitmap_get_bit(&e->names, val1 - 1);
446 * security_dump_masked_av - dumps masked permissions during
447 * security_compute_av due to RBAC, MLS/Constraint and Type bounds.
449 static int dump_masked_av_helper(void *k, void *d, void *args)
451 struct perm_datum *pdatum = d;
452 char **permission_names = args;
454 BUG_ON(pdatum->value < 1 || pdatum->value > 32);
456 permission_names[pdatum->value - 1] = (char *)k;
461 static void security_dump_masked_av(struct policydb *policydb,
462 struct context *scontext,
463 struct context *tcontext,
468 struct common_datum *common_dat;
469 struct class_datum *tclass_dat;
470 struct audit_buffer *ab;
472 char *scontext_name = NULL;
473 char *tcontext_name = NULL;
474 char *permission_names[32];
477 bool need_comma = false;
482 tclass_name = sym_name(policydb, SYM_CLASSES, tclass - 1);
483 tclass_dat = policydb->class_val_to_struct[tclass - 1];
484 common_dat = tclass_dat->comdatum;
486 /* init permission_names */
488 hashtab_map(&common_dat->permissions.table,
489 dump_masked_av_helper, permission_names) < 0)
492 if (hashtab_map(&tclass_dat->permissions.table,
493 dump_masked_av_helper, permission_names) < 0)
496 /* get scontext/tcontext in text form */
497 if (context_struct_to_string(policydb, scontext,
498 &scontext_name, &length) < 0)
501 if (context_struct_to_string(policydb, tcontext,
502 &tcontext_name, &length) < 0)
505 /* audit a message */
506 ab = audit_log_start(audit_context(),
507 GFP_ATOMIC, AUDIT_SELINUX_ERR);
511 audit_log_format(ab, "op=security_compute_av reason=%s "
512 "scontext=%s tcontext=%s tclass=%s perms=",
513 reason, scontext_name, tcontext_name, tclass_name);
515 for (index = 0; index < 32; index++) {
516 u32 mask = (1 << index);
518 if ((mask & permissions) == 0)
521 audit_log_format(ab, "%s%s",
522 need_comma ? "," : "",
523 permission_names[index]
524 ? permission_names[index] : "????");
529 /* release scontext/tcontext */
530 kfree(tcontext_name);
531 kfree(scontext_name);
537 * security_boundary_permission - drops violated permissions
538 * on boundary constraint.
540 static void type_attribute_bounds_av(struct policydb *policydb,
541 struct context *scontext,
542 struct context *tcontext,
544 struct av_decision *avd)
546 struct context lo_scontext;
547 struct context lo_tcontext, *tcontextp = tcontext;
548 struct av_decision lo_avd;
549 struct type_datum *source;
550 struct type_datum *target;
553 source = policydb->type_val_to_struct[scontext->type - 1];
559 target = policydb->type_val_to_struct[tcontext->type - 1];
562 memset(&lo_avd, 0, sizeof(lo_avd));
564 memcpy(&lo_scontext, scontext, sizeof(lo_scontext));
565 lo_scontext.type = source->bounds;
567 if (target->bounds) {
568 memcpy(&lo_tcontext, tcontext, sizeof(lo_tcontext));
569 lo_tcontext.type = target->bounds;
570 tcontextp = &lo_tcontext;
573 context_struct_compute_av(policydb, &lo_scontext,
579 masked = ~lo_avd.allowed & avd->allowed;
582 return; /* no masked permission */
584 /* mask violated permissions */
585 avd->allowed &= ~masked;
587 /* audit masked permissions */
588 security_dump_masked_av(policydb, scontext, tcontext,
589 tclass, masked, "bounds");
593 * flag which drivers have permissions
594 * only looking for ioctl based extended permssions
596 void services_compute_xperms_drivers(
597 struct extended_perms *xperms,
598 struct avtab_node *node)
602 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
603 /* if one or more driver has all permissions allowed */
604 for (i = 0; i < ARRAY_SIZE(xperms->drivers.p); i++)
605 xperms->drivers.p[i] |= node->datum.u.xperms->perms.p[i];
606 } else if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
607 /* if allowing permissions within a driver */
608 security_xperm_set(xperms->drivers.p,
609 node->datum.u.xperms->driver);
616 * Compute access vectors and extended permissions based on a context
617 * structure pair for the permissions in a particular class.
619 static void context_struct_compute_av(struct policydb *policydb,
620 struct context *scontext,
621 struct context *tcontext,
623 struct av_decision *avd,
624 struct extended_perms *xperms)
626 struct constraint_node *constraint;
627 struct role_allow *ra;
628 struct avtab_key avkey;
629 struct avtab_node *node;
630 struct class_datum *tclass_datum;
631 struct ebitmap *sattr, *tattr;
632 struct ebitmap_node *snode, *tnode;
637 avd->auditdeny = 0xffffffff;
639 memset(&xperms->drivers, 0, sizeof(xperms->drivers));
643 if (unlikely(!tclass || tclass > policydb->p_classes.nprim)) {
644 if (printk_ratelimit())
645 pr_warn("SELinux: Invalid class %hu\n", tclass);
649 tclass_datum = policydb->class_val_to_struct[tclass - 1];
652 * If a specific type enforcement rule was defined for
653 * this permission check, then use it.
655 avkey.target_class = tclass;
656 avkey.specified = AVTAB_AV | AVTAB_XPERMS;
657 sattr = &policydb->type_attr_map_array[scontext->type - 1];
658 tattr = &policydb->type_attr_map_array[tcontext->type - 1];
659 ebitmap_for_each_positive_bit(sattr, snode, i) {
660 ebitmap_for_each_positive_bit(tattr, tnode, j) {
661 avkey.source_type = i + 1;
662 avkey.target_type = j + 1;
663 for (node = avtab_search_node(&policydb->te_avtab,
666 node = avtab_search_node_next(node, avkey.specified)) {
667 if (node->key.specified == AVTAB_ALLOWED)
668 avd->allowed |= node->datum.u.data;
669 else if (node->key.specified == AVTAB_AUDITALLOW)
670 avd->auditallow |= node->datum.u.data;
671 else if (node->key.specified == AVTAB_AUDITDENY)
672 avd->auditdeny &= node->datum.u.data;
673 else if (xperms && (node->key.specified & AVTAB_XPERMS))
674 services_compute_xperms_drivers(xperms, node);
677 /* Check conditional av table for additional permissions */
678 cond_compute_av(&policydb->te_cond_avtab, &avkey,
685 * Remove any permissions prohibited by a constraint (this includes
688 constraint = tclass_datum->constraints;
690 if ((constraint->permissions & (avd->allowed)) &&
691 !constraint_expr_eval(policydb, scontext, tcontext, NULL,
693 avd->allowed &= ~(constraint->permissions);
695 constraint = constraint->next;
699 * If checking process transition permission and the
700 * role is changing, then check the (current_role, new_role)
703 if (tclass == policydb->process_class &&
704 (avd->allowed & policydb->process_trans_perms) &&
705 scontext->role != tcontext->role) {
706 for (ra = policydb->role_allow; ra; ra = ra->next) {
707 if (scontext->role == ra->role &&
708 tcontext->role == ra->new_role)
712 avd->allowed &= ~policydb->process_trans_perms;
716 * If the given source and target types have boundary
717 * constraint, lazy checks have to mask any violated
718 * permission and notice it to userspace via audit.
720 type_attribute_bounds_av(policydb, scontext, tcontext,
724 static int security_validtrans_handle_fail(struct selinux_state *state,
725 struct selinux_policy *policy,
726 struct sidtab_entry *oentry,
727 struct sidtab_entry *nentry,
728 struct sidtab_entry *tentry,
731 struct policydb *p = &policy->policydb;
732 struct sidtab *sidtab = policy->sidtab;
733 char *o = NULL, *n = NULL, *t = NULL;
734 u32 olen, nlen, tlen;
736 if (sidtab_entry_to_string(p, sidtab, oentry, &o, &olen))
738 if (sidtab_entry_to_string(p, sidtab, nentry, &n, &nlen))
740 if (sidtab_entry_to_string(p, sidtab, tentry, &t, &tlen))
742 audit_log(audit_context(), GFP_ATOMIC, AUDIT_SELINUX_ERR,
743 "op=security_validate_transition seresult=denied"
744 " oldcontext=%s newcontext=%s taskcontext=%s tclass=%s",
745 o, n, t, sym_name(p, SYM_CLASSES, tclass-1));
751 if (!enforcing_enabled(state))
756 static int security_compute_validatetrans(struct selinux_state *state,
757 u32 oldsid, u32 newsid, u32 tasksid,
758 u16 orig_tclass, bool user)
760 struct selinux_policy *policy;
761 struct policydb *policydb;
762 struct sidtab *sidtab;
763 struct sidtab_entry *oentry;
764 struct sidtab_entry *nentry;
765 struct sidtab_entry *tentry;
766 struct class_datum *tclass_datum;
767 struct constraint_node *constraint;
772 if (!selinux_initialized(state))
777 policy = rcu_dereference(state->policy);
778 policydb = &policy->policydb;
779 sidtab = policy->sidtab;
782 tclass = unmap_class(&policy->map, orig_tclass);
784 tclass = orig_tclass;
786 if (!tclass || tclass > policydb->p_classes.nprim) {
790 tclass_datum = policydb->class_val_to_struct[tclass - 1];
792 oentry = sidtab_search_entry(sidtab, oldsid);
794 pr_err("SELinux: %s: unrecognized SID %d\n",
800 nentry = sidtab_search_entry(sidtab, newsid);
802 pr_err("SELinux: %s: unrecognized SID %d\n",
808 tentry = sidtab_search_entry(sidtab, tasksid);
810 pr_err("SELinux: %s: unrecognized SID %d\n",
816 constraint = tclass_datum->validatetrans;
818 if (!constraint_expr_eval(policydb, &oentry->context,
819 &nentry->context, &tentry->context,
824 rc = security_validtrans_handle_fail(state,
832 constraint = constraint->next;
840 int security_validate_transition_user(struct selinux_state *state,
841 u32 oldsid, u32 newsid, u32 tasksid,
844 return security_compute_validatetrans(state, oldsid, newsid, tasksid,
848 int security_validate_transition(struct selinux_state *state,
849 u32 oldsid, u32 newsid, u32 tasksid,
852 return security_compute_validatetrans(state, oldsid, newsid, tasksid,
857 * security_bounded_transition - check whether the given
858 * transition is directed to bounded, or not.
859 * It returns 0, if @newsid is bounded by @oldsid.
860 * Otherwise, it returns error code.
862 * @oldsid : current security identifier
863 * @newsid : destinated security identifier
865 int security_bounded_transition(struct selinux_state *state,
866 u32 old_sid, u32 new_sid)
868 struct selinux_policy *policy;
869 struct policydb *policydb;
870 struct sidtab *sidtab;
871 struct sidtab_entry *old_entry, *new_entry;
872 struct type_datum *type;
876 if (!selinux_initialized(state))
880 policy = rcu_dereference(state->policy);
881 policydb = &policy->policydb;
882 sidtab = policy->sidtab;
885 old_entry = sidtab_search_entry(sidtab, old_sid);
887 pr_err("SELinux: %s: unrecognized SID %u\n",
893 new_entry = sidtab_search_entry(sidtab, new_sid);
895 pr_err("SELinux: %s: unrecognized SID %u\n",
901 /* type/domain unchanged */
902 if (old_entry->context.type == new_entry->context.type)
905 index = new_entry->context.type;
907 type = policydb->type_val_to_struct[index - 1];
910 /* not bounded anymore */
915 /* @newsid is bounded by @oldsid */
917 if (type->bounds == old_entry->context.type)
920 index = type->bounds;
924 char *old_name = NULL;
925 char *new_name = NULL;
928 if (!sidtab_entry_to_string(policydb, sidtab, old_entry,
929 &old_name, &length) &&
930 !sidtab_entry_to_string(policydb, sidtab, new_entry,
931 &new_name, &length)) {
932 audit_log(audit_context(),
933 GFP_ATOMIC, AUDIT_SELINUX_ERR,
934 "op=security_bounded_transition "
936 "oldcontext=%s newcontext=%s",
948 static void avd_init(struct selinux_policy *policy, struct av_decision *avd)
952 avd->auditdeny = 0xffffffff;
954 avd->seqno = policy->latest_granting;
960 void services_compute_xperms_decision(struct extended_perms_decision *xpermd,
961 struct avtab_node *node)
965 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
966 if (xpermd->driver != node->datum.u.xperms->driver)
968 } else if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
969 if (!security_xperm_test(node->datum.u.xperms->perms.p,
976 if (node->key.specified == AVTAB_XPERMS_ALLOWED) {
977 xpermd->used |= XPERMS_ALLOWED;
978 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
979 memset(xpermd->allowed->p, 0xff,
980 sizeof(xpermd->allowed->p));
982 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
983 for (i = 0; i < ARRAY_SIZE(xpermd->allowed->p); i++)
984 xpermd->allowed->p[i] |=
985 node->datum.u.xperms->perms.p[i];
987 } else if (node->key.specified == AVTAB_XPERMS_AUDITALLOW) {
988 xpermd->used |= XPERMS_AUDITALLOW;
989 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
990 memset(xpermd->auditallow->p, 0xff,
991 sizeof(xpermd->auditallow->p));
993 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
994 for (i = 0; i < ARRAY_SIZE(xpermd->auditallow->p); i++)
995 xpermd->auditallow->p[i] |=
996 node->datum.u.xperms->perms.p[i];
998 } else if (node->key.specified == AVTAB_XPERMS_DONTAUDIT) {
999 xpermd->used |= XPERMS_DONTAUDIT;
1000 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
1001 memset(xpermd->dontaudit->p, 0xff,
1002 sizeof(xpermd->dontaudit->p));
1004 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
1005 for (i = 0; i < ARRAY_SIZE(xpermd->dontaudit->p); i++)
1006 xpermd->dontaudit->p[i] |=
1007 node->datum.u.xperms->perms.p[i];
1014 void security_compute_xperms_decision(struct selinux_state *state,
1019 struct extended_perms_decision *xpermd)
1021 struct selinux_policy *policy;
1022 struct policydb *policydb;
1023 struct sidtab *sidtab;
1025 struct context *scontext, *tcontext;
1026 struct avtab_key avkey;
1027 struct avtab_node *node;
1028 struct ebitmap *sattr, *tattr;
1029 struct ebitmap_node *snode, *tnode;
1032 xpermd->driver = driver;
1034 memset(xpermd->allowed->p, 0, sizeof(xpermd->allowed->p));
1035 memset(xpermd->auditallow->p, 0, sizeof(xpermd->auditallow->p));
1036 memset(xpermd->dontaudit->p, 0, sizeof(xpermd->dontaudit->p));
1039 if (!selinux_initialized(state))
1042 policy = rcu_dereference(state->policy);
1043 policydb = &policy->policydb;
1044 sidtab = policy->sidtab;
1046 scontext = sidtab_search(sidtab, ssid);
1048 pr_err("SELinux: %s: unrecognized SID %d\n",
1053 tcontext = sidtab_search(sidtab, tsid);
1055 pr_err("SELinux: %s: unrecognized SID %d\n",
1060 tclass = unmap_class(&policy->map, orig_tclass);
1061 if (unlikely(orig_tclass && !tclass)) {
1062 if (policydb->allow_unknown)
1068 if (unlikely(!tclass || tclass > policydb->p_classes.nprim)) {
1069 pr_warn_ratelimited("SELinux: Invalid class %hu\n", tclass);
1073 avkey.target_class = tclass;
1074 avkey.specified = AVTAB_XPERMS;
1075 sattr = &policydb->type_attr_map_array[scontext->type - 1];
1076 tattr = &policydb->type_attr_map_array[tcontext->type - 1];
1077 ebitmap_for_each_positive_bit(sattr, snode, i) {
1078 ebitmap_for_each_positive_bit(tattr, tnode, j) {
1079 avkey.source_type = i + 1;
1080 avkey.target_type = j + 1;
1081 for (node = avtab_search_node(&policydb->te_avtab,
1084 node = avtab_search_node_next(node, avkey.specified))
1085 services_compute_xperms_decision(xpermd, node);
1087 cond_compute_xperms(&policydb->te_cond_avtab,
1095 memset(xpermd->allowed->p, 0xff, sizeof(xpermd->allowed->p));
1100 * security_compute_av - Compute access vector decisions.
1101 * @ssid: source security identifier
1102 * @tsid: target security identifier
1103 * @tclass: target security class
1104 * @avd: access vector decisions
1105 * @xperms: extended permissions
1107 * Compute a set of access vector decisions based on the
1108 * SID pair (@ssid, @tsid) for the permissions in @tclass.
1110 void security_compute_av(struct selinux_state *state,
1114 struct av_decision *avd,
1115 struct extended_perms *xperms)
1117 struct selinux_policy *policy;
1118 struct policydb *policydb;
1119 struct sidtab *sidtab;
1121 struct context *scontext = NULL, *tcontext = NULL;
1124 policy = rcu_dereference(state->policy);
1125 avd_init(policy, avd);
1127 if (!selinux_initialized(state))
1130 policydb = &policy->policydb;
1131 sidtab = policy->sidtab;
1133 scontext = sidtab_search(sidtab, ssid);
1135 pr_err("SELinux: %s: unrecognized SID %d\n",
1140 /* permissive domain? */
1141 if (ebitmap_get_bit(&policydb->permissive_map, scontext->type))
1142 avd->flags |= AVD_FLAGS_PERMISSIVE;
1144 tcontext = sidtab_search(sidtab, tsid);
1146 pr_err("SELinux: %s: unrecognized SID %d\n",
1151 tclass = unmap_class(&policy->map, orig_tclass);
1152 if (unlikely(orig_tclass && !tclass)) {
1153 if (policydb->allow_unknown)
1157 context_struct_compute_av(policydb, scontext, tcontext, tclass, avd,
1159 map_decision(&policy->map, orig_tclass, avd,
1160 policydb->allow_unknown);
1165 avd->allowed = 0xffffffff;
1169 void security_compute_av_user(struct selinux_state *state,
1173 struct av_decision *avd)
1175 struct selinux_policy *policy;
1176 struct policydb *policydb;
1177 struct sidtab *sidtab;
1178 struct context *scontext = NULL, *tcontext = NULL;
1181 policy = rcu_dereference(state->policy);
1182 avd_init(policy, avd);
1183 if (!selinux_initialized(state))
1186 policydb = &policy->policydb;
1187 sidtab = policy->sidtab;
1189 scontext = sidtab_search(sidtab, ssid);
1191 pr_err("SELinux: %s: unrecognized SID %d\n",
1196 /* permissive domain? */
1197 if (ebitmap_get_bit(&policydb->permissive_map, scontext->type))
1198 avd->flags |= AVD_FLAGS_PERMISSIVE;
1200 tcontext = sidtab_search(sidtab, tsid);
1202 pr_err("SELinux: %s: unrecognized SID %d\n",
1207 if (unlikely(!tclass)) {
1208 if (policydb->allow_unknown)
1213 context_struct_compute_av(policydb, scontext, tcontext, tclass, avd,
1219 avd->allowed = 0xffffffff;
1224 * Write the security context string representation of
1225 * the context structure `context' into a dynamically
1226 * allocated string of the correct size. Set `*scontext'
1227 * to point to this string and set `*scontext_len' to
1228 * the length of the string.
1230 static int context_struct_to_string(struct policydb *p,
1231 struct context *context,
1232 char **scontext, u32 *scontext_len)
1241 *scontext_len = context->len;
1243 *scontext = kstrdup(context->str, GFP_ATOMIC);
1250 /* Compute the size of the context. */
1251 *scontext_len += strlen(sym_name(p, SYM_USERS, context->user - 1)) + 1;
1252 *scontext_len += strlen(sym_name(p, SYM_ROLES, context->role - 1)) + 1;
1253 *scontext_len += strlen(sym_name(p, SYM_TYPES, context->type - 1)) + 1;
1254 *scontext_len += mls_compute_context_len(p, context);
1259 /* Allocate space for the context; caller must free this space. */
1260 scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
1263 *scontext = scontextp;
1266 * Copy the user name, role name and type name into the context.
1268 scontextp += sprintf(scontextp, "%s:%s:%s",
1269 sym_name(p, SYM_USERS, context->user - 1),
1270 sym_name(p, SYM_ROLES, context->role - 1),
1271 sym_name(p, SYM_TYPES, context->type - 1));
1273 mls_sid_to_context(p, context, &scontextp);
1280 static int sidtab_entry_to_string(struct policydb *p,
1281 struct sidtab *sidtab,
1282 struct sidtab_entry *entry,
1283 char **scontext, u32 *scontext_len)
1285 int rc = sidtab_sid2str_get(sidtab, entry, scontext, scontext_len);
1290 rc = context_struct_to_string(p, &entry->context, scontext,
1292 if (!rc && scontext)
1293 sidtab_sid2str_put(sidtab, entry, *scontext, *scontext_len);
1297 #include "initial_sid_to_string.h"
1299 int security_sidtab_hash_stats(struct selinux_state *state, char *page)
1301 struct selinux_policy *policy;
1304 if (!selinux_initialized(state)) {
1305 pr_err("SELinux: %s: called before initial load_policy\n",
1311 policy = rcu_dereference(state->policy);
1312 rc = sidtab_hash_stats(policy->sidtab, page);
1318 const char *security_get_initial_sid_context(u32 sid)
1320 if (unlikely(sid > SECINITSID_NUM))
1322 return initial_sid_to_string[sid];
1325 static int security_sid_to_context_core(struct selinux_state *state,
1326 u32 sid, char **scontext,
1327 u32 *scontext_len, int force,
1330 struct selinux_policy *policy;
1331 struct policydb *policydb;
1332 struct sidtab *sidtab;
1333 struct sidtab_entry *entry;
1340 if (!selinux_initialized(state)) {
1341 if (sid <= SECINITSID_NUM) {
1343 const char *s = initial_sid_to_string[sid];
1347 *scontext_len = strlen(s) + 1;
1350 scontextp = kmemdup(s, *scontext_len, GFP_ATOMIC);
1353 *scontext = scontextp;
1356 pr_err("SELinux: %s: called before initial "
1357 "load_policy on unknown SID %d\n", __func__, sid);
1361 policy = rcu_dereference(state->policy);
1362 policydb = &policy->policydb;
1363 sidtab = policy->sidtab;
1366 entry = sidtab_search_entry_force(sidtab, sid);
1368 entry = sidtab_search_entry(sidtab, sid);
1370 pr_err("SELinux: %s: unrecognized SID %d\n",
1375 if (only_invalid && !entry->context.len)
1378 rc = sidtab_entry_to_string(policydb, sidtab, entry, scontext,
1388 * security_sid_to_context - Obtain a context for a given SID.
1389 * @sid: security identifier, SID
1390 * @scontext: security context
1391 * @scontext_len: length in bytes
1393 * Write the string representation of the context associated with @sid
1394 * into a dynamically allocated string of the correct size. Set @scontext
1395 * to point to this string and set @scontext_len to the length of the string.
1397 int security_sid_to_context(struct selinux_state *state,
1398 u32 sid, char **scontext, u32 *scontext_len)
1400 return security_sid_to_context_core(state, sid, scontext,
1401 scontext_len, 0, 0);
1404 int security_sid_to_context_force(struct selinux_state *state, u32 sid,
1405 char **scontext, u32 *scontext_len)
1407 return security_sid_to_context_core(state, sid, scontext,
1408 scontext_len, 1, 0);
1412 * security_sid_to_context_inval - Obtain a context for a given SID if it
1414 * @sid: security identifier, SID
1415 * @scontext: security context
1416 * @scontext_len: length in bytes
1418 * Write the string representation of the context associated with @sid
1419 * into a dynamically allocated string of the correct size, but only if the
1420 * context is invalid in the current policy. Set @scontext to point to
1421 * this string (or NULL if the context is valid) and set @scontext_len to
1422 * the length of the string (or 0 if the context is valid).
1424 int security_sid_to_context_inval(struct selinux_state *state, u32 sid,
1425 char **scontext, u32 *scontext_len)
1427 return security_sid_to_context_core(state, sid, scontext,
1428 scontext_len, 1, 1);
1432 * Caveat: Mutates scontext.
1434 static int string_to_context_struct(struct policydb *pol,
1435 struct sidtab *sidtabp,
1437 struct context *ctx,
1440 struct role_datum *role;
1441 struct type_datum *typdatum;
1442 struct user_datum *usrdatum;
1443 char *scontextp, *p, oldc;
1448 /* Parse the security context. */
1451 scontextp = (char *) scontext;
1453 /* Extract the user. */
1455 while (*p && *p != ':')
1463 usrdatum = symtab_search(&pol->p_users, scontextp);
1467 ctx->user = usrdatum->value;
1471 while (*p && *p != ':')
1479 role = symtab_search(&pol->p_roles, scontextp);
1482 ctx->role = role->value;
1486 while (*p && *p != ':')
1491 typdatum = symtab_search(&pol->p_types, scontextp);
1492 if (!typdatum || typdatum->attribute)
1495 ctx->type = typdatum->value;
1497 rc = mls_context_to_sid(pol, oldc, p, ctx, sidtabp, def_sid);
1501 /* Check the validity of the new context. */
1503 if (!policydb_context_isvalid(pol, ctx))
1508 context_destroy(ctx);
1512 static int security_context_to_sid_core(struct selinux_state *state,
1513 const char *scontext, u32 scontext_len,
1514 u32 *sid, u32 def_sid, gfp_t gfp_flags,
1517 struct selinux_policy *policy;
1518 struct policydb *policydb;
1519 struct sidtab *sidtab;
1520 char *scontext2, *str = NULL;
1521 struct context context;
1524 /* An empty security context is never valid. */
1528 /* Copy the string to allow changes and ensure a NUL terminator */
1529 scontext2 = kmemdup_nul(scontext, scontext_len, gfp_flags);
1533 if (!selinux_initialized(state)) {
1536 for (i = 1; i < SECINITSID_NUM; i++) {
1537 const char *s = initial_sid_to_string[i];
1539 if (s && !strcmp(s, scontext2)) {
1544 *sid = SECINITSID_KERNEL;
1550 /* Save another copy for storing in uninterpreted form */
1552 str = kstrdup(scontext2, gfp_flags);
1558 policy = rcu_dereference(state->policy);
1559 policydb = &policy->policydb;
1560 sidtab = policy->sidtab;
1561 rc = string_to_context_struct(policydb, sidtab, scontext2,
1563 if (rc == -EINVAL && force) {
1565 context.len = strlen(str) + 1;
1569 rc = sidtab_context_to_sid(sidtab, &context, sid);
1570 if (rc == -ESTALE) {
1576 context_destroy(&context);
1579 context_destroy(&context);
1589 * security_context_to_sid - Obtain a SID for a given security context.
1590 * @scontext: security context
1591 * @scontext_len: length in bytes
1592 * @sid: security identifier, SID
1593 * @gfp: context for the allocation
1595 * Obtains a SID associated with the security context that
1596 * has the string representation specified by @scontext.
1597 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1598 * memory is available, or 0 on success.
1600 int security_context_to_sid(struct selinux_state *state,
1601 const char *scontext, u32 scontext_len, u32 *sid,
1604 return security_context_to_sid_core(state, scontext, scontext_len,
1605 sid, SECSID_NULL, gfp, 0);
1608 int security_context_str_to_sid(struct selinux_state *state,
1609 const char *scontext, u32 *sid, gfp_t gfp)
1611 return security_context_to_sid(state, scontext, strlen(scontext),
1616 * security_context_to_sid_default - Obtain a SID for a given security context,
1617 * falling back to specified default if needed.
1619 * @scontext: security context
1620 * @scontext_len: length in bytes
1621 * @sid: security identifier, SID
1622 * @def_sid: default SID to assign on error
1624 * Obtains a SID associated with the security context that
1625 * has the string representation specified by @scontext.
1626 * The default SID is passed to the MLS layer to be used to allow
1627 * kernel labeling of the MLS field if the MLS field is not present
1628 * (for upgrading to MLS without full relabel).
1629 * Implicitly forces adding of the context even if it cannot be mapped yet.
1630 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1631 * memory is available, or 0 on success.
1633 int security_context_to_sid_default(struct selinux_state *state,
1634 const char *scontext, u32 scontext_len,
1635 u32 *sid, u32 def_sid, gfp_t gfp_flags)
1637 return security_context_to_sid_core(state, scontext, scontext_len,
1638 sid, def_sid, gfp_flags, 1);
1641 int security_context_to_sid_force(struct selinux_state *state,
1642 const char *scontext, u32 scontext_len,
1645 return security_context_to_sid_core(state, scontext, scontext_len,
1646 sid, SECSID_NULL, GFP_KERNEL, 1);
1649 static int compute_sid_handle_invalid_context(
1650 struct selinux_state *state,
1651 struct selinux_policy *policy,
1652 struct sidtab_entry *sentry,
1653 struct sidtab_entry *tentry,
1655 struct context *newcontext)
1657 struct policydb *policydb = &policy->policydb;
1658 struct sidtab *sidtab = policy->sidtab;
1659 char *s = NULL, *t = NULL, *n = NULL;
1660 u32 slen, tlen, nlen;
1661 struct audit_buffer *ab;
1663 if (sidtab_entry_to_string(policydb, sidtab, sentry, &s, &slen))
1665 if (sidtab_entry_to_string(policydb, sidtab, tentry, &t, &tlen))
1667 if (context_struct_to_string(policydb, newcontext, &n, &nlen))
1669 ab = audit_log_start(audit_context(), GFP_ATOMIC, AUDIT_SELINUX_ERR);
1670 audit_log_format(ab,
1671 "op=security_compute_sid invalid_context=");
1672 /* no need to record the NUL with untrusted strings */
1673 audit_log_n_untrustedstring(ab, n, nlen - 1);
1674 audit_log_format(ab, " scontext=%s tcontext=%s tclass=%s",
1675 s, t, sym_name(policydb, SYM_CLASSES, tclass-1));
1681 if (!enforcing_enabled(state))
1686 static void filename_compute_type(struct policydb *policydb,
1687 struct context *newcontext,
1688 u32 stype, u32 ttype, u16 tclass,
1689 const char *objname)
1691 struct filename_trans_key ft;
1692 struct filename_trans_datum *datum;
1695 * Most filename trans rules are going to live in specific directories
1696 * like /dev or /var/run. This bitmap will quickly skip rule searches
1697 * if the ttype does not contain any rules.
1699 if (!ebitmap_get_bit(&policydb->filename_trans_ttypes, ttype))
1706 datum = policydb_filenametr_search(policydb, &ft);
1708 if (ebitmap_get_bit(&datum->stypes, stype - 1)) {
1709 newcontext->type = datum->otype;
1712 datum = datum->next;
1716 static int security_compute_sid(struct selinux_state *state,
1721 const char *objname,
1725 struct selinux_policy *policy;
1726 struct policydb *policydb;
1727 struct sidtab *sidtab;
1728 struct class_datum *cladatum;
1729 struct context *scontext, *tcontext, newcontext;
1730 struct sidtab_entry *sentry, *tentry;
1731 struct avtab_key avkey;
1732 struct avtab_datum *avdatum;
1733 struct avtab_node *node;
1738 if (!selinux_initialized(state)) {
1739 switch (orig_tclass) {
1740 case SECCLASS_PROCESS: /* kernel value */
1752 context_init(&newcontext);
1756 policy = rcu_dereference(state->policy);
1759 tclass = unmap_class(&policy->map, orig_tclass);
1760 sock = security_is_socket_class(orig_tclass);
1762 tclass = orig_tclass;
1763 sock = security_is_socket_class(map_class(&policy->map,
1767 policydb = &policy->policydb;
1768 sidtab = policy->sidtab;
1770 sentry = sidtab_search_entry(sidtab, ssid);
1772 pr_err("SELinux: %s: unrecognized SID %d\n",
1777 tentry = sidtab_search_entry(sidtab, tsid);
1779 pr_err("SELinux: %s: unrecognized SID %d\n",
1785 scontext = &sentry->context;
1786 tcontext = &tentry->context;
1788 if (tclass && tclass <= policydb->p_classes.nprim)
1789 cladatum = policydb->class_val_to_struct[tclass - 1];
1791 /* Set the user identity. */
1792 switch (specified) {
1793 case AVTAB_TRANSITION:
1795 if (cladatum && cladatum->default_user == DEFAULT_TARGET) {
1796 newcontext.user = tcontext->user;
1798 /* notice this gets both DEFAULT_SOURCE and unset */
1799 /* Use the process user identity. */
1800 newcontext.user = scontext->user;
1804 /* Use the related object owner. */
1805 newcontext.user = tcontext->user;
1809 /* Set the role to default values. */
1810 if (cladatum && cladatum->default_role == DEFAULT_SOURCE) {
1811 newcontext.role = scontext->role;
1812 } else if (cladatum && cladatum->default_role == DEFAULT_TARGET) {
1813 newcontext.role = tcontext->role;
1815 if ((tclass == policydb->process_class) || sock)
1816 newcontext.role = scontext->role;
1818 newcontext.role = OBJECT_R_VAL;
1821 /* Set the type to default values. */
1822 if (cladatum && cladatum->default_type == DEFAULT_SOURCE) {
1823 newcontext.type = scontext->type;
1824 } else if (cladatum && cladatum->default_type == DEFAULT_TARGET) {
1825 newcontext.type = tcontext->type;
1827 if ((tclass == policydb->process_class) || sock) {
1828 /* Use the type of process. */
1829 newcontext.type = scontext->type;
1831 /* Use the type of the related object. */
1832 newcontext.type = tcontext->type;
1836 /* Look for a type transition/member/change rule. */
1837 avkey.source_type = scontext->type;
1838 avkey.target_type = tcontext->type;
1839 avkey.target_class = tclass;
1840 avkey.specified = specified;
1841 avdatum = avtab_search(&policydb->te_avtab, &avkey);
1843 /* If no permanent rule, also check for enabled conditional rules */
1845 node = avtab_search_node(&policydb->te_cond_avtab, &avkey);
1846 for (; node; node = avtab_search_node_next(node, specified)) {
1847 if (node->key.specified & AVTAB_ENABLED) {
1848 avdatum = &node->datum;
1855 /* Use the type from the type transition/member/change rule. */
1856 newcontext.type = avdatum->u.data;
1859 /* if we have a objname this is a file trans check so check those rules */
1861 filename_compute_type(policydb, &newcontext, scontext->type,
1862 tcontext->type, tclass, objname);
1864 /* Check for class-specific changes. */
1865 if (specified & AVTAB_TRANSITION) {
1866 /* Look for a role transition rule. */
1867 struct role_trans_datum *rtd;
1868 struct role_trans_key rtk = {
1869 .role = scontext->role,
1870 .type = tcontext->type,
1874 rtd = policydb_roletr_search(policydb, &rtk);
1876 newcontext.role = rtd->new_role;
1879 /* Set the MLS attributes.
1880 This is done last because it may allocate memory. */
1881 rc = mls_compute_sid(policydb, scontext, tcontext, tclass, specified,
1886 /* Check the validity of the context. */
1887 if (!policydb_context_isvalid(policydb, &newcontext)) {
1888 rc = compute_sid_handle_invalid_context(state, policy, sentry,
1894 /* Obtain the sid for the context. */
1895 rc = sidtab_context_to_sid(sidtab, &newcontext, out_sid);
1896 if (rc == -ESTALE) {
1898 context_destroy(&newcontext);
1903 context_destroy(&newcontext);
1909 * security_transition_sid - Compute the SID for a new subject/object.
1910 * @ssid: source security identifier
1911 * @tsid: target security identifier
1912 * @tclass: target security class
1913 * @out_sid: security identifier for new subject/object
1915 * Compute a SID to use for labeling a new subject or object in the
1916 * class @tclass based on a SID pair (@ssid, @tsid).
1917 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1918 * if insufficient memory is available, or %0 if the new SID was
1919 * computed successfully.
1921 int security_transition_sid(struct selinux_state *state,
1922 u32 ssid, u32 tsid, u16 tclass,
1923 const struct qstr *qstr, u32 *out_sid)
1925 return security_compute_sid(state, ssid, tsid, tclass,
1927 qstr ? qstr->name : NULL, out_sid, true);
1930 int security_transition_sid_user(struct selinux_state *state,
1931 u32 ssid, u32 tsid, u16 tclass,
1932 const char *objname, u32 *out_sid)
1934 return security_compute_sid(state, ssid, tsid, tclass,
1936 objname, out_sid, false);
1940 * security_member_sid - Compute the SID for member selection.
1941 * @ssid: source security identifier
1942 * @tsid: target security identifier
1943 * @tclass: target security class
1944 * @out_sid: security identifier for selected member
1946 * Compute a SID to use when selecting a member of a polyinstantiated
1947 * object of class @tclass based on a SID pair (@ssid, @tsid).
1948 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1949 * if insufficient memory is available, or %0 if the SID was
1950 * computed successfully.
1952 int security_member_sid(struct selinux_state *state,
1958 return security_compute_sid(state, ssid, tsid, tclass,
1964 * security_change_sid - Compute the SID for object relabeling.
1965 * @ssid: source security identifier
1966 * @tsid: target security identifier
1967 * @tclass: target security class
1968 * @out_sid: security identifier for selected member
1970 * Compute a SID to use for relabeling an object of class @tclass
1971 * based on a SID pair (@ssid, @tsid).
1972 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1973 * if insufficient memory is available, or %0 if the SID was
1974 * computed successfully.
1976 int security_change_sid(struct selinux_state *state,
1982 return security_compute_sid(state,
1983 ssid, tsid, tclass, AVTAB_CHANGE, NULL,
1987 static inline int convert_context_handle_invalid_context(
1988 struct selinux_state *state,
1989 struct policydb *policydb,
1990 struct context *context)
1995 if (enforcing_enabled(state))
1998 if (!context_struct_to_string(policydb, context, &s, &len)) {
1999 pr_warn("SELinux: Context %s would be invalid if enforcing\n",
2007 * Convert the values in the security context
2008 * structure `oldc' from the values specified
2009 * in the policy `p->oldp' to the values specified
2010 * in the policy `p->newp', storing the new context
2011 * in `newc'. Verify that the context is valid
2012 * under the new policy.
2014 static int convert_context(struct context *oldc, struct context *newc, void *p)
2016 struct convert_context_args *args;
2017 struct ocontext *oc;
2018 struct role_datum *role;
2019 struct type_datum *typdatum;
2020 struct user_datum *usrdatum;
2028 s = kstrdup(oldc->str, GFP_KERNEL);
2032 rc = string_to_context_struct(args->newp, NULL, s,
2034 if (rc == -EINVAL) {
2036 * Retain string representation for later mapping.
2038 * IMPORTANT: We need to copy the contents of oldc->str
2039 * back into s again because string_to_context_struct()
2040 * may have garbled it.
2042 memcpy(s, oldc->str, oldc->len);
2045 newc->len = oldc->len;
2050 /* Other error condition, e.g. ENOMEM. */
2051 pr_err("SELinux: Unable to map context %s, rc = %d.\n",
2055 pr_info("SELinux: Context %s became valid (mapped).\n",
2062 /* Convert the user. */
2064 usrdatum = symtab_search(&args->newp->p_users,
2065 sym_name(args->oldp,
2066 SYM_USERS, oldc->user - 1));
2069 newc->user = usrdatum->value;
2071 /* Convert the role. */
2073 role = symtab_search(&args->newp->p_roles,
2074 sym_name(args->oldp, SYM_ROLES, oldc->role - 1));
2077 newc->role = role->value;
2079 /* Convert the type. */
2081 typdatum = symtab_search(&args->newp->p_types,
2082 sym_name(args->oldp,
2083 SYM_TYPES, oldc->type - 1));
2086 newc->type = typdatum->value;
2088 /* Convert the MLS fields if dealing with MLS policies */
2089 if (args->oldp->mls_enabled && args->newp->mls_enabled) {
2090 rc = mls_convert_context(args->oldp, args->newp, oldc, newc);
2093 } else if (!args->oldp->mls_enabled && args->newp->mls_enabled) {
2095 * Switching between non-MLS and MLS policy:
2096 * ensure that the MLS fields of the context for all
2097 * existing entries in the sidtab are filled in with a
2098 * suitable default value, likely taken from one of the
2101 oc = args->newp->ocontexts[OCON_ISID];
2102 while (oc && oc->sid[0] != SECINITSID_UNLABELED)
2106 pr_err("SELinux: unable to look up"
2107 " the initial SIDs list\n");
2110 rc = mls_range_set(newc, &oc->context[0].range);
2115 /* Check the validity of the new context. */
2116 if (!policydb_context_isvalid(args->newp, newc)) {
2117 rc = convert_context_handle_invalid_context(args->state,
2126 /* Map old representation to string and save it. */
2127 rc = context_struct_to_string(args->oldp, oldc, &s, &len);
2130 context_destroy(newc);
2133 pr_info("SELinux: Context %s became invalid (unmapped).\n",
2138 static void security_load_policycaps(struct selinux_state *state,
2139 struct selinux_policy *policy)
2143 struct ebitmap_node *node;
2145 p = &policy->policydb;
2147 for (i = 0; i < ARRAY_SIZE(state->policycap); i++)
2148 WRITE_ONCE(state->policycap[i],
2149 ebitmap_get_bit(&p->policycaps, i));
2151 for (i = 0; i < ARRAY_SIZE(selinux_policycap_names); i++)
2152 pr_info("SELinux: policy capability %s=%d\n",
2153 selinux_policycap_names[i],
2154 ebitmap_get_bit(&p->policycaps, i));
2156 ebitmap_for_each_positive_bit(&p->policycaps, node, i) {
2157 if (i >= ARRAY_SIZE(selinux_policycap_names))
2158 pr_info("SELinux: unknown policy capability %u\n",
2163 static int security_preserve_bools(struct selinux_policy *oldpolicy,
2164 struct selinux_policy *newpolicy);
2166 static void selinux_policy_free(struct selinux_policy *policy)
2171 sidtab_destroy(policy->sidtab);
2172 kfree(policy->map.mapping);
2173 policydb_destroy(&policy->policydb);
2174 kfree(policy->sidtab);
2178 static void selinux_policy_cond_free(struct selinux_policy *policy)
2180 cond_policydb_destroy_dup(&policy->policydb);
2184 void selinux_policy_cancel(struct selinux_state *state,
2185 struct selinux_load_state *load_state)
2187 struct selinux_policy *oldpolicy;
2189 oldpolicy = rcu_dereference_protected(state->policy,
2190 lockdep_is_held(&state->policy_mutex));
2192 sidtab_cancel_convert(oldpolicy->sidtab);
2193 selinux_policy_free(load_state->policy);
2194 kfree(load_state->convert_data);
2197 static void selinux_notify_policy_change(struct selinux_state *state,
2200 /* Flush external caches and notify userspace of policy load */
2201 avc_ss_reset(state->avc, seqno);
2202 selnl_notify_policyload(seqno);
2203 selinux_status_update_policyload(state, seqno);
2204 selinux_netlbl_cache_invalidate();
2205 selinux_xfrm_notify_policyload();
2206 selinux_ima_measure_state_locked(state);
2209 void selinux_policy_commit(struct selinux_state *state,
2210 struct selinux_load_state *load_state)
2212 struct selinux_policy *oldpolicy, *newpolicy = load_state->policy;
2213 unsigned long flags;
2216 oldpolicy = rcu_dereference_protected(state->policy,
2217 lockdep_is_held(&state->policy_mutex));
2219 /* If switching between different policy types, log MLS status */
2221 if (oldpolicy->policydb.mls_enabled && !newpolicy->policydb.mls_enabled)
2222 pr_info("SELinux: Disabling MLS support...\n");
2223 else if (!oldpolicy->policydb.mls_enabled && newpolicy->policydb.mls_enabled)
2224 pr_info("SELinux: Enabling MLS support...\n");
2227 /* Set latest granting seqno for new policy. */
2229 newpolicy->latest_granting = oldpolicy->latest_granting + 1;
2231 newpolicy->latest_granting = 1;
2232 seqno = newpolicy->latest_granting;
2234 /* Install the new policy. */
2236 sidtab_freeze_begin(oldpolicy->sidtab, &flags);
2237 rcu_assign_pointer(state->policy, newpolicy);
2238 sidtab_freeze_end(oldpolicy->sidtab, &flags);
2240 rcu_assign_pointer(state->policy, newpolicy);
2243 /* Load the policycaps from the new policy */
2244 security_load_policycaps(state, newpolicy);
2246 if (!selinux_initialized(state)) {
2248 * After first policy load, the security server is
2249 * marked as initialized and ready to handle requests and
2250 * any objects created prior to policy load are then labeled.
2252 selinux_mark_initialized(state);
2253 selinux_complete_init();
2256 /* Free the old policy */
2258 selinux_policy_free(oldpolicy);
2259 kfree(load_state->convert_data);
2261 /* Notify others of the policy change */
2262 selinux_notify_policy_change(state, seqno);
2266 * security_load_policy - Load a security policy configuration.
2267 * @data: binary policy data
2268 * @len: length of data in bytes
2270 * Load a new set of security policy configuration data,
2271 * validate it and convert the SID table as necessary.
2272 * This function will flush the access vector cache after
2273 * loading the new policy.
2275 int security_load_policy(struct selinux_state *state, void *data, size_t len,
2276 struct selinux_load_state *load_state)
2278 struct selinux_policy *newpolicy, *oldpolicy;
2279 struct selinux_policy_convert_data *convert_data;
2281 struct policy_file file = { data, len }, *fp = &file;
2283 newpolicy = kzalloc(sizeof(*newpolicy), GFP_KERNEL);
2287 newpolicy->sidtab = kzalloc(sizeof(*newpolicy->sidtab), GFP_KERNEL);
2288 if (!newpolicy->sidtab) {
2293 rc = policydb_read(&newpolicy->policydb, fp);
2297 newpolicy->policydb.len = len;
2298 rc = selinux_set_mapping(&newpolicy->policydb, secclass_map,
2303 rc = policydb_load_isids(&newpolicy->policydb, newpolicy->sidtab);
2305 pr_err("SELinux: unable to load the initial SIDs\n");
2309 if (!selinux_initialized(state)) {
2310 /* First policy load, so no need to preserve state from old policy */
2311 load_state->policy = newpolicy;
2312 load_state->convert_data = NULL;
2316 oldpolicy = rcu_dereference_protected(state->policy,
2317 lockdep_is_held(&state->policy_mutex));
2319 /* Preserve active boolean values from the old policy */
2320 rc = security_preserve_bools(oldpolicy, newpolicy);
2322 pr_err("SELinux: unable to preserve booleans\n");
2323 goto err_free_isids;
2326 convert_data = kmalloc(sizeof(*convert_data), GFP_KERNEL);
2327 if (!convert_data) {
2329 goto err_free_isids;
2333 * Convert the internal representations of contexts
2334 * in the new SID table.
2336 convert_data->args.state = state;
2337 convert_data->args.oldp = &oldpolicy->policydb;
2338 convert_data->args.newp = &newpolicy->policydb;
2340 convert_data->sidtab_params.func = convert_context;
2341 convert_data->sidtab_params.args = &convert_data->args;
2342 convert_data->sidtab_params.target = newpolicy->sidtab;
2344 rc = sidtab_convert(oldpolicy->sidtab, &convert_data->sidtab_params);
2346 pr_err("SELinux: unable to convert the internal"
2347 " representation of contexts in the new SID"
2349 goto err_free_convert_data;
2352 load_state->policy = newpolicy;
2353 load_state->convert_data = convert_data;
2356 err_free_convert_data:
2357 kfree(convert_data);
2359 sidtab_destroy(newpolicy->sidtab);
2361 kfree(newpolicy->map.mapping);
2363 policydb_destroy(&newpolicy->policydb);
2365 kfree(newpolicy->sidtab);
2373 * security_port_sid - Obtain the SID for a port.
2374 * @protocol: protocol number
2375 * @port: port number
2376 * @out_sid: security identifier
2378 int security_port_sid(struct selinux_state *state,
2379 u8 protocol, u16 port, u32 *out_sid)
2381 struct selinux_policy *policy;
2382 struct policydb *policydb;
2383 struct sidtab *sidtab;
2387 if (!selinux_initialized(state)) {
2388 *out_sid = SECINITSID_PORT;
2395 policy = rcu_dereference(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)
2410 rc = sidtab_context_to_sid(sidtab, &c->context[0],
2412 if (rc == -ESTALE) {
2419 *out_sid = c->sid[0];
2421 *out_sid = SECINITSID_PORT;
2430 * security_pkey_sid - Obtain the SID for a pkey.
2431 * @subnet_prefix: Subnet Prefix
2432 * @pkey_num: pkey number
2433 * @out_sid: security identifier
2435 int security_ib_pkey_sid(struct selinux_state *state,
2436 u64 subnet_prefix, u16 pkey_num, u32 *out_sid)
2438 struct selinux_policy *policy;
2439 struct policydb *policydb;
2440 struct sidtab *sidtab;
2444 if (!selinux_initialized(state)) {
2445 *out_sid = SECINITSID_UNLABELED;
2452 policy = rcu_dereference(state->policy);
2453 policydb = &policy->policydb;
2454 sidtab = policy->sidtab;
2456 c = policydb->ocontexts[OCON_IBPKEY];
2458 if (c->u.ibpkey.low_pkey <= pkey_num &&
2459 c->u.ibpkey.high_pkey >= pkey_num &&
2460 c->u.ibpkey.subnet_prefix == subnet_prefix)
2468 rc = sidtab_context_to_sid(sidtab,
2471 if (rc == -ESTALE) {
2478 *out_sid = c->sid[0];
2480 *out_sid = SECINITSID_UNLABELED;
2488 * security_ib_endport_sid - Obtain the SID for a subnet management interface.
2489 * @dev_name: device name
2490 * @port: port number
2491 * @out_sid: security identifier
2493 int security_ib_endport_sid(struct selinux_state *state,
2494 const char *dev_name, u8 port_num, u32 *out_sid)
2496 struct selinux_policy *policy;
2497 struct policydb *policydb;
2498 struct sidtab *sidtab;
2502 if (!selinux_initialized(state)) {
2503 *out_sid = SECINITSID_UNLABELED;
2510 policy = rcu_dereference(state->policy);
2511 policydb = &policy->policydb;
2512 sidtab = policy->sidtab;
2514 c = policydb->ocontexts[OCON_IBENDPORT];
2516 if (c->u.ibendport.port == port_num &&
2517 !strncmp(c->u.ibendport.dev_name,
2519 IB_DEVICE_NAME_MAX))
2527 rc = sidtab_context_to_sid(sidtab, &c->context[0],
2529 if (rc == -ESTALE) {
2536 *out_sid = c->sid[0];
2538 *out_sid = SECINITSID_UNLABELED;
2546 * security_netif_sid - Obtain the SID for a network interface.
2547 * @name: interface name
2548 * @if_sid: interface SID
2550 int security_netif_sid(struct selinux_state *state,
2551 char *name, u32 *if_sid)
2553 struct selinux_policy *policy;
2554 struct policydb *policydb;
2555 struct sidtab *sidtab;
2559 if (!selinux_initialized(state)) {
2560 *if_sid = SECINITSID_NETIF;
2567 policy = rcu_dereference(state->policy);
2568 policydb = &policy->policydb;
2569 sidtab = policy->sidtab;
2571 c = policydb->ocontexts[OCON_NETIF];
2573 if (strcmp(name, c->u.name) == 0)
2579 if (!c->sid[0] || !c->sid[1]) {
2580 rc = sidtab_context_to_sid(sidtab, &c->context[0],
2582 if (rc == -ESTALE) {
2588 rc = sidtab_context_to_sid(sidtab, &c->context[1],
2590 if (rc == -ESTALE) {
2597 *if_sid = c->sid[0];
2599 *if_sid = SECINITSID_NETIF;
2606 static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask)
2610 for (i = 0; i < 4; i++)
2611 if (addr[i] != (input[i] & mask[i])) {
2620 * security_node_sid - Obtain the SID for a node (host).
2621 * @domain: communication domain aka address family
2623 * @addrlen: address length in bytes
2624 * @out_sid: security identifier
2626 int security_node_sid(struct selinux_state *state,
2632 struct selinux_policy *policy;
2633 struct policydb *policydb;
2634 struct sidtab *sidtab;
2638 if (!selinux_initialized(state)) {
2639 *out_sid = SECINITSID_NODE;
2645 policy = rcu_dereference(state->policy);
2646 policydb = &policy->policydb;
2647 sidtab = policy->sidtab;
2654 if (addrlen != sizeof(u32))
2657 addr = *((u32 *)addrp);
2659 c = policydb->ocontexts[OCON_NODE];
2661 if (c->u.node.addr == (addr & c->u.node.mask))
2670 if (addrlen != sizeof(u64) * 2)
2672 c = policydb->ocontexts[OCON_NODE6];
2674 if (match_ipv6_addrmask(addrp, c->u.node6.addr,
2683 *out_sid = SECINITSID_NODE;
2689 rc = sidtab_context_to_sid(sidtab,
2692 if (rc == -ESTALE) {
2699 *out_sid = c->sid[0];
2701 *out_sid = SECINITSID_NODE;
2713 * security_get_user_sids - Obtain reachable SIDs for a user.
2714 * @fromsid: starting SID
2715 * @username: username
2716 * @sids: array of reachable SIDs for user
2717 * @nel: number of elements in @sids
2719 * Generate the set of SIDs for legal security contexts
2720 * for a given user that can be reached by @fromsid.
2721 * Set *@sids to point to a dynamically allocated
2722 * array containing the set of SIDs. Set *@nel to the
2723 * number of elements in the array.
2726 int security_get_user_sids(struct selinux_state *state,
2732 struct selinux_policy *policy;
2733 struct policydb *policydb;
2734 struct sidtab *sidtab;
2735 struct context *fromcon, usercon;
2736 u32 *mysids = NULL, *mysids2, sid;
2737 u32 i, j, mynel, maxnel = SIDS_NEL;
2738 struct user_datum *user;
2739 struct role_datum *role;
2740 struct ebitmap_node *rnode, *tnode;
2746 if (!selinux_initialized(state))
2749 mysids = kcalloc(maxnel, sizeof(*mysids), GFP_KERNEL);
2756 policy = rcu_dereference(state->policy);
2757 policydb = &policy->policydb;
2758 sidtab = policy->sidtab;
2760 context_init(&usercon);
2763 fromcon = sidtab_search(sidtab, fromsid);
2768 user = symtab_search(&policydb->p_users, username);
2772 usercon.user = user->value;
2774 ebitmap_for_each_positive_bit(&user->roles, rnode, i) {
2775 role = policydb->role_val_to_struct[i];
2776 usercon.role = i + 1;
2777 ebitmap_for_each_positive_bit(&role->types, tnode, j) {
2778 usercon.type = j + 1;
2780 if (mls_setup_user_range(policydb, fromcon, user,
2784 rc = sidtab_context_to_sid(sidtab, &usercon, &sid);
2785 if (rc == -ESTALE) {
2791 if (mynel < maxnel) {
2792 mysids[mynel++] = sid;
2796 mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
2799 memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
2802 mysids[mynel++] = sid;
2815 mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);
2820 for (i = 0, j = 0; i < mynel; i++) {
2821 struct av_decision dummy_avd;
2822 rc = avc_has_perm_noaudit(state,
2824 SECCLASS_PROCESS, /* kernel value */
2825 PROCESS__TRANSITION, AVC_STRICT,
2828 mysids2[j++] = mysids[i];
2838 * __security_genfs_sid - Helper to obtain a SID for a file in a filesystem
2839 * @fstype: filesystem type
2840 * @path: path from root of mount
2841 * @sclass: file security class
2842 * @sid: SID for path
2844 * Obtain a SID to use for a file in a filesystem that
2845 * cannot support xattr or use a fixed labeling behavior like
2846 * transition SIDs or task SIDs.
2848 * WARNING: This function may return -ESTALE, indicating that the caller
2849 * must retry the operation after re-acquiring the policy pointer!
2851 static inline int __security_genfs_sid(struct selinux_policy *policy,
2857 struct policydb *policydb = &policy->policydb;
2858 struct sidtab *sidtab = policy->sidtab;
2861 struct genfs *genfs;
2865 while (path[0] == '/' && path[1] == '/')
2868 sclass = unmap_class(&policy->map, orig_sclass);
2869 *sid = SECINITSID_UNLABELED;
2871 for (genfs = policydb->genfs; genfs; genfs = genfs->next) {
2872 cmp = strcmp(fstype, genfs->fstype);
2881 for (c = genfs->head; c; c = c->next) {
2882 len = strlen(c->u.name);
2883 if ((!c->v.sclass || sclass == c->v.sclass) &&
2884 (strncmp(c->u.name, path, len) == 0))
2893 rc = sidtab_context_to_sid(sidtab, &c->context[0], &c->sid[0]);
2905 * security_genfs_sid - Obtain a SID for a file in a filesystem
2906 * @fstype: filesystem type
2907 * @path: path from root of mount
2908 * @sclass: file security class
2909 * @sid: SID for path
2911 * Acquire policy_rwlock before calling __security_genfs_sid() and release
2914 int security_genfs_sid(struct selinux_state *state,
2920 struct selinux_policy *policy;
2923 if (!selinux_initialized(state)) {
2924 *sid = SECINITSID_UNLABELED;
2930 policy = rcu_dereference(state->policy);
2931 retval = __security_genfs_sid(policy, fstype, path,
2934 } while (retval == -ESTALE);
2938 int selinux_policy_genfs_sid(struct selinux_policy *policy,
2944 /* no lock required, policy is not yet accessible by other threads */
2945 return __security_genfs_sid(policy, fstype, path, orig_sclass, sid);
2949 * security_fs_use - Determine how to handle labeling for a filesystem.
2950 * @sb: superblock in question
2952 int security_fs_use(struct selinux_state *state, struct super_block *sb)
2954 struct selinux_policy *policy;
2955 struct policydb *policydb;
2956 struct sidtab *sidtab;
2959 struct superblock_security_struct *sbsec = selinux_superblock(sb);
2960 const char *fstype = sb->s_type->name;
2962 if (!selinux_initialized(state)) {
2963 sbsec->behavior = SECURITY_FS_USE_NONE;
2964 sbsec->sid = SECINITSID_UNLABELED;
2971 policy = rcu_dereference(state->policy);
2972 policydb = &policy->policydb;
2973 sidtab = policy->sidtab;
2975 c = policydb->ocontexts[OCON_FSUSE];
2977 if (strcmp(fstype, c->u.name) == 0)
2983 sbsec->behavior = c->v.behavior;
2985 rc = sidtab_context_to_sid(sidtab, &c->context[0],
2987 if (rc == -ESTALE) {
2994 sbsec->sid = c->sid[0];
2996 rc = __security_genfs_sid(policy, fstype, "/",
2997 SECCLASS_DIR, &sbsec->sid);
2998 if (rc == -ESTALE) {
3003 sbsec->behavior = SECURITY_FS_USE_NONE;
3006 sbsec->behavior = SECURITY_FS_USE_GENFS;
3015 int security_get_bools(struct selinux_policy *policy,
3016 u32 *len, char ***names, int **values)
3018 struct policydb *policydb;
3022 policydb = &policy->policydb;
3028 *len = policydb->p_bools.nprim;
3033 *names = kcalloc(*len, sizeof(char *), GFP_ATOMIC);
3038 *values = kcalloc(*len, sizeof(int), GFP_ATOMIC);
3042 for (i = 0; i < *len; i++) {
3043 (*values)[i] = policydb->bool_val_to_struct[i]->state;
3046 (*names)[i] = kstrdup(sym_name(policydb, SYM_BOOLS, i),
3056 for (i = 0; i < *len; i++)
3068 int security_set_bools(struct selinux_state *state, u32 len, int *values)
3070 struct selinux_policy *newpolicy, *oldpolicy;
3074 if (!selinux_initialized(state))
3077 oldpolicy = rcu_dereference_protected(state->policy,
3078 lockdep_is_held(&state->policy_mutex));
3080 /* Consistency check on number of booleans, should never fail */
3081 if (WARN_ON(len != oldpolicy->policydb.p_bools.nprim))
3084 newpolicy = kmemdup(oldpolicy, sizeof(*newpolicy), GFP_KERNEL);
3089 * Deep copy only the parts of the policydb that might be
3090 * modified as a result of changing booleans.
3092 rc = cond_policydb_dup(&newpolicy->policydb, &oldpolicy->policydb);
3098 /* Update the boolean states in the copy */
3099 for (i = 0; i < len; i++) {
3100 int new_state = !!values[i];
3101 int old_state = newpolicy->policydb.bool_val_to_struct[i]->state;
3103 if (new_state != old_state) {
3104 audit_log(audit_context(), GFP_ATOMIC,
3105 AUDIT_MAC_CONFIG_CHANGE,
3106 "bool=%s val=%d old_val=%d auid=%u ses=%u",
3107 sym_name(&newpolicy->policydb, SYM_BOOLS, i),
3110 from_kuid(&init_user_ns, audit_get_loginuid(current)),
3111 audit_get_sessionid(current));
3112 newpolicy->policydb.bool_val_to_struct[i]->state = new_state;
3116 /* Re-evaluate the conditional rules in the copy */
3117 evaluate_cond_nodes(&newpolicy->policydb);
3119 /* Set latest granting seqno for new policy */
3120 newpolicy->latest_granting = oldpolicy->latest_granting + 1;
3121 seqno = newpolicy->latest_granting;
3123 /* Install the new policy */
3124 rcu_assign_pointer(state->policy, newpolicy);
3127 * Free the conditional portions of the old policydb
3128 * that were copied for the new policy, and the oldpolicy
3129 * structure itself but not what it references.
3132 selinux_policy_cond_free(oldpolicy);
3134 /* Notify others of the policy change */
3135 selinux_notify_policy_change(state, seqno);
3139 int security_get_bool_value(struct selinux_state *state,
3142 struct selinux_policy *policy;
3143 struct policydb *policydb;
3147 if (!selinux_initialized(state))
3151 policy = rcu_dereference(state->policy);
3152 policydb = &policy->policydb;
3155 len = policydb->p_bools.nprim;
3159 rc = policydb->bool_val_to_struct[index]->state;
3165 static int security_preserve_bools(struct selinux_policy *oldpolicy,
3166 struct selinux_policy *newpolicy)
3168 int rc, *bvalues = NULL;
3169 char **bnames = NULL;
3170 struct cond_bool_datum *booldatum;
3173 rc = security_get_bools(oldpolicy, &nbools, &bnames, &bvalues);
3176 for (i = 0; i < nbools; i++) {
3177 booldatum = symtab_search(&newpolicy->policydb.p_bools,
3180 booldatum->state = bvalues[i];
3182 evaluate_cond_nodes(&newpolicy->policydb);
3186 for (i = 0; i < nbools; i++)
3195 * security_sid_mls_copy() - computes a new sid based on the given
3196 * sid and the mls portion of mls_sid.
3198 int security_sid_mls_copy(struct selinux_state *state,
3199 u32 sid, u32 mls_sid, u32 *new_sid)
3201 struct selinux_policy *policy;
3202 struct policydb *policydb;
3203 struct sidtab *sidtab;
3204 struct context *context1;
3205 struct context *context2;
3206 struct context newcon;
3211 if (!selinux_initialized(state)) {
3218 context_init(&newcon);
3221 policy = rcu_dereference(state->policy);
3222 policydb = &policy->policydb;
3223 sidtab = policy->sidtab;
3225 if (!policydb->mls_enabled) {
3231 context1 = sidtab_search(sidtab, sid);
3233 pr_err("SELinux: %s: unrecognized SID %d\n",
3239 context2 = sidtab_search(sidtab, mls_sid);
3241 pr_err("SELinux: %s: unrecognized SID %d\n",
3246 newcon.user = context1->user;
3247 newcon.role = context1->role;
3248 newcon.type = context1->type;
3249 rc = mls_context_cpy(&newcon, context2);
3253 /* Check the validity of the new context. */
3254 if (!policydb_context_isvalid(policydb, &newcon)) {
3255 rc = convert_context_handle_invalid_context(state, policydb,
3258 if (!context_struct_to_string(policydb, &newcon, &s,
3260 struct audit_buffer *ab;
3262 ab = audit_log_start(audit_context(),
3265 audit_log_format(ab,
3266 "op=security_sid_mls_copy invalid_context=");
3267 /* don't record NUL with untrusted strings */
3268 audit_log_n_untrustedstring(ab, s, len - 1);
3275 rc = sidtab_context_to_sid(sidtab, &newcon, new_sid);
3276 if (rc == -ESTALE) {
3278 context_destroy(&newcon);
3283 context_destroy(&newcon);
3288 * security_net_peersid_resolve - Compare and resolve two network peer SIDs
3289 * @nlbl_sid: NetLabel SID
3290 * @nlbl_type: NetLabel labeling protocol type
3291 * @xfrm_sid: XFRM SID
3294 * Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be
3295 * resolved into a single SID it is returned via @peer_sid and the function
3296 * returns zero. Otherwise @peer_sid is set to SECSID_NULL and the function
3297 * returns a negative value. A table summarizing the behavior is below:
3299 * | function return | @sid
3300 * ------------------------------+-----------------+-----------------
3301 * no peer labels | 0 | SECSID_NULL
3302 * single peer label | 0 | <peer_label>
3303 * multiple, consistent labels | 0 | <peer_label>
3304 * multiple, inconsistent labels | -<errno> | SECSID_NULL
3307 int security_net_peersid_resolve(struct selinux_state *state,
3308 u32 nlbl_sid, u32 nlbl_type,
3312 struct selinux_policy *policy;
3313 struct policydb *policydb;
3314 struct sidtab *sidtab;
3316 struct context *nlbl_ctx;
3317 struct context *xfrm_ctx;
3319 *peer_sid = SECSID_NULL;
3321 /* handle the common (which also happens to be the set of easy) cases
3322 * right away, these two if statements catch everything involving a
3323 * single or absent peer SID/label */
3324 if (xfrm_sid == SECSID_NULL) {
3325 *peer_sid = nlbl_sid;
3328 /* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a "fallback" label
3329 * and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label
3331 if (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) {
3332 *peer_sid = xfrm_sid;
3336 if (!selinux_initialized(state))
3340 policy = rcu_dereference(state->policy);
3341 policydb = &policy->policydb;
3342 sidtab = policy->sidtab;
3345 * We don't need to check initialized here since the only way both
3346 * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the
3347 * security server was initialized and state->initialized was true.
3349 if (!policydb->mls_enabled) {
3355 nlbl_ctx = sidtab_search(sidtab, nlbl_sid);
3357 pr_err("SELinux: %s: unrecognized SID %d\n",
3358 __func__, nlbl_sid);
3362 xfrm_ctx = sidtab_search(sidtab, xfrm_sid);
3364 pr_err("SELinux: %s: unrecognized SID %d\n",
3365 __func__, xfrm_sid);
3368 rc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES);
3372 /* at present NetLabel SIDs/labels really only carry MLS
3373 * information so if the MLS portion of the NetLabel SID
3374 * matches the MLS portion of the labeled XFRM SID/label
3375 * then pass along the XFRM SID as it is the most
3377 *peer_sid = xfrm_sid;
3383 static int get_classes_callback(void *k, void *d, void *args)
3385 struct class_datum *datum = d;
3386 char *name = k, **classes = args;
3387 int value = datum->value - 1;
3389 classes[value] = kstrdup(name, GFP_ATOMIC);
3390 if (!classes[value])
3396 int security_get_classes(struct selinux_policy *policy,
3397 char ***classes, int *nclasses)
3399 struct policydb *policydb;
3402 policydb = &policy->policydb;
3405 *nclasses = policydb->p_classes.nprim;
3406 *classes = kcalloc(*nclasses, sizeof(**classes), GFP_ATOMIC);
3410 rc = hashtab_map(&policydb->p_classes.table, get_classes_callback,
3414 for (i = 0; i < *nclasses; i++)
3415 kfree((*classes)[i]);
3423 static int get_permissions_callback(void *k, void *d, void *args)
3425 struct perm_datum *datum = d;
3426 char *name = k, **perms = args;
3427 int value = datum->value - 1;
3429 perms[value] = kstrdup(name, GFP_ATOMIC);
3436 int security_get_permissions(struct selinux_policy *policy,
3437 char *class, char ***perms, int *nperms)
3439 struct policydb *policydb;
3441 struct class_datum *match;
3443 policydb = &policy->policydb;
3446 match = symtab_search(&policydb->p_classes, class);
3448 pr_err("SELinux: %s: unrecognized class %s\n",
3454 *nperms = match->permissions.nprim;
3455 *perms = kcalloc(*nperms, sizeof(**perms), GFP_ATOMIC);
3459 if (match->comdatum) {
3460 rc = hashtab_map(&match->comdatum->permissions.table,
3461 get_permissions_callback, *perms);
3466 rc = hashtab_map(&match->permissions.table, get_permissions_callback,
3475 for (i = 0; i < *nperms; i++)
3481 int security_get_reject_unknown(struct selinux_state *state)
3483 struct selinux_policy *policy;
3486 if (!selinux_initialized(state))
3490 policy = rcu_dereference(state->policy);
3491 value = policy->policydb.reject_unknown;
3496 int security_get_allow_unknown(struct selinux_state *state)
3498 struct selinux_policy *policy;
3501 if (!selinux_initialized(state))
3505 policy = rcu_dereference(state->policy);
3506 value = policy->policydb.allow_unknown;
3512 * security_policycap_supported - Check for a specific policy capability
3513 * @req_cap: capability
3516 * This function queries the currently loaded policy to see if it supports the
3517 * capability specified by @req_cap. Returns true (1) if the capability is
3518 * supported, false (0) if it isn't supported.
3521 int security_policycap_supported(struct selinux_state *state,
3522 unsigned int req_cap)
3524 struct selinux_policy *policy;
3527 if (!selinux_initialized(state))
3531 policy = rcu_dereference(state->policy);
3532 rc = ebitmap_get_bit(&policy->policydb.policycaps, req_cap);
3538 struct selinux_audit_rule {
3540 struct context au_ctxt;
3543 void selinux_audit_rule_free(void *vrule)
3545 struct selinux_audit_rule *rule = vrule;
3548 context_destroy(&rule->au_ctxt);
3553 int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule)
3555 struct selinux_state *state = &selinux_state;
3556 struct selinux_policy *policy;
3557 struct policydb *policydb;
3558 struct selinux_audit_rule *tmprule;
3559 struct role_datum *roledatum;
3560 struct type_datum *typedatum;
3561 struct user_datum *userdatum;
3562 struct selinux_audit_rule **rule = (struct selinux_audit_rule **)vrule;
3567 if (!selinux_initialized(state))
3571 case AUDIT_SUBJ_USER:
3572 case AUDIT_SUBJ_ROLE:
3573 case AUDIT_SUBJ_TYPE:
3574 case AUDIT_OBJ_USER:
3575 case AUDIT_OBJ_ROLE:
3576 case AUDIT_OBJ_TYPE:
3577 /* only 'equals' and 'not equals' fit user, role, and type */
3578 if (op != Audit_equal && op != Audit_not_equal)
3581 case AUDIT_SUBJ_SEN:
3582 case AUDIT_SUBJ_CLR:
3583 case AUDIT_OBJ_LEV_LOW:
3584 case AUDIT_OBJ_LEV_HIGH:
3585 /* we do not allow a range, indicated by the presence of '-' */
3586 if (strchr(rulestr, '-'))
3590 /* only the above fields are valid */
3594 tmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL);
3598 context_init(&tmprule->au_ctxt);
3601 policy = rcu_dereference(state->policy);
3602 policydb = &policy->policydb;
3604 tmprule->au_seqno = policy->latest_granting;
3607 case AUDIT_SUBJ_USER:
3608 case AUDIT_OBJ_USER:
3610 userdatum = symtab_search(&policydb->p_users, rulestr);
3613 tmprule->au_ctxt.user = userdatum->value;
3615 case AUDIT_SUBJ_ROLE:
3616 case AUDIT_OBJ_ROLE:
3618 roledatum = symtab_search(&policydb->p_roles, rulestr);
3621 tmprule->au_ctxt.role = roledatum->value;
3623 case AUDIT_SUBJ_TYPE:
3624 case AUDIT_OBJ_TYPE:
3626 typedatum = symtab_search(&policydb->p_types, rulestr);
3629 tmprule->au_ctxt.type = typedatum->value;
3631 case AUDIT_SUBJ_SEN:
3632 case AUDIT_SUBJ_CLR:
3633 case AUDIT_OBJ_LEV_LOW:
3634 case AUDIT_OBJ_LEV_HIGH:
3635 rc = mls_from_string(policydb, rulestr, &tmprule->au_ctxt,
3646 selinux_audit_rule_free(tmprule);
3655 /* Check to see if the rule contains any selinux fields */
3656 int selinux_audit_rule_known(struct audit_krule *rule)
3660 for (i = 0; i < rule->field_count; i++) {
3661 struct audit_field *f = &rule->fields[i];
3663 case AUDIT_SUBJ_USER:
3664 case AUDIT_SUBJ_ROLE:
3665 case AUDIT_SUBJ_TYPE:
3666 case AUDIT_SUBJ_SEN:
3667 case AUDIT_SUBJ_CLR:
3668 case AUDIT_OBJ_USER:
3669 case AUDIT_OBJ_ROLE:
3670 case AUDIT_OBJ_TYPE:
3671 case AUDIT_OBJ_LEV_LOW:
3672 case AUDIT_OBJ_LEV_HIGH:
3680 int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule)
3682 struct selinux_state *state = &selinux_state;
3683 struct selinux_policy *policy;
3684 struct context *ctxt;
3685 struct mls_level *level;
3686 struct selinux_audit_rule *rule = vrule;
3689 if (unlikely(!rule)) {
3690 WARN_ONCE(1, "selinux_audit_rule_match: missing rule\n");
3694 if (!selinux_initialized(state))
3699 policy = rcu_dereference(state->policy);
3701 if (rule->au_seqno < policy->latest_granting) {
3706 ctxt = sidtab_search(policy->sidtab, sid);
3707 if (unlikely(!ctxt)) {
3708 WARN_ONCE(1, "selinux_audit_rule_match: unrecognized SID %d\n",
3714 /* a field/op pair that is not caught here will simply fall through
3717 case AUDIT_SUBJ_USER:
3718 case AUDIT_OBJ_USER:
3721 match = (ctxt->user == rule->au_ctxt.user);
3723 case Audit_not_equal:
3724 match = (ctxt->user != rule->au_ctxt.user);
3728 case AUDIT_SUBJ_ROLE:
3729 case AUDIT_OBJ_ROLE:
3732 match = (ctxt->role == rule->au_ctxt.role);
3734 case Audit_not_equal:
3735 match = (ctxt->role != rule->au_ctxt.role);
3739 case AUDIT_SUBJ_TYPE:
3740 case AUDIT_OBJ_TYPE:
3743 match = (ctxt->type == rule->au_ctxt.type);
3745 case Audit_not_equal:
3746 match = (ctxt->type != rule->au_ctxt.type);
3750 case AUDIT_SUBJ_SEN:
3751 case AUDIT_SUBJ_CLR:
3752 case AUDIT_OBJ_LEV_LOW:
3753 case AUDIT_OBJ_LEV_HIGH:
3754 level = ((field == AUDIT_SUBJ_SEN ||
3755 field == AUDIT_OBJ_LEV_LOW) ?
3756 &ctxt->range.level[0] : &ctxt->range.level[1]);
3759 match = mls_level_eq(&rule->au_ctxt.range.level[0],
3762 case Audit_not_equal:
3763 match = !mls_level_eq(&rule->au_ctxt.range.level[0],
3767 match = (mls_level_dom(&rule->au_ctxt.range.level[0],
3769 !mls_level_eq(&rule->au_ctxt.range.level[0],
3773 match = mls_level_dom(&rule->au_ctxt.range.level[0],
3777 match = (mls_level_dom(level,
3778 &rule->au_ctxt.range.level[0]) &&
3779 !mls_level_eq(level,
3780 &rule->au_ctxt.range.level[0]));
3783 match = mls_level_dom(level,
3784 &rule->au_ctxt.range.level[0]);
3794 static int aurule_avc_callback(u32 event)
3796 if (event == AVC_CALLBACK_RESET)
3797 return audit_update_lsm_rules();
3801 static int __init aurule_init(void)
3805 err = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET);
3807 panic("avc_add_callback() failed, error %d\n", err);
3811 __initcall(aurule_init);
3813 #ifdef CONFIG_NETLABEL
3815 * security_netlbl_cache_add - Add an entry to the NetLabel cache
3816 * @secattr: the NetLabel packet security attributes
3817 * @sid: the SELinux SID
3820 * Attempt to cache the context in @ctx, which was derived from the packet in
3821 * @skb, in the NetLabel subsystem cache. This function assumes @secattr has
3822 * already been initialized.
3825 static void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr,
3830 sid_cache = kmalloc(sizeof(*sid_cache), GFP_ATOMIC);
3831 if (sid_cache == NULL)
3833 secattr->cache = netlbl_secattr_cache_alloc(GFP_ATOMIC);
3834 if (secattr->cache == NULL) {
3840 secattr->cache->free = kfree;
3841 secattr->cache->data = sid_cache;
3842 secattr->flags |= NETLBL_SECATTR_CACHE;
3846 * security_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID
3847 * @secattr: the NetLabel packet security attributes
3848 * @sid: the SELinux SID
3851 * Convert the given NetLabel security attributes in @secattr into a
3852 * SELinux SID. If the @secattr field does not contain a full SELinux
3853 * SID/context then use SECINITSID_NETMSG as the foundation. If possible the
3854 * 'cache' field of @secattr is set and the CACHE flag is set; this is to
3855 * allow the @secattr to be used by NetLabel to cache the secattr to SID
3856 * conversion for future lookups. Returns zero on success, negative values on
3860 int security_netlbl_secattr_to_sid(struct selinux_state *state,
3861 struct netlbl_lsm_secattr *secattr,
3864 struct selinux_policy *policy;
3865 struct policydb *policydb;
3866 struct sidtab *sidtab;
3868 struct context *ctx;
3869 struct context ctx_new;
3871 if (!selinux_initialized(state)) {
3879 policy = rcu_dereference(state->policy);
3880 policydb = &policy->policydb;
3881 sidtab = policy->sidtab;
3883 if (secattr->flags & NETLBL_SECATTR_CACHE)
3884 *sid = *(u32 *)secattr->cache->data;
3885 else if (secattr->flags & NETLBL_SECATTR_SECID)
3886 *sid = secattr->attr.secid;
3887 else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) {
3889 ctx = sidtab_search(sidtab, SECINITSID_NETMSG);
3893 context_init(&ctx_new);
3894 ctx_new.user = ctx->user;
3895 ctx_new.role = ctx->role;
3896 ctx_new.type = ctx->type;
3897 mls_import_netlbl_lvl(policydb, &ctx_new, secattr);
3898 if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
3899 rc = mls_import_netlbl_cat(policydb, &ctx_new, secattr);
3904 if (!mls_context_isvalid(policydb, &ctx_new)) {
3905 ebitmap_destroy(&ctx_new.range.level[0].cat);
3909 rc = sidtab_context_to_sid(sidtab, &ctx_new, sid);
3910 ebitmap_destroy(&ctx_new.range.level[0].cat);
3911 if (rc == -ESTALE) {
3918 security_netlbl_cache_add(secattr, *sid);
3928 * security_netlbl_sid_to_secattr - Convert a SELinux SID to a NetLabel secattr
3929 * @sid: the SELinux SID
3930 * @secattr: the NetLabel packet security attributes
3933 * Convert the given SELinux SID in @sid into a NetLabel security attribute.
3934 * Returns zero on success, negative values on failure.
3937 int security_netlbl_sid_to_secattr(struct selinux_state *state,
3938 u32 sid, struct netlbl_lsm_secattr *secattr)
3940 struct selinux_policy *policy;
3941 struct policydb *policydb;
3943 struct context *ctx;
3945 if (!selinux_initialized(state))
3949 policy = rcu_dereference(state->policy);
3950 policydb = &policy->policydb;
3953 ctx = sidtab_search(policy->sidtab, sid);
3958 secattr->domain = kstrdup(sym_name(policydb, SYM_TYPES, ctx->type - 1),
3960 if (secattr->domain == NULL)
3963 secattr->attr.secid = sid;
3964 secattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID;
3965 mls_export_netlbl_lvl(policydb, ctx, secattr);
3966 rc = mls_export_netlbl_cat(policydb, ctx, secattr);
3971 #endif /* CONFIG_NETLABEL */
3974 * __security_read_policy - read the policy.
3975 * @policy: SELinux policy
3976 * @data: binary policy data
3977 * @len: length of data in bytes
3980 static int __security_read_policy(struct selinux_policy *policy,
3981 void *data, size_t *len)
3984 struct policy_file fp;
3989 rc = policydb_write(&policy->policydb, &fp);
3993 *len = (unsigned long)fp.data - (unsigned long)data;
3998 * security_read_policy - read the policy.
3999 * @state: selinux_state
4000 * @data: binary policy data
4001 * @len: length of data in bytes
4004 int security_read_policy(struct selinux_state *state,
4005 void **data, size_t *len)
4007 struct selinux_policy *policy;
4009 policy = rcu_dereference_protected(
4010 state->policy, lockdep_is_held(&state->policy_mutex));
4014 *len = policy->policydb.len;
4015 *data = vmalloc_user(*len);
4019 return __security_read_policy(policy, *data, len);
4023 * security_read_state_kernel - read the policy.
4024 * @state: selinux_state
4025 * @data: binary policy data
4026 * @len: length of data in bytes
4028 * Allocates kernel memory for reading SELinux policy.
4029 * This function is for internal use only and should not
4030 * be used for returning data to user space.
4032 * This function must be called with policy_mutex held.
4034 int security_read_state_kernel(struct selinux_state *state,
4035 void **data, size_t *len)
4037 struct selinux_policy *policy;
4039 policy = rcu_dereference_protected(
4040 state->policy, lockdep_is_held(&state->policy_mutex));
4044 *len = policy->policydb.len;
4045 *data = vmalloc(*len);
4049 return __security_read_policy(policy, *data, len);