2 * Implementation of the security services.
4 * Authors : Stephen Smalley, <sds@tycho.nsa.gov>
5 * James Morris <jmorris@redhat.com>
7 * Updated: Trusted Computer Solutions, Inc. <dgoeddel@trustedcs.com>
9 * Support for enhanced MLS infrastructure.
10 * Support for context based audit filters.
12 * Updated: Frank Mayer <mayerf@tresys.com> and Karl MacMillan <kmacmillan@tresys.com>
14 * Added conditional policy language extensions
16 * Updated: Hewlett-Packard <paul@paul-moore.com>
18 * Added support for NetLabel
19 * Added support for the policy capability bitmap
21 * Updated: Chad Sellers <csellers@tresys.com>
23 * Added validation of kernel classes and permissions
25 * Updated: KaiGai Kohei <kaigai@ak.jp.nec.com>
27 * Added support for bounds domain and audit messaged on masked permissions
29 * Updated: Guido Trentalancia <guido@trentalancia.com>
31 * Added support for runtime switching of the policy type
33 * Copyright (C) 2008, 2009 NEC Corporation
34 * Copyright (C) 2006, 2007 Hewlett-Packard Development Company, L.P.
35 * Copyright (C) 2004-2006 Trusted Computer Solutions, Inc.
36 * Copyright (C) 2003 - 2004, 2006 Tresys Technology, LLC
37 * Copyright (C) 2003 Red Hat, Inc., James Morris <jmorris@redhat.com>
38 * This program is free software; you can redistribute it and/or modify
39 * it under the terms of the GNU General Public License as published by
40 * the Free Software Foundation, version 2.
42 #include <linux/kernel.h>
43 #include <linux/slab.h>
44 #include <linux/string.h>
45 #include <linux/spinlock.h>
46 #include <linux/rcupdate.h>
47 #include <linux/errno.h>
49 #include <linux/sched.h>
50 #include <linux/audit.h>
51 #include <linux/mutex.h>
52 #include <linux/selinux.h>
53 #include <linux/flex_array.h>
54 #include <linux/vmalloc.h>
55 #include <net/netlabel.h>
65 #include "conditional.h"
73 /* Policy capability names */
74 char *selinux_policycap_names[__POLICYDB_CAPABILITY_MAX] = {
75 "network_peer_controls",
77 "extended_socket_class",
78 "always_check_network",
80 "nnp_nosuid_transition"
83 static struct selinux_ss selinux_ss;
85 void selinux_ss_init(struct selinux_ss **ss)
87 rwlock_init(&selinux_ss.policy_rwlock);
88 mutex_init(&selinux_ss.status_lock);
92 /* Forward declaration. */
93 static int context_struct_to_string(struct policydb *policydb,
94 struct context *context,
98 static void context_struct_compute_av(struct policydb *policydb,
99 struct context *scontext,
100 struct context *tcontext,
102 struct av_decision *avd,
103 struct extended_perms *xperms);
105 static int selinux_set_mapping(struct policydb *pol,
106 struct security_class_mapping *map,
107 struct selinux_map *out_map)
111 bool print_unknown_handle = false;
113 /* Find number of classes in the input mapping */
120 /* Allocate space for the class records, plus one for class zero */
121 out_map->mapping = kcalloc(++i, sizeof(*out_map->mapping), GFP_ATOMIC);
122 if (!out_map->mapping)
125 /* Store the raw class and permission values */
127 while (map[j].name) {
128 struct security_class_mapping *p_in = map + (j++);
129 struct selinux_mapping *p_out = out_map->mapping + j;
131 /* An empty class string skips ahead */
132 if (!strcmp(p_in->name, "")) {
133 p_out->num_perms = 0;
137 p_out->value = string_to_security_class(pol, p_in->name);
139 pr_info("SELinux: Class %s not defined in policy.\n",
141 if (pol->reject_unknown)
143 p_out->num_perms = 0;
144 print_unknown_handle = true;
149 while (p_in->perms[k]) {
150 /* An empty permission string skips ahead */
151 if (!*p_in->perms[k]) {
155 p_out->perms[k] = string_to_av_perm(pol, p_out->value,
157 if (!p_out->perms[k]) {
158 pr_info("SELinux: Permission %s in class %s not defined in policy.\n",
159 p_in->perms[k], p_in->name);
160 if (pol->reject_unknown)
162 print_unknown_handle = true;
167 p_out->num_perms = k;
170 if (print_unknown_handle)
171 pr_info("SELinux: the above unknown classes and permissions will be %s\n",
172 pol->allow_unknown ? "allowed" : "denied");
177 kfree(out_map->mapping);
178 out_map->mapping = NULL;
183 * Get real, policy values from mapped values
186 static u16 unmap_class(struct selinux_map *map, u16 tclass)
188 if (tclass < map->size)
189 return map->mapping[tclass].value;
195 * Get kernel value for class from its policy value
197 static u16 map_class(struct selinux_map *map, u16 pol_value)
201 for (i = 1; i < map->size; i++) {
202 if (map->mapping[i].value == pol_value)
206 return SECCLASS_NULL;
209 static void map_decision(struct selinux_map *map,
210 u16 tclass, struct av_decision *avd,
213 if (tclass < map->size) {
214 struct selinux_mapping *mapping = &map->mapping[tclass];
215 unsigned int i, n = mapping->num_perms;
218 for (i = 0, result = 0; i < n; i++) {
219 if (avd->allowed & mapping->perms[i])
221 if (allow_unknown && !mapping->perms[i])
224 avd->allowed = result;
226 for (i = 0, result = 0; i < n; i++)
227 if (avd->auditallow & mapping->perms[i])
229 avd->auditallow = result;
231 for (i = 0, result = 0; i < n; i++) {
232 if (avd->auditdeny & mapping->perms[i])
234 if (!allow_unknown && !mapping->perms[i])
238 * In case the kernel has a bug and requests a permission
239 * between num_perms and the maximum permission number, we
240 * should audit that denial
242 for (; i < (sizeof(u32)*8); i++)
244 avd->auditdeny = result;
248 int security_mls_enabled(struct selinux_state *state)
250 struct policydb *p = &state->ss->policydb;
252 return p->mls_enabled;
256 * Return the boolean value of a constraint expression
257 * when it is applied to the specified source and target
260 * xcontext is a special beast... It is used by the validatetrans rules
261 * only. For these rules, scontext is the context before the transition,
262 * tcontext is the context after the transition, and xcontext is the context
263 * of the process performing the transition. All other callers of
264 * constraint_expr_eval should pass in NULL for xcontext.
266 static int constraint_expr_eval(struct policydb *policydb,
267 struct context *scontext,
268 struct context *tcontext,
269 struct context *xcontext,
270 struct constraint_expr *cexpr)
274 struct role_datum *r1, *r2;
275 struct mls_level *l1, *l2;
276 struct constraint_expr *e;
277 int s[CEXPR_MAXDEPTH];
280 for (e = cexpr; e; e = e->next) {
281 switch (e->expr_type) {
297 if (sp == (CEXPR_MAXDEPTH - 1))
301 val1 = scontext->user;
302 val2 = tcontext->user;
305 val1 = scontext->type;
306 val2 = tcontext->type;
309 val1 = scontext->role;
310 val2 = tcontext->role;
311 r1 = policydb->role_val_to_struct[val1 - 1];
312 r2 = policydb->role_val_to_struct[val2 - 1];
315 s[++sp] = ebitmap_get_bit(&r1->dominates,
319 s[++sp] = ebitmap_get_bit(&r2->dominates,
323 s[++sp] = (!ebitmap_get_bit(&r1->dominates,
325 !ebitmap_get_bit(&r2->dominates,
333 l1 = &(scontext->range.level[0]);
334 l2 = &(tcontext->range.level[0]);
337 l1 = &(scontext->range.level[0]);
338 l2 = &(tcontext->range.level[1]);
341 l1 = &(scontext->range.level[1]);
342 l2 = &(tcontext->range.level[0]);
345 l1 = &(scontext->range.level[1]);
346 l2 = &(tcontext->range.level[1]);
349 l1 = &(scontext->range.level[0]);
350 l2 = &(scontext->range.level[1]);
353 l1 = &(tcontext->range.level[0]);
354 l2 = &(tcontext->range.level[1]);
359 s[++sp] = mls_level_eq(l1, l2);
362 s[++sp] = !mls_level_eq(l1, l2);
365 s[++sp] = mls_level_dom(l1, l2);
368 s[++sp] = mls_level_dom(l2, l1);
371 s[++sp] = mls_level_incomp(l2, l1);
385 s[++sp] = (val1 == val2);
388 s[++sp] = (val1 != val2);
396 if (sp == (CEXPR_MAXDEPTH-1))
399 if (e->attr & CEXPR_TARGET)
401 else if (e->attr & CEXPR_XTARGET) {
408 if (e->attr & CEXPR_USER)
410 else if (e->attr & CEXPR_ROLE)
412 else if (e->attr & CEXPR_TYPE)
421 s[++sp] = ebitmap_get_bit(&e->names, val1 - 1);
424 s[++sp] = !ebitmap_get_bit(&e->names, val1 - 1);
442 * security_dump_masked_av - dumps masked permissions during
443 * security_compute_av due to RBAC, MLS/Constraint and Type bounds.
445 static int dump_masked_av_helper(void *k, void *d, void *args)
447 struct perm_datum *pdatum = d;
448 char **permission_names = args;
450 BUG_ON(pdatum->value < 1 || pdatum->value > 32);
452 permission_names[pdatum->value - 1] = (char *)k;
457 static void security_dump_masked_av(struct policydb *policydb,
458 struct context *scontext,
459 struct context *tcontext,
464 struct common_datum *common_dat;
465 struct class_datum *tclass_dat;
466 struct audit_buffer *ab;
468 char *scontext_name = NULL;
469 char *tcontext_name = NULL;
470 char *permission_names[32];
473 bool need_comma = false;
478 tclass_name = sym_name(policydb, SYM_CLASSES, tclass - 1);
479 tclass_dat = policydb->class_val_to_struct[tclass - 1];
480 common_dat = tclass_dat->comdatum;
482 /* init permission_names */
484 hashtab_map(common_dat->permissions.table,
485 dump_masked_av_helper, permission_names) < 0)
488 if (hashtab_map(tclass_dat->permissions.table,
489 dump_masked_av_helper, permission_names) < 0)
492 /* get scontext/tcontext in text form */
493 if (context_struct_to_string(policydb, scontext,
494 &scontext_name, &length) < 0)
497 if (context_struct_to_string(policydb, tcontext,
498 &tcontext_name, &length) < 0)
501 /* audit a message */
502 ab = audit_log_start(audit_context(),
503 GFP_ATOMIC, AUDIT_SELINUX_ERR);
507 audit_log_format(ab, "op=security_compute_av reason=%s "
508 "scontext=%s tcontext=%s tclass=%s perms=",
509 reason, scontext_name, tcontext_name, tclass_name);
511 for (index = 0; index < 32; index++) {
512 u32 mask = (1 << index);
514 if ((mask & permissions) == 0)
517 audit_log_format(ab, "%s%s",
518 need_comma ? "," : "",
519 permission_names[index]
520 ? permission_names[index] : "????");
525 /* release scontext/tcontext */
526 kfree(tcontext_name);
527 kfree(scontext_name);
533 * security_boundary_permission - drops violated permissions
534 * on boundary constraint.
536 static void type_attribute_bounds_av(struct policydb *policydb,
537 struct context *scontext,
538 struct context *tcontext,
540 struct av_decision *avd)
542 struct context lo_scontext;
543 struct context lo_tcontext, *tcontextp = tcontext;
544 struct av_decision lo_avd;
545 struct type_datum *source;
546 struct type_datum *target;
549 source = flex_array_get_ptr(policydb->type_val_to_struct_array,
556 target = flex_array_get_ptr(policydb->type_val_to_struct_array,
560 memset(&lo_avd, 0, sizeof(lo_avd));
562 memcpy(&lo_scontext, scontext, sizeof(lo_scontext));
563 lo_scontext.type = source->bounds;
565 if (target->bounds) {
566 memcpy(&lo_tcontext, tcontext, sizeof(lo_tcontext));
567 lo_tcontext.type = target->bounds;
568 tcontextp = &lo_tcontext;
571 context_struct_compute_av(policydb, &lo_scontext,
577 masked = ~lo_avd.allowed & avd->allowed;
580 return; /* no masked permission */
582 /* mask violated permissions */
583 avd->allowed &= ~masked;
585 /* audit masked permissions */
586 security_dump_masked_av(policydb, scontext, tcontext,
587 tclass, masked, "bounds");
591 * flag which drivers have permissions
592 * only looking for ioctl based extended permssions
594 void services_compute_xperms_drivers(
595 struct extended_perms *xperms,
596 struct avtab_node *node)
600 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
601 /* if one or more driver has all permissions allowed */
602 for (i = 0; i < ARRAY_SIZE(xperms->drivers.p); i++)
603 xperms->drivers.p[i] |= node->datum.u.xperms->perms.p[i];
604 } else if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
605 /* if allowing permissions within a driver */
606 security_xperm_set(xperms->drivers.p,
607 node->datum.u.xperms->driver);
610 /* If no ioctl commands are allowed, ignore auditallow and auditdeny */
611 if (node->key.specified & AVTAB_XPERMS_ALLOWED)
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 = flex_array_get(policydb->type_attr_map_array,
660 tattr = flex_array_get(policydb->type_attr_map_array,
663 ebitmap_for_each_positive_bit(sattr, snode, i) {
664 ebitmap_for_each_positive_bit(tattr, tnode, j) {
665 avkey.source_type = i + 1;
666 avkey.target_type = j + 1;
667 for (node = avtab_search_node(&policydb->te_avtab,
670 node = avtab_search_node_next(node, avkey.specified)) {
671 if (node->key.specified == AVTAB_ALLOWED)
672 avd->allowed |= node->datum.u.data;
673 else if (node->key.specified == AVTAB_AUDITALLOW)
674 avd->auditallow |= node->datum.u.data;
675 else if (node->key.specified == AVTAB_AUDITDENY)
676 avd->auditdeny &= node->datum.u.data;
677 else if (xperms && (node->key.specified & AVTAB_XPERMS))
678 services_compute_xperms_drivers(xperms, node);
681 /* Check conditional av table for additional permissions */
682 cond_compute_av(&policydb->te_cond_avtab, &avkey,
689 * Remove any permissions prohibited by a constraint (this includes
692 constraint = tclass_datum->constraints;
694 if ((constraint->permissions & (avd->allowed)) &&
695 !constraint_expr_eval(policydb, scontext, tcontext, NULL,
697 avd->allowed &= ~(constraint->permissions);
699 constraint = constraint->next;
703 * If checking process transition permission and the
704 * role is changing, then check the (current_role, new_role)
707 if (tclass == policydb->process_class &&
708 (avd->allowed & policydb->process_trans_perms) &&
709 scontext->role != tcontext->role) {
710 for (ra = policydb->role_allow; ra; ra = ra->next) {
711 if (scontext->role == ra->role &&
712 tcontext->role == ra->new_role)
716 avd->allowed &= ~policydb->process_trans_perms;
720 * If the given source and target types have boundary
721 * constraint, lazy checks have to mask any violated
722 * permission and notice it to userspace via audit.
724 type_attribute_bounds_av(policydb, scontext, tcontext,
728 static int security_validtrans_handle_fail(struct selinux_state *state,
729 struct context *ocontext,
730 struct context *ncontext,
731 struct context *tcontext,
734 struct policydb *p = &state->ss->policydb;
735 char *o = NULL, *n = NULL, *t = NULL;
736 u32 olen, nlen, tlen;
738 if (context_struct_to_string(p, ocontext, &o, &olen))
740 if (context_struct_to_string(p, ncontext, &n, &nlen))
742 if (context_struct_to_string(p, tcontext, &t, &tlen))
744 audit_log(audit_context(), GFP_ATOMIC, AUDIT_SELINUX_ERR,
745 "op=security_validate_transition seresult=denied"
746 " oldcontext=%s newcontext=%s taskcontext=%s tclass=%s",
747 o, n, t, sym_name(p, SYM_CLASSES, tclass-1));
753 if (!enforcing_enabled(state))
758 static int security_compute_validatetrans(struct selinux_state *state,
759 u32 oldsid, u32 newsid, u32 tasksid,
760 u16 orig_tclass, bool user)
762 struct policydb *policydb;
763 struct sidtab *sidtab;
764 struct context *ocontext;
765 struct context *ncontext;
766 struct context *tcontext;
767 struct class_datum *tclass_datum;
768 struct constraint_node *constraint;
773 if (!state->initialized)
776 read_lock(&state->ss->policy_rwlock);
778 policydb = &state->ss->policydb;
779 sidtab = &state->ss->sidtab;
782 tclass = unmap_class(&state->ss->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 ocontext = sidtab_search(sidtab, oldsid);
794 pr_err("SELinux: %s: unrecognized SID %d\n",
800 ncontext = sidtab_search(sidtab, newsid);
802 pr_err("SELinux: %s: unrecognized SID %d\n",
808 tcontext = sidtab_search(sidtab, tasksid);
810 pr_err("SELinux: %s: unrecognized SID %d\n",
816 constraint = tclass_datum->validatetrans;
818 if (!constraint_expr_eval(policydb, ocontext, ncontext,
819 tcontext, constraint->expr)) {
823 rc = security_validtrans_handle_fail(state,
830 constraint = constraint->next;
834 read_unlock(&state->ss->policy_rwlock);
838 int security_validate_transition_user(struct selinux_state *state,
839 u32 oldsid, u32 newsid, u32 tasksid,
842 return security_compute_validatetrans(state, oldsid, newsid, tasksid,
846 int security_validate_transition(struct selinux_state *state,
847 u32 oldsid, u32 newsid, u32 tasksid,
850 return security_compute_validatetrans(state, oldsid, newsid, tasksid,
855 * security_bounded_transition - check whether the given
856 * transition is directed to bounded, or not.
857 * It returns 0, if @newsid is bounded by @oldsid.
858 * Otherwise, it returns error code.
860 * @oldsid : current security identifier
861 * @newsid : destinated security identifier
863 int security_bounded_transition(struct selinux_state *state,
864 u32 old_sid, u32 new_sid)
866 struct policydb *policydb;
867 struct sidtab *sidtab;
868 struct context *old_context, *new_context;
869 struct type_datum *type;
873 if (!state->initialized)
876 read_lock(&state->ss->policy_rwlock);
878 policydb = &state->ss->policydb;
879 sidtab = &state->ss->sidtab;
882 old_context = sidtab_search(sidtab, old_sid);
884 pr_err("SELinux: %s: unrecognized SID %u\n",
890 new_context = sidtab_search(sidtab, new_sid);
892 pr_err("SELinux: %s: unrecognized SID %u\n",
898 /* type/domain unchanged */
899 if (old_context->type == new_context->type)
902 index = new_context->type;
904 type = flex_array_get_ptr(policydb->type_val_to_struct_array,
908 /* not bounded anymore */
913 /* @newsid is bounded by @oldsid */
915 if (type->bounds == old_context->type)
918 index = type->bounds;
922 char *old_name = NULL;
923 char *new_name = NULL;
926 if (!context_struct_to_string(policydb, old_context,
927 &old_name, &length) &&
928 !context_struct_to_string(policydb, new_context,
929 &new_name, &length)) {
930 audit_log(audit_context(),
931 GFP_ATOMIC, AUDIT_SELINUX_ERR,
932 "op=security_bounded_transition "
934 "oldcontext=%s newcontext=%s",
941 read_unlock(&state->ss->policy_rwlock);
946 static void avd_init(struct selinux_state *state, struct av_decision *avd)
950 avd->auditdeny = 0xffffffff;
951 avd->seqno = state->ss->latest_granting;
955 void services_compute_xperms_decision(struct extended_perms_decision *xpermd,
956 struct avtab_node *node)
960 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
961 if (xpermd->driver != node->datum.u.xperms->driver)
963 } else if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
964 if (!security_xperm_test(node->datum.u.xperms->perms.p,
971 if (node->key.specified == AVTAB_XPERMS_ALLOWED) {
972 xpermd->used |= XPERMS_ALLOWED;
973 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
974 memset(xpermd->allowed->p, 0xff,
975 sizeof(xpermd->allowed->p));
977 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
978 for (i = 0; i < ARRAY_SIZE(xpermd->allowed->p); i++)
979 xpermd->allowed->p[i] |=
980 node->datum.u.xperms->perms.p[i];
982 } else if (node->key.specified == AVTAB_XPERMS_AUDITALLOW) {
983 xpermd->used |= XPERMS_AUDITALLOW;
984 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
985 memset(xpermd->auditallow->p, 0xff,
986 sizeof(xpermd->auditallow->p));
988 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
989 for (i = 0; i < ARRAY_SIZE(xpermd->auditallow->p); i++)
990 xpermd->auditallow->p[i] |=
991 node->datum.u.xperms->perms.p[i];
993 } else if (node->key.specified == AVTAB_XPERMS_DONTAUDIT) {
994 xpermd->used |= XPERMS_DONTAUDIT;
995 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
996 memset(xpermd->dontaudit->p, 0xff,
997 sizeof(xpermd->dontaudit->p));
999 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
1000 for (i = 0; i < ARRAY_SIZE(xpermd->dontaudit->p); i++)
1001 xpermd->dontaudit->p[i] |=
1002 node->datum.u.xperms->perms.p[i];
1009 void security_compute_xperms_decision(struct selinux_state *state,
1014 struct extended_perms_decision *xpermd)
1016 struct policydb *policydb;
1017 struct sidtab *sidtab;
1019 struct context *scontext, *tcontext;
1020 struct avtab_key avkey;
1021 struct avtab_node *node;
1022 struct ebitmap *sattr, *tattr;
1023 struct ebitmap_node *snode, *tnode;
1026 xpermd->driver = driver;
1028 memset(xpermd->allowed->p, 0, sizeof(xpermd->allowed->p));
1029 memset(xpermd->auditallow->p, 0, sizeof(xpermd->auditallow->p));
1030 memset(xpermd->dontaudit->p, 0, sizeof(xpermd->dontaudit->p));
1032 read_lock(&state->ss->policy_rwlock);
1033 if (!state->initialized)
1036 policydb = &state->ss->policydb;
1037 sidtab = &state->ss->sidtab;
1039 scontext = sidtab_search(sidtab, ssid);
1041 pr_err("SELinux: %s: unrecognized SID %d\n",
1046 tcontext = sidtab_search(sidtab, tsid);
1048 pr_err("SELinux: %s: unrecognized SID %d\n",
1053 tclass = unmap_class(&state->ss->map, orig_tclass);
1054 if (unlikely(orig_tclass && !tclass)) {
1055 if (policydb->allow_unknown)
1061 if (unlikely(!tclass || tclass > policydb->p_classes.nprim)) {
1062 pr_warn_ratelimited("SELinux: Invalid class %hu\n", tclass);
1066 avkey.target_class = tclass;
1067 avkey.specified = AVTAB_XPERMS;
1068 sattr = flex_array_get(policydb->type_attr_map_array,
1069 scontext->type - 1);
1071 tattr = flex_array_get(policydb->type_attr_map_array,
1072 tcontext->type - 1);
1074 ebitmap_for_each_positive_bit(sattr, snode, i) {
1075 ebitmap_for_each_positive_bit(tattr, tnode, j) {
1076 avkey.source_type = i + 1;
1077 avkey.target_type = j + 1;
1078 for (node = avtab_search_node(&policydb->te_avtab,
1081 node = avtab_search_node_next(node, avkey.specified))
1082 services_compute_xperms_decision(xpermd, node);
1084 cond_compute_xperms(&policydb->te_cond_avtab,
1089 read_unlock(&state->ss->policy_rwlock);
1092 memset(xpermd->allowed->p, 0xff, sizeof(xpermd->allowed->p));
1097 * security_compute_av - Compute access vector decisions.
1098 * @ssid: source security identifier
1099 * @tsid: target security identifier
1100 * @tclass: target security class
1101 * @avd: access vector decisions
1102 * @xperms: extended permissions
1104 * Compute a set of access vector decisions based on the
1105 * SID pair (@ssid, @tsid) for the permissions in @tclass.
1107 void security_compute_av(struct selinux_state *state,
1111 struct av_decision *avd,
1112 struct extended_perms *xperms)
1114 struct policydb *policydb;
1115 struct sidtab *sidtab;
1117 struct context *scontext = NULL, *tcontext = NULL;
1119 read_lock(&state->ss->policy_rwlock);
1120 avd_init(state, avd);
1122 if (!state->initialized)
1125 policydb = &state->ss->policydb;
1126 sidtab = &state->ss->sidtab;
1128 scontext = sidtab_search(sidtab, ssid);
1130 pr_err("SELinux: %s: unrecognized SID %d\n",
1135 /* permissive domain? */
1136 if (ebitmap_get_bit(&policydb->permissive_map, scontext->type))
1137 avd->flags |= AVD_FLAGS_PERMISSIVE;
1139 tcontext = sidtab_search(sidtab, tsid);
1141 pr_err("SELinux: %s: unrecognized SID %d\n",
1146 tclass = unmap_class(&state->ss->map, orig_tclass);
1147 if (unlikely(orig_tclass && !tclass)) {
1148 if (policydb->allow_unknown)
1152 context_struct_compute_av(policydb, scontext, tcontext, tclass, avd,
1154 map_decision(&state->ss->map, orig_tclass, avd,
1155 policydb->allow_unknown);
1157 read_unlock(&state->ss->policy_rwlock);
1160 avd->allowed = 0xffffffff;
1164 void security_compute_av_user(struct selinux_state *state,
1168 struct av_decision *avd)
1170 struct policydb *policydb;
1171 struct sidtab *sidtab;
1172 struct context *scontext = NULL, *tcontext = NULL;
1174 read_lock(&state->ss->policy_rwlock);
1175 avd_init(state, avd);
1176 if (!state->initialized)
1179 policydb = &state->ss->policydb;
1180 sidtab = &state->ss->sidtab;
1182 scontext = sidtab_search(sidtab, ssid);
1184 pr_err("SELinux: %s: unrecognized SID %d\n",
1189 /* permissive domain? */
1190 if (ebitmap_get_bit(&policydb->permissive_map, scontext->type))
1191 avd->flags |= AVD_FLAGS_PERMISSIVE;
1193 tcontext = sidtab_search(sidtab, tsid);
1195 pr_err("SELinux: %s: unrecognized SID %d\n",
1200 if (unlikely(!tclass)) {
1201 if (policydb->allow_unknown)
1206 context_struct_compute_av(policydb, scontext, tcontext, tclass, avd,
1209 read_unlock(&state->ss->policy_rwlock);
1212 avd->allowed = 0xffffffff;
1217 * Write the security context string representation of
1218 * the context structure `context' into a dynamically
1219 * allocated string of the correct size. Set `*scontext'
1220 * to point to this string and set `*scontext_len' to
1221 * the length of the string.
1223 static int context_struct_to_string(struct policydb *p,
1224 struct context *context,
1225 char **scontext, u32 *scontext_len)
1234 *scontext_len = context->len;
1236 *scontext = kstrdup(context->str, GFP_ATOMIC);
1243 /* Compute the size of the context. */
1244 *scontext_len += strlen(sym_name(p, SYM_USERS, context->user - 1)) + 1;
1245 *scontext_len += strlen(sym_name(p, SYM_ROLES, context->role - 1)) + 1;
1246 *scontext_len += strlen(sym_name(p, SYM_TYPES, context->type - 1)) + 1;
1247 *scontext_len += mls_compute_context_len(p, context);
1252 /* Allocate space for the context; caller must free this space. */
1253 scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
1256 *scontext = scontextp;
1259 * Copy the user name, role name and type name into the context.
1261 scontextp += sprintf(scontextp, "%s:%s:%s",
1262 sym_name(p, SYM_USERS, context->user - 1),
1263 sym_name(p, SYM_ROLES, context->role - 1),
1264 sym_name(p, SYM_TYPES, context->type - 1));
1266 mls_sid_to_context(p, context, &scontextp);
1273 #include "initial_sid_to_string.h"
1275 const char *security_get_initial_sid_context(u32 sid)
1277 if (unlikely(sid > SECINITSID_NUM))
1279 return initial_sid_to_string[sid];
1282 static int security_sid_to_context_core(struct selinux_state *state,
1283 u32 sid, char **scontext,
1284 u32 *scontext_len, int force)
1286 struct policydb *policydb;
1287 struct sidtab *sidtab;
1288 struct context *context;
1295 if (!state->initialized) {
1296 if (sid <= SECINITSID_NUM) {
1299 *scontext_len = strlen(initial_sid_to_string[sid]) + 1;
1302 scontextp = kmemdup(initial_sid_to_string[sid],
1303 *scontext_len, GFP_ATOMIC);
1308 *scontext = scontextp;
1311 pr_err("SELinux: %s: called before initial "
1312 "load_policy on unknown SID %d\n", __func__, sid);
1316 read_lock(&state->ss->policy_rwlock);
1317 policydb = &state->ss->policydb;
1318 sidtab = &state->ss->sidtab;
1320 context = sidtab_search_force(sidtab, sid);
1322 context = sidtab_search(sidtab, sid);
1324 pr_err("SELinux: %s: unrecognized SID %d\n",
1329 rc = context_struct_to_string(policydb, context, scontext,
1332 read_unlock(&state->ss->policy_rwlock);
1339 * security_sid_to_context - Obtain a context for a given SID.
1340 * @sid: security identifier, SID
1341 * @scontext: security context
1342 * @scontext_len: length in bytes
1344 * Write the string representation of the context associated with @sid
1345 * into a dynamically allocated string of the correct size. Set @scontext
1346 * to point to this string and set @scontext_len to the length of the string.
1348 int security_sid_to_context(struct selinux_state *state,
1349 u32 sid, char **scontext, u32 *scontext_len)
1351 return security_sid_to_context_core(state, sid, scontext,
1355 int security_sid_to_context_force(struct selinux_state *state, u32 sid,
1356 char **scontext, u32 *scontext_len)
1358 return security_sid_to_context_core(state, sid, scontext,
1363 * Caveat: Mutates scontext.
1365 static int string_to_context_struct(struct policydb *pol,
1366 struct sidtab *sidtabp,
1369 struct context *ctx,
1372 struct role_datum *role;
1373 struct type_datum *typdatum;
1374 struct user_datum *usrdatum;
1375 char *scontextp, *p, oldc;
1380 /* Parse the security context. */
1383 scontextp = (char *) scontext;
1385 /* Extract the user. */
1387 while (*p && *p != ':')
1395 usrdatum = hashtab_search(pol->p_users.table, scontextp);
1399 ctx->user = usrdatum->value;
1403 while (*p && *p != ':')
1411 role = hashtab_search(pol->p_roles.table, scontextp);
1414 ctx->role = role->value;
1418 while (*p && *p != ':')
1423 typdatum = hashtab_search(pol->p_types.table, scontextp);
1424 if (!typdatum || typdatum->attribute)
1427 ctx->type = typdatum->value;
1429 rc = mls_context_to_sid(pol, oldc, &p, ctx, sidtabp, def_sid);
1434 if ((p - scontext) < scontext_len)
1437 /* Check the validity of the new context. */
1438 if (!policydb_context_isvalid(pol, ctx))
1443 context_destroy(ctx);
1447 static int security_context_to_sid_core(struct selinux_state *state,
1448 const char *scontext, u32 scontext_len,
1449 u32 *sid, u32 def_sid, gfp_t gfp_flags,
1452 struct policydb *policydb;
1453 struct sidtab *sidtab;
1454 char *scontext2, *str = NULL;
1455 struct context context;
1458 /* An empty security context is never valid. */
1462 /* Copy the string to allow changes and ensure a NUL terminator */
1463 scontext2 = kmemdup_nul(scontext, scontext_len, gfp_flags);
1467 if (!state->initialized) {
1470 for (i = 1; i < SECINITSID_NUM; i++) {
1471 if (!strcmp(initial_sid_to_string[i], scontext2)) {
1476 *sid = SECINITSID_KERNEL;
1482 /* Save another copy for storing in uninterpreted form */
1484 str = kstrdup(scontext2, gfp_flags);
1488 read_lock(&state->ss->policy_rwlock);
1489 policydb = &state->ss->policydb;
1490 sidtab = &state->ss->sidtab;
1491 rc = string_to_context_struct(policydb, sidtab, scontext2,
1492 scontext_len, &context, def_sid);
1493 if (rc == -EINVAL && force) {
1495 context.len = strlen(str) + 1;
1499 rc = sidtab_context_to_sid(sidtab, &context, sid);
1500 context_destroy(&context);
1502 read_unlock(&state->ss->policy_rwlock);
1510 * security_context_to_sid - Obtain a SID for a given security context.
1511 * @scontext: security context
1512 * @scontext_len: length in bytes
1513 * @sid: security identifier, SID
1514 * @gfp: context for the allocation
1516 * Obtains a SID associated with the security context that
1517 * has the string representation specified by @scontext.
1518 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1519 * memory is available, or 0 on success.
1521 int security_context_to_sid(struct selinux_state *state,
1522 const char *scontext, u32 scontext_len, u32 *sid,
1525 return security_context_to_sid_core(state, scontext, scontext_len,
1526 sid, SECSID_NULL, gfp, 0);
1529 int security_context_str_to_sid(struct selinux_state *state,
1530 const char *scontext, u32 *sid, gfp_t gfp)
1532 return security_context_to_sid(state, scontext, strlen(scontext),
1537 * security_context_to_sid_default - Obtain a SID for a given security context,
1538 * falling back to specified default if needed.
1540 * @scontext: security context
1541 * @scontext_len: length in bytes
1542 * @sid: security identifier, SID
1543 * @def_sid: default SID to assign on error
1545 * Obtains a SID associated with the security context that
1546 * has the string representation specified by @scontext.
1547 * The default SID is passed to the MLS layer to be used to allow
1548 * kernel labeling of the MLS field if the MLS field is not present
1549 * (for upgrading to MLS without full relabel).
1550 * Implicitly forces adding of the context even if it cannot be mapped yet.
1551 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1552 * memory is available, or 0 on success.
1554 int security_context_to_sid_default(struct selinux_state *state,
1555 const char *scontext, u32 scontext_len,
1556 u32 *sid, u32 def_sid, gfp_t gfp_flags)
1558 return security_context_to_sid_core(state, scontext, scontext_len,
1559 sid, def_sid, gfp_flags, 1);
1562 int security_context_to_sid_force(struct selinux_state *state,
1563 const char *scontext, u32 scontext_len,
1566 return security_context_to_sid_core(state, scontext, scontext_len,
1567 sid, SECSID_NULL, GFP_KERNEL, 1);
1570 static int compute_sid_handle_invalid_context(
1571 struct selinux_state *state,
1572 struct context *scontext,
1573 struct context *tcontext,
1575 struct context *newcontext)
1577 struct policydb *policydb = &state->ss->policydb;
1578 char *s = NULL, *t = NULL, *n = NULL;
1579 u32 slen, tlen, nlen;
1581 if (context_struct_to_string(policydb, scontext, &s, &slen))
1583 if (context_struct_to_string(policydb, tcontext, &t, &tlen))
1585 if (context_struct_to_string(policydb, newcontext, &n, &nlen))
1587 audit_log(audit_context(), GFP_ATOMIC, AUDIT_SELINUX_ERR,
1588 "op=security_compute_sid invalid_context=%s"
1592 n, s, t, sym_name(policydb, SYM_CLASSES, tclass-1));
1597 if (!enforcing_enabled(state))
1602 static void filename_compute_type(struct policydb *policydb,
1603 struct context *newcontext,
1604 u32 stype, u32 ttype, u16 tclass,
1605 const char *objname)
1607 struct filename_trans ft;
1608 struct filename_trans_datum *otype;
1611 * Most filename trans rules are going to live in specific directories
1612 * like /dev or /var/run. This bitmap will quickly skip rule searches
1613 * if the ttype does not contain any rules.
1615 if (!ebitmap_get_bit(&policydb->filename_trans_ttypes, ttype))
1623 otype = hashtab_search(policydb->filename_trans, &ft);
1625 newcontext->type = otype->otype;
1628 static int security_compute_sid(struct selinux_state *state,
1633 const char *objname,
1637 struct policydb *policydb;
1638 struct sidtab *sidtab;
1639 struct class_datum *cladatum = NULL;
1640 struct context *scontext = NULL, *tcontext = NULL, newcontext;
1641 struct role_trans *roletr = NULL;
1642 struct avtab_key avkey;
1643 struct avtab_datum *avdatum;
1644 struct avtab_node *node;
1649 if (!state->initialized) {
1650 switch (orig_tclass) {
1651 case SECCLASS_PROCESS: /* kernel value */
1661 context_init(&newcontext);
1663 read_lock(&state->ss->policy_rwlock);
1666 tclass = unmap_class(&state->ss->map, orig_tclass);
1667 sock = security_is_socket_class(orig_tclass);
1669 tclass = orig_tclass;
1670 sock = security_is_socket_class(map_class(&state->ss->map,
1674 policydb = &state->ss->policydb;
1675 sidtab = &state->ss->sidtab;
1677 scontext = sidtab_search(sidtab, ssid);
1679 pr_err("SELinux: %s: unrecognized SID %d\n",
1684 tcontext = sidtab_search(sidtab, tsid);
1686 pr_err("SELinux: %s: unrecognized SID %d\n",
1692 if (tclass && tclass <= policydb->p_classes.nprim)
1693 cladatum = policydb->class_val_to_struct[tclass - 1];
1695 /* Set the user identity. */
1696 switch (specified) {
1697 case AVTAB_TRANSITION:
1699 if (cladatum && cladatum->default_user == DEFAULT_TARGET) {
1700 newcontext.user = tcontext->user;
1702 /* notice this gets both DEFAULT_SOURCE and unset */
1703 /* Use the process user identity. */
1704 newcontext.user = scontext->user;
1708 /* Use the related object owner. */
1709 newcontext.user = tcontext->user;
1713 /* Set the role to default values. */
1714 if (cladatum && cladatum->default_role == DEFAULT_SOURCE) {
1715 newcontext.role = scontext->role;
1716 } else if (cladatum && cladatum->default_role == DEFAULT_TARGET) {
1717 newcontext.role = tcontext->role;
1719 if ((tclass == policydb->process_class) || (sock == true))
1720 newcontext.role = scontext->role;
1722 newcontext.role = OBJECT_R_VAL;
1725 /* Set the type to default values. */
1726 if (cladatum && cladatum->default_type == DEFAULT_SOURCE) {
1727 newcontext.type = scontext->type;
1728 } else if (cladatum && cladatum->default_type == DEFAULT_TARGET) {
1729 newcontext.type = tcontext->type;
1731 if ((tclass == policydb->process_class) || (sock == true)) {
1732 /* Use the type of process. */
1733 newcontext.type = scontext->type;
1735 /* Use the type of the related object. */
1736 newcontext.type = tcontext->type;
1740 /* Look for a type transition/member/change rule. */
1741 avkey.source_type = scontext->type;
1742 avkey.target_type = tcontext->type;
1743 avkey.target_class = tclass;
1744 avkey.specified = specified;
1745 avdatum = avtab_search(&policydb->te_avtab, &avkey);
1747 /* If no permanent rule, also check for enabled conditional rules */
1749 node = avtab_search_node(&policydb->te_cond_avtab, &avkey);
1750 for (; node; node = avtab_search_node_next(node, specified)) {
1751 if (node->key.specified & AVTAB_ENABLED) {
1752 avdatum = &node->datum;
1759 /* Use the type from the type transition/member/change rule. */
1760 newcontext.type = avdatum->u.data;
1763 /* if we have a objname this is a file trans check so check those rules */
1765 filename_compute_type(policydb, &newcontext, scontext->type,
1766 tcontext->type, tclass, objname);
1768 /* Check for class-specific changes. */
1769 if (specified & AVTAB_TRANSITION) {
1770 /* Look for a role transition rule. */
1771 for (roletr = policydb->role_tr; roletr;
1772 roletr = roletr->next) {
1773 if ((roletr->role == scontext->role) &&
1774 (roletr->type == tcontext->type) &&
1775 (roletr->tclass == tclass)) {
1776 /* Use the role transition rule. */
1777 newcontext.role = roletr->new_role;
1783 /* Set the MLS attributes.
1784 This is done last because it may allocate memory. */
1785 rc = mls_compute_sid(policydb, scontext, tcontext, tclass, specified,
1790 /* Check the validity of the context. */
1791 if (!policydb_context_isvalid(policydb, &newcontext)) {
1792 rc = compute_sid_handle_invalid_context(state, scontext,
1799 /* Obtain the sid for the context. */
1800 rc = sidtab_context_to_sid(sidtab, &newcontext, out_sid);
1802 read_unlock(&state->ss->policy_rwlock);
1803 context_destroy(&newcontext);
1809 * security_transition_sid - Compute the SID for a new subject/object.
1810 * @ssid: source security identifier
1811 * @tsid: target security identifier
1812 * @tclass: target security class
1813 * @out_sid: security identifier for new subject/object
1815 * Compute a SID to use for labeling a new subject or object in the
1816 * class @tclass based on a SID pair (@ssid, @tsid).
1817 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1818 * if insufficient memory is available, or %0 if the new SID was
1819 * computed successfully.
1821 int security_transition_sid(struct selinux_state *state,
1822 u32 ssid, u32 tsid, u16 tclass,
1823 const struct qstr *qstr, u32 *out_sid)
1825 return security_compute_sid(state, ssid, tsid, tclass,
1827 qstr ? qstr->name : NULL, out_sid, true);
1830 int security_transition_sid_user(struct selinux_state *state,
1831 u32 ssid, u32 tsid, u16 tclass,
1832 const char *objname, u32 *out_sid)
1834 return security_compute_sid(state, ssid, tsid, tclass,
1836 objname, out_sid, false);
1840 * security_member_sid - Compute the SID for member selection.
1841 * @ssid: source security identifier
1842 * @tsid: target security identifier
1843 * @tclass: target security class
1844 * @out_sid: security identifier for selected member
1846 * Compute a SID to use when selecting a member of a polyinstantiated
1847 * object of class @tclass based on a SID pair (@ssid, @tsid).
1848 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1849 * if insufficient memory is available, or %0 if the SID was
1850 * computed successfully.
1852 int security_member_sid(struct selinux_state *state,
1858 return security_compute_sid(state, ssid, tsid, tclass,
1864 * security_change_sid - Compute the SID for object relabeling.
1865 * @ssid: source security identifier
1866 * @tsid: target security identifier
1867 * @tclass: target security class
1868 * @out_sid: security identifier for selected member
1870 * Compute a SID to use for relabeling an object of class @tclass
1871 * based on a SID pair (@ssid, @tsid).
1872 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1873 * if insufficient memory is available, or %0 if the SID was
1874 * computed successfully.
1876 int security_change_sid(struct selinux_state *state,
1882 return security_compute_sid(state,
1883 ssid, tsid, tclass, AVTAB_CHANGE, NULL,
1887 /* Clone the SID into the new SID table. */
1888 static int clone_sid(u32 sid,
1889 struct context *context,
1892 struct sidtab *s = arg;
1894 if (sid > SECINITSID_NUM)
1895 return sidtab_insert(s, sid, context);
1900 static inline int convert_context_handle_invalid_context(
1901 struct selinux_state *state,
1902 struct context *context)
1904 struct policydb *policydb = &state->ss->policydb;
1908 if (enforcing_enabled(state))
1911 if (!context_struct_to_string(policydb, context, &s, &len)) {
1912 pr_warn("SELinux: Context %s would be invalid if enforcing\n",
1919 struct convert_context_args {
1920 struct selinux_state *state;
1921 struct policydb *oldp;
1922 struct policydb *newp;
1926 * Convert the values in the security context
1927 * structure `c' from the values specified
1928 * in the policy `p->oldp' to the values specified
1929 * in the policy `p->newp'. Verify that the
1930 * context is valid under the new policy.
1932 static int convert_context(u32 key,
1936 struct convert_context_args *args;
1937 struct context oldc;
1938 struct ocontext *oc;
1939 struct mls_range *range;
1940 struct role_datum *role;
1941 struct type_datum *typdatum;
1942 struct user_datum *usrdatum;
1947 if (key <= SECINITSID_NUM)
1956 s = kstrdup(c->str, GFP_KERNEL);
1960 rc = string_to_context_struct(args->newp, NULL, s,
1961 c->len, &ctx, SECSID_NULL);
1964 pr_info("SELinux: Context %s became valid (mapped).\n",
1966 /* Replace string with mapped representation. */
1968 memcpy(c, &ctx, sizeof(*c));
1970 } else if (rc == -EINVAL) {
1971 /* Retain string representation for later mapping. */
1975 /* Other error condition, e.g. ENOMEM. */
1976 pr_err("SELinux: Unable to map context %s, rc = %d.\n",
1982 rc = context_cpy(&oldc, c);
1986 /* Convert the user. */
1988 usrdatum = hashtab_search(args->newp->p_users.table,
1989 sym_name(args->oldp, SYM_USERS, c->user - 1));
1992 c->user = usrdatum->value;
1994 /* Convert the role. */
1996 role = hashtab_search(args->newp->p_roles.table,
1997 sym_name(args->oldp, SYM_ROLES, c->role - 1));
2000 c->role = role->value;
2002 /* Convert the type. */
2004 typdatum = hashtab_search(args->newp->p_types.table,
2005 sym_name(args->oldp, SYM_TYPES, c->type - 1));
2008 c->type = typdatum->value;
2010 /* Convert the MLS fields if dealing with MLS policies */
2011 if (args->oldp->mls_enabled && args->newp->mls_enabled) {
2012 rc = mls_convert_context(args->oldp, args->newp, c);
2015 } else if (args->oldp->mls_enabled && !args->newp->mls_enabled) {
2017 * Switching between MLS and non-MLS policy:
2018 * free any storage used by the MLS fields in the
2019 * context for all existing entries in the sidtab.
2021 mls_context_destroy(c);
2022 } else if (!args->oldp->mls_enabled && args->newp->mls_enabled) {
2024 * Switching between non-MLS and MLS policy:
2025 * ensure that the MLS fields of the context for all
2026 * existing entries in the sidtab are filled in with a
2027 * suitable default value, likely taken from one of the
2030 oc = args->newp->ocontexts[OCON_ISID];
2031 while (oc && oc->sid[0] != SECINITSID_UNLABELED)
2035 pr_err("SELinux: unable to look up"
2036 " the initial SIDs list\n");
2039 range = &oc->context[0].range;
2040 rc = mls_range_set(c, range);
2045 /* Check the validity of the new context. */
2046 if (!policydb_context_isvalid(args->newp, c)) {
2047 rc = convert_context_handle_invalid_context(args->state,
2053 context_destroy(&oldc);
2059 /* Map old representation to string and save it. */
2060 rc = context_struct_to_string(args->oldp, &oldc, &s, &len);
2063 context_destroy(&oldc);
2067 pr_info("SELinux: Context %s became invalid (unmapped).\n",
2073 static void security_load_policycaps(struct selinux_state *state)
2075 struct policydb *p = &state->ss->policydb;
2077 struct ebitmap_node *node;
2079 for (i = 0; i < ARRAY_SIZE(state->policycap); i++)
2080 state->policycap[i] = ebitmap_get_bit(&p->policycaps, i);
2082 for (i = 0; i < ARRAY_SIZE(selinux_policycap_names); i++)
2083 pr_info("SELinux: policy capability %s=%d\n",
2084 selinux_policycap_names[i],
2085 ebitmap_get_bit(&p->policycaps, i));
2087 ebitmap_for_each_positive_bit(&p->policycaps, node, i) {
2088 if (i >= ARRAY_SIZE(selinux_policycap_names))
2089 pr_info("SELinux: unknown policy capability %u\n",
2094 static int security_preserve_bools(struct selinux_state *state,
2095 struct policydb *newpolicydb);
2098 * security_load_policy - Load a security policy configuration.
2099 * @data: binary policy data
2100 * @len: length of data in bytes
2102 * Load a new set of security policy configuration data,
2103 * validate it and convert the SID table as necessary.
2104 * This function will flush the access vector cache after
2105 * loading the new policy.
2107 int security_load_policy(struct selinux_state *state, void *data, size_t len)
2109 struct policydb *policydb;
2110 struct sidtab *sidtab;
2111 struct policydb *oldpolicydb, *newpolicydb;
2112 struct sidtab oldsidtab, newsidtab;
2113 struct selinux_mapping *oldmapping;
2114 struct selinux_map newmap;
2115 struct convert_context_args args;
2118 struct policy_file file = { data, len }, *fp = &file;
2120 oldpolicydb = kcalloc(2, sizeof(*oldpolicydb), GFP_KERNEL);
2125 newpolicydb = oldpolicydb + 1;
2127 policydb = &state->ss->policydb;
2128 sidtab = &state->ss->sidtab;
2130 if (!state->initialized) {
2131 rc = policydb_read(policydb, fp);
2135 policydb->len = len;
2136 rc = selinux_set_mapping(policydb, secclass_map,
2139 policydb_destroy(policydb);
2143 rc = policydb_load_isids(policydb, sidtab);
2145 policydb_destroy(policydb);
2149 security_load_policycaps(state);
2150 state->initialized = 1;
2151 seqno = ++state->ss->latest_granting;
2152 selinux_complete_init();
2153 avc_ss_reset(state->avc, seqno);
2154 selnl_notify_policyload(seqno);
2155 selinux_status_update_policyload(state, seqno);
2156 selinux_netlbl_cache_invalidate();
2157 selinux_xfrm_notify_policyload();
2162 sidtab_hash_eval(sidtab, "sids");
2165 rc = policydb_read(newpolicydb, fp);
2169 newpolicydb->len = len;
2170 /* If switching between different policy types, log MLS status */
2171 if (policydb->mls_enabled && !newpolicydb->mls_enabled)
2172 pr_info("SELinux: Disabling MLS support...\n");
2173 else if (!policydb->mls_enabled && newpolicydb->mls_enabled)
2174 pr_info("SELinux: Enabling MLS support...\n");
2176 rc = policydb_load_isids(newpolicydb, &newsidtab);
2178 pr_err("SELinux: unable to load the initial SIDs\n");
2179 policydb_destroy(newpolicydb);
2183 rc = selinux_set_mapping(newpolicydb, secclass_map, &newmap);
2187 rc = security_preserve_bools(state, newpolicydb);
2189 pr_err("SELinux: unable to preserve booleans\n");
2193 /* Clone the SID table. */
2194 sidtab_shutdown(sidtab);
2196 rc = sidtab_map(sidtab, clone_sid, &newsidtab);
2201 * Convert the internal representations of contexts
2202 * in the new SID table.
2205 args.oldp = policydb;
2206 args.newp = newpolicydb;
2207 rc = sidtab_map(&newsidtab, convert_context, &args);
2209 pr_err("SELinux: unable to convert the internal"
2210 " representation of contexts in the new SID"
2215 /* Save the old policydb and SID table to free later. */
2216 memcpy(oldpolicydb, policydb, sizeof(*policydb));
2217 sidtab_set(&oldsidtab, sidtab);
2219 /* Install the new policydb and SID table. */
2220 write_lock_irq(&state->ss->policy_rwlock);
2221 memcpy(policydb, newpolicydb, sizeof(*policydb));
2222 sidtab_set(sidtab, &newsidtab);
2223 security_load_policycaps(state);
2224 oldmapping = state->ss->map.mapping;
2225 state->ss->map.mapping = newmap.mapping;
2226 state->ss->map.size = newmap.size;
2227 seqno = ++state->ss->latest_granting;
2228 write_unlock_irq(&state->ss->policy_rwlock);
2230 /* Free the old policydb and SID table. */
2231 policydb_destroy(oldpolicydb);
2232 sidtab_destroy(&oldsidtab);
2235 avc_ss_reset(state->avc, seqno);
2236 selnl_notify_policyload(seqno);
2237 selinux_status_update_policyload(state, seqno);
2238 selinux_netlbl_cache_invalidate();
2239 selinux_xfrm_notify_policyload();
2245 kfree(newmap.mapping);
2246 sidtab_destroy(&newsidtab);
2247 policydb_destroy(newpolicydb);
2254 size_t security_policydb_len(struct selinux_state *state)
2256 struct policydb *p = &state->ss->policydb;
2259 read_lock(&state->ss->policy_rwlock);
2261 read_unlock(&state->ss->policy_rwlock);
2267 * security_port_sid - Obtain the SID for a port.
2268 * @protocol: protocol number
2269 * @port: port number
2270 * @out_sid: security identifier
2272 int security_port_sid(struct selinux_state *state,
2273 u8 protocol, u16 port, u32 *out_sid)
2275 struct policydb *policydb;
2276 struct sidtab *sidtab;
2280 read_lock(&state->ss->policy_rwlock);
2282 policydb = &state->ss->policydb;
2283 sidtab = &state->ss->sidtab;
2285 c = policydb->ocontexts[OCON_PORT];
2287 if (c->u.port.protocol == protocol &&
2288 c->u.port.low_port <= port &&
2289 c->u.port.high_port >= port)
2296 rc = sidtab_context_to_sid(sidtab,
2302 *out_sid = c->sid[0];
2304 *out_sid = SECINITSID_PORT;
2308 read_unlock(&state->ss->policy_rwlock);
2313 * security_pkey_sid - Obtain the SID for a pkey.
2314 * @subnet_prefix: Subnet Prefix
2315 * @pkey_num: pkey number
2316 * @out_sid: security identifier
2318 int security_ib_pkey_sid(struct selinux_state *state,
2319 u64 subnet_prefix, u16 pkey_num, u32 *out_sid)
2321 struct policydb *policydb;
2322 struct sidtab *sidtab;
2326 read_lock(&state->ss->policy_rwlock);
2328 policydb = &state->ss->policydb;
2329 sidtab = &state->ss->sidtab;
2331 c = policydb->ocontexts[OCON_IBPKEY];
2333 if (c->u.ibpkey.low_pkey <= pkey_num &&
2334 c->u.ibpkey.high_pkey >= pkey_num &&
2335 c->u.ibpkey.subnet_prefix == subnet_prefix)
2343 rc = sidtab_context_to_sid(sidtab,
2349 *out_sid = c->sid[0];
2351 *out_sid = SECINITSID_UNLABELED;
2354 read_unlock(&state->ss->policy_rwlock);
2359 * security_ib_endport_sid - Obtain the SID for a subnet management interface.
2360 * @dev_name: device name
2361 * @port: port number
2362 * @out_sid: security identifier
2364 int security_ib_endport_sid(struct selinux_state *state,
2365 const char *dev_name, u8 port_num, u32 *out_sid)
2367 struct policydb *policydb;
2368 struct sidtab *sidtab;
2372 read_lock(&state->ss->policy_rwlock);
2374 policydb = &state->ss->policydb;
2375 sidtab = &state->ss->sidtab;
2377 c = policydb->ocontexts[OCON_IBENDPORT];
2379 if (c->u.ibendport.port == port_num &&
2380 !strncmp(c->u.ibendport.dev_name,
2382 IB_DEVICE_NAME_MAX))
2390 rc = sidtab_context_to_sid(sidtab,
2396 *out_sid = c->sid[0];
2398 *out_sid = SECINITSID_UNLABELED;
2401 read_unlock(&state->ss->policy_rwlock);
2406 * security_netif_sid - Obtain the SID for a network interface.
2407 * @name: interface name
2408 * @if_sid: interface SID
2410 int security_netif_sid(struct selinux_state *state,
2411 char *name, u32 *if_sid)
2413 struct policydb *policydb;
2414 struct sidtab *sidtab;
2418 read_lock(&state->ss->policy_rwlock);
2420 policydb = &state->ss->policydb;
2421 sidtab = &state->ss->sidtab;
2423 c = policydb->ocontexts[OCON_NETIF];
2425 if (strcmp(name, c->u.name) == 0)
2431 if (!c->sid[0] || !c->sid[1]) {
2432 rc = sidtab_context_to_sid(sidtab,
2437 rc = sidtab_context_to_sid(sidtab,
2443 *if_sid = c->sid[0];
2445 *if_sid = SECINITSID_NETIF;
2448 read_unlock(&state->ss->policy_rwlock);
2452 static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask)
2456 for (i = 0; i < 4; i++)
2457 if (addr[i] != (input[i] & mask[i])) {
2466 * security_node_sid - Obtain the SID for a node (host).
2467 * @domain: communication domain aka address family
2469 * @addrlen: address length in bytes
2470 * @out_sid: security identifier
2472 int security_node_sid(struct selinux_state *state,
2478 struct policydb *policydb;
2479 struct sidtab *sidtab;
2483 read_lock(&state->ss->policy_rwlock);
2485 policydb = &state->ss->policydb;
2486 sidtab = &state->ss->sidtab;
2493 if (addrlen != sizeof(u32))
2496 addr = *((u32 *)addrp);
2498 c = policydb->ocontexts[OCON_NODE];
2500 if (c->u.node.addr == (addr & c->u.node.mask))
2509 if (addrlen != sizeof(u64) * 2)
2511 c = policydb->ocontexts[OCON_NODE6];
2513 if (match_ipv6_addrmask(addrp, c->u.node6.addr,
2522 *out_sid = SECINITSID_NODE;
2528 rc = sidtab_context_to_sid(sidtab,
2534 *out_sid = c->sid[0];
2536 *out_sid = SECINITSID_NODE;
2541 read_unlock(&state->ss->policy_rwlock);
2548 * security_get_user_sids - Obtain reachable SIDs for a user.
2549 * @fromsid: starting SID
2550 * @username: username
2551 * @sids: array of reachable SIDs for user
2552 * @nel: number of elements in @sids
2554 * Generate the set of SIDs for legal security contexts
2555 * for a given user that can be reached by @fromsid.
2556 * Set *@sids to point to a dynamically allocated
2557 * array containing the set of SIDs. Set *@nel to the
2558 * number of elements in the array.
2561 int security_get_user_sids(struct selinux_state *state,
2567 struct policydb *policydb;
2568 struct sidtab *sidtab;
2569 struct context *fromcon, usercon;
2570 u32 *mysids = NULL, *mysids2, sid;
2571 u32 mynel = 0, maxnel = SIDS_NEL;
2572 struct user_datum *user;
2573 struct role_datum *role;
2574 struct ebitmap_node *rnode, *tnode;
2580 if (!state->initialized)
2583 read_lock(&state->ss->policy_rwlock);
2585 policydb = &state->ss->policydb;
2586 sidtab = &state->ss->sidtab;
2588 context_init(&usercon);
2591 fromcon = sidtab_search(sidtab, fromsid);
2596 user = hashtab_search(policydb->p_users.table, username);
2600 usercon.user = user->value;
2603 mysids = kcalloc(maxnel, sizeof(*mysids), GFP_ATOMIC);
2607 ebitmap_for_each_positive_bit(&user->roles, rnode, i) {
2608 role = policydb->role_val_to_struct[i];
2609 usercon.role = i + 1;
2610 ebitmap_for_each_positive_bit(&role->types, tnode, j) {
2611 usercon.type = j + 1;
2613 if (mls_setup_user_range(policydb, fromcon, user,
2617 rc = sidtab_context_to_sid(sidtab, &usercon, &sid);
2620 if (mynel < maxnel) {
2621 mysids[mynel++] = sid;
2625 mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
2628 memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
2631 mysids[mynel++] = sid;
2637 read_unlock(&state->ss->policy_rwlock);
2644 mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);
2649 for (i = 0, j = 0; i < mynel; i++) {
2650 struct av_decision dummy_avd;
2651 rc = avc_has_perm_noaudit(state,
2653 SECCLASS_PROCESS, /* kernel value */
2654 PROCESS__TRANSITION, AVC_STRICT,
2657 mysids2[j++] = mysids[i];
2669 * __security_genfs_sid - Helper to obtain a SID for a file in a filesystem
2670 * @fstype: filesystem type
2671 * @path: path from root of mount
2672 * @sclass: file security class
2673 * @sid: SID for path
2675 * Obtain a SID to use for a file in a filesystem that
2676 * cannot support xattr or use a fixed labeling behavior like
2677 * transition SIDs or task SIDs.
2679 * The caller must acquire the policy_rwlock before calling this function.
2681 static inline int __security_genfs_sid(struct selinux_state *state,
2687 struct policydb *policydb = &state->ss->policydb;
2688 struct sidtab *sidtab = &state->ss->sidtab;
2691 struct genfs *genfs;
2695 while (path[0] == '/' && path[1] == '/')
2698 sclass = unmap_class(&state->ss->map, orig_sclass);
2699 *sid = SECINITSID_UNLABELED;
2701 for (genfs = policydb->genfs; genfs; genfs = genfs->next) {
2702 cmp = strcmp(fstype, genfs->fstype);
2711 for (c = genfs->head; c; c = c->next) {
2712 len = strlen(c->u.name);
2713 if ((!c->v.sclass || sclass == c->v.sclass) &&
2714 (strncmp(c->u.name, path, len) == 0))
2723 rc = sidtab_context_to_sid(sidtab, &c->context[0], &c->sid[0]);
2735 * security_genfs_sid - Obtain a SID for a file in a filesystem
2736 * @fstype: filesystem type
2737 * @path: path from root of mount
2738 * @sclass: file security class
2739 * @sid: SID for path
2741 * Acquire policy_rwlock before calling __security_genfs_sid() and release
2744 int security_genfs_sid(struct selinux_state *state,
2752 read_lock(&state->ss->policy_rwlock);
2753 retval = __security_genfs_sid(state, fstype, path, orig_sclass, sid);
2754 read_unlock(&state->ss->policy_rwlock);
2759 * security_fs_use - Determine how to handle labeling for a filesystem.
2760 * @sb: superblock in question
2762 int security_fs_use(struct selinux_state *state, struct super_block *sb)
2764 struct policydb *policydb;
2765 struct sidtab *sidtab;
2768 struct superblock_security_struct *sbsec = sb->s_security;
2769 const char *fstype = sb->s_type->name;
2771 read_lock(&state->ss->policy_rwlock);
2773 policydb = &state->ss->policydb;
2774 sidtab = &state->ss->sidtab;
2776 c = policydb->ocontexts[OCON_FSUSE];
2778 if (strcmp(fstype, c->u.name) == 0)
2784 sbsec->behavior = c->v.behavior;
2786 rc = sidtab_context_to_sid(sidtab, &c->context[0],
2791 sbsec->sid = c->sid[0];
2793 rc = __security_genfs_sid(state, fstype, "/", SECCLASS_DIR,
2796 sbsec->behavior = SECURITY_FS_USE_NONE;
2799 sbsec->behavior = SECURITY_FS_USE_GENFS;
2804 read_unlock(&state->ss->policy_rwlock);
2808 int security_get_bools(struct selinux_state *state,
2809 int *len, char ***names, int **values)
2811 struct policydb *policydb;
2814 if (!state->initialized) {
2821 read_lock(&state->ss->policy_rwlock);
2823 policydb = &state->ss->policydb;
2829 *len = policydb->p_bools.nprim;
2834 *names = kcalloc(*len, sizeof(char *), GFP_ATOMIC);
2839 *values = kcalloc(*len, sizeof(int), GFP_ATOMIC);
2843 for (i = 0; i < *len; i++) {
2844 (*values)[i] = policydb->bool_val_to_struct[i]->state;
2847 (*names)[i] = kstrdup(sym_name(policydb, SYM_BOOLS, i),
2854 read_unlock(&state->ss->policy_rwlock);
2858 for (i = 0; i < *len; i++)
2870 int security_set_bools(struct selinux_state *state, int len, int *values)
2872 struct policydb *policydb;
2874 int lenp, seqno = 0;
2875 struct cond_node *cur;
2877 write_lock_irq(&state->ss->policy_rwlock);
2879 policydb = &state->ss->policydb;
2882 lenp = policydb->p_bools.nprim;
2886 for (i = 0; i < len; i++) {
2887 if (!!values[i] != policydb->bool_val_to_struct[i]->state) {
2888 audit_log(audit_context(), GFP_ATOMIC,
2889 AUDIT_MAC_CONFIG_CHANGE,
2890 "bool=%s val=%d old_val=%d auid=%u ses=%u",
2891 sym_name(policydb, SYM_BOOLS, i),
2893 policydb->bool_val_to_struct[i]->state,
2894 from_kuid(&init_user_ns, audit_get_loginuid(current)),
2895 audit_get_sessionid(current));
2898 policydb->bool_val_to_struct[i]->state = 1;
2900 policydb->bool_val_to_struct[i]->state = 0;
2903 for (cur = policydb->cond_list; cur; cur = cur->next) {
2904 rc = evaluate_cond_node(policydb, cur);
2909 seqno = ++state->ss->latest_granting;
2912 write_unlock_irq(&state->ss->policy_rwlock);
2914 avc_ss_reset(state->avc, seqno);
2915 selnl_notify_policyload(seqno);
2916 selinux_status_update_policyload(state, seqno);
2917 selinux_xfrm_notify_policyload();
2922 int security_get_bool_value(struct selinux_state *state,
2925 struct policydb *policydb;
2929 read_lock(&state->ss->policy_rwlock);
2931 policydb = &state->ss->policydb;
2934 len = policydb->p_bools.nprim;
2938 rc = policydb->bool_val_to_struct[index]->state;
2940 read_unlock(&state->ss->policy_rwlock);
2944 static int security_preserve_bools(struct selinux_state *state,
2945 struct policydb *policydb)
2947 int rc, nbools = 0, *bvalues = NULL, i;
2948 char **bnames = NULL;
2949 struct cond_bool_datum *booldatum;
2950 struct cond_node *cur;
2952 rc = security_get_bools(state, &nbools, &bnames, &bvalues);
2955 for (i = 0; i < nbools; i++) {
2956 booldatum = hashtab_search(policydb->p_bools.table, bnames[i]);
2958 booldatum->state = bvalues[i];
2960 for (cur = policydb->cond_list; cur; cur = cur->next) {
2961 rc = evaluate_cond_node(policydb, cur);
2968 for (i = 0; i < nbools; i++)
2977 * security_sid_mls_copy() - computes a new sid based on the given
2978 * sid and the mls portion of mls_sid.
2980 int security_sid_mls_copy(struct selinux_state *state,
2981 u32 sid, u32 mls_sid, u32 *new_sid)
2983 struct policydb *policydb = &state->ss->policydb;
2984 struct sidtab *sidtab = &state->ss->sidtab;
2985 struct context *context1;
2986 struct context *context2;
2987 struct context newcon;
2993 if (!state->initialized || !policydb->mls_enabled) {
2998 context_init(&newcon);
3000 read_lock(&state->ss->policy_rwlock);
3003 context1 = sidtab_search(sidtab, sid);
3005 pr_err("SELinux: %s: unrecognized SID %d\n",
3011 context2 = sidtab_search(sidtab, mls_sid);
3013 pr_err("SELinux: %s: unrecognized SID %d\n",
3018 newcon.user = context1->user;
3019 newcon.role = context1->role;
3020 newcon.type = context1->type;
3021 rc = mls_context_cpy(&newcon, context2);
3025 /* Check the validity of the new context. */
3026 if (!policydb_context_isvalid(policydb, &newcon)) {
3027 rc = convert_context_handle_invalid_context(state, &newcon);
3029 if (!context_struct_to_string(policydb, &newcon, &s,
3031 audit_log(audit_context(),
3032 GFP_ATOMIC, AUDIT_SELINUX_ERR,
3033 "op=security_sid_mls_copy "
3034 "invalid_context=%s", s);
3041 rc = sidtab_context_to_sid(sidtab, &newcon, new_sid);
3043 read_unlock(&state->ss->policy_rwlock);
3044 context_destroy(&newcon);
3050 * security_net_peersid_resolve - Compare and resolve two network peer SIDs
3051 * @nlbl_sid: NetLabel SID
3052 * @nlbl_type: NetLabel labeling protocol type
3053 * @xfrm_sid: XFRM SID
3056 * Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be
3057 * resolved into a single SID it is returned via @peer_sid and the function
3058 * returns zero. Otherwise @peer_sid is set to SECSID_NULL and the function
3059 * returns a negative value. A table summarizing the behavior is below:
3061 * | function return | @sid
3062 * ------------------------------+-----------------+-----------------
3063 * no peer labels | 0 | SECSID_NULL
3064 * single peer label | 0 | <peer_label>
3065 * multiple, consistent labels | 0 | <peer_label>
3066 * multiple, inconsistent labels | -<errno> | SECSID_NULL
3069 int security_net_peersid_resolve(struct selinux_state *state,
3070 u32 nlbl_sid, u32 nlbl_type,
3074 struct policydb *policydb = &state->ss->policydb;
3075 struct sidtab *sidtab = &state->ss->sidtab;
3077 struct context *nlbl_ctx;
3078 struct context *xfrm_ctx;
3080 *peer_sid = SECSID_NULL;
3082 /* handle the common (which also happens to be the set of easy) cases
3083 * right away, these two if statements catch everything involving a
3084 * single or absent peer SID/label */
3085 if (xfrm_sid == SECSID_NULL) {
3086 *peer_sid = nlbl_sid;
3089 /* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a "fallback" label
3090 * and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label
3092 if (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) {
3093 *peer_sid = xfrm_sid;
3098 * We don't need to check initialized here since the only way both
3099 * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the
3100 * security server was initialized and state->initialized was true.
3102 if (!policydb->mls_enabled)
3105 read_lock(&state->ss->policy_rwlock);
3108 nlbl_ctx = sidtab_search(sidtab, nlbl_sid);
3110 pr_err("SELinux: %s: unrecognized SID %d\n",
3111 __func__, nlbl_sid);
3115 xfrm_ctx = sidtab_search(sidtab, xfrm_sid);
3117 pr_err("SELinux: %s: unrecognized SID %d\n",
3118 __func__, xfrm_sid);
3121 rc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES);
3125 /* at present NetLabel SIDs/labels really only carry MLS
3126 * information so if the MLS portion of the NetLabel SID
3127 * matches the MLS portion of the labeled XFRM SID/label
3128 * then pass along the XFRM SID as it is the most
3130 *peer_sid = xfrm_sid;
3132 read_unlock(&state->ss->policy_rwlock);
3136 static int get_classes_callback(void *k, void *d, void *args)
3138 struct class_datum *datum = d;
3139 char *name = k, **classes = args;
3140 int value = datum->value - 1;
3142 classes[value] = kstrdup(name, GFP_ATOMIC);
3143 if (!classes[value])
3149 int security_get_classes(struct selinux_state *state,
3150 char ***classes, int *nclasses)
3152 struct policydb *policydb = &state->ss->policydb;
3155 if (!state->initialized) {
3161 read_lock(&state->ss->policy_rwlock);
3164 *nclasses = policydb->p_classes.nprim;
3165 *classes = kcalloc(*nclasses, sizeof(**classes), GFP_ATOMIC);
3169 rc = hashtab_map(policydb->p_classes.table, get_classes_callback,
3173 for (i = 0; i < *nclasses; i++)
3174 kfree((*classes)[i]);
3179 read_unlock(&state->ss->policy_rwlock);
3183 static int get_permissions_callback(void *k, void *d, void *args)
3185 struct perm_datum *datum = d;
3186 char *name = k, **perms = args;
3187 int value = datum->value - 1;
3189 perms[value] = kstrdup(name, GFP_ATOMIC);
3196 int security_get_permissions(struct selinux_state *state,
3197 char *class, char ***perms, int *nperms)
3199 struct policydb *policydb = &state->ss->policydb;
3201 struct class_datum *match;
3203 read_lock(&state->ss->policy_rwlock);
3206 match = hashtab_search(policydb->p_classes.table, class);
3208 pr_err("SELinux: %s: unrecognized class %s\n",
3214 *nperms = match->permissions.nprim;
3215 *perms = kcalloc(*nperms, sizeof(**perms), GFP_ATOMIC);
3219 if (match->comdatum) {
3220 rc = hashtab_map(match->comdatum->permissions.table,
3221 get_permissions_callback, *perms);
3226 rc = hashtab_map(match->permissions.table, get_permissions_callback,
3232 read_unlock(&state->ss->policy_rwlock);
3236 read_unlock(&state->ss->policy_rwlock);
3237 for (i = 0; i < *nperms; i++)
3243 int security_get_reject_unknown(struct selinux_state *state)
3245 return state->ss->policydb.reject_unknown;
3248 int security_get_allow_unknown(struct selinux_state *state)
3250 return state->ss->policydb.allow_unknown;
3254 * security_policycap_supported - Check for a specific policy capability
3255 * @req_cap: capability
3258 * This function queries the currently loaded policy to see if it supports the
3259 * capability specified by @req_cap. Returns true (1) if the capability is
3260 * supported, false (0) if it isn't supported.
3263 int security_policycap_supported(struct selinux_state *state,
3264 unsigned int req_cap)
3266 struct policydb *policydb = &state->ss->policydb;
3269 read_lock(&state->ss->policy_rwlock);
3270 rc = ebitmap_get_bit(&policydb->policycaps, req_cap);
3271 read_unlock(&state->ss->policy_rwlock);
3276 struct selinux_audit_rule {
3278 struct context au_ctxt;
3281 void selinux_audit_rule_free(void *vrule)
3283 struct selinux_audit_rule *rule = vrule;
3286 context_destroy(&rule->au_ctxt);
3291 int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule)
3293 struct selinux_state *state = &selinux_state;
3294 struct policydb *policydb = &state->ss->policydb;
3295 struct selinux_audit_rule *tmprule;
3296 struct role_datum *roledatum;
3297 struct type_datum *typedatum;
3298 struct user_datum *userdatum;
3299 struct selinux_audit_rule **rule = (struct selinux_audit_rule **)vrule;
3304 if (!state->initialized)
3308 case AUDIT_SUBJ_USER:
3309 case AUDIT_SUBJ_ROLE:
3310 case AUDIT_SUBJ_TYPE:
3311 case AUDIT_OBJ_USER:
3312 case AUDIT_OBJ_ROLE:
3313 case AUDIT_OBJ_TYPE:
3314 /* only 'equals' and 'not equals' fit user, role, and type */
3315 if (op != Audit_equal && op != Audit_not_equal)
3318 case AUDIT_SUBJ_SEN:
3319 case AUDIT_SUBJ_CLR:
3320 case AUDIT_OBJ_LEV_LOW:
3321 case AUDIT_OBJ_LEV_HIGH:
3322 /* we do not allow a range, indicated by the presence of '-' */
3323 if (strchr(rulestr, '-'))
3327 /* only the above fields are valid */
3331 tmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL);
3335 context_init(&tmprule->au_ctxt);
3337 read_lock(&state->ss->policy_rwlock);
3339 tmprule->au_seqno = state->ss->latest_granting;
3342 case AUDIT_SUBJ_USER:
3343 case AUDIT_OBJ_USER:
3345 userdatum = hashtab_search(policydb->p_users.table, rulestr);
3348 tmprule->au_ctxt.user = userdatum->value;
3350 case AUDIT_SUBJ_ROLE:
3351 case AUDIT_OBJ_ROLE:
3353 roledatum = hashtab_search(policydb->p_roles.table, rulestr);
3356 tmprule->au_ctxt.role = roledatum->value;
3358 case AUDIT_SUBJ_TYPE:
3359 case AUDIT_OBJ_TYPE:
3361 typedatum = hashtab_search(policydb->p_types.table, rulestr);
3364 tmprule->au_ctxt.type = typedatum->value;
3366 case AUDIT_SUBJ_SEN:
3367 case AUDIT_SUBJ_CLR:
3368 case AUDIT_OBJ_LEV_LOW:
3369 case AUDIT_OBJ_LEV_HIGH:
3370 rc = mls_from_string(policydb, rulestr, &tmprule->au_ctxt,
3378 read_unlock(&state->ss->policy_rwlock);
3381 selinux_audit_rule_free(tmprule);
3390 /* Check to see if the rule contains any selinux fields */
3391 int selinux_audit_rule_known(struct audit_krule *rule)
3395 for (i = 0; i < rule->field_count; i++) {
3396 struct audit_field *f = &rule->fields[i];
3398 case AUDIT_SUBJ_USER:
3399 case AUDIT_SUBJ_ROLE:
3400 case AUDIT_SUBJ_TYPE:
3401 case AUDIT_SUBJ_SEN:
3402 case AUDIT_SUBJ_CLR:
3403 case AUDIT_OBJ_USER:
3404 case AUDIT_OBJ_ROLE:
3405 case AUDIT_OBJ_TYPE:
3406 case AUDIT_OBJ_LEV_LOW:
3407 case AUDIT_OBJ_LEV_HIGH:
3415 int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule,
3416 struct audit_context *actx)
3418 struct selinux_state *state = &selinux_state;
3419 struct context *ctxt;
3420 struct mls_level *level;
3421 struct selinux_audit_rule *rule = vrule;
3424 if (unlikely(!rule)) {
3425 WARN_ONCE(1, "selinux_audit_rule_match: missing rule\n");
3429 read_lock(&state->ss->policy_rwlock);
3431 if (rule->au_seqno < state->ss->latest_granting) {
3436 ctxt = sidtab_search(&state->ss->sidtab, sid);
3437 if (unlikely(!ctxt)) {
3438 WARN_ONCE(1, "selinux_audit_rule_match: unrecognized SID %d\n",
3444 /* a field/op pair that is not caught here will simply fall through
3447 case AUDIT_SUBJ_USER:
3448 case AUDIT_OBJ_USER:
3451 match = (ctxt->user == rule->au_ctxt.user);
3453 case Audit_not_equal:
3454 match = (ctxt->user != rule->au_ctxt.user);
3458 case AUDIT_SUBJ_ROLE:
3459 case AUDIT_OBJ_ROLE:
3462 match = (ctxt->role == rule->au_ctxt.role);
3464 case Audit_not_equal:
3465 match = (ctxt->role != rule->au_ctxt.role);
3469 case AUDIT_SUBJ_TYPE:
3470 case AUDIT_OBJ_TYPE:
3473 match = (ctxt->type == rule->au_ctxt.type);
3475 case Audit_not_equal:
3476 match = (ctxt->type != rule->au_ctxt.type);
3480 case AUDIT_SUBJ_SEN:
3481 case AUDIT_SUBJ_CLR:
3482 case AUDIT_OBJ_LEV_LOW:
3483 case AUDIT_OBJ_LEV_HIGH:
3484 level = ((field == AUDIT_SUBJ_SEN ||
3485 field == AUDIT_OBJ_LEV_LOW) ?
3486 &ctxt->range.level[0] : &ctxt->range.level[1]);
3489 match = mls_level_eq(&rule->au_ctxt.range.level[0],
3492 case Audit_not_equal:
3493 match = !mls_level_eq(&rule->au_ctxt.range.level[0],
3497 match = (mls_level_dom(&rule->au_ctxt.range.level[0],
3499 !mls_level_eq(&rule->au_ctxt.range.level[0],
3503 match = mls_level_dom(&rule->au_ctxt.range.level[0],
3507 match = (mls_level_dom(level,
3508 &rule->au_ctxt.range.level[0]) &&
3509 !mls_level_eq(level,
3510 &rule->au_ctxt.range.level[0]));
3513 match = mls_level_dom(level,
3514 &rule->au_ctxt.range.level[0]);
3520 read_unlock(&state->ss->policy_rwlock);
3524 static int (*aurule_callback)(void) = audit_update_lsm_rules;
3526 static int aurule_avc_callback(u32 event)
3530 if (event == AVC_CALLBACK_RESET && aurule_callback)
3531 err = aurule_callback();
3535 static int __init aurule_init(void)
3539 err = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET);
3541 panic("avc_add_callback() failed, error %d\n", err);
3545 __initcall(aurule_init);
3547 #ifdef CONFIG_NETLABEL
3549 * security_netlbl_cache_add - Add an entry to the NetLabel cache
3550 * @secattr: the NetLabel packet security attributes
3551 * @sid: the SELinux SID
3554 * Attempt to cache the context in @ctx, which was derived from the packet in
3555 * @skb, in the NetLabel subsystem cache. This function assumes @secattr has
3556 * already been initialized.
3559 static void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr,
3564 sid_cache = kmalloc(sizeof(*sid_cache), GFP_ATOMIC);
3565 if (sid_cache == NULL)
3567 secattr->cache = netlbl_secattr_cache_alloc(GFP_ATOMIC);
3568 if (secattr->cache == NULL) {
3574 secattr->cache->free = kfree;
3575 secattr->cache->data = sid_cache;
3576 secattr->flags |= NETLBL_SECATTR_CACHE;
3580 * security_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID
3581 * @secattr: the NetLabel packet security attributes
3582 * @sid: the SELinux SID
3585 * Convert the given NetLabel security attributes in @secattr into a
3586 * SELinux SID. If the @secattr field does not contain a full SELinux
3587 * SID/context then use SECINITSID_NETMSG as the foundation. If possible the
3588 * 'cache' field of @secattr is set and the CACHE flag is set; this is to
3589 * allow the @secattr to be used by NetLabel to cache the secattr to SID
3590 * conversion for future lookups. Returns zero on success, negative values on
3594 int security_netlbl_secattr_to_sid(struct selinux_state *state,
3595 struct netlbl_lsm_secattr *secattr,
3598 struct policydb *policydb = &state->ss->policydb;
3599 struct sidtab *sidtab = &state->ss->sidtab;
3601 struct context *ctx;
3602 struct context ctx_new;
3604 if (!state->initialized) {
3609 read_lock(&state->ss->policy_rwlock);
3611 if (secattr->flags & NETLBL_SECATTR_CACHE)
3612 *sid = *(u32 *)secattr->cache->data;
3613 else if (secattr->flags & NETLBL_SECATTR_SECID)
3614 *sid = secattr->attr.secid;
3615 else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) {
3617 ctx = sidtab_search(sidtab, SECINITSID_NETMSG);
3621 context_init(&ctx_new);
3622 ctx_new.user = ctx->user;
3623 ctx_new.role = ctx->role;
3624 ctx_new.type = ctx->type;
3625 mls_import_netlbl_lvl(policydb, &ctx_new, secattr);
3626 if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
3627 rc = mls_import_netlbl_cat(policydb, &ctx_new, secattr);
3632 if (!mls_context_isvalid(policydb, &ctx_new))
3635 rc = sidtab_context_to_sid(sidtab, &ctx_new, sid);
3639 security_netlbl_cache_add(secattr, *sid);
3641 ebitmap_destroy(&ctx_new.range.level[0].cat);
3645 read_unlock(&state->ss->policy_rwlock);
3648 ebitmap_destroy(&ctx_new.range.level[0].cat);
3650 read_unlock(&state->ss->policy_rwlock);
3655 * security_netlbl_sid_to_secattr - Convert a SELinux SID to a NetLabel secattr
3656 * @sid: the SELinux SID
3657 * @secattr: the NetLabel packet security attributes
3660 * Convert the given SELinux SID in @sid into a NetLabel security attribute.
3661 * Returns zero on success, negative values on failure.
3664 int security_netlbl_sid_to_secattr(struct selinux_state *state,
3665 u32 sid, struct netlbl_lsm_secattr *secattr)
3667 struct policydb *policydb = &state->ss->policydb;
3669 struct context *ctx;
3671 if (!state->initialized)
3674 read_lock(&state->ss->policy_rwlock);
3677 ctx = sidtab_search(&state->ss->sidtab, sid);
3682 secattr->domain = kstrdup(sym_name(policydb, SYM_TYPES, ctx->type - 1),
3684 if (secattr->domain == NULL)
3687 secattr->attr.secid = sid;
3688 secattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID;
3689 mls_export_netlbl_lvl(policydb, ctx, secattr);
3690 rc = mls_export_netlbl_cat(policydb, ctx, secattr);
3692 read_unlock(&state->ss->policy_rwlock);
3695 #endif /* CONFIG_NETLABEL */
3698 * security_read_policy - read the policy.
3699 * @data: binary policy data
3700 * @len: length of data in bytes
3703 int security_read_policy(struct selinux_state *state,
3704 void **data, size_t *len)
3706 struct policydb *policydb = &state->ss->policydb;
3708 struct policy_file fp;
3710 if (!state->initialized)
3713 *len = security_policydb_len(state);
3715 *data = vmalloc_user(*len);
3722 read_lock(&state->ss->policy_rwlock);
3723 rc = policydb_write(policydb, &fp);
3724 read_unlock(&state->ss->policy_rwlock);
3729 *len = (unsigned long)fp.data - (unsigned long)*data;