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 <net/netlabel.h>
60 #include "conditional.h"
68 /* Policy capability names */
69 const char *selinux_policycap_names[__POLICYDB_CAPABILITY_MAX] = {
70 "network_peer_controls",
72 "extended_socket_class",
73 "always_check_network",
75 "nnp_nosuid_transition",
76 "genfs_seclabel_symlinks"
79 static struct selinux_ss selinux_ss;
81 void selinux_ss_init(struct selinux_ss **ss)
83 rwlock_init(&selinux_ss.policy_rwlock);
87 /* Forward declaration. */
88 static int context_struct_to_string(struct policydb *policydb,
89 struct context *context,
93 static int sidtab_entry_to_string(struct policydb *policydb,
94 struct sidtab *sidtab,
95 struct sidtab_entry *entry,
99 static void context_struct_compute_av(struct policydb *policydb,
100 struct context *scontext,
101 struct context *tcontext,
103 struct av_decision *avd,
104 struct extended_perms *xperms);
106 static int selinux_set_mapping(struct policydb *pol,
107 struct security_class_mapping *map,
108 struct selinux_map *out_map)
112 bool print_unknown_handle = false;
114 /* Find number of classes in the input mapping */
121 /* Allocate space for the class records, plus one for class zero */
122 out_map->mapping = kcalloc(++i, sizeof(*out_map->mapping), GFP_ATOMIC);
123 if (!out_map->mapping)
126 /* Store the raw class and permission values */
128 while (map[j].name) {
129 struct security_class_mapping *p_in = map + (j++);
130 struct selinux_mapping *p_out = out_map->mapping + j;
132 /* An empty class string skips ahead */
133 if (!strcmp(p_in->name, "")) {
134 p_out->num_perms = 0;
138 p_out->value = string_to_security_class(pol, p_in->name);
140 pr_info("SELinux: Class %s not defined in policy.\n",
142 if (pol->reject_unknown)
144 p_out->num_perms = 0;
145 print_unknown_handle = true;
150 while (p_in->perms[k]) {
151 /* An empty permission string skips ahead */
152 if (!*p_in->perms[k]) {
156 p_out->perms[k] = string_to_av_perm(pol, p_out->value,
158 if (!p_out->perms[k]) {
159 pr_info("SELinux: Permission %s in class %s not defined in policy.\n",
160 p_in->perms[k], p_in->name);
161 if (pol->reject_unknown)
163 print_unknown_handle = true;
168 p_out->num_perms = k;
171 if (print_unknown_handle)
172 pr_info("SELinux: the above unknown classes and permissions will be %s\n",
173 pol->allow_unknown ? "allowed" : "denied");
178 kfree(out_map->mapping);
179 out_map->mapping = NULL;
184 * Get real, policy values from mapped values
187 static u16 unmap_class(struct selinux_map *map, u16 tclass)
189 if (tclass < map->size)
190 return map->mapping[tclass].value;
196 * Get kernel value for class from its policy value
198 static u16 map_class(struct selinux_map *map, u16 pol_value)
202 for (i = 1; i < map->size; i++) {
203 if (map->mapping[i].value == pol_value)
207 return SECCLASS_NULL;
210 static void map_decision(struct selinux_map *map,
211 u16 tclass, struct av_decision *avd,
214 if (tclass < map->size) {
215 struct selinux_mapping *mapping = &map->mapping[tclass];
216 unsigned int i, n = mapping->num_perms;
219 for (i = 0, result = 0; i < n; i++) {
220 if (avd->allowed & mapping->perms[i])
222 if (allow_unknown && !mapping->perms[i])
225 avd->allowed = result;
227 for (i = 0, result = 0; i < n; i++)
228 if (avd->auditallow & mapping->perms[i])
230 avd->auditallow = result;
232 for (i = 0, result = 0; i < n; i++) {
233 if (avd->auditdeny & mapping->perms[i])
235 if (!allow_unknown && !mapping->perms[i])
239 * In case the kernel has a bug and requests a permission
240 * between num_perms and the maximum permission number, we
241 * should audit that denial
243 for (; i < (sizeof(u32)*8); i++)
245 avd->auditdeny = result;
249 int security_mls_enabled(struct selinux_state *state)
251 struct policydb *p = &state->ss->policydb;
253 return p->mls_enabled;
257 * Return the boolean value of a constraint expression
258 * when it is applied to the specified source and target
261 * xcontext is a special beast... It is used by the validatetrans rules
262 * only. For these rules, scontext is the context before the transition,
263 * tcontext is the context after the transition, and xcontext is the context
264 * of the process performing the transition. All other callers of
265 * constraint_expr_eval should pass in NULL for xcontext.
267 static int constraint_expr_eval(struct policydb *policydb,
268 struct context *scontext,
269 struct context *tcontext,
270 struct context *xcontext,
271 struct constraint_expr *cexpr)
275 struct role_datum *r1, *r2;
276 struct mls_level *l1, *l2;
277 struct constraint_expr *e;
278 int s[CEXPR_MAXDEPTH];
281 for (e = cexpr; e; e = e->next) {
282 switch (e->expr_type) {
298 if (sp == (CEXPR_MAXDEPTH - 1))
302 val1 = scontext->user;
303 val2 = tcontext->user;
306 val1 = scontext->type;
307 val2 = tcontext->type;
310 val1 = scontext->role;
311 val2 = tcontext->role;
312 r1 = policydb->role_val_to_struct[val1 - 1];
313 r2 = policydb->role_val_to_struct[val2 - 1];
316 s[++sp] = ebitmap_get_bit(&r1->dominates,
320 s[++sp] = ebitmap_get_bit(&r2->dominates,
324 s[++sp] = (!ebitmap_get_bit(&r1->dominates,
326 !ebitmap_get_bit(&r2->dominates,
334 l1 = &(scontext->range.level[0]);
335 l2 = &(tcontext->range.level[0]);
338 l1 = &(scontext->range.level[0]);
339 l2 = &(tcontext->range.level[1]);
342 l1 = &(scontext->range.level[1]);
343 l2 = &(tcontext->range.level[0]);
346 l1 = &(scontext->range.level[1]);
347 l2 = &(tcontext->range.level[1]);
350 l1 = &(scontext->range.level[0]);
351 l2 = &(scontext->range.level[1]);
354 l1 = &(tcontext->range.level[0]);
355 l2 = &(tcontext->range.level[1]);
360 s[++sp] = mls_level_eq(l1, l2);
363 s[++sp] = !mls_level_eq(l1, l2);
366 s[++sp] = mls_level_dom(l1, l2);
369 s[++sp] = mls_level_dom(l2, l1);
372 s[++sp] = mls_level_incomp(l2, l1);
386 s[++sp] = (val1 == val2);
389 s[++sp] = (val1 != val2);
397 if (sp == (CEXPR_MAXDEPTH-1))
400 if (e->attr & CEXPR_TARGET)
402 else if (e->attr & CEXPR_XTARGET) {
409 if (e->attr & CEXPR_USER)
411 else if (e->attr & CEXPR_ROLE)
413 else if (e->attr & CEXPR_TYPE)
422 s[++sp] = ebitmap_get_bit(&e->names, val1 - 1);
425 s[++sp] = !ebitmap_get_bit(&e->names, val1 - 1);
443 * security_dump_masked_av - dumps masked permissions during
444 * security_compute_av due to RBAC, MLS/Constraint and Type bounds.
446 static int dump_masked_av_helper(void *k, void *d, void *args)
448 struct perm_datum *pdatum = d;
449 char **permission_names = args;
451 BUG_ON(pdatum->value < 1 || pdatum->value > 32);
453 permission_names[pdatum->value - 1] = (char *)k;
458 static void security_dump_masked_av(struct policydb *policydb,
459 struct context *scontext,
460 struct context *tcontext,
465 struct common_datum *common_dat;
466 struct class_datum *tclass_dat;
467 struct audit_buffer *ab;
469 char *scontext_name = NULL;
470 char *tcontext_name = NULL;
471 char *permission_names[32];
474 bool need_comma = false;
479 tclass_name = sym_name(policydb, SYM_CLASSES, tclass - 1);
480 tclass_dat = policydb->class_val_to_struct[tclass - 1];
481 common_dat = tclass_dat->comdatum;
483 /* init permission_names */
485 hashtab_map(common_dat->permissions.table,
486 dump_masked_av_helper, permission_names) < 0)
489 if (hashtab_map(tclass_dat->permissions.table,
490 dump_masked_av_helper, permission_names) < 0)
493 /* get scontext/tcontext in text form */
494 if (context_struct_to_string(policydb, scontext,
495 &scontext_name, &length) < 0)
498 if (context_struct_to_string(policydb, tcontext,
499 &tcontext_name, &length) < 0)
502 /* audit a message */
503 ab = audit_log_start(audit_context(),
504 GFP_ATOMIC, AUDIT_SELINUX_ERR);
508 audit_log_format(ab, "op=security_compute_av reason=%s "
509 "scontext=%s tcontext=%s tclass=%s perms=",
510 reason, scontext_name, tcontext_name, tclass_name);
512 for (index = 0; index < 32; index++) {
513 u32 mask = (1 << index);
515 if ((mask & permissions) == 0)
518 audit_log_format(ab, "%s%s",
519 need_comma ? "," : "",
520 permission_names[index]
521 ? permission_names[index] : "????");
526 /* release scontext/tcontext */
527 kfree(tcontext_name);
528 kfree(scontext_name);
534 * security_boundary_permission - drops violated permissions
535 * on boundary constraint.
537 static void type_attribute_bounds_av(struct policydb *policydb,
538 struct context *scontext,
539 struct context *tcontext,
541 struct av_decision *avd)
543 struct context lo_scontext;
544 struct context lo_tcontext, *tcontextp = tcontext;
545 struct av_decision lo_avd;
546 struct type_datum *source;
547 struct type_datum *target;
550 source = policydb->type_val_to_struct[scontext->type - 1];
556 target = policydb->type_val_to_struct[tcontext->type - 1];
559 memset(&lo_avd, 0, sizeof(lo_avd));
561 memcpy(&lo_scontext, scontext, sizeof(lo_scontext));
562 lo_scontext.type = source->bounds;
564 if (target->bounds) {
565 memcpy(&lo_tcontext, tcontext, sizeof(lo_tcontext));
566 lo_tcontext.type = target->bounds;
567 tcontextp = &lo_tcontext;
570 context_struct_compute_av(policydb, &lo_scontext,
576 masked = ~lo_avd.allowed & avd->allowed;
579 return; /* no masked permission */
581 /* mask violated permissions */
582 avd->allowed &= ~masked;
584 /* audit masked permissions */
585 security_dump_masked_av(policydb, scontext, tcontext,
586 tclass, masked, "bounds");
590 * flag which drivers have permissions
591 * only looking for ioctl based extended permssions
593 void services_compute_xperms_drivers(
594 struct extended_perms *xperms,
595 struct avtab_node *node)
599 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
600 /* if one or more driver has all permissions allowed */
601 for (i = 0; i < ARRAY_SIZE(xperms->drivers.p); i++)
602 xperms->drivers.p[i] |= node->datum.u.xperms->perms.p[i];
603 } else if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
604 /* if allowing permissions within a driver */
605 security_xperm_set(xperms->drivers.p,
606 node->datum.u.xperms->driver);
609 /* If no ioctl commands are allowed, ignore auditallow and auditdeny */
610 if (node->key.specified & AVTAB_XPERMS_ALLOWED)
615 * Compute access vectors and extended permissions based on a context
616 * structure pair for the permissions in a particular class.
618 static void context_struct_compute_av(struct policydb *policydb,
619 struct context *scontext,
620 struct context *tcontext,
622 struct av_decision *avd,
623 struct extended_perms *xperms)
625 struct constraint_node *constraint;
626 struct role_allow *ra;
627 struct avtab_key avkey;
628 struct avtab_node *node;
629 struct class_datum *tclass_datum;
630 struct ebitmap *sattr, *tattr;
631 struct ebitmap_node *snode, *tnode;
636 avd->auditdeny = 0xffffffff;
638 memset(&xperms->drivers, 0, sizeof(xperms->drivers));
642 if (unlikely(!tclass || tclass > policydb->p_classes.nprim)) {
643 if (printk_ratelimit())
644 pr_warn("SELinux: Invalid class %hu\n", tclass);
648 tclass_datum = policydb->class_val_to_struct[tclass - 1];
651 * If a specific type enforcement rule was defined for
652 * this permission check, then use it.
654 avkey.target_class = tclass;
655 avkey.specified = AVTAB_AV | AVTAB_XPERMS;
656 sattr = &policydb->type_attr_map_array[scontext->type - 1];
657 tattr = &policydb->type_attr_map_array[tcontext->type - 1];
658 ebitmap_for_each_positive_bit(sattr, snode, i) {
659 ebitmap_for_each_positive_bit(tattr, tnode, j) {
660 avkey.source_type = i + 1;
661 avkey.target_type = j + 1;
662 for (node = avtab_search_node(&policydb->te_avtab,
665 node = avtab_search_node_next(node, avkey.specified)) {
666 if (node->key.specified == AVTAB_ALLOWED)
667 avd->allowed |= node->datum.u.data;
668 else if (node->key.specified == AVTAB_AUDITALLOW)
669 avd->auditallow |= node->datum.u.data;
670 else if (node->key.specified == AVTAB_AUDITDENY)
671 avd->auditdeny &= node->datum.u.data;
672 else if (xperms && (node->key.specified & AVTAB_XPERMS))
673 services_compute_xperms_drivers(xperms, node);
676 /* Check conditional av table for additional permissions */
677 cond_compute_av(&policydb->te_cond_avtab, &avkey,
684 * Remove any permissions prohibited by a constraint (this includes
687 constraint = tclass_datum->constraints;
689 if ((constraint->permissions & (avd->allowed)) &&
690 !constraint_expr_eval(policydb, scontext, tcontext, NULL,
692 avd->allowed &= ~(constraint->permissions);
694 constraint = constraint->next;
698 * If checking process transition permission and the
699 * role is changing, then check the (current_role, new_role)
702 if (tclass == policydb->process_class &&
703 (avd->allowed & policydb->process_trans_perms) &&
704 scontext->role != tcontext->role) {
705 for (ra = policydb->role_allow; ra; ra = ra->next) {
706 if (scontext->role == ra->role &&
707 tcontext->role == ra->new_role)
711 avd->allowed &= ~policydb->process_trans_perms;
715 * If the given source and target types have boundary
716 * constraint, lazy checks have to mask any violated
717 * permission and notice it to userspace via audit.
719 type_attribute_bounds_av(policydb, scontext, tcontext,
723 static int security_validtrans_handle_fail(struct selinux_state *state,
724 struct sidtab_entry *oentry,
725 struct sidtab_entry *nentry,
726 struct sidtab_entry *tentry,
729 struct policydb *p = &state->ss->policydb;
730 struct sidtab *sidtab = state->ss->sidtab;
731 char *o = NULL, *n = NULL, *t = NULL;
732 u32 olen, nlen, tlen;
734 if (sidtab_entry_to_string(p, sidtab, oentry, &o, &olen))
736 if (sidtab_entry_to_string(p, sidtab, nentry, &n, &nlen))
738 if (sidtab_entry_to_string(p, sidtab, tentry, &t, &tlen))
740 audit_log(audit_context(), GFP_ATOMIC, AUDIT_SELINUX_ERR,
741 "op=security_validate_transition seresult=denied"
742 " oldcontext=%s newcontext=%s taskcontext=%s tclass=%s",
743 o, n, t, sym_name(p, SYM_CLASSES, tclass-1));
749 if (!enforcing_enabled(state))
754 static int security_compute_validatetrans(struct selinux_state *state,
755 u32 oldsid, u32 newsid, u32 tasksid,
756 u16 orig_tclass, bool user)
758 struct policydb *policydb;
759 struct sidtab *sidtab;
760 struct sidtab_entry *oentry;
761 struct sidtab_entry *nentry;
762 struct sidtab_entry *tentry;
763 struct class_datum *tclass_datum;
764 struct constraint_node *constraint;
769 if (!selinux_initialized(state))
772 read_lock(&state->ss->policy_rwlock);
774 policydb = &state->ss->policydb;
775 sidtab = state->ss->sidtab;
778 tclass = unmap_class(&state->ss->map, orig_tclass);
780 tclass = orig_tclass;
782 if (!tclass || tclass > policydb->p_classes.nprim) {
786 tclass_datum = policydb->class_val_to_struct[tclass - 1];
788 oentry = sidtab_search_entry(sidtab, oldsid);
790 pr_err("SELinux: %s: unrecognized SID %d\n",
796 nentry = sidtab_search_entry(sidtab, newsid);
798 pr_err("SELinux: %s: unrecognized SID %d\n",
804 tentry = sidtab_search_entry(sidtab, tasksid);
806 pr_err("SELinux: %s: unrecognized SID %d\n",
812 constraint = tclass_datum->validatetrans;
814 if (!constraint_expr_eval(policydb, &oentry->context,
815 &nentry->context, &tentry->context,
820 rc = security_validtrans_handle_fail(state,
827 constraint = constraint->next;
831 read_unlock(&state->ss->policy_rwlock);
835 int security_validate_transition_user(struct selinux_state *state,
836 u32 oldsid, u32 newsid, u32 tasksid,
839 return security_compute_validatetrans(state, oldsid, newsid, tasksid,
843 int security_validate_transition(struct selinux_state *state,
844 u32 oldsid, u32 newsid, u32 tasksid,
847 return security_compute_validatetrans(state, oldsid, newsid, tasksid,
852 * security_bounded_transition - check whether the given
853 * transition is directed to bounded, or not.
854 * It returns 0, if @newsid is bounded by @oldsid.
855 * Otherwise, it returns error code.
857 * @oldsid : current security identifier
858 * @newsid : destinated security identifier
860 int security_bounded_transition(struct selinux_state *state,
861 u32 old_sid, u32 new_sid)
863 struct policydb *policydb;
864 struct sidtab *sidtab;
865 struct sidtab_entry *old_entry, *new_entry;
866 struct type_datum *type;
870 if (!selinux_initialized(state))
873 read_lock(&state->ss->policy_rwlock);
875 policydb = &state->ss->policydb;
876 sidtab = state->ss->sidtab;
879 old_entry = sidtab_search_entry(sidtab, old_sid);
881 pr_err("SELinux: %s: unrecognized SID %u\n",
887 new_entry = sidtab_search_entry(sidtab, new_sid);
889 pr_err("SELinux: %s: unrecognized SID %u\n",
895 /* type/domain unchanged */
896 if (old_entry->context.type == new_entry->context.type)
899 index = new_entry->context.type;
901 type = policydb->type_val_to_struct[index - 1];
904 /* not bounded anymore */
909 /* @newsid is bounded by @oldsid */
911 if (type->bounds == old_entry->context.type)
914 index = type->bounds;
918 char *old_name = NULL;
919 char *new_name = NULL;
922 if (!sidtab_entry_to_string(policydb, sidtab, old_entry,
923 &old_name, &length) &&
924 !sidtab_entry_to_string(policydb, sidtab, new_entry,
925 &new_name, &length)) {
926 audit_log(audit_context(),
927 GFP_ATOMIC, AUDIT_SELINUX_ERR,
928 "op=security_bounded_transition "
930 "oldcontext=%s newcontext=%s",
937 read_unlock(&state->ss->policy_rwlock);
942 static void avd_init(struct selinux_state *state, struct av_decision *avd)
946 avd->auditdeny = 0xffffffff;
947 avd->seqno = state->ss->latest_granting;
951 void services_compute_xperms_decision(struct extended_perms_decision *xpermd,
952 struct avtab_node *node)
956 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
957 if (xpermd->driver != node->datum.u.xperms->driver)
959 } else if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
960 if (!security_xperm_test(node->datum.u.xperms->perms.p,
967 if (node->key.specified == AVTAB_XPERMS_ALLOWED) {
968 xpermd->used |= XPERMS_ALLOWED;
969 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
970 memset(xpermd->allowed->p, 0xff,
971 sizeof(xpermd->allowed->p));
973 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
974 for (i = 0; i < ARRAY_SIZE(xpermd->allowed->p); i++)
975 xpermd->allowed->p[i] |=
976 node->datum.u.xperms->perms.p[i];
978 } else if (node->key.specified == AVTAB_XPERMS_AUDITALLOW) {
979 xpermd->used |= XPERMS_AUDITALLOW;
980 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
981 memset(xpermd->auditallow->p, 0xff,
982 sizeof(xpermd->auditallow->p));
984 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
985 for (i = 0; i < ARRAY_SIZE(xpermd->auditallow->p); i++)
986 xpermd->auditallow->p[i] |=
987 node->datum.u.xperms->perms.p[i];
989 } else if (node->key.specified == AVTAB_XPERMS_DONTAUDIT) {
990 xpermd->used |= XPERMS_DONTAUDIT;
991 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
992 memset(xpermd->dontaudit->p, 0xff,
993 sizeof(xpermd->dontaudit->p));
995 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
996 for (i = 0; i < ARRAY_SIZE(xpermd->dontaudit->p); i++)
997 xpermd->dontaudit->p[i] |=
998 node->datum.u.xperms->perms.p[i];
1005 void security_compute_xperms_decision(struct selinux_state *state,
1010 struct extended_perms_decision *xpermd)
1012 struct policydb *policydb;
1013 struct sidtab *sidtab;
1015 struct context *scontext, *tcontext;
1016 struct avtab_key avkey;
1017 struct avtab_node *node;
1018 struct ebitmap *sattr, *tattr;
1019 struct ebitmap_node *snode, *tnode;
1022 xpermd->driver = driver;
1024 memset(xpermd->allowed->p, 0, sizeof(xpermd->allowed->p));
1025 memset(xpermd->auditallow->p, 0, sizeof(xpermd->auditallow->p));
1026 memset(xpermd->dontaudit->p, 0, sizeof(xpermd->dontaudit->p));
1028 read_lock(&state->ss->policy_rwlock);
1029 if (!selinux_initialized(state))
1032 policydb = &state->ss->policydb;
1033 sidtab = state->ss->sidtab;
1035 scontext = sidtab_search(sidtab, ssid);
1037 pr_err("SELinux: %s: unrecognized SID %d\n",
1042 tcontext = sidtab_search(sidtab, tsid);
1044 pr_err("SELinux: %s: unrecognized SID %d\n",
1049 tclass = unmap_class(&state->ss->map, orig_tclass);
1050 if (unlikely(orig_tclass && !tclass)) {
1051 if (policydb->allow_unknown)
1057 if (unlikely(!tclass || tclass > policydb->p_classes.nprim)) {
1058 pr_warn_ratelimited("SELinux: Invalid class %hu\n", tclass);
1062 avkey.target_class = tclass;
1063 avkey.specified = AVTAB_XPERMS;
1064 sattr = &policydb->type_attr_map_array[scontext->type - 1];
1065 tattr = &policydb->type_attr_map_array[tcontext->type - 1];
1066 ebitmap_for_each_positive_bit(sattr, snode, i) {
1067 ebitmap_for_each_positive_bit(tattr, tnode, j) {
1068 avkey.source_type = i + 1;
1069 avkey.target_type = j + 1;
1070 for (node = avtab_search_node(&policydb->te_avtab,
1073 node = avtab_search_node_next(node, avkey.specified))
1074 services_compute_xperms_decision(xpermd, node);
1076 cond_compute_xperms(&policydb->te_cond_avtab,
1081 read_unlock(&state->ss->policy_rwlock);
1084 memset(xpermd->allowed->p, 0xff, sizeof(xpermd->allowed->p));
1089 * security_compute_av - Compute access vector decisions.
1090 * @ssid: source security identifier
1091 * @tsid: target security identifier
1092 * @tclass: target security class
1093 * @avd: access vector decisions
1094 * @xperms: extended permissions
1096 * Compute a set of access vector decisions based on the
1097 * SID pair (@ssid, @tsid) for the permissions in @tclass.
1099 void security_compute_av(struct selinux_state *state,
1103 struct av_decision *avd,
1104 struct extended_perms *xperms)
1106 struct policydb *policydb;
1107 struct sidtab *sidtab;
1109 struct context *scontext = NULL, *tcontext = NULL;
1111 read_lock(&state->ss->policy_rwlock);
1112 avd_init(state, avd);
1114 if (!selinux_initialized(state))
1117 policydb = &state->ss->policydb;
1118 sidtab = state->ss->sidtab;
1120 scontext = sidtab_search(sidtab, ssid);
1122 pr_err("SELinux: %s: unrecognized SID %d\n",
1127 /* permissive domain? */
1128 if (ebitmap_get_bit(&policydb->permissive_map, scontext->type))
1129 avd->flags |= AVD_FLAGS_PERMISSIVE;
1131 tcontext = sidtab_search(sidtab, tsid);
1133 pr_err("SELinux: %s: unrecognized SID %d\n",
1138 tclass = unmap_class(&state->ss->map, orig_tclass);
1139 if (unlikely(orig_tclass && !tclass)) {
1140 if (policydb->allow_unknown)
1144 context_struct_compute_av(policydb, scontext, tcontext, tclass, avd,
1146 map_decision(&state->ss->map, orig_tclass, avd,
1147 policydb->allow_unknown);
1149 read_unlock(&state->ss->policy_rwlock);
1152 avd->allowed = 0xffffffff;
1156 void security_compute_av_user(struct selinux_state *state,
1160 struct av_decision *avd)
1162 struct policydb *policydb;
1163 struct sidtab *sidtab;
1164 struct context *scontext = NULL, *tcontext = NULL;
1166 read_lock(&state->ss->policy_rwlock);
1167 avd_init(state, avd);
1168 if (!selinux_initialized(state))
1171 policydb = &state->ss->policydb;
1172 sidtab = state->ss->sidtab;
1174 scontext = sidtab_search(sidtab, ssid);
1176 pr_err("SELinux: %s: unrecognized SID %d\n",
1181 /* permissive domain? */
1182 if (ebitmap_get_bit(&policydb->permissive_map, scontext->type))
1183 avd->flags |= AVD_FLAGS_PERMISSIVE;
1185 tcontext = sidtab_search(sidtab, tsid);
1187 pr_err("SELinux: %s: unrecognized SID %d\n",
1192 if (unlikely(!tclass)) {
1193 if (policydb->allow_unknown)
1198 context_struct_compute_av(policydb, scontext, tcontext, tclass, avd,
1201 read_unlock(&state->ss->policy_rwlock);
1204 avd->allowed = 0xffffffff;
1209 * Write the security context string representation of
1210 * the context structure `context' into a dynamically
1211 * allocated string of the correct size. Set `*scontext'
1212 * to point to this string and set `*scontext_len' to
1213 * the length of the string.
1215 static int context_struct_to_string(struct policydb *p,
1216 struct context *context,
1217 char **scontext, u32 *scontext_len)
1226 *scontext_len = context->len;
1228 *scontext = kstrdup(context->str, GFP_ATOMIC);
1235 /* Compute the size of the context. */
1236 *scontext_len += strlen(sym_name(p, SYM_USERS, context->user - 1)) + 1;
1237 *scontext_len += strlen(sym_name(p, SYM_ROLES, context->role - 1)) + 1;
1238 *scontext_len += strlen(sym_name(p, SYM_TYPES, context->type - 1)) + 1;
1239 *scontext_len += mls_compute_context_len(p, context);
1244 /* Allocate space for the context; caller must free this space. */
1245 scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
1248 *scontext = scontextp;
1251 * Copy the user name, role name and type name into the context.
1253 scontextp += sprintf(scontextp, "%s:%s:%s",
1254 sym_name(p, SYM_USERS, context->user - 1),
1255 sym_name(p, SYM_ROLES, context->role - 1),
1256 sym_name(p, SYM_TYPES, context->type - 1));
1258 mls_sid_to_context(p, context, &scontextp);
1265 static int sidtab_entry_to_string(struct policydb *p,
1266 struct sidtab *sidtab,
1267 struct sidtab_entry *entry,
1268 char **scontext, u32 *scontext_len)
1270 int rc = sidtab_sid2str_get(sidtab, entry, scontext, scontext_len);
1275 rc = context_struct_to_string(p, &entry->context, scontext,
1277 if (!rc && scontext)
1278 sidtab_sid2str_put(sidtab, entry, *scontext, *scontext_len);
1282 #include "initial_sid_to_string.h"
1284 int security_sidtab_hash_stats(struct selinux_state *state, char *page)
1288 if (!selinux_initialized(state)) {
1289 pr_err("SELinux: %s: called before initial load_policy\n",
1294 read_lock(&state->ss->policy_rwlock);
1295 rc = sidtab_hash_stats(state->ss->sidtab, page);
1296 read_unlock(&state->ss->policy_rwlock);
1301 const char *security_get_initial_sid_context(u32 sid)
1303 if (unlikely(sid > SECINITSID_NUM))
1305 return initial_sid_to_string[sid];
1308 static int security_sid_to_context_core(struct selinux_state *state,
1309 u32 sid, char **scontext,
1310 u32 *scontext_len, int force,
1313 struct policydb *policydb;
1314 struct sidtab *sidtab;
1315 struct sidtab_entry *entry;
1322 if (!selinux_initialized(state)) {
1323 if (sid <= SECINITSID_NUM) {
1325 const char *s = initial_sid_to_string[sid];
1329 *scontext_len = strlen(s) + 1;
1332 scontextp = kmemdup(s, *scontext_len, GFP_ATOMIC);
1335 *scontext = scontextp;
1338 pr_err("SELinux: %s: called before initial "
1339 "load_policy on unknown SID %d\n", __func__, sid);
1342 read_lock(&state->ss->policy_rwlock);
1343 policydb = &state->ss->policydb;
1344 sidtab = state->ss->sidtab;
1347 entry = sidtab_search_entry_force(sidtab, sid);
1349 entry = sidtab_search_entry(sidtab, sid);
1351 pr_err("SELinux: %s: unrecognized SID %d\n",
1356 if (only_invalid && !entry->context.len)
1359 rc = sidtab_entry_to_string(policydb, sidtab, entry, scontext,
1363 read_unlock(&state->ss->policy_rwlock);
1369 * security_sid_to_context - Obtain a context for a given SID.
1370 * @sid: security identifier, SID
1371 * @scontext: security context
1372 * @scontext_len: length in bytes
1374 * Write the string representation of the context associated with @sid
1375 * into a dynamically allocated string of the correct size. Set @scontext
1376 * to point to this string and set @scontext_len to the length of the string.
1378 int security_sid_to_context(struct selinux_state *state,
1379 u32 sid, char **scontext, u32 *scontext_len)
1381 return security_sid_to_context_core(state, sid, scontext,
1382 scontext_len, 0, 0);
1385 int security_sid_to_context_force(struct selinux_state *state, u32 sid,
1386 char **scontext, u32 *scontext_len)
1388 return security_sid_to_context_core(state, sid, scontext,
1389 scontext_len, 1, 0);
1393 * security_sid_to_context_inval - Obtain a context for a given SID if it
1395 * @sid: security identifier, SID
1396 * @scontext: security context
1397 * @scontext_len: length in bytes
1399 * Write the string representation of the context associated with @sid
1400 * into a dynamically allocated string of the correct size, but only if the
1401 * context is invalid in the current policy. Set @scontext to point to
1402 * this string (or NULL if the context is valid) and set @scontext_len to
1403 * the length of the string (or 0 if the context is valid).
1405 int security_sid_to_context_inval(struct selinux_state *state, u32 sid,
1406 char **scontext, u32 *scontext_len)
1408 return security_sid_to_context_core(state, sid, scontext,
1409 scontext_len, 1, 1);
1413 * Caveat: Mutates scontext.
1415 static int string_to_context_struct(struct policydb *pol,
1416 struct sidtab *sidtabp,
1418 struct context *ctx,
1421 struct role_datum *role;
1422 struct type_datum *typdatum;
1423 struct user_datum *usrdatum;
1424 char *scontextp, *p, oldc;
1429 /* Parse the security context. */
1432 scontextp = (char *) scontext;
1434 /* Extract the user. */
1436 while (*p && *p != ':')
1444 usrdatum = hashtab_search(pol->p_users.table, scontextp);
1448 ctx->user = usrdatum->value;
1452 while (*p && *p != ':')
1460 role = hashtab_search(pol->p_roles.table, scontextp);
1463 ctx->role = role->value;
1467 while (*p && *p != ':')
1472 typdatum = hashtab_search(pol->p_types.table, scontextp);
1473 if (!typdatum || typdatum->attribute)
1476 ctx->type = typdatum->value;
1478 rc = mls_context_to_sid(pol, oldc, p, ctx, sidtabp, def_sid);
1482 /* Check the validity of the new context. */
1484 if (!policydb_context_isvalid(pol, ctx))
1489 context_destroy(ctx);
1493 int context_add_hash(struct policydb *policydb,
1494 struct context *context)
1501 context->hash = context_compute_hash(context->str);
1503 rc = context_struct_to_string(policydb, context,
1507 context->hash = context_compute_hash(str);
1513 static int context_struct_to_sid(struct selinux_state *state,
1514 struct context *context, u32 *sid)
1517 struct sidtab *sidtab = state->ss->sidtab;
1518 struct policydb *policydb = &state->ss->policydb;
1520 if (!context->hash) {
1521 rc = context_add_hash(policydb, context);
1526 return sidtab_context_to_sid(sidtab, context, sid);
1529 static int security_context_to_sid_core(struct selinux_state *state,
1530 const char *scontext, u32 scontext_len,
1531 u32 *sid, u32 def_sid, gfp_t gfp_flags,
1534 struct policydb *policydb;
1535 struct sidtab *sidtab;
1536 char *scontext2, *str = NULL;
1537 struct context context;
1540 /* An empty security context is never valid. */
1544 /* Copy the string to allow changes and ensure a NUL terminator */
1545 scontext2 = kmemdup_nul(scontext, scontext_len, gfp_flags);
1549 if (!selinux_initialized(state)) {
1552 for (i = 1; i < SECINITSID_NUM; i++) {
1553 const char *s = initial_sid_to_string[i];
1555 if (s && !strcmp(s, scontext2)) {
1560 *sid = SECINITSID_KERNEL;
1566 /* Save another copy for storing in uninterpreted form */
1568 str = kstrdup(scontext2, gfp_flags);
1572 read_lock(&state->ss->policy_rwlock);
1573 policydb = &state->ss->policydb;
1574 sidtab = state->ss->sidtab;
1575 rc = string_to_context_struct(policydb, sidtab, scontext2,
1577 if (rc == -EINVAL && force) {
1579 context.len = strlen(str) + 1;
1583 rc = context_struct_to_sid(state, &context, sid);
1584 context_destroy(&context);
1586 read_unlock(&state->ss->policy_rwlock);
1594 * security_context_to_sid - Obtain a SID for a given security context.
1595 * @scontext: security context
1596 * @scontext_len: length in bytes
1597 * @sid: security identifier, SID
1598 * @gfp: context for the allocation
1600 * Obtains a SID associated with the security context that
1601 * has the string representation specified by @scontext.
1602 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1603 * memory is available, or 0 on success.
1605 int security_context_to_sid(struct selinux_state *state,
1606 const char *scontext, u32 scontext_len, u32 *sid,
1609 return security_context_to_sid_core(state, scontext, scontext_len,
1610 sid, SECSID_NULL, gfp, 0);
1613 int security_context_str_to_sid(struct selinux_state *state,
1614 const char *scontext, u32 *sid, gfp_t gfp)
1616 return security_context_to_sid(state, scontext, strlen(scontext),
1621 * security_context_to_sid_default - Obtain a SID for a given security context,
1622 * falling back to specified default if needed.
1624 * @scontext: security context
1625 * @scontext_len: length in bytes
1626 * @sid: security identifier, SID
1627 * @def_sid: default SID to assign on error
1629 * Obtains a SID associated with the security context that
1630 * has the string representation specified by @scontext.
1631 * The default SID is passed to the MLS layer to be used to allow
1632 * kernel labeling of the MLS field if the MLS field is not present
1633 * (for upgrading to MLS without full relabel).
1634 * Implicitly forces adding of the context even if it cannot be mapped yet.
1635 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1636 * memory is available, or 0 on success.
1638 int security_context_to_sid_default(struct selinux_state *state,
1639 const char *scontext, u32 scontext_len,
1640 u32 *sid, u32 def_sid, gfp_t gfp_flags)
1642 return security_context_to_sid_core(state, scontext, scontext_len,
1643 sid, def_sid, gfp_flags, 1);
1646 int security_context_to_sid_force(struct selinux_state *state,
1647 const char *scontext, u32 scontext_len,
1650 return security_context_to_sid_core(state, scontext, scontext_len,
1651 sid, SECSID_NULL, GFP_KERNEL, 1);
1654 static int compute_sid_handle_invalid_context(
1655 struct selinux_state *state,
1656 struct sidtab_entry *sentry,
1657 struct sidtab_entry *tentry,
1659 struct context *newcontext)
1661 struct policydb *policydb = &state->ss->policydb;
1662 struct sidtab *sidtab = state->ss->sidtab;
1663 char *s = NULL, *t = NULL, *n = NULL;
1664 u32 slen, tlen, nlen;
1665 struct audit_buffer *ab;
1667 if (sidtab_entry_to_string(policydb, sidtab, sentry, &s, &slen))
1669 if (sidtab_entry_to_string(policydb, sidtab, tentry, &t, &tlen))
1671 if (context_struct_to_string(policydb, newcontext, &n, &nlen))
1673 ab = audit_log_start(audit_context(), GFP_ATOMIC, AUDIT_SELINUX_ERR);
1674 audit_log_format(ab,
1675 "op=security_compute_sid invalid_context=");
1676 /* no need to record the NUL with untrusted strings */
1677 audit_log_n_untrustedstring(ab, n, nlen - 1);
1678 audit_log_format(ab, " scontext=%s tcontext=%s tclass=%s",
1679 s, t, sym_name(policydb, SYM_CLASSES, tclass-1));
1685 if (!enforcing_enabled(state))
1690 static void filename_compute_type(struct policydb *policydb,
1691 struct context *newcontext,
1692 u32 stype, u32 ttype, u16 tclass,
1693 const char *objname)
1695 struct filename_trans_key ft;
1696 struct filename_trans_datum *datum;
1699 * Most filename trans rules are going to live in specific directories
1700 * like /dev or /var/run. This bitmap will quickly skip rule searches
1701 * if the ttype does not contain any rules.
1703 if (!ebitmap_get_bit(&policydb->filename_trans_ttypes, ttype))
1710 datum = hashtab_search(policydb->filename_trans, &ft);
1712 if (ebitmap_get_bit(&datum->stypes, stype - 1)) {
1713 newcontext->type = datum->otype;
1716 datum = datum->next;
1720 static int security_compute_sid(struct selinux_state *state,
1725 const char *objname,
1729 struct policydb *policydb;
1730 struct sidtab *sidtab;
1731 struct class_datum *cladatum = NULL;
1732 struct context *scontext, *tcontext, newcontext;
1733 struct sidtab_entry *sentry, *tentry;
1734 struct role_trans *roletr = NULL;
1735 struct avtab_key avkey;
1736 struct avtab_datum *avdatum;
1737 struct avtab_node *node;
1742 if (!selinux_initialized(state)) {
1743 switch (orig_tclass) {
1744 case SECCLASS_PROCESS: /* kernel value */
1754 context_init(&newcontext);
1756 read_lock(&state->ss->policy_rwlock);
1759 tclass = unmap_class(&state->ss->map, orig_tclass);
1760 sock = security_is_socket_class(orig_tclass);
1762 tclass = orig_tclass;
1763 sock = security_is_socket_class(map_class(&state->ss->map,
1767 policydb = &state->ss->policydb;
1768 sidtab = state->ss->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 for (roletr = policydb->role_tr; roletr;
1868 roletr = roletr->next) {
1869 if ((roletr->role == scontext->role) &&
1870 (roletr->type == tcontext->type) &&
1871 (roletr->tclass == tclass)) {
1872 /* Use the role transition rule. */
1873 newcontext.role = roletr->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, sentry, tentry,
1889 tclass, &newcontext);
1893 /* Obtain the sid for the context. */
1894 rc = context_struct_to_sid(state, &newcontext, out_sid);
1896 read_unlock(&state->ss->policy_rwlock);
1897 context_destroy(&newcontext);
1903 * security_transition_sid - Compute the SID for a new subject/object.
1904 * @ssid: source security identifier
1905 * @tsid: target security identifier
1906 * @tclass: target security class
1907 * @out_sid: security identifier for new subject/object
1909 * Compute a SID to use for labeling a new subject or object in the
1910 * class @tclass based on a SID pair (@ssid, @tsid).
1911 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1912 * if insufficient memory is available, or %0 if the new SID was
1913 * computed successfully.
1915 int security_transition_sid(struct selinux_state *state,
1916 u32 ssid, u32 tsid, u16 tclass,
1917 const struct qstr *qstr, u32 *out_sid)
1919 return security_compute_sid(state, ssid, tsid, tclass,
1921 qstr ? qstr->name : NULL, out_sid, true);
1924 int security_transition_sid_user(struct selinux_state *state,
1925 u32 ssid, u32 tsid, u16 tclass,
1926 const char *objname, u32 *out_sid)
1928 return security_compute_sid(state, ssid, tsid, tclass,
1930 objname, out_sid, false);
1934 * security_member_sid - Compute the SID for member selection.
1935 * @ssid: source security identifier
1936 * @tsid: target security identifier
1937 * @tclass: target security class
1938 * @out_sid: security identifier for selected member
1940 * Compute a SID to use when selecting a member of a polyinstantiated
1941 * object of class @tclass based on a SID pair (@ssid, @tsid).
1942 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1943 * if insufficient memory is available, or %0 if the SID was
1944 * computed successfully.
1946 int security_member_sid(struct selinux_state *state,
1952 return security_compute_sid(state, ssid, tsid, tclass,
1958 * security_change_sid - Compute the SID for object relabeling.
1959 * @ssid: source security identifier
1960 * @tsid: target security identifier
1961 * @tclass: target security class
1962 * @out_sid: security identifier for selected member
1964 * Compute a SID to use for relabeling an object of class @tclass
1965 * based on a SID pair (@ssid, @tsid).
1966 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1967 * if insufficient memory is available, or %0 if the SID was
1968 * computed successfully.
1970 int security_change_sid(struct selinux_state *state,
1976 return security_compute_sid(state,
1977 ssid, tsid, tclass, AVTAB_CHANGE, NULL,
1981 static inline int convert_context_handle_invalid_context(
1982 struct selinux_state *state,
1983 struct context *context)
1985 struct policydb *policydb = &state->ss->policydb;
1989 if (enforcing_enabled(state))
1992 if (!context_struct_to_string(policydb, context, &s, &len)) {
1993 pr_warn("SELinux: Context %s would be invalid if enforcing\n",
2000 struct convert_context_args {
2001 struct selinux_state *state;
2002 struct policydb *oldp;
2003 struct policydb *newp;
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;
2046 newc->hash = oldc->hash;
2051 /* Other error condition, e.g. ENOMEM. */
2052 pr_err("SELinux: Unable to map context %s, rc = %d.\n",
2056 pr_info("SELinux: Context %s became valid (mapped).\n",
2063 /* Convert the user. */
2065 usrdatum = hashtab_search(args->newp->p_users.table,
2066 sym_name(args->oldp,
2067 SYM_USERS, oldc->user - 1));
2070 newc->user = usrdatum->value;
2072 /* Convert the role. */
2074 role = hashtab_search(args->newp->p_roles.table,
2075 sym_name(args->oldp, SYM_ROLES, oldc->role - 1));
2078 newc->role = role->value;
2080 /* Convert the type. */
2082 typdatum = hashtab_search(args->newp->p_types.table,
2083 sym_name(args->oldp,
2084 SYM_TYPES, oldc->type - 1));
2087 newc->type = typdatum->value;
2089 /* Convert the MLS fields if dealing with MLS policies */
2090 if (args->oldp->mls_enabled && args->newp->mls_enabled) {
2091 rc = mls_convert_context(args->oldp, args->newp, oldc, newc);
2094 } else if (!args->oldp->mls_enabled && args->newp->mls_enabled) {
2096 * Switching between non-MLS and MLS policy:
2097 * ensure that the MLS fields of the context for all
2098 * existing entries in the sidtab are filled in with a
2099 * suitable default value, likely taken from one of the
2102 oc = args->newp->ocontexts[OCON_ISID];
2103 while (oc && oc->sid[0] != SECINITSID_UNLABELED)
2107 pr_err("SELinux: unable to look up"
2108 " the initial SIDs list\n");
2111 rc = mls_range_set(newc, &oc->context[0].range);
2116 /* Check the validity of the new context. */
2117 if (!policydb_context_isvalid(args->newp, newc)) {
2118 rc = convert_context_handle_invalid_context(args->state, oldc);
2123 rc = context_add_hash(args->newp, newc);
2129 /* Map old representation to string and save it. */
2130 rc = context_struct_to_string(args->oldp, oldc, &s, &len);
2133 context_destroy(newc);
2136 newc->hash = context_compute_hash(s);
2137 pr_info("SELinux: Context %s became invalid (unmapped).\n",
2142 static void security_load_policycaps(struct selinux_state *state)
2144 struct policydb *p = &state->ss->policydb;
2146 struct ebitmap_node *node;
2148 for (i = 0; i < ARRAY_SIZE(state->policycap); i++)
2149 state->policycap[i] = 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_state *state,
2164 struct policydb *newpolicydb);
2167 * security_load_policy - Load a security policy configuration.
2168 * @data: binary policy data
2169 * @len: length of data in bytes
2171 * Load a new set of security policy configuration data,
2172 * validate it and convert the SID table as necessary.
2173 * This function will flush the access vector cache after
2174 * loading the new policy.
2176 int security_load_policy(struct selinux_state *state, void *data, size_t len)
2178 struct policydb *policydb;
2179 struct sidtab *oldsidtab, *newsidtab;
2180 struct policydb *oldpolicydb, *newpolicydb;
2181 struct selinux_mapping *oldmapping;
2182 struct selinux_map newmap;
2183 struct sidtab_convert_params convert_params;
2184 struct convert_context_args args;
2187 struct policy_file file = { data, len }, *fp = &file;
2189 policydb = &state->ss->policydb;
2191 newsidtab = kmalloc(sizeof(*newsidtab), GFP_KERNEL);
2195 if (!selinux_initialized(state)) {
2196 rc = policydb_read(policydb, fp);
2202 policydb->len = len;
2203 rc = selinux_set_mapping(policydb, secclass_map,
2207 policydb_destroy(policydb);
2211 rc = policydb_load_isids(policydb, newsidtab);
2214 policydb_destroy(policydb);
2218 state->ss->sidtab = newsidtab;
2219 security_load_policycaps(state);
2220 selinux_mark_initialized(state);
2221 seqno = ++state->ss->latest_granting;
2222 selinux_complete_init();
2223 avc_ss_reset(state->avc, seqno);
2224 selnl_notify_policyload(seqno);
2225 selinux_status_update_policyload(state, seqno);
2226 selinux_netlbl_cache_invalidate();
2227 selinux_xfrm_notify_policyload();
2231 oldpolicydb = kcalloc(2, sizeof(*oldpolicydb), GFP_KERNEL);
2236 newpolicydb = oldpolicydb + 1;
2238 rc = policydb_read(newpolicydb, fp);
2244 newpolicydb->len = len;
2245 /* If switching between different policy types, log MLS status */
2246 if (policydb->mls_enabled && !newpolicydb->mls_enabled)
2247 pr_info("SELinux: Disabling MLS support...\n");
2248 else if (!policydb->mls_enabled && newpolicydb->mls_enabled)
2249 pr_info("SELinux: Enabling MLS support...\n");
2251 rc = policydb_load_isids(newpolicydb, newsidtab);
2253 pr_err("SELinux: unable to load the initial SIDs\n");
2254 policydb_destroy(newpolicydb);
2259 rc = selinux_set_mapping(newpolicydb, secclass_map, &newmap);
2263 rc = security_preserve_bools(state, newpolicydb);
2265 pr_err("SELinux: unable to preserve booleans\n");
2269 oldsidtab = state->ss->sidtab;
2272 * Convert the internal representations of contexts
2273 * in the new SID table.
2276 args.oldp = policydb;
2277 args.newp = newpolicydb;
2279 convert_params.func = convert_context;
2280 convert_params.args = &args;
2281 convert_params.target = newsidtab;
2283 rc = sidtab_convert(oldsidtab, &convert_params);
2285 pr_err("SELinux: unable to convert the internal"
2286 " representation of contexts in the new SID"
2291 /* Save the old policydb and SID table to free later. */
2292 memcpy(oldpolicydb, policydb, sizeof(*policydb));
2294 /* Install the new policydb and SID table. */
2295 write_lock_irq(&state->ss->policy_rwlock);
2296 memcpy(policydb, newpolicydb, sizeof(*policydb));
2297 state->ss->sidtab = newsidtab;
2298 security_load_policycaps(state);
2299 oldmapping = state->ss->map.mapping;
2300 state->ss->map.mapping = newmap.mapping;
2301 state->ss->map.size = newmap.size;
2302 seqno = ++state->ss->latest_granting;
2303 write_unlock_irq(&state->ss->policy_rwlock);
2305 /* Free the old policydb and SID table. */
2306 policydb_destroy(oldpolicydb);
2307 sidtab_destroy(oldsidtab);
2311 avc_ss_reset(state->avc, seqno);
2312 selnl_notify_policyload(seqno);
2313 selinux_status_update_policyload(state, seqno);
2314 selinux_netlbl_cache_invalidate();
2315 selinux_xfrm_notify_policyload();
2321 kfree(newmap.mapping);
2322 sidtab_destroy(newsidtab);
2324 policydb_destroy(newpolicydb);
2331 size_t security_policydb_len(struct selinux_state *state)
2333 struct policydb *p = &state->ss->policydb;
2336 read_lock(&state->ss->policy_rwlock);
2338 read_unlock(&state->ss->policy_rwlock);
2344 * security_port_sid - Obtain the SID for a port.
2345 * @protocol: protocol number
2346 * @port: port number
2347 * @out_sid: security identifier
2349 int security_port_sid(struct selinux_state *state,
2350 u8 protocol, u16 port, u32 *out_sid)
2352 struct policydb *policydb;
2356 read_lock(&state->ss->policy_rwlock);
2358 policydb = &state->ss->policydb;
2360 c = policydb->ocontexts[OCON_PORT];
2362 if (c->u.port.protocol == protocol &&
2363 c->u.port.low_port <= port &&
2364 c->u.port.high_port >= port)
2371 rc = context_struct_to_sid(state, &c->context[0],
2376 *out_sid = c->sid[0];
2378 *out_sid = SECINITSID_PORT;
2382 read_unlock(&state->ss->policy_rwlock);
2387 * security_pkey_sid - Obtain the SID for a pkey.
2388 * @subnet_prefix: Subnet Prefix
2389 * @pkey_num: pkey number
2390 * @out_sid: security identifier
2392 int security_ib_pkey_sid(struct selinux_state *state,
2393 u64 subnet_prefix, u16 pkey_num, u32 *out_sid)
2395 struct policydb *policydb;
2399 read_lock(&state->ss->policy_rwlock);
2401 policydb = &state->ss->policydb;
2403 c = policydb->ocontexts[OCON_IBPKEY];
2405 if (c->u.ibpkey.low_pkey <= pkey_num &&
2406 c->u.ibpkey.high_pkey >= pkey_num &&
2407 c->u.ibpkey.subnet_prefix == subnet_prefix)
2415 rc = context_struct_to_sid(state,
2421 *out_sid = c->sid[0];
2423 *out_sid = SECINITSID_UNLABELED;
2426 read_unlock(&state->ss->policy_rwlock);
2431 * security_ib_endport_sid - Obtain the SID for a subnet management interface.
2432 * @dev_name: device name
2433 * @port: port number
2434 * @out_sid: security identifier
2436 int security_ib_endport_sid(struct selinux_state *state,
2437 const char *dev_name, u8 port_num, u32 *out_sid)
2439 struct policydb *policydb;
2443 read_lock(&state->ss->policy_rwlock);
2445 policydb = &state->ss->policydb;
2447 c = policydb->ocontexts[OCON_IBENDPORT];
2449 if (c->u.ibendport.port == port_num &&
2450 !strncmp(c->u.ibendport.dev_name,
2452 IB_DEVICE_NAME_MAX))
2460 rc = context_struct_to_sid(state, &c->context[0],
2465 *out_sid = c->sid[0];
2467 *out_sid = SECINITSID_UNLABELED;
2470 read_unlock(&state->ss->policy_rwlock);
2475 * security_netif_sid - Obtain the SID for a network interface.
2476 * @name: interface name
2477 * @if_sid: interface SID
2479 int security_netif_sid(struct selinux_state *state,
2480 char *name, u32 *if_sid)
2482 struct policydb *policydb;
2486 read_lock(&state->ss->policy_rwlock);
2488 policydb = &state->ss->policydb;
2490 c = policydb->ocontexts[OCON_NETIF];
2492 if (strcmp(name, c->u.name) == 0)
2498 if (!c->sid[0] || !c->sid[1]) {
2499 rc = context_struct_to_sid(state, &c->context[0],
2503 rc = context_struct_to_sid(state, &c->context[1],
2508 *if_sid = c->sid[0];
2510 *if_sid = SECINITSID_NETIF;
2513 read_unlock(&state->ss->policy_rwlock);
2517 static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask)
2521 for (i = 0; i < 4; i++)
2522 if (addr[i] != (input[i] & mask[i])) {
2531 * security_node_sid - Obtain the SID for a node (host).
2532 * @domain: communication domain aka address family
2534 * @addrlen: address length in bytes
2535 * @out_sid: security identifier
2537 int security_node_sid(struct selinux_state *state,
2543 struct policydb *policydb;
2547 read_lock(&state->ss->policy_rwlock);
2549 policydb = &state->ss->policydb;
2556 if (addrlen != sizeof(u32))
2559 addr = *((u32 *)addrp);
2561 c = policydb->ocontexts[OCON_NODE];
2563 if (c->u.node.addr == (addr & c->u.node.mask))
2572 if (addrlen != sizeof(u64) * 2)
2574 c = policydb->ocontexts[OCON_NODE6];
2576 if (match_ipv6_addrmask(addrp, c->u.node6.addr,
2585 *out_sid = SECINITSID_NODE;
2591 rc = context_struct_to_sid(state,
2597 *out_sid = c->sid[0];
2599 *out_sid = SECINITSID_NODE;
2604 read_unlock(&state->ss->policy_rwlock);
2611 * security_get_user_sids - Obtain reachable SIDs for a user.
2612 * @fromsid: starting SID
2613 * @username: username
2614 * @sids: array of reachable SIDs for user
2615 * @nel: number of elements in @sids
2617 * Generate the set of SIDs for legal security contexts
2618 * for a given user that can be reached by @fromsid.
2619 * Set *@sids to point to a dynamically allocated
2620 * array containing the set of SIDs. Set *@nel to the
2621 * number of elements in the array.
2624 int security_get_user_sids(struct selinux_state *state,
2630 struct policydb *policydb;
2631 struct sidtab *sidtab;
2632 struct context *fromcon, usercon;
2633 u32 *mysids = NULL, *mysids2, sid;
2634 u32 mynel = 0, maxnel = SIDS_NEL;
2635 struct user_datum *user;
2636 struct role_datum *role;
2637 struct ebitmap_node *rnode, *tnode;
2643 if (!selinux_initialized(state))
2646 read_lock(&state->ss->policy_rwlock);
2648 policydb = &state->ss->policydb;
2649 sidtab = state->ss->sidtab;
2651 context_init(&usercon);
2654 fromcon = sidtab_search(sidtab, fromsid);
2659 user = hashtab_search(policydb->p_users.table, username);
2663 usercon.user = user->value;
2666 mysids = kcalloc(maxnel, sizeof(*mysids), GFP_ATOMIC);
2670 ebitmap_for_each_positive_bit(&user->roles, rnode, i) {
2671 role = policydb->role_val_to_struct[i];
2672 usercon.role = i + 1;
2673 ebitmap_for_each_positive_bit(&role->types, tnode, j) {
2674 usercon.type = j + 1;
2676 * The same context struct is reused here so the hash
2681 if (mls_setup_user_range(policydb, fromcon, user,
2685 rc = context_struct_to_sid(state, &usercon, &sid);
2688 if (mynel < maxnel) {
2689 mysids[mynel++] = sid;
2693 mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
2696 memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
2699 mysids[mynel++] = sid;
2705 read_unlock(&state->ss->policy_rwlock);
2712 mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);
2717 for (i = 0, j = 0; i < mynel; i++) {
2718 struct av_decision dummy_avd;
2719 rc = avc_has_perm_noaudit(state,
2721 SECCLASS_PROCESS, /* kernel value */
2722 PROCESS__TRANSITION, AVC_STRICT,
2725 mysids2[j++] = mysids[i];
2737 * __security_genfs_sid - Helper to obtain a SID for a file in a filesystem
2738 * @fstype: filesystem type
2739 * @path: path from root of mount
2740 * @sclass: file security class
2741 * @sid: SID for path
2743 * Obtain a SID to use for a file in a filesystem that
2744 * cannot support xattr or use a fixed labeling behavior like
2745 * transition SIDs or task SIDs.
2747 * The caller must acquire the policy_rwlock before calling this function.
2749 static inline int __security_genfs_sid(struct selinux_state *state,
2755 struct policydb *policydb = &state->ss->policydb;
2758 struct genfs *genfs;
2762 while (path[0] == '/' && path[1] == '/')
2765 sclass = unmap_class(&state->ss->map, orig_sclass);
2766 *sid = SECINITSID_UNLABELED;
2768 for (genfs = policydb->genfs; genfs; genfs = genfs->next) {
2769 cmp = strcmp(fstype, genfs->fstype);
2778 for (c = genfs->head; c; c = c->next) {
2779 len = strlen(c->u.name);
2780 if ((!c->v.sclass || sclass == c->v.sclass) &&
2781 (strncmp(c->u.name, path, len) == 0))
2790 rc = context_struct_to_sid(state, &c->context[0], &c->sid[0]);
2802 * security_genfs_sid - Obtain a SID for a file in a filesystem
2803 * @fstype: filesystem type
2804 * @path: path from root of mount
2805 * @sclass: file security class
2806 * @sid: SID for path
2808 * Acquire policy_rwlock before calling __security_genfs_sid() and release
2811 int security_genfs_sid(struct selinux_state *state,
2819 read_lock(&state->ss->policy_rwlock);
2820 retval = __security_genfs_sid(state, fstype, path, orig_sclass, sid);
2821 read_unlock(&state->ss->policy_rwlock);
2826 * security_fs_use - Determine how to handle labeling for a filesystem.
2827 * @sb: superblock in question
2829 int security_fs_use(struct selinux_state *state, struct super_block *sb)
2831 struct policydb *policydb;
2834 struct superblock_security_struct *sbsec = sb->s_security;
2835 const char *fstype = sb->s_type->name;
2837 read_lock(&state->ss->policy_rwlock);
2839 policydb = &state->ss->policydb;
2841 c = policydb->ocontexts[OCON_FSUSE];
2843 if (strcmp(fstype, c->u.name) == 0)
2849 sbsec->behavior = c->v.behavior;
2851 rc = context_struct_to_sid(state, &c->context[0],
2856 sbsec->sid = c->sid[0];
2858 rc = __security_genfs_sid(state, fstype, "/", SECCLASS_DIR,
2861 sbsec->behavior = SECURITY_FS_USE_NONE;
2864 sbsec->behavior = SECURITY_FS_USE_GENFS;
2869 read_unlock(&state->ss->policy_rwlock);
2873 int security_get_bools(struct selinux_state *state,
2874 u32 *len, char ***names, int **values)
2876 struct policydb *policydb;
2880 if (!selinux_initialized(state)) {
2887 read_lock(&state->ss->policy_rwlock);
2889 policydb = &state->ss->policydb;
2895 *len = policydb->p_bools.nprim;
2900 *names = kcalloc(*len, sizeof(char *), GFP_ATOMIC);
2905 *values = kcalloc(*len, sizeof(int), GFP_ATOMIC);
2909 for (i = 0; i < *len; i++) {
2910 (*values)[i] = policydb->bool_val_to_struct[i]->state;
2913 (*names)[i] = kstrdup(sym_name(policydb, SYM_BOOLS, i),
2920 read_unlock(&state->ss->policy_rwlock);
2924 for (i = 0; i < *len; i++)
2932 int security_set_bools(struct selinux_state *state, u32 len, int *values)
2934 struct policydb *policydb;
2936 u32 i, lenp, seqno = 0;
2938 write_lock_irq(&state->ss->policy_rwlock);
2940 policydb = &state->ss->policydb;
2943 lenp = policydb->p_bools.nprim;
2947 for (i = 0; i < len; i++) {
2948 if (!!values[i] != policydb->bool_val_to_struct[i]->state) {
2949 audit_log(audit_context(), GFP_ATOMIC,
2950 AUDIT_MAC_CONFIG_CHANGE,
2951 "bool=%s val=%d old_val=%d auid=%u ses=%u",
2952 sym_name(policydb, SYM_BOOLS, i),
2954 policydb->bool_val_to_struct[i]->state,
2955 from_kuid(&init_user_ns, audit_get_loginuid(current)),
2956 audit_get_sessionid(current));
2959 policydb->bool_val_to_struct[i]->state = 1;
2961 policydb->bool_val_to_struct[i]->state = 0;
2964 evaluate_cond_nodes(policydb);
2966 seqno = ++state->ss->latest_granting;
2969 write_unlock_irq(&state->ss->policy_rwlock);
2971 avc_ss_reset(state->avc, seqno);
2972 selnl_notify_policyload(seqno);
2973 selinux_status_update_policyload(state, seqno);
2974 selinux_xfrm_notify_policyload();
2979 int security_get_bool_value(struct selinux_state *state,
2982 struct policydb *policydb;
2986 read_lock(&state->ss->policy_rwlock);
2988 policydb = &state->ss->policydb;
2991 len = policydb->p_bools.nprim;
2995 rc = policydb->bool_val_to_struct[index]->state;
2997 read_unlock(&state->ss->policy_rwlock);
3001 static int security_preserve_bools(struct selinux_state *state,
3002 struct policydb *policydb)
3004 int rc, *bvalues = NULL;
3005 char **bnames = NULL;
3006 struct cond_bool_datum *booldatum;
3009 rc = security_get_bools(state, &nbools, &bnames, &bvalues);
3012 for (i = 0; i < nbools; i++) {
3013 booldatum = hashtab_search(policydb->p_bools.table, bnames[i]);
3015 booldatum->state = bvalues[i];
3017 evaluate_cond_nodes(policydb);
3021 for (i = 0; i < nbools; i++)
3030 * security_sid_mls_copy() - computes a new sid based on the given
3031 * sid and the mls portion of mls_sid.
3033 int security_sid_mls_copy(struct selinux_state *state,
3034 u32 sid, u32 mls_sid, u32 *new_sid)
3036 struct policydb *policydb = &state->ss->policydb;
3037 struct sidtab *sidtab = state->ss->sidtab;
3038 struct context *context1;
3039 struct context *context2;
3040 struct context newcon;
3046 if (!selinux_initialized(state) || !policydb->mls_enabled) {
3051 context_init(&newcon);
3053 read_lock(&state->ss->policy_rwlock);
3056 context1 = sidtab_search(sidtab, sid);
3058 pr_err("SELinux: %s: unrecognized SID %d\n",
3064 context2 = sidtab_search(sidtab, mls_sid);
3066 pr_err("SELinux: %s: unrecognized SID %d\n",
3071 newcon.user = context1->user;
3072 newcon.role = context1->role;
3073 newcon.type = context1->type;
3074 rc = mls_context_cpy(&newcon, context2);
3078 /* Check the validity of the new context. */
3079 if (!policydb_context_isvalid(policydb, &newcon)) {
3080 rc = convert_context_handle_invalid_context(state, &newcon);
3082 if (!context_struct_to_string(policydb, &newcon, &s,
3084 struct audit_buffer *ab;
3086 ab = audit_log_start(audit_context(),
3089 audit_log_format(ab,
3090 "op=security_sid_mls_copy invalid_context=");
3091 /* don't record NUL with untrusted strings */
3092 audit_log_n_untrustedstring(ab, s, len - 1);
3099 rc = context_struct_to_sid(state, &newcon, new_sid);
3101 read_unlock(&state->ss->policy_rwlock);
3102 context_destroy(&newcon);
3108 * security_net_peersid_resolve - Compare and resolve two network peer SIDs
3109 * @nlbl_sid: NetLabel SID
3110 * @nlbl_type: NetLabel labeling protocol type
3111 * @xfrm_sid: XFRM SID
3114 * Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be
3115 * resolved into a single SID it is returned via @peer_sid and the function
3116 * returns zero. Otherwise @peer_sid is set to SECSID_NULL and the function
3117 * returns a negative value. A table summarizing the behavior is below:
3119 * | function return | @sid
3120 * ------------------------------+-----------------+-----------------
3121 * no peer labels | 0 | SECSID_NULL
3122 * single peer label | 0 | <peer_label>
3123 * multiple, consistent labels | 0 | <peer_label>
3124 * multiple, inconsistent labels | -<errno> | SECSID_NULL
3127 int security_net_peersid_resolve(struct selinux_state *state,
3128 u32 nlbl_sid, u32 nlbl_type,
3132 struct policydb *policydb = &state->ss->policydb;
3133 struct sidtab *sidtab = state->ss->sidtab;
3135 struct context *nlbl_ctx;
3136 struct context *xfrm_ctx;
3138 *peer_sid = SECSID_NULL;
3140 /* handle the common (which also happens to be the set of easy) cases
3141 * right away, these two if statements catch everything involving a
3142 * single or absent peer SID/label */
3143 if (xfrm_sid == SECSID_NULL) {
3144 *peer_sid = nlbl_sid;
3147 /* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a "fallback" label
3148 * and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label
3150 if (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) {
3151 *peer_sid = xfrm_sid;
3156 * We don't need to check initialized here since the only way both
3157 * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the
3158 * security server was initialized and state->initialized was true.
3160 if (!policydb->mls_enabled)
3163 read_lock(&state->ss->policy_rwlock);
3166 nlbl_ctx = sidtab_search(sidtab, nlbl_sid);
3168 pr_err("SELinux: %s: unrecognized SID %d\n",
3169 __func__, nlbl_sid);
3173 xfrm_ctx = sidtab_search(sidtab, xfrm_sid);
3175 pr_err("SELinux: %s: unrecognized SID %d\n",
3176 __func__, xfrm_sid);
3179 rc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES);
3183 /* at present NetLabel SIDs/labels really only carry MLS
3184 * information so if the MLS portion of the NetLabel SID
3185 * matches the MLS portion of the labeled XFRM SID/label
3186 * then pass along the XFRM SID as it is the most
3188 *peer_sid = xfrm_sid;
3190 read_unlock(&state->ss->policy_rwlock);
3194 static int get_classes_callback(void *k, void *d, void *args)
3196 struct class_datum *datum = d;
3197 char *name = k, **classes = args;
3198 int value = datum->value - 1;
3200 classes[value] = kstrdup(name, GFP_ATOMIC);
3201 if (!classes[value])
3207 int security_get_classes(struct selinux_state *state,
3208 char ***classes, int *nclasses)
3210 struct policydb *policydb = &state->ss->policydb;
3213 if (!selinux_initialized(state)) {
3219 read_lock(&state->ss->policy_rwlock);
3222 *nclasses = policydb->p_classes.nprim;
3223 *classes = kcalloc(*nclasses, sizeof(**classes), GFP_ATOMIC);
3227 rc = hashtab_map(policydb->p_classes.table, get_classes_callback,
3231 for (i = 0; i < *nclasses; i++)
3232 kfree((*classes)[i]);
3237 read_unlock(&state->ss->policy_rwlock);
3241 static int get_permissions_callback(void *k, void *d, void *args)
3243 struct perm_datum *datum = d;
3244 char *name = k, **perms = args;
3245 int value = datum->value - 1;
3247 perms[value] = kstrdup(name, GFP_ATOMIC);
3254 int security_get_permissions(struct selinux_state *state,
3255 char *class, char ***perms, int *nperms)
3257 struct policydb *policydb = &state->ss->policydb;
3259 struct class_datum *match;
3261 read_lock(&state->ss->policy_rwlock);
3264 match = hashtab_search(policydb->p_classes.table, class);
3266 pr_err("SELinux: %s: unrecognized class %s\n",
3272 *nperms = match->permissions.nprim;
3273 *perms = kcalloc(*nperms, sizeof(**perms), GFP_ATOMIC);
3277 if (match->comdatum) {
3278 rc = hashtab_map(match->comdatum->permissions.table,
3279 get_permissions_callback, *perms);
3284 rc = hashtab_map(match->permissions.table, get_permissions_callback,
3290 read_unlock(&state->ss->policy_rwlock);
3294 read_unlock(&state->ss->policy_rwlock);
3295 for (i = 0; i < *nperms; i++)
3301 int security_get_reject_unknown(struct selinux_state *state)
3303 return state->ss->policydb.reject_unknown;
3306 int security_get_allow_unknown(struct selinux_state *state)
3308 return state->ss->policydb.allow_unknown;
3312 * security_policycap_supported - Check for a specific policy capability
3313 * @req_cap: capability
3316 * This function queries the currently loaded policy to see if it supports the
3317 * capability specified by @req_cap. Returns true (1) if the capability is
3318 * supported, false (0) if it isn't supported.
3321 int security_policycap_supported(struct selinux_state *state,
3322 unsigned int req_cap)
3324 struct policydb *policydb = &state->ss->policydb;
3327 read_lock(&state->ss->policy_rwlock);
3328 rc = ebitmap_get_bit(&policydb->policycaps, req_cap);
3329 read_unlock(&state->ss->policy_rwlock);
3334 struct selinux_audit_rule {
3336 struct context au_ctxt;
3339 void selinux_audit_rule_free(void *vrule)
3341 struct selinux_audit_rule *rule = vrule;
3344 context_destroy(&rule->au_ctxt);
3349 int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule)
3351 struct selinux_state *state = &selinux_state;
3352 struct policydb *policydb = &state->ss->policydb;
3353 struct selinux_audit_rule *tmprule;
3354 struct role_datum *roledatum;
3355 struct type_datum *typedatum;
3356 struct user_datum *userdatum;
3357 struct selinux_audit_rule **rule = (struct selinux_audit_rule **)vrule;
3362 if (!selinux_initialized(state))
3366 case AUDIT_SUBJ_USER:
3367 case AUDIT_SUBJ_ROLE:
3368 case AUDIT_SUBJ_TYPE:
3369 case AUDIT_OBJ_USER:
3370 case AUDIT_OBJ_ROLE:
3371 case AUDIT_OBJ_TYPE:
3372 /* only 'equals' and 'not equals' fit user, role, and type */
3373 if (op != Audit_equal && op != Audit_not_equal)
3376 case AUDIT_SUBJ_SEN:
3377 case AUDIT_SUBJ_CLR:
3378 case AUDIT_OBJ_LEV_LOW:
3379 case AUDIT_OBJ_LEV_HIGH:
3380 /* we do not allow a range, indicated by the presence of '-' */
3381 if (strchr(rulestr, '-'))
3385 /* only the above fields are valid */
3389 tmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL);
3393 context_init(&tmprule->au_ctxt);
3395 read_lock(&state->ss->policy_rwlock);
3397 tmprule->au_seqno = state->ss->latest_granting;
3400 case AUDIT_SUBJ_USER:
3401 case AUDIT_OBJ_USER:
3403 userdatum = hashtab_search(policydb->p_users.table, rulestr);
3406 tmprule->au_ctxt.user = userdatum->value;
3408 case AUDIT_SUBJ_ROLE:
3409 case AUDIT_OBJ_ROLE:
3411 roledatum = hashtab_search(policydb->p_roles.table, rulestr);
3414 tmprule->au_ctxt.role = roledatum->value;
3416 case AUDIT_SUBJ_TYPE:
3417 case AUDIT_OBJ_TYPE:
3419 typedatum = hashtab_search(policydb->p_types.table, rulestr);
3422 tmprule->au_ctxt.type = typedatum->value;
3424 case AUDIT_SUBJ_SEN:
3425 case AUDIT_SUBJ_CLR:
3426 case AUDIT_OBJ_LEV_LOW:
3427 case AUDIT_OBJ_LEV_HIGH:
3428 rc = mls_from_string(policydb, rulestr, &tmprule->au_ctxt,
3436 read_unlock(&state->ss->policy_rwlock);
3439 selinux_audit_rule_free(tmprule);
3448 /* Check to see if the rule contains any selinux fields */
3449 int selinux_audit_rule_known(struct audit_krule *rule)
3453 for (i = 0; i < rule->field_count; i++) {
3454 struct audit_field *f = &rule->fields[i];
3456 case AUDIT_SUBJ_USER:
3457 case AUDIT_SUBJ_ROLE:
3458 case AUDIT_SUBJ_TYPE:
3459 case AUDIT_SUBJ_SEN:
3460 case AUDIT_SUBJ_CLR:
3461 case AUDIT_OBJ_USER:
3462 case AUDIT_OBJ_ROLE:
3463 case AUDIT_OBJ_TYPE:
3464 case AUDIT_OBJ_LEV_LOW:
3465 case AUDIT_OBJ_LEV_HIGH:
3473 int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule)
3475 struct selinux_state *state = &selinux_state;
3476 struct context *ctxt;
3477 struct mls_level *level;
3478 struct selinux_audit_rule *rule = vrule;
3481 if (unlikely(!rule)) {
3482 WARN_ONCE(1, "selinux_audit_rule_match: missing rule\n");
3486 read_lock(&state->ss->policy_rwlock);
3488 if (rule->au_seqno < state->ss->latest_granting) {
3493 ctxt = sidtab_search(state->ss->sidtab, sid);
3494 if (unlikely(!ctxt)) {
3495 WARN_ONCE(1, "selinux_audit_rule_match: unrecognized SID %d\n",
3501 /* a field/op pair that is not caught here will simply fall through
3504 case AUDIT_SUBJ_USER:
3505 case AUDIT_OBJ_USER:
3508 match = (ctxt->user == rule->au_ctxt.user);
3510 case Audit_not_equal:
3511 match = (ctxt->user != rule->au_ctxt.user);
3515 case AUDIT_SUBJ_ROLE:
3516 case AUDIT_OBJ_ROLE:
3519 match = (ctxt->role == rule->au_ctxt.role);
3521 case Audit_not_equal:
3522 match = (ctxt->role != rule->au_ctxt.role);
3526 case AUDIT_SUBJ_TYPE:
3527 case AUDIT_OBJ_TYPE:
3530 match = (ctxt->type == rule->au_ctxt.type);
3532 case Audit_not_equal:
3533 match = (ctxt->type != rule->au_ctxt.type);
3537 case AUDIT_SUBJ_SEN:
3538 case AUDIT_SUBJ_CLR:
3539 case AUDIT_OBJ_LEV_LOW:
3540 case AUDIT_OBJ_LEV_HIGH:
3541 level = ((field == AUDIT_SUBJ_SEN ||
3542 field == AUDIT_OBJ_LEV_LOW) ?
3543 &ctxt->range.level[0] : &ctxt->range.level[1]);
3546 match = mls_level_eq(&rule->au_ctxt.range.level[0],
3549 case Audit_not_equal:
3550 match = !mls_level_eq(&rule->au_ctxt.range.level[0],
3554 match = (mls_level_dom(&rule->au_ctxt.range.level[0],
3556 !mls_level_eq(&rule->au_ctxt.range.level[0],
3560 match = mls_level_dom(&rule->au_ctxt.range.level[0],
3564 match = (mls_level_dom(level,
3565 &rule->au_ctxt.range.level[0]) &&
3566 !mls_level_eq(level,
3567 &rule->au_ctxt.range.level[0]));
3570 match = mls_level_dom(level,
3571 &rule->au_ctxt.range.level[0]);
3577 read_unlock(&state->ss->policy_rwlock);
3581 static int (*aurule_callback)(void) = audit_update_lsm_rules;
3583 static int aurule_avc_callback(u32 event)
3587 if (event == AVC_CALLBACK_RESET && aurule_callback)
3588 err = aurule_callback();
3592 static int __init aurule_init(void)
3596 err = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET);
3598 panic("avc_add_callback() failed, error %d\n", err);
3602 __initcall(aurule_init);
3604 #ifdef CONFIG_NETLABEL
3606 * security_netlbl_cache_add - Add an entry to the NetLabel cache
3607 * @secattr: the NetLabel packet security attributes
3608 * @sid: the SELinux SID
3611 * Attempt to cache the context in @ctx, which was derived from the packet in
3612 * @skb, in the NetLabel subsystem cache. This function assumes @secattr has
3613 * already been initialized.
3616 static void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr,
3621 sid_cache = kmalloc(sizeof(*sid_cache), GFP_ATOMIC);
3622 if (sid_cache == NULL)
3624 secattr->cache = netlbl_secattr_cache_alloc(GFP_ATOMIC);
3625 if (secattr->cache == NULL) {
3631 secattr->cache->free = kfree;
3632 secattr->cache->data = sid_cache;
3633 secattr->flags |= NETLBL_SECATTR_CACHE;
3637 * security_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID
3638 * @secattr: the NetLabel packet security attributes
3639 * @sid: the SELinux SID
3642 * Convert the given NetLabel security attributes in @secattr into a
3643 * SELinux SID. If the @secattr field does not contain a full SELinux
3644 * SID/context then use SECINITSID_NETMSG as the foundation. If possible the
3645 * 'cache' field of @secattr is set and the CACHE flag is set; this is to
3646 * allow the @secattr to be used by NetLabel to cache the secattr to SID
3647 * conversion for future lookups. Returns zero on success, negative values on
3651 int security_netlbl_secattr_to_sid(struct selinux_state *state,
3652 struct netlbl_lsm_secattr *secattr,
3655 struct policydb *policydb = &state->ss->policydb;
3656 struct sidtab *sidtab = state->ss->sidtab;
3658 struct context *ctx;
3659 struct context ctx_new;
3661 if (!selinux_initialized(state)) {
3666 read_lock(&state->ss->policy_rwlock);
3668 if (secattr->flags & NETLBL_SECATTR_CACHE)
3669 *sid = *(u32 *)secattr->cache->data;
3670 else if (secattr->flags & NETLBL_SECATTR_SECID)
3671 *sid = secattr->attr.secid;
3672 else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) {
3674 ctx = sidtab_search(sidtab, SECINITSID_NETMSG);
3678 context_init(&ctx_new);
3679 ctx_new.user = ctx->user;
3680 ctx_new.role = ctx->role;
3681 ctx_new.type = ctx->type;
3682 mls_import_netlbl_lvl(policydb, &ctx_new, secattr);
3683 if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
3684 rc = mls_import_netlbl_cat(policydb, &ctx_new, secattr);
3689 if (!mls_context_isvalid(policydb, &ctx_new))
3692 rc = context_struct_to_sid(state, &ctx_new, sid);
3696 security_netlbl_cache_add(secattr, *sid);
3698 ebitmap_destroy(&ctx_new.range.level[0].cat);
3702 read_unlock(&state->ss->policy_rwlock);
3705 ebitmap_destroy(&ctx_new.range.level[0].cat);
3707 read_unlock(&state->ss->policy_rwlock);
3712 * security_netlbl_sid_to_secattr - Convert a SELinux SID to a NetLabel secattr
3713 * @sid: the SELinux SID
3714 * @secattr: the NetLabel packet security attributes
3717 * Convert the given SELinux SID in @sid into a NetLabel security attribute.
3718 * Returns zero on success, negative values on failure.
3721 int security_netlbl_sid_to_secattr(struct selinux_state *state,
3722 u32 sid, struct netlbl_lsm_secattr *secattr)
3724 struct policydb *policydb = &state->ss->policydb;
3726 struct context *ctx;
3728 if (!selinux_initialized(state))
3731 read_lock(&state->ss->policy_rwlock);
3734 ctx = sidtab_search(state->ss->sidtab, sid);
3739 secattr->domain = kstrdup(sym_name(policydb, SYM_TYPES, ctx->type - 1),
3741 if (secattr->domain == NULL)
3744 secattr->attr.secid = sid;
3745 secattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID;
3746 mls_export_netlbl_lvl(policydb, ctx, secattr);
3747 rc = mls_export_netlbl_cat(policydb, ctx, secattr);
3749 read_unlock(&state->ss->policy_rwlock);
3752 #endif /* CONFIG_NETLABEL */
3755 * security_read_policy - read the policy.
3756 * @data: binary policy data
3757 * @len: length of data in bytes
3760 int security_read_policy(struct selinux_state *state,
3761 void **data, size_t *len)
3763 struct policydb *policydb = &state->ss->policydb;
3765 struct policy_file fp;
3767 if (!selinux_initialized(state))
3770 *len = security_policydb_len(state);
3772 *data = vmalloc_user(*len);
3779 read_lock(&state->ss->policy_rwlock);
3780 rc = policydb_write(policydb, &fp);
3781 read_unlock(&state->ss->policy_rwlock);
3786 *len = (unsigned long)fp.data - (unsigned long)*data;