2 * Implementation of the security services.
4 * Authors : Stephen Smalley, <sds@epoch.ncsc.mil>
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.moore@hp.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 * Copyright (C) 2008, 2009 NEC Corporation
30 * Copyright (C) 2006, 2007 Hewlett-Packard Development Company, L.P.
31 * Copyright (C) 2004-2006 Trusted Computer Solutions, Inc.
32 * Copyright (C) 2003 - 2004, 2006 Tresys Technology, LLC
33 * Copyright (C) 2003 Red Hat, Inc., James Morris <jmorris@redhat.com>
34 * This program is free software; you can redistribute it and/or modify
35 * it under the terms of the GNU General Public License as published by
36 * the Free Software Foundation, version 2.
38 #include <linux/kernel.h>
39 #include <linux/slab.h>
40 #include <linux/string.h>
41 #include <linux/spinlock.h>
42 #include <linux/rcupdate.h>
43 #include <linux/errno.h>
45 #include <linux/sched.h>
46 #include <linux/audit.h>
47 #include <linux/mutex.h>
48 #include <linux/selinux.h>
49 #include <net/netlabel.h>
59 #include "conditional.h"
67 extern void selnl_notify_policyload(u32 seqno);
68 unsigned int policydb_loaded_version;
70 int selinux_policycap_netpeer;
71 int selinux_policycap_openperm;
73 static DEFINE_RWLOCK(policy_rwlock);
75 static struct sidtab sidtab;
76 struct policydb policydb;
80 * The largest sequence number that has been used when
81 * providing an access decision to the access vector cache.
82 * The sequence number only changes when a policy change
85 static u32 latest_granting;
87 /* Forward declaration. */
88 static int context_struct_to_string(struct context *context, char **scontext,
91 static int context_struct_compute_av(struct context *scontext,
92 struct context *tcontext,
95 struct av_decision *avd);
97 struct selinux_mapping {
98 u16 value; /* policy value */
100 u32 perms[sizeof(u32) * 8];
103 static struct selinux_mapping *current_mapping;
104 static u16 current_mapping_size;
106 static int selinux_set_mapping(struct policydb *pol,
107 struct security_class_mapping *map,
108 struct selinux_mapping **out_map_p,
111 struct selinux_mapping *out_map = NULL;
112 size_t size = sizeof(struct selinux_mapping);
115 bool print_unknown_handle = false;
117 /* Find number of classes in the input mapping */
124 /* Allocate space for the class records, plus one for class zero */
125 out_map = kcalloc(++i, size, GFP_ATOMIC);
129 /* Store the raw class and permission values */
131 while (map[j].name) {
132 struct security_class_mapping *p_in = map + (j++);
133 struct selinux_mapping *p_out = out_map + j;
135 /* An empty class string skips ahead */
136 if (!strcmp(p_in->name, "")) {
137 p_out->num_perms = 0;
141 p_out->value = string_to_security_class(pol, p_in->name);
144 "SELinux: Class %s not defined in policy.\n",
146 if (pol->reject_unknown)
148 p_out->num_perms = 0;
149 print_unknown_handle = true;
154 while (p_in->perms && p_in->perms[k]) {
155 /* An empty permission string skips ahead */
156 if (!*p_in->perms[k]) {
160 p_out->perms[k] = string_to_av_perm(pol, p_out->value,
162 if (!p_out->perms[k]) {
164 "SELinux: Permission %s in class %s not defined in policy.\n",
165 p_in->perms[k], p_in->name);
166 if (pol->reject_unknown)
168 print_unknown_handle = true;
173 p_out->num_perms = k;
176 if (print_unknown_handle)
177 printk(KERN_INFO "SELinux: the above unknown classes and permissions will be %s\n",
178 pol->allow_unknown ? "allowed" : "denied");
180 *out_map_p = out_map;
189 * Get real, policy values from mapped values
192 static u16 unmap_class(u16 tclass)
194 if (tclass < current_mapping_size)
195 return current_mapping[tclass].value;
200 static u32 unmap_perm(u16 tclass, u32 tperm)
202 if (tclass < current_mapping_size) {
206 for (i = 0; i < current_mapping[tclass].num_perms; i++)
207 if (tperm & (1<<i)) {
208 kperm |= current_mapping[tclass].perms[i];
217 static void map_decision(u16 tclass, struct av_decision *avd,
220 if (tclass < current_mapping_size) {
221 unsigned i, n = current_mapping[tclass].num_perms;
224 for (i = 0, result = 0; i < n; i++) {
225 if (avd->allowed & current_mapping[tclass].perms[i])
227 if (allow_unknown && !current_mapping[tclass].perms[i])
230 avd->allowed = result;
232 for (i = 0, result = 0; i < n; i++)
233 if (avd->auditallow & current_mapping[tclass].perms[i])
235 avd->auditallow = result;
237 for (i = 0, result = 0; i < n; i++) {
238 if (avd->auditdeny & current_mapping[tclass].perms[i])
240 if (!allow_unknown && !current_mapping[tclass].perms[i])
243 avd->auditdeny = result;
249 * Return the boolean value of a constraint expression
250 * when it is applied to the specified source and target
253 * xcontext is a special beast... It is used by the validatetrans rules
254 * only. For these rules, scontext is the context before the transition,
255 * tcontext is the context after the transition, and xcontext is the context
256 * of the process performing the transition. All other callers of
257 * constraint_expr_eval should pass in NULL for xcontext.
259 static int constraint_expr_eval(struct context *scontext,
260 struct context *tcontext,
261 struct context *xcontext,
262 struct constraint_expr *cexpr)
266 struct role_datum *r1, *r2;
267 struct mls_level *l1, *l2;
268 struct constraint_expr *e;
269 int s[CEXPR_MAXDEPTH];
272 for (e = cexpr; e; e = e->next) {
273 switch (e->expr_type) {
289 if (sp == (CEXPR_MAXDEPTH-1))
293 val1 = scontext->user;
294 val2 = tcontext->user;
297 val1 = scontext->type;
298 val2 = tcontext->type;
301 val1 = scontext->role;
302 val2 = tcontext->role;
303 r1 = policydb.role_val_to_struct[val1 - 1];
304 r2 = policydb.role_val_to_struct[val2 - 1];
307 s[++sp] = ebitmap_get_bit(&r1->dominates,
311 s[++sp] = ebitmap_get_bit(&r2->dominates,
315 s[++sp] = (!ebitmap_get_bit(&r1->dominates,
317 !ebitmap_get_bit(&r2->dominates,
325 l1 = &(scontext->range.level[0]);
326 l2 = &(tcontext->range.level[0]);
329 l1 = &(scontext->range.level[0]);
330 l2 = &(tcontext->range.level[1]);
333 l1 = &(scontext->range.level[1]);
334 l2 = &(tcontext->range.level[0]);
337 l1 = &(scontext->range.level[1]);
338 l2 = &(tcontext->range.level[1]);
341 l1 = &(scontext->range.level[0]);
342 l2 = &(scontext->range.level[1]);
345 l1 = &(tcontext->range.level[0]);
346 l2 = &(tcontext->range.level[1]);
351 s[++sp] = mls_level_eq(l1, l2);
354 s[++sp] = !mls_level_eq(l1, l2);
357 s[++sp] = mls_level_dom(l1, l2);
360 s[++sp] = mls_level_dom(l2, l1);
363 s[++sp] = mls_level_incomp(l2, l1);
377 s[++sp] = (val1 == val2);
380 s[++sp] = (val1 != val2);
388 if (sp == (CEXPR_MAXDEPTH-1))
391 if (e->attr & CEXPR_TARGET)
393 else if (e->attr & CEXPR_XTARGET) {
400 if (e->attr & CEXPR_USER)
402 else if (e->attr & CEXPR_ROLE)
404 else if (e->attr & CEXPR_TYPE)
413 s[++sp] = ebitmap_get_bit(&e->names, val1 - 1);
416 s[++sp] = !ebitmap_get_bit(&e->names, val1 - 1);
434 * security_dump_masked_av - dumps masked permissions during
435 * security_compute_av due to RBAC, MLS/Constraint and Type bounds.
437 static int dump_masked_av_helper(void *k, void *d, void *args)
439 struct perm_datum *pdatum = d;
440 char **permission_names = args;
442 BUG_ON(pdatum->value < 1 || pdatum->value > 32);
444 permission_names[pdatum->value - 1] = (char *)k;
449 static void security_dump_masked_av(struct context *scontext,
450 struct context *tcontext,
455 struct common_datum *common_dat;
456 struct class_datum *tclass_dat;
457 struct audit_buffer *ab;
459 char *scontext_name = NULL;
460 char *tcontext_name = NULL;
461 char *permission_names[32];
463 bool need_comma = false;
468 tclass_name = policydb.p_class_val_to_name[tclass - 1];
469 tclass_dat = policydb.class_val_to_struct[tclass - 1];
470 common_dat = tclass_dat->comdatum;
472 /* init permission_names */
474 hashtab_map(common_dat->permissions.table,
475 dump_masked_av_helper, permission_names) < 0)
478 if (hashtab_map(tclass_dat->permissions.table,
479 dump_masked_av_helper, permission_names) < 0)
482 /* get scontext/tcontext in text form */
483 if (context_struct_to_string(scontext,
484 &scontext_name, &length) < 0)
487 if (context_struct_to_string(tcontext,
488 &tcontext_name, &length) < 0)
491 /* audit a message */
492 ab = audit_log_start(current->audit_context,
493 GFP_ATOMIC, AUDIT_SELINUX_ERR);
497 audit_log_format(ab, "op=security_compute_av reason=%s "
498 "scontext=%s tcontext=%s tclass=%s perms=",
499 reason, scontext_name, tcontext_name, tclass_name);
501 for (index = 0; index < 32; index++) {
502 u32 mask = (1 << index);
504 if ((mask & permissions) == 0)
507 audit_log_format(ab, "%s%s",
508 need_comma ? "," : "",
509 permission_names[index]
510 ? permission_names[index] : "????");
515 /* release scontext/tcontext */
516 kfree(tcontext_name);
517 kfree(scontext_name);
523 * security_boundary_permission - drops violated permissions
524 * on boundary constraint.
526 static void type_attribute_bounds_av(struct context *scontext,
527 struct context *tcontext,
530 struct av_decision *avd)
532 struct context lo_scontext;
533 struct context lo_tcontext;
534 struct av_decision lo_avd;
535 struct type_datum *source
536 = policydb.type_val_to_struct[scontext->type - 1];
537 struct type_datum *target
538 = policydb.type_val_to_struct[tcontext->type - 1];
541 if (source->bounds) {
542 memset(&lo_avd, 0, sizeof(lo_avd));
544 memcpy(&lo_scontext, scontext, sizeof(lo_scontext));
545 lo_scontext.type = source->bounds;
547 context_struct_compute_av(&lo_scontext,
552 if ((lo_avd.allowed & avd->allowed) == avd->allowed)
553 return; /* no masked permission */
554 masked = ~lo_avd.allowed & avd->allowed;
557 if (target->bounds) {
558 memset(&lo_avd, 0, sizeof(lo_avd));
560 memcpy(&lo_tcontext, tcontext, sizeof(lo_tcontext));
561 lo_tcontext.type = target->bounds;
563 context_struct_compute_av(scontext,
568 if ((lo_avd.allowed & avd->allowed) == avd->allowed)
569 return; /* no masked permission */
570 masked = ~lo_avd.allowed & avd->allowed;
573 if (source->bounds && target->bounds) {
574 memset(&lo_avd, 0, sizeof(lo_avd));
576 * lo_scontext and lo_tcontext are already
580 context_struct_compute_av(&lo_scontext,
585 if ((lo_avd.allowed & avd->allowed) == avd->allowed)
586 return; /* no masked permission */
587 masked = ~lo_avd.allowed & avd->allowed;
591 /* mask violated permissions */
592 avd->allowed &= ~masked;
594 /* audit masked permissions */
595 security_dump_masked_av(scontext, tcontext,
596 tclass, masked, "bounds");
601 * Compute access vectors based on a context structure pair for
602 * the permissions in a particular class.
604 static int context_struct_compute_av(struct context *scontext,
605 struct context *tcontext,
608 struct av_decision *avd)
610 struct constraint_node *constraint;
611 struct role_allow *ra;
612 struct avtab_key avkey;
613 struct avtab_node *node;
614 struct class_datum *tclass_datum;
615 struct ebitmap *sattr, *tattr;
616 struct ebitmap_node *snode, *tnode;
620 * Remap extended Netlink classes for old policy versions.
621 * Do this here rather than socket_type_to_security_class()
622 * in case a newer policy version is loaded, allowing sockets
623 * to remain in the correct class.
625 if (policydb_loaded_version < POLICYDB_VERSION_NLCLASS)
626 if (tclass >= unmap_class(SECCLASS_NETLINK_ROUTE_SOCKET) &&
627 tclass <= unmap_class(SECCLASS_NETLINK_DNRT_SOCKET))
628 tclass = unmap_class(SECCLASS_NETLINK_SOCKET);
631 * Initialize the access vectors to the default values.
635 avd->auditdeny = 0xffffffff;
636 avd->seqno = latest_granting;
639 if (unlikely(!tclass || tclass > policydb.p_classes.nprim)) {
640 if (printk_ratelimit())
641 printk(KERN_WARNING "SELinux: Invalid class %hu\n", tclass);
645 tclass_datum = policydb.class_val_to_struct[tclass - 1];
648 * If a specific type enforcement rule was defined for
649 * this permission check, then use it.
651 avkey.target_class = tclass;
652 avkey.specified = AVTAB_AV;
653 sattr = &policydb.type_attr_map[scontext->type - 1];
654 tattr = &policydb.type_attr_map[tcontext->type - 1];
655 ebitmap_for_each_positive_bit(sattr, snode, i) {
656 ebitmap_for_each_positive_bit(tattr, tnode, j) {
657 avkey.source_type = i + 1;
658 avkey.target_type = j + 1;
659 for (node = avtab_search_node(&policydb.te_avtab, &avkey);
661 node = avtab_search_node_next(node, avkey.specified)) {
662 if (node->key.specified == AVTAB_ALLOWED)
663 avd->allowed |= node->datum.data;
664 else if (node->key.specified == AVTAB_AUDITALLOW)
665 avd->auditallow |= node->datum.data;
666 else if (node->key.specified == AVTAB_AUDITDENY)
667 avd->auditdeny &= node->datum.data;
670 /* Check conditional av table for additional permissions */
671 cond_compute_av(&policydb.te_cond_avtab, &avkey, avd);
677 * Remove any permissions prohibited by a constraint (this includes
680 constraint = tclass_datum->constraints;
682 if ((constraint->permissions & (avd->allowed)) &&
683 !constraint_expr_eval(scontext, tcontext, NULL,
685 avd->allowed &= ~(constraint->permissions);
687 constraint = constraint->next;
691 * If checking process transition permission and the
692 * role is changing, then check the (current_role, new_role)
695 if (tclass == policydb.process_class &&
696 (avd->allowed & policydb.process_trans_perms) &&
697 scontext->role != tcontext->role) {
698 for (ra = policydb.role_allow; ra; ra = ra->next) {
699 if (scontext->role == ra->role &&
700 tcontext->role == ra->new_role)
704 avd->allowed &= ~policydb.process_trans_perms;
708 * If the given source and target types have boundary
709 * constraint, lazy checks have to mask any violated
710 * permission and notice it to userspace via audit.
712 type_attribute_bounds_av(scontext, tcontext,
713 tclass, requested, avd);
718 static int security_validtrans_handle_fail(struct context *ocontext,
719 struct context *ncontext,
720 struct context *tcontext,
723 char *o = NULL, *n = NULL, *t = NULL;
724 u32 olen, nlen, tlen;
726 if (context_struct_to_string(ocontext, &o, &olen) < 0)
728 if (context_struct_to_string(ncontext, &n, &nlen) < 0)
730 if (context_struct_to_string(tcontext, &t, &tlen) < 0)
732 audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
733 "security_validate_transition: denied for"
734 " oldcontext=%s newcontext=%s taskcontext=%s tclass=%s",
735 o, n, t, policydb.p_class_val_to_name[tclass-1]);
741 if (!selinux_enforcing)
746 int security_validate_transition(u32 oldsid, u32 newsid, u32 tasksid,
749 struct context *ocontext;
750 struct context *ncontext;
751 struct context *tcontext;
752 struct class_datum *tclass_datum;
753 struct constraint_node *constraint;
760 read_lock(&policy_rwlock);
762 tclass = unmap_class(orig_tclass);
765 * Remap extended Netlink classes for old policy versions.
766 * Do this here rather than socket_type_to_security_class()
767 * in case a newer policy version is loaded, allowing sockets
768 * to remain in the correct class.
770 if (policydb_loaded_version < POLICYDB_VERSION_NLCLASS)
771 if (tclass >= unmap_class(SECCLASS_NETLINK_ROUTE_SOCKET) &&
772 tclass <= unmap_class(SECCLASS_NETLINK_DNRT_SOCKET))
773 tclass = unmap_class(SECCLASS_NETLINK_SOCKET);
775 if (!tclass || tclass > policydb.p_classes.nprim) {
776 printk(KERN_ERR "SELinux: %s: unrecognized class %d\n",
781 tclass_datum = policydb.class_val_to_struct[tclass - 1];
783 ocontext = sidtab_search(&sidtab, oldsid);
785 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
791 ncontext = sidtab_search(&sidtab, newsid);
793 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
799 tcontext = sidtab_search(&sidtab, tasksid);
801 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
807 constraint = tclass_datum->validatetrans;
809 if (!constraint_expr_eval(ocontext, ncontext, tcontext,
811 rc = security_validtrans_handle_fail(ocontext, ncontext,
815 constraint = constraint->next;
819 read_unlock(&policy_rwlock);
824 * security_bounded_transition - check whether the given
825 * transition is directed to bounded, or not.
826 * It returns 0, if @newsid is bounded by @oldsid.
827 * Otherwise, it returns error code.
829 * @oldsid : current security identifier
830 * @newsid : destinated security identifier
832 int security_bounded_transition(u32 old_sid, u32 new_sid)
834 struct context *old_context, *new_context;
835 struct type_datum *type;
839 read_lock(&policy_rwlock);
841 old_context = sidtab_search(&sidtab, old_sid);
843 printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n",
848 new_context = sidtab_search(&sidtab, new_sid);
850 printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n",
855 /* type/domain unchaned */
856 if (old_context->type == new_context->type) {
861 index = new_context->type;
863 type = policydb.type_val_to_struct[index - 1];
866 /* not bounded anymore */
872 /* @newsid is bounded by @oldsid */
873 if (type->bounds == old_context->type) {
877 index = type->bounds;
881 char *old_name = NULL;
882 char *new_name = NULL;
885 if (!context_struct_to_string(old_context,
886 &old_name, &length) &&
887 !context_struct_to_string(new_context,
888 &new_name, &length)) {
889 audit_log(current->audit_context,
890 GFP_ATOMIC, AUDIT_SELINUX_ERR,
891 "op=security_bounded_transition "
893 "oldcontext=%s newcontext=%s",
900 read_unlock(&policy_rwlock);
906 static int security_compute_av_core(u32 ssid,
910 struct av_decision *avd)
912 struct context *scontext = NULL, *tcontext = NULL;
915 scontext = sidtab_search(&sidtab, ssid);
917 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
921 tcontext = sidtab_search(&sidtab, tsid);
923 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
928 rc = context_struct_compute_av(scontext, tcontext, tclass,
931 /* permissive domain? */
932 if (ebitmap_get_bit(&policydb.permissive_map, scontext->type))
933 avd->flags |= AVD_FLAGS_PERMISSIVE;
939 * security_compute_av - Compute access vector decisions.
940 * @ssid: source security identifier
941 * @tsid: target security identifier
942 * @tclass: target security class
943 * @requested: requested permissions
944 * @avd: access vector decisions
946 * Compute a set of access vector decisions based on the
947 * SID pair (@ssid, @tsid) for the permissions in @tclass.
948 * Return -%EINVAL if any of the parameters are invalid or %0
949 * if the access vector decisions were computed successfully.
951 int security_compute_av(u32 ssid,
955 struct av_decision *avd)
964 read_lock(&policy_rwlock);
965 requested = unmap_perm(orig_tclass, orig_requested);
966 tclass = unmap_class(orig_tclass);
967 if (unlikely(orig_tclass && !tclass)) {
968 if (policydb.allow_unknown)
972 rc = security_compute_av_core(ssid, tsid, tclass, requested, avd);
973 map_decision(orig_tclass, avd, policydb.allow_unknown);
974 read_unlock(&policy_rwlock);
977 avd->allowed = 0xffffffff;
979 avd->auditdeny = 0xffffffff;
980 avd->seqno = latest_granting;
985 int security_compute_av_user(u32 ssid,
989 struct av_decision *avd)
993 if (!ss_initialized) {
994 avd->allowed = 0xffffffff;
996 avd->auditdeny = 0xffffffff;
997 avd->seqno = latest_granting;
1001 read_lock(&policy_rwlock);
1002 rc = security_compute_av_core(ssid, tsid, tclass, requested, avd);
1003 read_unlock(&policy_rwlock);
1008 * Write the security context string representation of
1009 * the context structure `context' into a dynamically
1010 * allocated string of the correct size. Set `*scontext'
1011 * to point to this string and set `*scontext_len' to
1012 * the length of the string.
1014 static int context_struct_to_string(struct context *context, char **scontext, u32 *scontext_len)
1022 *scontext_len = context->len;
1023 *scontext = kstrdup(context->str, GFP_ATOMIC);
1029 /* Compute the size of the context. */
1030 *scontext_len += strlen(policydb.p_user_val_to_name[context->user - 1]) + 1;
1031 *scontext_len += strlen(policydb.p_role_val_to_name[context->role - 1]) + 1;
1032 *scontext_len += strlen(policydb.p_type_val_to_name[context->type - 1]) + 1;
1033 *scontext_len += mls_compute_context_len(context);
1035 /* Allocate space for the context; caller must free this space. */
1036 scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
1039 *scontext = scontextp;
1042 * Copy the user name, role name and type name into the context.
1044 sprintf(scontextp, "%s:%s:%s",
1045 policydb.p_user_val_to_name[context->user - 1],
1046 policydb.p_role_val_to_name[context->role - 1],
1047 policydb.p_type_val_to_name[context->type - 1]);
1048 scontextp += strlen(policydb.p_user_val_to_name[context->user - 1]) +
1049 1 + strlen(policydb.p_role_val_to_name[context->role - 1]) +
1050 1 + strlen(policydb.p_type_val_to_name[context->type - 1]);
1052 mls_sid_to_context(context, &scontextp);
1059 #include "initial_sid_to_string.h"
1061 const char *security_get_initial_sid_context(u32 sid)
1063 if (unlikely(sid > SECINITSID_NUM))
1065 return initial_sid_to_string[sid];
1068 static int security_sid_to_context_core(u32 sid, char **scontext,
1069 u32 *scontext_len, int force)
1071 struct context *context;
1077 if (!ss_initialized) {
1078 if (sid <= SECINITSID_NUM) {
1081 *scontext_len = strlen(initial_sid_to_string[sid]) + 1;
1082 scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
1087 strcpy(scontextp, initial_sid_to_string[sid]);
1088 *scontext = scontextp;
1091 printk(KERN_ERR "SELinux: %s: called before initial "
1092 "load_policy on unknown SID %d\n", __func__, sid);
1096 read_lock(&policy_rwlock);
1098 context = sidtab_search_force(&sidtab, sid);
1100 context = sidtab_search(&sidtab, sid);
1102 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
1107 rc = context_struct_to_string(context, scontext, scontext_len);
1109 read_unlock(&policy_rwlock);
1116 * security_sid_to_context - Obtain a context for a given SID.
1117 * @sid: security identifier, SID
1118 * @scontext: security context
1119 * @scontext_len: length in bytes
1121 * Write the string representation of the context associated with @sid
1122 * into a dynamically allocated string of the correct size. Set @scontext
1123 * to point to this string and set @scontext_len to the length of the string.
1125 int security_sid_to_context(u32 sid, char **scontext, u32 *scontext_len)
1127 return security_sid_to_context_core(sid, scontext, scontext_len, 0);
1130 int security_sid_to_context_force(u32 sid, char **scontext, u32 *scontext_len)
1132 return security_sid_to_context_core(sid, scontext, scontext_len, 1);
1136 * Caveat: Mutates scontext.
1138 static int string_to_context_struct(struct policydb *pol,
1139 struct sidtab *sidtabp,
1142 struct context *ctx,
1145 struct role_datum *role;
1146 struct type_datum *typdatum;
1147 struct user_datum *usrdatum;
1148 char *scontextp, *p, oldc;
1153 /* Parse the security context. */
1156 scontextp = (char *) scontext;
1158 /* Extract the user. */
1160 while (*p && *p != ':')
1168 usrdatum = hashtab_search(pol->p_users.table, scontextp);
1172 ctx->user = usrdatum->value;
1176 while (*p && *p != ':')
1184 role = hashtab_search(pol->p_roles.table, scontextp);
1187 ctx->role = role->value;
1191 while (*p && *p != ':')
1196 typdatum = hashtab_search(pol->p_types.table, scontextp);
1197 if (!typdatum || typdatum->attribute)
1200 ctx->type = typdatum->value;
1202 rc = mls_context_to_sid(pol, oldc, &p, ctx, sidtabp, def_sid);
1206 if ((p - scontext) < scontext_len) {
1211 /* Check the validity of the new context. */
1212 if (!policydb_context_isvalid(pol, ctx)) {
1219 context_destroy(ctx);
1223 static int security_context_to_sid_core(const char *scontext, u32 scontext_len,
1224 u32 *sid, u32 def_sid, gfp_t gfp_flags,
1227 char *scontext2, *str = NULL;
1228 struct context context;
1231 if (!ss_initialized) {
1234 for (i = 1; i < SECINITSID_NUM; i++) {
1235 if (!strcmp(initial_sid_to_string[i], scontext)) {
1240 *sid = SECINITSID_KERNEL;
1245 /* Copy the string so that we can modify the copy as we parse it. */
1246 scontext2 = kmalloc(scontext_len+1, gfp_flags);
1249 memcpy(scontext2, scontext, scontext_len);
1250 scontext2[scontext_len] = 0;
1253 /* Save another copy for storing in uninterpreted form */
1254 str = kstrdup(scontext2, gfp_flags);
1261 read_lock(&policy_rwlock);
1262 rc = string_to_context_struct(&policydb, &sidtab,
1263 scontext2, scontext_len,
1265 if (rc == -EINVAL && force) {
1267 context.len = scontext_len;
1271 rc = sidtab_context_to_sid(&sidtab, &context, sid);
1272 context_destroy(&context);
1274 read_unlock(&policy_rwlock);
1281 * security_context_to_sid - Obtain a SID for a given security context.
1282 * @scontext: security context
1283 * @scontext_len: length in bytes
1284 * @sid: security identifier, SID
1286 * Obtains a SID associated with the security context that
1287 * has the string representation specified by @scontext.
1288 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1289 * memory is available, or 0 on success.
1291 int security_context_to_sid(const char *scontext, u32 scontext_len, u32 *sid)
1293 return security_context_to_sid_core(scontext, scontext_len,
1294 sid, SECSID_NULL, GFP_KERNEL, 0);
1298 * security_context_to_sid_default - Obtain a SID for a given security context,
1299 * falling back to specified default if needed.
1301 * @scontext: security context
1302 * @scontext_len: length in bytes
1303 * @sid: security identifier, SID
1304 * @def_sid: default SID to assign on error
1306 * Obtains a SID associated with the security context that
1307 * has the string representation specified by @scontext.
1308 * The default SID is passed to the MLS layer to be used to allow
1309 * kernel labeling of the MLS field if the MLS field is not present
1310 * (for upgrading to MLS without full relabel).
1311 * Implicitly forces adding of the context even if it cannot be mapped yet.
1312 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1313 * memory is available, or 0 on success.
1315 int security_context_to_sid_default(const char *scontext, u32 scontext_len,
1316 u32 *sid, u32 def_sid, gfp_t gfp_flags)
1318 return security_context_to_sid_core(scontext, scontext_len,
1319 sid, def_sid, gfp_flags, 1);
1322 int security_context_to_sid_force(const char *scontext, u32 scontext_len,
1325 return security_context_to_sid_core(scontext, scontext_len,
1326 sid, SECSID_NULL, GFP_KERNEL, 1);
1329 static int compute_sid_handle_invalid_context(
1330 struct context *scontext,
1331 struct context *tcontext,
1333 struct context *newcontext)
1335 char *s = NULL, *t = NULL, *n = NULL;
1336 u32 slen, tlen, nlen;
1338 if (context_struct_to_string(scontext, &s, &slen) < 0)
1340 if (context_struct_to_string(tcontext, &t, &tlen) < 0)
1342 if (context_struct_to_string(newcontext, &n, &nlen) < 0)
1344 audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
1345 "security_compute_sid: invalid context %s"
1349 n, s, t, policydb.p_class_val_to_name[tclass-1]);
1354 if (!selinux_enforcing)
1359 static int security_compute_sid(u32 ssid,
1366 struct context *scontext = NULL, *tcontext = NULL, newcontext;
1367 struct role_trans *roletr = NULL;
1368 struct avtab_key avkey;
1369 struct avtab_datum *avdatum;
1370 struct avtab_node *node;
1374 if (!ss_initialized) {
1375 switch (orig_tclass) {
1376 case SECCLASS_PROCESS: /* kernel value */
1386 context_init(&newcontext);
1388 read_lock(&policy_rwlock);
1391 tclass = unmap_class(orig_tclass);
1393 tclass = orig_tclass;
1395 scontext = sidtab_search(&sidtab, ssid);
1397 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
1402 tcontext = sidtab_search(&sidtab, tsid);
1404 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
1410 /* Set the user identity. */
1411 switch (specified) {
1412 case AVTAB_TRANSITION:
1414 /* Use the process user identity. */
1415 newcontext.user = scontext->user;
1418 /* Use the related object owner. */
1419 newcontext.user = tcontext->user;
1423 /* Set the role and type to default values. */
1424 if (tclass == policydb.process_class) {
1425 /* Use the current role and type of process. */
1426 newcontext.role = scontext->role;
1427 newcontext.type = scontext->type;
1429 /* Use the well-defined object role. */
1430 newcontext.role = OBJECT_R_VAL;
1431 /* Use the type of the related object. */
1432 newcontext.type = tcontext->type;
1435 /* Look for a type transition/member/change rule. */
1436 avkey.source_type = scontext->type;
1437 avkey.target_type = tcontext->type;
1438 avkey.target_class = tclass;
1439 avkey.specified = specified;
1440 avdatum = avtab_search(&policydb.te_avtab, &avkey);
1442 /* If no permanent rule, also check for enabled conditional rules */
1444 node = avtab_search_node(&policydb.te_cond_avtab, &avkey);
1445 for (; node; node = avtab_search_node_next(node, specified)) {
1446 if (node->key.specified & AVTAB_ENABLED) {
1447 avdatum = &node->datum;
1454 /* Use the type from the type transition/member/change rule. */
1455 newcontext.type = avdatum->data;
1458 /* Check for class-specific changes. */
1459 if (tclass == policydb.process_class) {
1460 if (specified & AVTAB_TRANSITION) {
1461 /* Look for a role transition rule. */
1462 for (roletr = policydb.role_tr; roletr;
1463 roletr = roletr->next) {
1464 if (roletr->role == scontext->role &&
1465 roletr->type == tcontext->type) {
1466 /* Use the role transition rule. */
1467 newcontext.role = roletr->new_role;
1474 /* Set the MLS attributes.
1475 This is done last because it may allocate memory. */
1476 rc = mls_compute_sid(scontext, tcontext, tclass, specified, &newcontext);
1480 /* Check the validity of the context. */
1481 if (!policydb_context_isvalid(&policydb, &newcontext)) {
1482 rc = compute_sid_handle_invalid_context(scontext,
1489 /* Obtain the sid for the context. */
1490 rc = sidtab_context_to_sid(&sidtab, &newcontext, out_sid);
1492 read_unlock(&policy_rwlock);
1493 context_destroy(&newcontext);
1499 * security_transition_sid - Compute the SID for a new subject/object.
1500 * @ssid: source security identifier
1501 * @tsid: target security identifier
1502 * @tclass: target security class
1503 * @out_sid: security identifier for new subject/object
1505 * Compute a SID to use for labeling a new subject or object in the
1506 * class @tclass based on a SID pair (@ssid, @tsid).
1507 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1508 * if insufficient memory is available, or %0 if the new SID was
1509 * computed successfully.
1511 int security_transition_sid(u32 ssid,
1516 return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION,
1520 int security_transition_sid_user(u32 ssid,
1525 return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION,
1530 * security_member_sid - Compute the SID for member selection.
1531 * @ssid: source security identifier
1532 * @tsid: target security identifier
1533 * @tclass: target security class
1534 * @out_sid: security identifier for selected member
1536 * Compute a SID to use when selecting a member of a polyinstantiated
1537 * object of class @tclass based on a SID pair (@ssid, @tsid).
1538 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1539 * if insufficient memory is available, or %0 if the SID was
1540 * computed successfully.
1542 int security_member_sid(u32 ssid,
1547 return security_compute_sid(ssid, tsid, tclass, AVTAB_MEMBER, out_sid,
1552 * security_change_sid - Compute the SID for object relabeling.
1553 * @ssid: source security identifier
1554 * @tsid: target security identifier
1555 * @tclass: target security class
1556 * @out_sid: security identifier for selected member
1558 * Compute a SID to use for relabeling an object of class @tclass
1559 * based on a SID pair (@ssid, @tsid).
1560 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1561 * if insufficient memory is available, or %0 if the SID was
1562 * computed successfully.
1564 int security_change_sid(u32 ssid,
1569 return security_compute_sid(ssid, tsid, tclass, AVTAB_CHANGE, out_sid,
1573 /* Clone the SID into the new SID table. */
1574 static int clone_sid(u32 sid,
1575 struct context *context,
1578 struct sidtab *s = arg;
1580 return sidtab_insert(s, sid, context);
1583 static inline int convert_context_handle_invalid_context(struct context *context)
1587 if (selinux_enforcing) {
1593 if (!context_struct_to_string(context, &s, &len)) {
1595 "SELinux: Context %s would be invalid if enforcing\n",
1603 struct convert_context_args {
1604 struct policydb *oldp;
1605 struct policydb *newp;
1609 * Convert the values in the security context
1610 * structure `c' from the values specified
1611 * in the policy `p->oldp' to the values specified
1612 * in the policy `p->newp'. Verify that the
1613 * context is valid under the new policy.
1615 static int convert_context(u32 key,
1619 struct convert_context_args *args;
1620 struct context oldc;
1621 struct role_datum *role;
1622 struct type_datum *typdatum;
1623 struct user_datum *usrdatum;
1632 s = kstrdup(c->str, GFP_KERNEL);
1637 rc = string_to_context_struct(args->newp, NULL, s,
1638 c->len, &ctx, SECSID_NULL);
1642 "SELinux: Context %s became valid (mapped).\n",
1644 /* Replace string with mapped representation. */
1646 memcpy(c, &ctx, sizeof(*c));
1648 } else if (rc == -EINVAL) {
1649 /* Retain string representation for later mapping. */
1653 /* Other error condition, e.g. ENOMEM. */
1655 "SELinux: Unable to map context %s, rc = %d.\n",
1661 rc = context_cpy(&oldc, c);
1667 /* Convert the user. */
1668 usrdatum = hashtab_search(args->newp->p_users.table,
1669 args->oldp->p_user_val_to_name[c->user - 1]);
1672 c->user = usrdatum->value;
1674 /* Convert the role. */
1675 role = hashtab_search(args->newp->p_roles.table,
1676 args->oldp->p_role_val_to_name[c->role - 1]);
1679 c->role = role->value;
1681 /* Convert the type. */
1682 typdatum = hashtab_search(args->newp->p_types.table,
1683 args->oldp->p_type_val_to_name[c->type - 1]);
1686 c->type = typdatum->value;
1688 rc = mls_convert_context(args->oldp, args->newp, c);
1692 /* Check the validity of the new context. */
1693 if (!policydb_context_isvalid(args->newp, c)) {
1694 rc = convert_context_handle_invalid_context(&oldc);
1699 context_destroy(&oldc);
1704 /* Map old representation to string and save it. */
1705 if (context_struct_to_string(&oldc, &s, &len))
1707 context_destroy(&oldc);
1712 "SELinux: Context %s became invalid (unmapped).\n",
1718 static void security_load_policycaps(void)
1720 selinux_policycap_netpeer = ebitmap_get_bit(&policydb.policycaps,
1721 POLICYDB_CAPABILITY_NETPEER);
1722 selinux_policycap_openperm = ebitmap_get_bit(&policydb.policycaps,
1723 POLICYDB_CAPABILITY_OPENPERM);
1726 extern void selinux_complete_init(void);
1727 static int security_preserve_bools(struct policydb *p);
1730 * security_load_policy - Load a security policy configuration.
1731 * @data: binary policy data
1732 * @len: length of data in bytes
1734 * Load a new set of security policy configuration data,
1735 * validate it and convert the SID table as necessary.
1736 * This function will flush the access vector cache after
1737 * loading the new policy.
1739 int security_load_policy(void *data, size_t len)
1741 struct policydb oldpolicydb, newpolicydb;
1742 struct sidtab oldsidtab, newsidtab;
1743 struct selinux_mapping *oldmap, *map = NULL;
1744 struct convert_context_args args;
1748 struct policy_file file = { data, len }, *fp = &file;
1750 if (!ss_initialized) {
1752 if (policydb_read(&policydb, fp)) {
1753 avtab_cache_destroy();
1756 if (selinux_set_mapping(&policydb, secclass_map,
1758 ¤t_mapping_size)) {
1759 policydb_destroy(&policydb);
1760 avtab_cache_destroy();
1763 if (policydb_load_isids(&policydb, &sidtab)) {
1764 policydb_destroy(&policydb);
1765 avtab_cache_destroy();
1768 security_load_policycaps();
1769 policydb_loaded_version = policydb.policyvers;
1771 seqno = ++latest_granting;
1772 selinux_complete_init();
1773 avc_ss_reset(seqno);
1774 selnl_notify_policyload(seqno);
1775 selinux_netlbl_cache_invalidate();
1776 selinux_xfrm_notify_policyload();
1781 sidtab_hash_eval(&sidtab, "sids");
1784 if (policydb_read(&newpolicydb, fp))
1787 if (sidtab_init(&newsidtab)) {
1788 policydb_destroy(&newpolicydb);
1792 if (selinux_set_mapping(&newpolicydb, secclass_map,
1796 rc = security_preserve_bools(&newpolicydb);
1798 printk(KERN_ERR "SELinux: unable to preserve booleans\n");
1802 /* Clone the SID table. */
1803 sidtab_shutdown(&sidtab);
1804 if (sidtab_map(&sidtab, clone_sid, &newsidtab)) {
1810 * Convert the internal representations of contexts
1811 * in the new SID table.
1813 args.oldp = &policydb;
1814 args.newp = &newpolicydb;
1815 rc = sidtab_map(&newsidtab, convert_context, &args);
1819 /* Save the old policydb and SID table to free later. */
1820 memcpy(&oldpolicydb, &policydb, sizeof policydb);
1821 sidtab_set(&oldsidtab, &sidtab);
1823 /* Install the new policydb and SID table. */
1824 write_lock_irq(&policy_rwlock);
1825 memcpy(&policydb, &newpolicydb, sizeof policydb);
1826 sidtab_set(&sidtab, &newsidtab);
1827 security_load_policycaps();
1828 oldmap = current_mapping;
1829 current_mapping = map;
1830 current_mapping_size = map_size;
1831 seqno = ++latest_granting;
1832 policydb_loaded_version = policydb.policyvers;
1833 write_unlock_irq(&policy_rwlock);
1835 /* Free the old policydb and SID table. */
1836 policydb_destroy(&oldpolicydb);
1837 sidtab_destroy(&oldsidtab);
1840 avc_ss_reset(seqno);
1841 selnl_notify_policyload(seqno);
1842 selinux_netlbl_cache_invalidate();
1843 selinux_xfrm_notify_policyload();
1849 sidtab_destroy(&newsidtab);
1850 policydb_destroy(&newpolicydb);
1856 * security_port_sid - Obtain the SID for a port.
1857 * @protocol: protocol number
1858 * @port: port number
1859 * @out_sid: security identifier
1861 int security_port_sid(u8 protocol, u16 port, u32 *out_sid)
1866 read_lock(&policy_rwlock);
1868 c = policydb.ocontexts[OCON_PORT];
1870 if (c->u.port.protocol == protocol &&
1871 c->u.port.low_port <= port &&
1872 c->u.port.high_port >= port)
1879 rc = sidtab_context_to_sid(&sidtab,
1885 *out_sid = c->sid[0];
1887 *out_sid = SECINITSID_PORT;
1891 read_unlock(&policy_rwlock);
1896 * security_netif_sid - Obtain the SID for a network interface.
1897 * @name: interface name
1898 * @if_sid: interface SID
1900 int security_netif_sid(char *name, u32 *if_sid)
1905 read_lock(&policy_rwlock);
1907 c = policydb.ocontexts[OCON_NETIF];
1909 if (strcmp(name, c->u.name) == 0)
1915 if (!c->sid[0] || !c->sid[1]) {
1916 rc = sidtab_context_to_sid(&sidtab,
1921 rc = sidtab_context_to_sid(&sidtab,
1927 *if_sid = c->sid[0];
1929 *if_sid = SECINITSID_NETIF;
1932 read_unlock(&policy_rwlock);
1936 static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask)
1940 for (i = 0; i < 4; i++)
1941 if (addr[i] != (input[i] & mask[i])) {
1950 * security_node_sid - Obtain the SID for a node (host).
1951 * @domain: communication domain aka address family
1953 * @addrlen: address length in bytes
1954 * @out_sid: security identifier
1956 int security_node_sid(u16 domain,
1964 read_lock(&policy_rwlock);
1970 if (addrlen != sizeof(u32)) {
1975 addr = *((u32 *)addrp);
1977 c = policydb.ocontexts[OCON_NODE];
1979 if (c->u.node.addr == (addr & c->u.node.mask))
1987 if (addrlen != sizeof(u64) * 2) {
1991 c = policydb.ocontexts[OCON_NODE6];
1993 if (match_ipv6_addrmask(addrp, c->u.node6.addr,
2001 *out_sid = SECINITSID_NODE;
2007 rc = sidtab_context_to_sid(&sidtab,
2013 *out_sid = c->sid[0];
2015 *out_sid = SECINITSID_NODE;
2019 read_unlock(&policy_rwlock);
2026 * security_get_user_sids - Obtain reachable SIDs for a user.
2027 * @fromsid: starting SID
2028 * @username: username
2029 * @sids: array of reachable SIDs for user
2030 * @nel: number of elements in @sids
2032 * Generate the set of SIDs for legal security contexts
2033 * for a given user that can be reached by @fromsid.
2034 * Set *@sids to point to a dynamically allocated
2035 * array containing the set of SIDs. Set *@nel to the
2036 * number of elements in the array.
2039 int security_get_user_sids(u32 fromsid,
2044 struct context *fromcon, usercon;
2045 u32 *mysids = NULL, *mysids2, sid;
2046 u32 mynel = 0, maxnel = SIDS_NEL;
2047 struct user_datum *user;
2048 struct role_datum *role;
2049 struct ebitmap_node *rnode, *tnode;
2055 if (!ss_initialized)
2058 read_lock(&policy_rwlock);
2060 context_init(&usercon);
2062 fromcon = sidtab_search(&sidtab, fromsid);
2068 user = hashtab_search(policydb.p_users.table, username);
2073 usercon.user = user->value;
2075 mysids = kcalloc(maxnel, sizeof(*mysids), GFP_ATOMIC);
2081 ebitmap_for_each_positive_bit(&user->roles, rnode, i) {
2082 role = policydb.role_val_to_struct[i];
2084 ebitmap_for_each_positive_bit(&role->types, tnode, j) {
2087 if (mls_setup_user_range(fromcon, user, &usercon))
2090 rc = sidtab_context_to_sid(&sidtab, &usercon, &sid);
2093 if (mynel < maxnel) {
2094 mysids[mynel++] = sid;
2097 mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
2102 memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
2105 mysids[mynel++] = sid;
2111 read_unlock(&policy_rwlock);
2117 mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);
2123 for (i = 0, j = 0; i < mynel; i++) {
2124 rc = avc_has_perm_noaudit(fromsid, mysids[i],
2125 SECCLASS_PROCESS, /* kernel value */
2126 PROCESS__TRANSITION, AVC_STRICT,
2129 mysids2[j++] = mysids[i];
2141 * security_genfs_sid - Obtain a SID for a file in a filesystem
2142 * @fstype: filesystem type
2143 * @path: path from root of mount
2144 * @sclass: file security class
2145 * @sid: SID for path
2147 * Obtain a SID to use for a file in a filesystem that
2148 * cannot support xattr or use a fixed labeling behavior like
2149 * transition SIDs or task SIDs.
2151 int security_genfs_sid(const char *fstype,
2158 struct genfs *genfs;
2160 int rc = 0, cmp = 0;
2162 while (path[0] == '/' && path[1] == '/')
2165 read_lock(&policy_rwlock);
2167 sclass = unmap_class(orig_sclass);
2169 for (genfs = policydb.genfs; genfs; genfs = genfs->next) {
2170 cmp = strcmp(fstype, genfs->fstype);
2175 if (!genfs || cmp) {
2176 *sid = SECINITSID_UNLABELED;
2181 for (c = genfs->head; c; c = c->next) {
2182 len = strlen(c->u.name);
2183 if ((!c->v.sclass || sclass == c->v.sclass) &&
2184 (strncmp(c->u.name, path, len) == 0))
2189 *sid = SECINITSID_UNLABELED;
2195 rc = sidtab_context_to_sid(&sidtab,
2204 read_unlock(&policy_rwlock);
2209 * security_fs_use - Determine how to handle labeling for a filesystem.
2210 * @fstype: filesystem type
2211 * @behavior: labeling behavior
2212 * @sid: SID for filesystem (superblock)
2214 int security_fs_use(
2216 unsigned int *behavior,
2222 read_lock(&policy_rwlock);
2224 c = policydb.ocontexts[OCON_FSUSE];
2226 if (strcmp(fstype, c->u.name) == 0)
2232 *behavior = c->v.behavior;
2234 rc = sidtab_context_to_sid(&sidtab,
2242 rc = security_genfs_sid(fstype, "/", SECCLASS_DIR, sid);
2244 *behavior = SECURITY_FS_USE_NONE;
2247 *behavior = SECURITY_FS_USE_GENFS;
2252 read_unlock(&policy_rwlock);
2256 int security_get_bools(int *len, char ***names, int **values)
2258 int i, rc = -ENOMEM;
2260 read_lock(&policy_rwlock);
2264 *len = policydb.p_bools.nprim;
2270 *names = kcalloc(*len, sizeof(char *), GFP_ATOMIC);
2274 *values = kcalloc(*len, sizeof(int), GFP_ATOMIC);
2278 for (i = 0; i < *len; i++) {
2280 (*values)[i] = policydb.bool_val_to_struct[i]->state;
2281 name_len = strlen(policydb.p_bool_val_to_name[i]) + 1;
2282 (*names)[i] = kmalloc(sizeof(char) * name_len, GFP_ATOMIC);
2285 strncpy((*names)[i], policydb.p_bool_val_to_name[i], name_len);
2286 (*names)[i][name_len - 1] = 0;
2290 read_unlock(&policy_rwlock);
2294 for (i = 0; i < *len; i++)
2302 int security_set_bools(int len, int *values)
2305 int lenp, seqno = 0;
2306 struct cond_node *cur;
2308 write_lock_irq(&policy_rwlock);
2310 lenp = policydb.p_bools.nprim;
2316 for (i = 0; i < len; i++) {
2317 if (!!values[i] != policydb.bool_val_to_struct[i]->state) {
2318 audit_log(current->audit_context, GFP_ATOMIC,
2319 AUDIT_MAC_CONFIG_CHANGE,
2320 "bool=%s val=%d old_val=%d auid=%u ses=%u",
2321 policydb.p_bool_val_to_name[i],
2323 policydb.bool_val_to_struct[i]->state,
2324 audit_get_loginuid(current),
2325 audit_get_sessionid(current));
2328 policydb.bool_val_to_struct[i]->state = 1;
2330 policydb.bool_val_to_struct[i]->state = 0;
2333 for (cur = policydb.cond_list; cur; cur = cur->next) {
2334 rc = evaluate_cond_node(&policydb, cur);
2339 seqno = ++latest_granting;
2342 write_unlock_irq(&policy_rwlock);
2344 avc_ss_reset(seqno);
2345 selnl_notify_policyload(seqno);
2346 selinux_xfrm_notify_policyload();
2351 int security_get_bool_value(int bool)
2356 read_lock(&policy_rwlock);
2358 len = policydb.p_bools.nprim;
2364 rc = policydb.bool_val_to_struct[bool]->state;
2366 read_unlock(&policy_rwlock);
2370 static int security_preserve_bools(struct policydb *p)
2372 int rc, nbools = 0, *bvalues = NULL, i;
2373 char **bnames = NULL;
2374 struct cond_bool_datum *booldatum;
2375 struct cond_node *cur;
2377 rc = security_get_bools(&nbools, &bnames, &bvalues);
2380 for (i = 0; i < nbools; i++) {
2381 booldatum = hashtab_search(p->p_bools.table, bnames[i]);
2383 booldatum->state = bvalues[i];
2385 for (cur = p->cond_list; cur; cur = cur->next) {
2386 rc = evaluate_cond_node(p, cur);
2393 for (i = 0; i < nbools; i++)
2402 * security_sid_mls_copy() - computes a new sid based on the given
2403 * sid and the mls portion of mls_sid.
2405 int security_sid_mls_copy(u32 sid, u32 mls_sid, u32 *new_sid)
2407 struct context *context1;
2408 struct context *context2;
2409 struct context newcon;
2414 if (!ss_initialized || !selinux_mls_enabled) {
2419 context_init(&newcon);
2421 read_lock(&policy_rwlock);
2422 context1 = sidtab_search(&sidtab, sid);
2424 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2430 context2 = sidtab_search(&sidtab, mls_sid);
2432 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2438 newcon.user = context1->user;
2439 newcon.role = context1->role;
2440 newcon.type = context1->type;
2441 rc = mls_context_cpy(&newcon, context2);
2445 /* Check the validity of the new context. */
2446 if (!policydb_context_isvalid(&policydb, &newcon)) {
2447 rc = convert_context_handle_invalid_context(&newcon);
2452 rc = sidtab_context_to_sid(&sidtab, &newcon, new_sid);
2456 if (!context_struct_to_string(&newcon, &s, &len)) {
2457 audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2458 "security_sid_mls_copy: invalid context %s", s);
2463 read_unlock(&policy_rwlock);
2464 context_destroy(&newcon);
2470 * security_net_peersid_resolve - Compare and resolve two network peer SIDs
2471 * @nlbl_sid: NetLabel SID
2472 * @nlbl_type: NetLabel labeling protocol type
2473 * @xfrm_sid: XFRM SID
2476 * Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be
2477 * resolved into a single SID it is returned via @peer_sid and the function
2478 * returns zero. Otherwise @peer_sid is set to SECSID_NULL and the function
2479 * returns a negative value. A table summarizing the behavior is below:
2481 * | function return | @sid
2482 * ------------------------------+-----------------+-----------------
2483 * no peer labels | 0 | SECSID_NULL
2484 * single peer label | 0 | <peer_label>
2485 * multiple, consistent labels | 0 | <peer_label>
2486 * multiple, inconsistent labels | -<errno> | SECSID_NULL
2489 int security_net_peersid_resolve(u32 nlbl_sid, u32 nlbl_type,
2494 struct context *nlbl_ctx;
2495 struct context *xfrm_ctx;
2497 /* handle the common (which also happens to be the set of easy) cases
2498 * right away, these two if statements catch everything involving a
2499 * single or absent peer SID/label */
2500 if (xfrm_sid == SECSID_NULL) {
2501 *peer_sid = nlbl_sid;
2504 /* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a "fallback" label
2505 * and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label
2507 if (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) {
2508 *peer_sid = xfrm_sid;
2512 /* we don't need to check ss_initialized here since the only way both
2513 * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the
2514 * security server was initialized and ss_initialized was true */
2515 if (!selinux_mls_enabled) {
2516 *peer_sid = SECSID_NULL;
2520 read_lock(&policy_rwlock);
2522 nlbl_ctx = sidtab_search(&sidtab, nlbl_sid);
2524 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2525 __func__, nlbl_sid);
2529 xfrm_ctx = sidtab_search(&sidtab, xfrm_sid);
2531 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2532 __func__, xfrm_sid);
2536 rc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES);
2539 read_unlock(&policy_rwlock);
2541 /* at present NetLabel SIDs/labels really only carry MLS
2542 * information so if the MLS portion of the NetLabel SID
2543 * matches the MLS portion of the labeled XFRM SID/label
2544 * then pass along the XFRM SID as it is the most
2546 *peer_sid = xfrm_sid;
2548 *peer_sid = SECSID_NULL;
2552 static int get_classes_callback(void *k, void *d, void *args)
2554 struct class_datum *datum = d;
2555 char *name = k, **classes = args;
2556 int value = datum->value - 1;
2558 classes[value] = kstrdup(name, GFP_ATOMIC);
2559 if (!classes[value])
2565 int security_get_classes(char ***classes, int *nclasses)
2569 read_lock(&policy_rwlock);
2571 *nclasses = policydb.p_classes.nprim;
2572 *classes = kcalloc(*nclasses, sizeof(*classes), GFP_ATOMIC);
2576 rc = hashtab_map(policydb.p_classes.table, get_classes_callback,
2580 for (i = 0; i < *nclasses; i++)
2581 kfree((*classes)[i]);
2586 read_unlock(&policy_rwlock);
2590 static int get_permissions_callback(void *k, void *d, void *args)
2592 struct perm_datum *datum = d;
2593 char *name = k, **perms = args;
2594 int value = datum->value - 1;
2596 perms[value] = kstrdup(name, GFP_ATOMIC);
2603 int security_get_permissions(char *class, char ***perms, int *nperms)
2605 int rc = -ENOMEM, i;
2606 struct class_datum *match;
2608 read_lock(&policy_rwlock);
2610 match = hashtab_search(policydb.p_classes.table, class);
2612 printk(KERN_ERR "SELinux: %s: unrecognized class %s\n",
2618 *nperms = match->permissions.nprim;
2619 *perms = kcalloc(*nperms, sizeof(*perms), GFP_ATOMIC);
2623 if (match->comdatum) {
2624 rc = hashtab_map(match->comdatum->permissions.table,
2625 get_permissions_callback, *perms);
2630 rc = hashtab_map(match->permissions.table, get_permissions_callback,
2636 read_unlock(&policy_rwlock);
2640 read_unlock(&policy_rwlock);
2641 for (i = 0; i < *nperms; i++)
2647 int security_get_reject_unknown(void)
2649 return policydb.reject_unknown;
2652 int security_get_allow_unknown(void)
2654 return policydb.allow_unknown;
2658 * security_policycap_supported - Check for a specific policy capability
2659 * @req_cap: capability
2662 * This function queries the currently loaded policy to see if it supports the
2663 * capability specified by @req_cap. Returns true (1) if the capability is
2664 * supported, false (0) if it isn't supported.
2667 int security_policycap_supported(unsigned int req_cap)
2671 read_lock(&policy_rwlock);
2672 rc = ebitmap_get_bit(&policydb.policycaps, req_cap);
2673 read_unlock(&policy_rwlock);
2678 struct selinux_audit_rule {
2680 struct context au_ctxt;
2683 void selinux_audit_rule_free(void *vrule)
2685 struct selinux_audit_rule *rule = vrule;
2688 context_destroy(&rule->au_ctxt);
2693 int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule)
2695 struct selinux_audit_rule *tmprule;
2696 struct role_datum *roledatum;
2697 struct type_datum *typedatum;
2698 struct user_datum *userdatum;
2699 struct selinux_audit_rule **rule = (struct selinux_audit_rule **)vrule;
2704 if (!ss_initialized)
2708 case AUDIT_SUBJ_USER:
2709 case AUDIT_SUBJ_ROLE:
2710 case AUDIT_SUBJ_TYPE:
2711 case AUDIT_OBJ_USER:
2712 case AUDIT_OBJ_ROLE:
2713 case AUDIT_OBJ_TYPE:
2714 /* only 'equals' and 'not equals' fit user, role, and type */
2715 if (op != Audit_equal && op != Audit_not_equal)
2718 case AUDIT_SUBJ_SEN:
2719 case AUDIT_SUBJ_CLR:
2720 case AUDIT_OBJ_LEV_LOW:
2721 case AUDIT_OBJ_LEV_HIGH:
2722 /* we do not allow a range, indicated by the presense of '-' */
2723 if (strchr(rulestr, '-'))
2727 /* only the above fields are valid */
2731 tmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL);
2735 context_init(&tmprule->au_ctxt);
2737 read_lock(&policy_rwlock);
2739 tmprule->au_seqno = latest_granting;
2742 case AUDIT_SUBJ_USER:
2743 case AUDIT_OBJ_USER:
2744 userdatum = hashtab_search(policydb.p_users.table, rulestr);
2748 tmprule->au_ctxt.user = userdatum->value;
2750 case AUDIT_SUBJ_ROLE:
2751 case AUDIT_OBJ_ROLE:
2752 roledatum = hashtab_search(policydb.p_roles.table, rulestr);
2756 tmprule->au_ctxt.role = roledatum->value;
2758 case AUDIT_SUBJ_TYPE:
2759 case AUDIT_OBJ_TYPE:
2760 typedatum = hashtab_search(policydb.p_types.table, rulestr);
2764 tmprule->au_ctxt.type = typedatum->value;
2766 case AUDIT_SUBJ_SEN:
2767 case AUDIT_SUBJ_CLR:
2768 case AUDIT_OBJ_LEV_LOW:
2769 case AUDIT_OBJ_LEV_HIGH:
2770 rc = mls_from_string(rulestr, &tmprule->au_ctxt, GFP_ATOMIC);
2774 read_unlock(&policy_rwlock);
2777 selinux_audit_rule_free(tmprule);
2786 /* Check to see if the rule contains any selinux fields */
2787 int selinux_audit_rule_known(struct audit_krule *rule)
2791 for (i = 0; i < rule->field_count; i++) {
2792 struct audit_field *f = &rule->fields[i];
2794 case AUDIT_SUBJ_USER:
2795 case AUDIT_SUBJ_ROLE:
2796 case AUDIT_SUBJ_TYPE:
2797 case AUDIT_SUBJ_SEN:
2798 case AUDIT_SUBJ_CLR:
2799 case AUDIT_OBJ_USER:
2800 case AUDIT_OBJ_ROLE:
2801 case AUDIT_OBJ_TYPE:
2802 case AUDIT_OBJ_LEV_LOW:
2803 case AUDIT_OBJ_LEV_HIGH:
2811 int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule,
2812 struct audit_context *actx)
2814 struct context *ctxt;
2815 struct mls_level *level;
2816 struct selinux_audit_rule *rule = vrule;
2820 audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2821 "selinux_audit_rule_match: missing rule\n");
2825 read_lock(&policy_rwlock);
2827 if (rule->au_seqno < latest_granting) {
2828 audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2829 "selinux_audit_rule_match: stale rule\n");
2834 ctxt = sidtab_search(&sidtab, sid);
2836 audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2837 "selinux_audit_rule_match: unrecognized SID %d\n",
2843 /* a field/op pair that is not caught here will simply fall through
2846 case AUDIT_SUBJ_USER:
2847 case AUDIT_OBJ_USER:
2850 match = (ctxt->user == rule->au_ctxt.user);
2852 case Audit_not_equal:
2853 match = (ctxt->user != rule->au_ctxt.user);
2857 case AUDIT_SUBJ_ROLE:
2858 case AUDIT_OBJ_ROLE:
2861 match = (ctxt->role == rule->au_ctxt.role);
2863 case Audit_not_equal:
2864 match = (ctxt->role != rule->au_ctxt.role);
2868 case AUDIT_SUBJ_TYPE:
2869 case AUDIT_OBJ_TYPE:
2872 match = (ctxt->type == rule->au_ctxt.type);
2874 case Audit_not_equal:
2875 match = (ctxt->type != rule->au_ctxt.type);
2879 case AUDIT_SUBJ_SEN:
2880 case AUDIT_SUBJ_CLR:
2881 case AUDIT_OBJ_LEV_LOW:
2882 case AUDIT_OBJ_LEV_HIGH:
2883 level = ((field == AUDIT_SUBJ_SEN ||
2884 field == AUDIT_OBJ_LEV_LOW) ?
2885 &ctxt->range.level[0] : &ctxt->range.level[1]);
2888 match = mls_level_eq(&rule->au_ctxt.range.level[0],
2891 case Audit_not_equal:
2892 match = !mls_level_eq(&rule->au_ctxt.range.level[0],
2896 match = (mls_level_dom(&rule->au_ctxt.range.level[0],
2898 !mls_level_eq(&rule->au_ctxt.range.level[0],
2902 match = mls_level_dom(&rule->au_ctxt.range.level[0],
2906 match = (mls_level_dom(level,
2907 &rule->au_ctxt.range.level[0]) &&
2908 !mls_level_eq(level,
2909 &rule->au_ctxt.range.level[0]));
2912 match = mls_level_dom(level,
2913 &rule->au_ctxt.range.level[0]);
2919 read_unlock(&policy_rwlock);
2923 static int (*aurule_callback)(void) = audit_update_lsm_rules;
2925 static int aurule_avc_callback(u32 event, u32 ssid, u32 tsid,
2926 u16 class, u32 perms, u32 *retained)
2930 if (event == AVC_CALLBACK_RESET && aurule_callback)
2931 err = aurule_callback();
2935 static int __init aurule_init(void)
2939 err = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET,
2940 SECSID_NULL, SECSID_NULL, SECCLASS_NULL, 0);
2942 panic("avc_add_callback() failed, error %d\n", err);
2946 __initcall(aurule_init);
2948 #ifdef CONFIG_NETLABEL
2950 * security_netlbl_cache_add - Add an entry to the NetLabel cache
2951 * @secattr: the NetLabel packet security attributes
2952 * @sid: the SELinux SID
2955 * Attempt to cache the context in @ctx, which was derived from the packet in
2956 * @skb, in the NetLabel subsystem cache. This function assumes @secattr has
2957 * already been initialized.
2960 static void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr,
2965 sid_cache = kmalloc(sizeof(*sid_cache), GFP_ATOMIC);
2966 if (sid_cache == NULL)
2968 secattr->cache = netlbl_secattr_cache_alloc(GFP_ATOMIC);
2969 if (secattr->cache == NULL) {
2975 secattr->cache->free = kfree;
2976 secattr->cache->data = sid_cache;
2977 secattr->flags |= NETLBL_SECATTR_CACHE;
2981 * security_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID
2982 * @secattr: the NetLabel packet security attributes
2983 * @sid: the SELinux SID
2986 * Convert the given NetLabel security attributes in @secattr into a
2987 * SELinux SID. If the @secattr field does not contain a full SELinux
2988 * SID/context then use SECINITSID_NETMSG as the foundation. If possibile the
2989 * 'cache' field of @secattr is set and the CACHE flag is set; this is to
2990 * allow the @secattr to be used by NetLabel to cache the secattr to SID
2991 * conversion for future lookups. Returns zero on success, negative values on
2995 int security_netlbl_secattr_to_sid(struct netlbl_lsm_secattr *secattr,
2999 struct context *ctx;
3000 struct context ctx_new;
3002 if (!ss_initialized) {
3007 read_lock(&policy_rwlock);
3009 if (secattr->flags & NETLBL_SECATTR_CACHE) {
3010 *sid = *(u32 *)secattr->cache->data;
3012 } else if (secattr->flags & NETLBL_SECATTR_SECID) {
3013 *sid = secattr->attr.secid;
3015 } else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) {
3016 ctx = sidtab_search(&sidtab, SECINITSID_NETMSG);
3018 goto netlbl_secattr_to_sid_return;
3020 context_init(&ctx_new);
3021 ctx_new.user = ctx->user;
3022 ctx_new.role = ctx->role;
3023 ctx_new.type = ctx->type;
3024 mls_import_netlbl_lvl(&ctx_new, secattr);
3025 if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
3026 if (ebitmap_netlbl_import(&ctx_new.range.level[0].cat,
3027 secattr->attr.mls.cat) != 0)
3028 goto netlbl_secattr_to_sid_return;
3029 memcpy(&ctx_new.range.level[1].cat,
3030 &ctx_new.range.level[0].cat,
3031 sizeof(ctx_new.range.level[0].cat));
3033 if (mls_context_isvalid(&policydb, &ctx_new) != 1)
3034 goto netlbl_secattr_to_sid_return_cleanup;
3036 rc = sidtab_context_to_sid(&sidtab, &ctx_new, sid);
3038 goto netlbl_secattr_to_sid_return_cleanup;
3040 security_netlbl_cache_add(secattr, *sid);
3042 ebitmap_destroy(&ctx_new.range.level[0].cat);
3048 netlbl_secattr_to_sid_return:
3049 read_unlock(&policy_rwlock);
3051 netlbl_secattr_to_sid_return_cleanup:
3052 ebitmap_destroy(&ctx_new.range.level[0].cat);
3053 goto netlbl_secattr_to_sid_return;
3057 * security_netlbl_sid_to_secattr - Convert a SELinux SID to a NetLabel secattr
3058 * @sid: the SELinux SID
3059 * @secattr: the NetLabel packet security attributes
3062 * Convert the given SELinux SID in @sid into a NetLabel security attribute.
3063 * Returns zero on success, negative values on failure.
3066 int security_netlbl_sid_to_secattr(u32 sid, struct netlbl_lsm_secattr *secattr)
3069 struct context *ctx;
3071 if (!ss_initialized)
3074 read_lock(&policy_rwlock);
3075 ctx = sidtab_search(&sidtab, sid);
3078 goto netlbl_sid_to_secattr_failure;
3080 secattr->domain = kstrdup(policydb.p_type_val_to_name[ctx->type - 1],
3082 if (secattr->domain == NULL) {
3084 goto netlbl_sid_to_secattr_failure;
3086 secattr->attr.secid = sid;
3087 secattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID;
3088 mls_export_netlbl_lvl(ctx, secattr);
3089 rc = mls_export_netlbl_cat(ctx, secattr);
3091 goto netlbl_sid_to_secattr_failure;
3092 read_unlock(&policy_rwlock);
3096 netlbl_sid_to_secattr_failure:
3097 read_unlock(&policy_rwlock);
3100 #endif /* CONFIG_NETLABEL */