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 * Updated: Guido Trentalancia <guido@trentalancia.com>
31 * Added support for runtime switching of the policy type
33 * Copyright (C) 2008, 2009 NEC Corporation
34 * Copyright (C) 2006, 2007 Hewlett-Packard Development Company, L.P.
35 * Copyright (C) 2004-2006 Trusted Computer Solutions, Inc.
36 * Copyright (C) 2003 - 2004, 2006 Tresys Technology, LLC
37 * Copyright (C) 2003 Red Hat, Inc., James Morris <jmorris@redhat.com>
38 * This program is free software; you can redistribute it and/or modify
39 * it under the terms of the GNU General Public License as published by
40 * the Free Software Foundation, version 2.
42 #include <linux/kernel.h>
43 #include <linux/slab.h>
44 #include <linux/string.h>
45 #include <linux/spinlock.h>
46 #include <linux/rcupdate.h>
47 #include <linux/errno.h>
49 #include <linux/sched.h>
50 #include <linux/audit.h>
51 #include <linux/mutex.h>
52 #include <linux/selinux.h>
53 #include <linux/flex_array.h>
54 #include <net/netlabel.h>
64 #include "conditional.h"
72 extern void selnl_notify_policyload(u32 seqno);
74 int selinux_policycap_netpeer;
75 int selinux_policycap_openperm;
77 static DEFINE_RWLOCK(policy_rwlock);
79 static struct sidtab sidtab;
80 struct policydb policydb;
84 * The largest sequence number that has been used when
85 * providing an access decision to the access vector cache.
86 * The sequence number only changes when a policy change
89 static u32 latest_granting;
91 /* Forward declaration. */
92 static int context_struct_to_string(struct context *context, char **scontext,
95 static void context_struct_compute_av(struct context *scontext,
96 struct context *tcontext,
98 struct av_decision *avd);
100 struct selinux_mapping {
101 u16 value; /* policy value */
103 u32 perms[sizeof(u32) * 8];
106 static struct selinux_mapping *current_mapping;
107 static u16 current_mapping_size;
109 static int selinux_set_mapping(struct policydb *pol,
110 struct security_class_mapping *map,
111 struct selinux_mapping **out_map_p,
114 struct selinux_mapping *out_map = NULL;
115 size_t size = sizeof(struct selinux_mapping);
118 bool print_unknown_handle = false;
120 /* Find number of classes in the input mapping */
127 /* Allocate space for the class records, plus one for class zero */
128 out_map = kcalloc(++i, size, GFP_ATOMIC);
132 /* Store the raw class and permission values */
134 while (map[j].name) {
135 struct security_class_mapping *p_in = map + (j++);
136 struct selinux_mapping *p_out = out_map + j;
138 /* An empty class string skips ahead */
139 if (!strcmp(p_in->name, "")) {
140 p_out->num_perms = 0;
144 p_out->value = string_to_security_class(pol, p_in->name);
147 "SELinux: Class %s not defined in policy.\n",
149 if (pol->reject_unknown)
151 p_out->num_perms = 0;
152 print_unknown_handle = true;
157 while (p_in->perms && p_in->perms[k]) {
158 /* An empty permission string skips ahead */
159 if (!*p_in->perms[k]) {
163 p_out->perms[k] = string_to_av_perm(pol, p_out->value,
165 if (!p_out->perms[k]) {
167 "SELinux: Permission %s in class %s not defined in policy.\n",
168 p_in->perms[k], p_in->name);
169 if (pol->reject_unknown)
171 print_unknown_handle = true;
176 p_out->num_perms = k;
179 if (print_unknown_handle)
180 printk(KERN_INFO "SELinux: the above unknown classes and permissions will be %s\n",
181 pol->allow_unknown ? "allowed" : "denied");
183 *out_map_p = out_map;
192 * Get real, policy values from mapped values
195 static u16 unmap_class(u16 tclass)
197 if (tclass < current_mapping_size)
198 return current_mapping[tclass].value;
203 static void map_decision(u16 tclass, struct av_decision *avd,
206 if (tclass < current_mapping_size) {
207 unsigned i, n = current_mapping[tclass].num_perms;
210 for (i = 0, result = 0; i < n; i++) {
211 if (avd->allowed & current_mapping[tclass].perms[i])
213 if (allow_unknown && !current_mapping[tclass].perms[i])
216 avd->allowed = result;
218 for (i = 0, result = 0; i < n; i++)
219 if (avd->auditallow & current_mapping[tclass].perms[i])
221 avd->auditallow = result;
223 for (i = 0, result = 0; i < n; i++) {
224 if (avd->auditdeny & current_mapping[tclass].perms[i])
226 if (!allow_unknown && !current_mapping[tclass].perms[i])
230 * In case the kernel has a bug and requests a permission
231 * between num_perms and the maximum permission number, we
232 * should audit that denial
234 for (; i < (sizeof(u32)*8); i++)
236 avd->auditdeny = result;
240 int security_mls_enabled(void)
242 return policydb.mls_enabled;
246 * Return the boolean value of a constraint expression
247 * when it is applied to the specified source and target
250 * xcontext is a special beast... It is used by the validatetrans rules
251 * only. For these rules, scontext is the context before the transition,
252 * tcontext is the context after the transition, and xcontext is the context
253 * of the process performing the transition. All other callers of
254 * constraint_expr_eval should pass in NULL for xcontext.
256 static int constraint_expr_eval(struct context *scontext,
257 struct context *tcontext,
258 struct context *xcontext,
259 struct constraint_expr *cexpr)
263 struct role_datum *r1, *r2;
264 struct mls_level *l1, *l2;
265 struct constraint_expr *e;
266 int s[CEXPR_MAXDEPTH];
269 for (e = cexpr; e; e = e->next) {
270 switch (e->expr_type) {
286 if (sp == (CEXPR_MAXDEPTH - 1))
290 val1 = scontext->user;
291 val2 = tcontext->user;
294 val1 = scontext->type;
295 val2 = tcontext->type;
298 val1 = scontext->role;
299 val2 = tcontext->role;
300 r1 = policydb.role_val_to_struct[val1 - 1];
301 r2 = policydb.role_val_to_struct[val2 - 1];
304 s[++sp] = ebitmap_get_bit(&r1->dominates,
308 s[++sp] = ebitmap_get_bit(&r2->dominates,
312 s[++sp] = (!ebitmap_get_bit(&r1->dominates,
314 !ebitmap_get_bit(&r2->dominates,
322 l1 = &(scontext->range.level[0]);
323 l2 = &(tcontext->range.level[0]);
326 l1 = &(scontext->range.level[0]);
327 l2 = &(tcontext->range.level[1]);
330 l1 = &(scontext->range.level[1]);
331 l2 = &(tcontext->range.level[0]);
334 l1 = &(scontext->range.level[1]);
335 l2 = &(tcontext->range.level[1]);
338 l1 = &(scontext->range.level[0]);
339 l2 = &(scontext->range.level[1]);
342 l1 = &(tcontext->range.level[0]);
343 l2 = &(tcontext->range.level[1]);
348 s[++sp] = mls_level_eq(l1, l2);
351 s[++sp] = !mls_level_eq(l1, l2);
354 s[++sp] = mls_level_dom(l1, l2);
357 s[++sp] = mls_level_dom(l2, l1);
360 s[++sp] = mls_level_incomp(l2, l1);
374 s[++sp] = (val1 == val2);
377 s[++sp] = (val1 != val2);
385 if (sp == (CEXPR_MAXDEPTH-1))
388 if (e->attr & CEXPR_TARGET)
390 else if (e->attr & CEXPR_XTARGET) {
397 if (e->attr & CEXPR_USER)
399 else if (e->attr & CEXPR_ROLE)
401 else if (e->attr & CEXPR_TYPE)
410 s[++sp] = ebitmap_get_bit(&e->names, val1 - 1);
413 s[++sp] = !ebitmap_get_bit(&e->names, val1 - 1);
431 * security_dump_masked_av - dumps masked permissions during
432 * security_compute_av due to RBAC, MLS/Constraint and Type bounds.
434 static int dump_masked_av_helper(void *k, void *d, void *args)
436 struct perm_datum *pdatum = d;
437 char **permission_names = args;
439 BUG_ON(pdatum->value < 1 || pdatum->value > 32);
441 permission_names[pdatum->value - 1] = (char *)k;
446 static void security_dump_masked_av(struct context *scontext,
447 struct context *tcontext,
452 struct common_datum *common_dat;
453 struct class_datum *tclass_dat;
454 struct audit_buffer *ab;
456 char *scontext_name = NULL;
457 char *tcontext_name = NULL;
458 char *permission_names[32];
461 bool need_comma = false;
466 tclass_name = policydb.p_class_val_to_name[tclass - 1];
467 tclass_dat = policydb.class_val_to_struct[tclass - 1];
468 common_dat = tclass_dat->comdatum;
470 /* init permission_names */
472 hashtab_map(common_dat->permissions.table,
473 dump_masked_av_helper, permission_names) < 0)
476 if (hashtab_map(tclass_dat->permissions.table,
477 dump_masked_av_helper, permission_names) < 0)
480 /* get scontext/tcontext in text form */
481 if (context_struct_to_string(scontext,
482 &scontext_name, &length) < 0)
485 if (context_struct_to_string(tcontext,
486 &tcontext_name, &length) < 0)
489 /* audit a message */
490 ab = audit_log_start(current->audit_context,
491 GFP_ATOMIC, AUDIT_SELINUX_ERR);
495 audit_log_format(ab, "op=security_compute_av reason=%s "
496 "scontext=%s tcontext=%s tclass=%s perms=",
497 reason, scontext_name, tcontext_name, tclass_name);
499 for (index = 0; index < 32; index++) {
500 u32 mask = (1 << index);
502 if ((mask & permissions) == 0)
505 audit_log_format(ab, "%s%s",
506 need_comma ? "," : "",
507 permission_names[index]
508 ? permission_names[index] : "????");
513 /* release scontext/tcontext */
514 kfree(tcontext_name);
515 kfree(scontext_name);
521 * security_boundary_permission - drops violated permissions
522 * on boundary constraint.
524 static void type_attribute_bounds_av(struct context *scontext,
525 struct context *tcontext,
527 struct av_decision *avd)
529 struct context lo_scontext;
530 struct context lo_tcontext;
531 struct av_decision lo_avd;
532 struct type_datum *source
533 = policydb.type_val_to_struct[scontext->type - 1];
534 struct type_datum *target
535 = policydb.type_val_to_struct[tcontext->type - 1];
538 if (source->bounds) {
539 memset(&lo_avd, 0, sizeof(lo_avd));
541 memcpy(&lo_scontext, scontext, sizeof(lo_scontext));
542 lo_scontext.type = source->bounds;
544 context_struct_compute_av(&lo_scontext,
548 if ((lo_avd.allowed & avd->allowed) == avd->allowed)
549 return; /* no masked permission */
550 masked = ~lo_avd.allowed & avd->allowed;
553 if (target->bounds) {
554 memset(&lo_avd, 0, sizeof(lo_avd));
556 memcpy(&lo_tcontext, tcontext, sizeof(lo_tcontext));
557 lo_tcontext.type = target->bounds;
559 context_struct_compute_av(scontext,
563 if ((lo_avd.allowed & avd->allowed) == avd->allowed)
564 return; /* no masked permission */
565 masked = ~lo_avd.allowed & avd->allowed;
568 if (source->bounds && target->bounds) {
569 memset(&lo_avd, 0, sizeof(lo_avd));
571 * lo_scontext and lo_tcontext are already
575 context_struct_compute_av(&lo_scontext,
579 if ((lo_avd.allowed & avd->allowed) == avd->allowed)
580 return; /* no masked permission */
581 masked = ~lo_avd.allowed & avd->allowed;
585 /* mask violated permissions */
586 avd->allowed &= ~masked;
588 /* audit masked permissions */
589 security_dump_masked_av(scontext, tcontext,
590 tclass, masked, "bounds");
595 * Compute access vectors based on a context structure pair for
596 * the permissions in a particular class.
598 static void context_struct_compute_av(struct context *scontext,
599 struct context *tcontext,
601 struct av_decision *avd)
603 struct constraint_node *constraint;
604 struct role_allow *ra;
605 struct avtab_key avkey;
606 struct avtab_node *node;
607 struct class_datum *tclass_datum;
608 struct ebitmap *sattr, *tattr;
609 struct ebitmap_node *snode, *tnode;
614 avd->auditdeny = 0xffffffff;
616 if (unlikely(!tclass || tclass > policydb.p_classes.nprim)) {
617 if (printk_ratelimit())
618 printk(KERN_WARNING "SELinux: Invalid class %hu\n", tclass);
622 tclass_datum = policydb.class_val_to_struct[tclass - 1];
625 * If a specific type enforcement rule was defined for
626 * this permission check, then use it.
628 avkey.target_class = tclass;
629 avkey.specified = AVTAB_AV;
630 sattr = flex_array_get(policydb.type_attr_map_array, scontext->type - 1);
632 tattr = flex_array_get(policydb.type_attr_map_array, tcontext->type - 1);
634 ebitmap_for_each_positive_bit(sattr, snode, i) {
635 ebitmap_for_each_positive_bit(tattr, tnode, j) {
636 avkey.source_type = i + 1;
637 avkey.target_type = j + 1;
638 for (node = avtab_search_node(&policydb.te_avtab, &avkey);
640 node = avtab_search_node_next(node, avkey.specified)) {
641 if (node->key.specified == AVTAB_ALLOWED)
642 avd->allowed |= node->datum.data;
643 else if (node->key.specified == AVTAB_AUDITALLOW)
644 avd->auditallow |= node->datum.data;
645 else if (node->key.specified == AVTAB_AUDITDENY)
646 avd->auditdeny &= node->datum.data;
649 /* Check conditional av table for additional permissions */
650 cond_compute_av(&policydb.te_cond_avtab, &avkey, avd);
656 * Remove any permissions prohibited by a constraint (this includes
659 constraint = tclass_datum->constraints;
661 if ((constraint->permissions & (avd->allowed)) &&
662 !constraint_expr_eval(scontext, tcontext, NULL,
664 avd->allowed &= ~(constraint->permissions);
666 constraint = constraint->next;
670 * If checking process transition permission and the
671 * role is changing, then check the (current_role, new_role)
674 if (tclass == policydb.process_class &&
675 (avd->allowed & policydb.process_trans_perms) &&
676 scontext->role != tcontext->role) {
677 for (ra = policydb.role_allow; ra; ra = ra->next) {
678 if (scontext->role == ra->role &&
679 tcontext->role == ra->new_role)
683 avd->allowed &= ~policydb.process_trans_perms;
687 * If the given source and target types have boundary
688 * constraint, lazy checks have to mask any violated
689 * permission and notice it to userspace via audit.
691 type_attribute_bounds_av(scontext, tcontext,
695 static int security_validtrans_handle_fail(struct context *ocontext,
696 struct context *ncontext,
697 struct context *tcontext,
700 char *o = NULL, *n = NULL, *t = NULL;
701 u32 olen, nlen, tlen;
703 if (context_struct_to_string(ocontext, &o, &olen) < 0)
705 if (context_struct_to_string(ncontext, &n, &nlen) < 0)
707 if (context_struct_to_string(tcontext, &t, &tlen) < 0)
709 audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
710 "security_validate_transition: denied for"
711 " oldcontext=%s newcontext=%s taskcontext=%s tclass=%s",
712 o, n, t, policydb.p_class_val_to_name[tclass-1]);
718 if (!selinux_enforcing)
723 int security_validate_transition(u32 oldsid, u32 newsid, u32 tasksid,
726 struct context *ocontext;
727 struct context *ncontext;
728 struct context *tcontext;
729 struct class_datum *tclass_datum;
730 struct constraint_node *constraint;
737 read_lock(&policy_rwlock);
739 tclass = unmap_class(orig_tclass);
741 if (!tclass || tclass > policydb.p_classes.nprim) {
742 printk(KERN_ERR "SELinux: %s: unrecognized class %d\n",
747 tclass_datum = policydb.class_val_to_struct[tclass - 1];
749 ocontext = sidtab_search(&sidtab, oldsid);
751 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
757 ncontext = sidtab_search(&sidtab, newsid);
759 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
765 tcontext = sidtab_search(&sidtab, tasksid);
767 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
773 constraint = tclass_datum->validatetrans;
775 if (!constraint_expr_eval(ocontext, ncontext, tcontext,
777 rc = security_validtrans_handle_fail(ocontext, ncontext,
781 constraint = constraint->next;
785 read_unlock(&policy_rwlock);
790 * security_bounded_transition - check whether the given
791 * transition is directed to bounded, or not.
792 * It returns 0, if @newsid is bounded by @oldsid.
793 * Otherwise, it returns error code.
795 * @oldsid : current security identifier
796 * @newsid : destinated security identifier
798 int security_bounded_transition(u32 old_sid, u32 new_sid)
800 struct context *old_context, *new_context;
801 struct type_datum *type;
805 read_lock(&policy_rwlock);
807 old_context = sidtab_search(&sidtab, old_sid);
809 printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n",
814 new_context = sidtab_search(&sidtab, new_sid);
816 printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n",
821 /* type/domain unchanged */
822 if (old_context->type == new_context->type) {
827 index = new_context->type;
829 type = policydb.type_val_to_struct[index - 1];
832 /* not bounded anymore */
838 /* @newsid is bounded by @oldsid */
839 if (type->bounds == old_context->type) {
843 index = type->bounds;
847 char *old_name = NULL;
848 char *new_name = NULL;
851 if (!context_struct_to_string(old_context,
852 &old_name, &length) &&
853 !context_struct_to_string(new_context,
854 &new_name, &length)) {
855 audit_log(current->audit_context,
856 GFP_ATOMIC, AUDIT_SELINUX_ERR,
857 "op=security_bounded_transition "
859 "oldcontext=%s newcontext=%s",
866 read_unlock(&policy_rwlock);
871 static void avd_init(struct av_decision *avd)
875 avd->auditdeny = 0xffffffff;
876 avd->seqno = latest_granting;
882 * security_compute_av - Compute access vector decisions.
883 * @ssid: source security identifier
884 * @tsid: target security identifier
885 * @tclass: target security class
886 * @avd: access vector decisions
888 * Compute a set of access vector decisions based on the
889 * SID pair (@ssid, @tsid) for the permissions in @tclass.
891 void security_compute_av(u32 ssid,
894 struct av_decision *avd)
897 struct context *scontext = NULL, *tcontext = NULL;
899 read_lock(&policy_rwlock);
904 scontext = sidtab_search(&sidtab, ssid);
906 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
911 /* permissive domain? */
912 if (ebitmap_get_bit(&policydb.permissive_map, scontext->type))
913 avd->flags |= AVD_FLAGS_PERMISSIVE;
915 tcontext = sidtab_search(&sidtab, tsid);
917 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
922 tclass = unmap_class(orig_tclass);
923 if (unlikely(orig_tclass && !tclass)) {
924 if (policydb.allow_unknown)
928 context_struct_compute_av(scontext, tcontext, tclass, avd);
929 map_decision(orig_tclass, avd, policydb.allow_unknown);
931 read_unlock(&policy_rwlock);
934 avd->allowed = 0xffffffff;
938 void security_compute_av_user(u32 ssid,
941 struct av_decision *avd)
943 struct context *scontext = NULL, *tcontext = NULL;
945 read_lock(&policy_rwlock);
950 scontext = sidtab_search(&sidtab, ssid);
952 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
957 /* permissive domain? */
958 if (ebitmap_get_bit(&policydb.permissive_map, scontext->type))
959 avd->flags |= AVD_FLAGS_PERMISSIVE;
961 tcontext = sidtab_search(&sidtab, tsid);
963 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
968 if (unlikely(!tclass)) {
969 if (policydb.allow_unknown)
974 context_struct_compute_av(scontext, tcontext, tclass, avd);
976 read_unlock(&policy_rwlock);
979 avd->allowed = 0xffffffff;
984 * Write the security context string representation of
985 * the context structure `context' into a dynamically
986 * allocated string of the correct size. Set `*scontext'
987 * to point to this string and set `*scontext_len' to
988 * the length of the string.
990 static int context_struct_to_string(struct context *context, char **scontext, u32 *scontext_len)
999 *scontext_len = context->len;
1000 *scontext = kstrdup(context->str, GFP_ATOMIC);
1006 /* Compute the size of the context. */
1007 *scontext_len += strlen(policydb.p_user_val_to_name[context->user - 1]) + 1;
1008 *scontext_len += strlen(policydb.p_role_val_to_name[context->role - 1]) + 1;
1009 *scontext_len += strlen(policydb.p_type_val_to_name[context->type - 1]) + 1;
1010 *scontext_len += mls_compute_context_len(context);
1015 /* Allocate space for the context; caller must free this space. */
1016 scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
1019 *scontext = scontextp;
1022 * Copy the user name, role name and type name into the context.
1024 sprintf(scontextp, "%s:%s:%s",
1025 policydb.p_user_val_to_name[context->user - 1],
1026 policydb.p_role_val_to_name[context->role - 1],
1027 policydb.p_type_val_to_name[context->type - 1]);
1028 scontextp += strlen(policydb.p_user_val_to_name[context->user - 1]) +
1029 1 + strlen(policydb.p_role_val_to_name[context->role - 1]) +
1030 1 + strlen(policydb.p_type_val_to_name[context->type - 1]);
1032 mls_sid_to_context(context, &scontextp);
1039 #include "initial_sid_to_string.h"
1041 const char *security_get_initial_sid_context(u32 sid)
1043 if (unlikely(sid > SECINITSID_NUM))
1045 return initial_sid_to_string[sid];
1048 static int security_sid_to_context_core(u32 sid, char **scontext,
1049 u32 *scontext_len, int force)
1051 struct context *context;
1058 if (!ss_initialized) {
1059 if (sid <= SECINITSID_NUM) {
1062 *scontext_len = strlen(initial_sid_to_string[sid]) + 1;
1065 scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
1070 strcpy(scontextp, initial_sid_to_string[sid]);
1071 *scontext = scontextp;
1074 printk(KERN_ERR "SELinux: %s: called before initial "
1075 "load_policy on unknown SID %d\n", __func__, sid);
1079 read_lock(&policy_rwlock);
1081 context = sidtab_search_force(&sidtab, sid);
1083 context = sidtab_search(&sidtab, sid);
1085 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
1090 rc = context_struct_to_string(context, scontext, scontext_len);
1092 read_unlock(&policy_rwlock);
1099 * security_sid_to_context - Obtain a context for a given SID.
1100 * @sid: security identifier, SID
1101 * @scontext: security context
1102 * @scontext_len: length in bytes
1104 * Write the string representation of the context associated with @sid
1105 * into a dynamically allocated string of the correct size. Set @scontext
1106 * to point to this string and set @scontext_len to the length of the string.
1108 int security_sid_to_context(u32 sid, char **scontext, u32 *scontext_len)
1110 return security_sid_to_context_core(sid, scontext, scontext_len, 0);
1113 int security_sid_to_context_force(u32 sid, char **scontext, u32 *scontext_len)
1115 return security_sid_to_context_core(sid, scontext, scontext_len, 1);
1119 * Caveat: Mutates scontext.
1121 static int string_to_context_struct(struct policydb *pol,
1122 struct sidtab *sidtabp,
1125 struct context *ctx,
1128 struct role_datum *role;
1129 struct type_datum *typdatum;
1130 struct user_datum *usrdatum;
1131 char *scontextp, *p, oldc;
1136 /* Parse the security context. */
1139 scontextp = (char *) scontext;
1141 /* Extract the user. */
1143 while (*p && *p != ':')
1151 usrdatum = hashtab_search(pol->p_users.table, scontextp);
1155 ctx->user = usrdatum->value;
1159 while (*p && *p != ':')
1167 role = hashtab_search(pol->p_roles.table, scontextp);
1170 ctx->role = role->value;
1174 while (*p && *p != ':')
1179 typdatum = hashtab_search(pol->p_types.table, scontextp);
1180 if (!typdatum || typdatum->attribute)
1183 ctx->type = typdatum->value;
1185 rc = mls_context_to_sid(pol, oldc, &p, ctx, sidtabp, def_sid);
1189 if ((p - scontext) < scontext_len) {
1194 /* Check the validity of the new context. */
1195 if (!policydb_context_isvalid(pol, ctx)) {
1202 context_destroy(ctx);
1206 static int security_context_to_sid_core(const char *scontext, u32 scontext_len,
1207 u32 *sid, u32 def_sid, gfp_t gfp_flags,
1210 char *scontext2, *str = NULL;
1211 struct context context;
1214 if (!ss_initialized) {
1217 for (i = 1; i < SECINITSID_NUM; i++) {
1218 if (!strcmp(initial_sid_to_string[i], scontext)) {
1223 *sid = SECINITSID_KERNEL;
1228 /* Copy the string so that we can modify the copy as we parse it. */
1229 scontext2 = kmalloc(scontext_len + 1, gfp_flags);
1232 memcpy(scontext2, scontext, scontext_len);
1233 scontext2[scontext_len] = 0;
1236 /* Save another copy for storing in uninterpreted form */
1237 str = kstrdup(scontext2, gfp_flags);
1244 read_lock(&policy_rwlock);
1245 rc = string_to_context_struct(&policydb, &sidtab,
1246 scontext2, scontext_len,
1248 if (rc == -EINVAL && force) {
1250 context.len = scontext_len;
1254 rc = sidtab_context_to_sid(&sidtab, &context, sid);
1255 context_destroy(&context);
1257 read_unlock(&policy_rwlock);
1264 * security_context_to_sid - Obtain a SID for a given security context.
1265 * @scontext: security context
1266 * @scontext_len: length in bytes
1267 * @sid: security identifier, SID
1269 * Obtains a SID associated with the security context that
1270 * has the string representation specified by @scontext.
1271 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1272 * memory is available, or 0 on success.
1274 int security_context_to_sid(const char *scontext, u32 scontext_len, u32 *sid)
1276 return security_context_to_sid_core(scontext, scontext_len,
1277 sid, SECSID_NULL, GFP_KERNEL, 0);
1281 * security_context_to_sid_default - Obtain a SID for a given security context,
1282 * falling back to specified default if needed.
1284 * @scontext: security context
1285 * @scontext_len: length in bytes
1286 * @sid: security identifier, SID
1287 * @def_sid: default SID to assign on error
1289 * Obtains a SID associated with the security context that
1290 * has the string representation specified by @scontext.
1291 * The default SID is passed to the MLS layer to be used to allow
1292 * kernel labeling of the MLS field if the MLS field is not present
1293 * (for upgrading to MLS without full relabel).
1294 * Implicitly forces adding of the context even if it cannot be mapped yet.
1295 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1296 * memory is available, or 0 on success.
1298 int security_context_to_sid_default(const char *scontext, u32 scontext_len,
1299 u32 *sid, u32 def_sid, gfp_t gfp_flags)
1301 return security_context_to_sid_core(scontext, scontext_len,
1302 sid, def_sid, gfp_flags, 1);
1305 int security_context_to_sid_force(const char *scontext, u32 scontext_len,
1308 return security_context_to_sid_core(scontext, scontext_len,
1309 sid, SECSID_NULL, GFP_KERNEL, 1);
1312 static int compute_sid_handle_invalid_context(
1313 struct context *scontext,
1314 struct context *tcontext,
1316 struct context *newcontext)
1318 char *s = NULL, *t = NULL, *n = NULL;
1319 u32 slen, tlen, nlen;
1321 if (context_struct_to_string(scontext, &s, &slen) < 0)
1323 if (context_struct_to_string(tcontext, &t, &tlen) < 0)
1325 if (context_struct_to_string(newcontext, &n, &nlen) < 0)
1327 audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
1328 "security_compute_sid: invalid context %s"
1332 n, s, t, policydb.p_class_val_to_name[tclass-1]);
1337 if (!selinux_enforcing)
1342 static int security_compute_sid(u32 ssid,
1349 struct context *scontext = NULL, *tcontext = NULL, newcontext;
1350 struct role_trans *roletr = NULL;
1351 struct avtab_key avkey;
1352 struct avtab_datum *avdatum;
1353 struct avtab_node *node;
1357 if (!ss_initialized) {
1358 switch (orig_tclass) {
1359 case SECCLASS_PROCESS: /* kernel value */
1369 context_init(&newcontext);
1371 read_lock(&policy_rwlock);
1374 tclass = unmap_class(orig_tclass);
1376 tclass = orig_tclass;
1378 scontext = sidtab_search(&sidtab, ssid);
1380 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
1385 tcontext = sidtab_search(&sidtab, tsid);
1387 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
1393 /* Set the user identity. */
1394 switch (specified) {
1395 case AVTAB_TRANSITION:
1397 /* Use the process user identity. */
1398 newcontext.user = scontext->user;
1401 /* Use the related object owner. */
1402 newcontext.user = tcontext->user;
1406 /* Set the role and type to default values. */
1407 if (tclass == policydb.process_class) {
1408 /* Use the current role and type of process. */
1409 newcontext.role = scontext->role;
1410 newcontext.type = scontext->type;
1412 /* Use the well-defined object role. */
1413 newcontext.role = OBJECT_R_VAL;
1414 /* Use the type of the related object. */
1415 newcontext.type = tcontext->type;
1418 /* Look for a type transition/member/change rule. */
1419 avkey.source_type = scontext->type;
1420 avkey.target_type = tcontext->type;
1421 avkey.target_class = tclass;
1422 avkey.specified = specified;
1423 avdatum = avtab_search(&policydb.te_avtab, &avkey);
1425 /* If no permanent rule, also check for enabled conditional rules */
1427 node = avtab_search_node(&policydb.te_cond_avtab, &avkey);
1428 for (; node; node = avtab_search_node_next(node, specified)) {
1429 if (node->key.specified & AVTAB_ENABLED) {
1430 avdatum = &node->datum;
1437 /* Use the type from the type transition/member/change rule. */
1438 newcontext.type = avdatum->data;
1441 /* Check for class-specific changes. */
1442 if (tclass == policydb.process_class) {
1443 if (specified & AVTAB_TRANSITION) {
1444 /* Look for a role transition rule. */
1445 for (roletr = policydb.role_tr; roletr;
1446 roletr = roletr->next) {
1447 if (roletr->role == scontext->role &&
1448 roletr->type == tcontext->type) {
1449 /* Use the role transition rule. */
1450 newcontext.role = roletr->new_role;
1457 /* Set the MLS attributes.
1458 This is done last because it may allocate memory. */
1459 rc = mls_compute_sid(scontext, tcontext, tclass, specified, &newcontext);
1463 /* Check the validity of the context. */
1464 if (!policydb_context_isvalid(&policydb, &newcontext)) {
1465 rc = compute_sid_handle_invalid_context(scontext,
1472 /* Obtain the sid for the context. */
1473 rc = sidtab_context_to_sid(&sidtab, &newcontext, out_sid);
1475 read_unlock(&policy_rwlock);
1476 context_destroy(&newcontext);
1482 * security_transition_sid - Compute the SID for a new subject/object.
1483 * @ssid: source security identifier
1484 * @tsid: target security identifier
1485 * @tclass: target security class
1486 * @out_sid: security identifier for new subject/object
1488 * Compute a SID to use for labeling a new subject or object in the
1489 * class @tclass based on a SID pair (@ssid, @tsid).
1490 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1491 * if insufficient memory is available, or %0 if the new SID was
1492 * computed successfully.
1494 int security_transition_sid(u32 ssid,
1499 return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION,
1503 int security_transition_sid_user(u32 ssid,
1508 return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION,
1513 * security_member_sid - Compute the SID for member selection.
1514 * @ssid: source security identifier
1515 * @tsid: target security identifier
1516 * @tclass: target security class
1517 * @out_sid: security identifier for selected member
1519 * Compute a SID to use when selecting a member of a polyinstantiated
1520 * object of class @tclass based on a SID pair (@ssid, @tsid).
1521 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1522 * if insufficient memory is available, or %0 if the SID was
1523 * computed successfully.
1525 int security_member_sid(u32 ssid,
1530 return security_compute_sid(ssid, tsid, tclass, AVTAB_MEMBER, out_sid,
1535 * security_change_sid - Compute the SID for object relabeling.
1536 * @ssid: source security identifier
1537 * @tsid: target security identifier
1538 * @tclass: target security class
1539 * @out_sid: security identifier for selected member
1541 * Compute a SID to use for relabeling an object of class @tclass
1542 * based on a SID pair (@ssid, @tsid).
1543 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1544 * if insufficient memory is available, or %0 if the SID was
1545 * computed successfully.
1547 int security_change_sid(u32 ssid,
1552 return security_compute_sid(ssid, tsid, tclass, AVTAB_CHANGE, out_sid,
1556 /* Clone the SID into the new SID table. */
1557 static int clone_sid(u32 sid,
1558 struct context *context,
1561 struct sidtab *s = arg;
1563 if (sid > SECINITSID_NUM)
1564 return sidtab_insert(s, sid, context);
1569 static inline int convert_context_handle_invalid_context(struct context *context)
1573 if (selinux_enforcing) {
1579 if (!context_struct_to_string(context, &s, &len)) {
1581 "SELinux: Context %s would be invalid if enforcing\n",
1589 struct convert_context_args {
1590 struct policydb *oldp;
1591 struct policydb *newp;
1595 * Convert the values in the security context
1596 * structure `c' from the values specified
1597 * in the policy `p->oldp' to the values specified
1598 * in the policy `p->newp'. Verify that the
1599 * context is valid under the new policy.
1601 static int convert_context(u32 key,
1605 struct convert_context_args *args;
1606 struct context oldc;
1607 struct ocontext *oc;
1608 struct mls_range *range;
1609 struct role_datum *role;
1610 struct type_datum *typdatum;
1611 struct user_datum *usrdatum;
1616 if (key <= SECINITSID_NUM)
1623 s = kstrdup(c->str, GFP_KERNEL);
1628 rc = string_to_context_struct(args->newp, NULL, s,
1629 c->len, &ctx, SECSID_NULL);
1633 "SELinux: Context %s became valid (mapped).\n",
1635 /* Replace string with mapped representation. */
1637 memcpy(c, &ctx, sizeof(*c));
1639 } else if (rc == -EINVAL) {
1640 /* Retain string representation for later mapping. */
1644 /* Other error condition, e.g. ENOMEM. */
1646 "SELinux: Unable to map context %s, rc = %d.\n",
1652 rc = context_cpy(&oldc, c);
1658 /* Convert the user. */
1659 usrdatum = hashtab_search(args->newp->p_users.table,
1660 args->oldp->p_user_val_to_name[c->user - 1]);
1663 c->user = usrdatum->value;
1665 /* Convert the role. */
1666 role = hashtab_search(args->newp->p_roles.table,
1667 args->oldp->p_role_val_to_name[c->role - 1]);
1670 c->role = role->value;
1672 /* Convert the type. */
1673 typdatum = hashtab_search(args->newp->p_types.table,
1674 args->oldp->p_type_val_to_name[c->type - 1]);
1677 c->type = typdatum->value;
1679 /* Convert the MLS fields if dealing with MLS policies */
1680 if (args->oldp->mls_enabled && args->newp->mls_enabled) {
1681 rc = mls_convert_context(args->oldp, args->newp, c);
1684 } else if (args->oldp->mls_enabled && !args->newp->mls_enabled) {
1686 * Switching between MLS and non-MLS policy:
1687 * free any storage used by the MLS fields in the
1688 * context for all existing entries in the sidtab.
1690 mls_context_destroy(c);
1691 } else if (!args->oldp->mls_enabled && args->newp->mls_enabled) {
1693 * Switching between non-MLS and MLS policy:
1694 * ensure that the MLS fields of the context for all
1695 * existing entries in the sidtab are filled in with a
1696 * suitable default value, likely taken from one of the
1699 oc = args->newp->ocontexts[OCON_ISID];
1700 while (oc && oc->sid[0] != SECINITSID_UNLABELED)
1703 printk(KERN_ERR "SELinux: unable to look up"
1704 " the initial SIDs list\n");
1707 range = &oc->context[0].range;
1708 rc = mls_range_set(c, range);
1713 /* Check the validity of the new context. */
1714 if (!policydb_context_isvalid(args->newp, c)) {
1715 rc = convert_context_handle_invalid_context(&oldc);
1720 context_destroy(&oldc);
1725 /* Map old representation to string and save it. */
1726 if (context_struct_to_string(&oldc, &s, &len))
1728 context_destroy(&oldc);
1733 "SELinux: Context %s became invalid (unmapped).\n",
1739 static void security_load_policycaps(void)
1741 selinux_policycap_netpeer = ebitmap_get_bit(&policydb.policycaps,
1742 POLICYDB_CAPABILITY_NETPEER);
1743 selinux_policycap_openperm = ebitmap_get_bit(&policydb.policycaps,
1744 POLICYDB_CAPABILITY_OPENPERM);
1747 extern void selinux_complete_init(void);
1748 static int security_preserve_bools(struct policydb *p);
1751 * security_load_policy - Load a security policy configuration.
1752 * @data: binary policy data
1753 * @len: length of data in bytes
1755 * Load a new set of security policy configuration data,
1756 * validate it and convert the SID table as necessary.
1757 * This function will flush the access vector cache after
1758 * loading the new policy.
1760 int security_load_policy(void *data, size_t len)
1762 struct policydb oldpolicydb, newpolicydb;
1763 struct sidtab oldsidtab, newsidtab;
1764 struct selinux_mapping *oldmap, *map = NULL;
1765 struct convert_context_args args;
1769 struct policy_file file = { data, len }, *fp = &file;
1771 if (!ss_initialized) {
1773 rc = policydb_read(&policydb, fp);
1775 avtab_cache_destroy();
1780 rc = selinux_set_mapping(&policydb, secclass_map,
1782 ¤t_mapping_size);
1784 policydb_destroy(&policydb);
1785 avtab_cache_destroy();
1789 rc = policydb_load_isids(&policydb, &sidtab);
1791 policydb_destroy(&policydb);
1792 avtab_cache_destroy();
1796 security_load_policycaps();
1798 seqno = ++latest_granting;
1799 selinux_complete_init();
1800 avc_ss_reset(seqno);
1801 selnl_notify_policyload(seqno);
1802 selinux_status_update_policyload(seqno);
1803 selinux_netlbl_cache_invalidate();
1804 selinux_xfrm_notify_policyload();
1809 sidtab_hash_eval(&sidtab, "sids");
1812 rc = policydb_read(&newpolicydb, fp);
1816 newpolicydb.len = len;
1817 /* If switching between different policy types, log MLS status */
1818 if (policydb.mls_enabled && !newpolicydb.mls_enabled)
1819 printk(KERN_INFO "SELinux: Disabling MLS support...\n");
1820 else if (!policydb.mls_enabled && newpolicydb.mls_enabled)
1821 printk(KERN_INFO "SELinux: Enabling MLS support...\n");
1823 rc = policydb_load_isids(&newpolicydb, &newsidtab);
1825 printk(KERN_ERR "SELinux: unable to load the initial SIDs\n");
1826 policydb_destroy(&newpolicydb);
1830 rc = selinux_set_mapping(&newpolicydb, secclass_map, &map, &map_size);
1834 rc = security_preserve_bools(&newpolicydb);
1836 printk(KERN_ERR "SELinux: unable to preserve booleans\n");
1840 /* Clone the SID table. */
1841 sidtab_shutdown(&sidtab);
1843 rc = sidtab_map(&sidtab, clone_sid, &newsidtab);
1848 * Convert the internal representations of contexts
1849 * in the new SID table.
1851 args.oldp = &policydb;
1852 args.newp = &newpolicydb;
1853 rc = sidtab_map(&newsidtab, convert_context, &args);
1855 printk(KERN_ERR "SELinux: unable to convert the internal"
1856 " representation of contexts in the new SID"
1861 /* Save the old policydb and SID table to free later. */
1862 memcpy(&oldpolicydb, &policydb, sizeof policydb);
1863 sidtab_set(&oldsidtab, &sidtab);
1865 /* Install the new policydb and SID table. */
1866 write_lock_irq(&policy_rwlock);
1867 memcpy(&policydb, &newpolicydb, sizeof policydb);
1868 sidtab_set(&sidtab, &newsidtab);
1869 security_load_policycaps();
1870 oldmap = current_mapping;
1871 current_mapping = map;
1872 current_mapping_size = map_size;
1873 seqno = ++latest_granting;
1874 write_unlock_irq(&policy_rwlock);
1876 /* Free the old policydb and SID table. */
1877 policydb_destroy(&oldpolicydb);
1878 sidtab_destroy(&oldsidtab);
1881 avc_ss_reset(seqno);
1882 selnl_notify_policyload(seqno);
1883 selinux_status_update_policyload(seqno);
1884 selinux_netlbl_cache_invalidate();
1885 selinux_xfrm_notify_policyload();
1891 sidtab_destroy(&newsidtab);
1892 policydb_destroy(&newpolicydb);
1897 size_t security_policydb_len(void)
1901 read_lock(&policy_rwlock);
1903 read_unlock(&policy_rwlock);
1909 * security_port_sid - Obtain the SID for a port.
1910 * @protocol: protocol number
1911 * @port: port number
1912 * @out_sid: security identifier
1914 int security_port_sid(u8 protocol, u16 port, u32 *out_sid)
1919 read_lock(&policy_rwlock);
1921 c = policydb.ocontexts[OCON_PORT];
1923 if (c->u.port.protocol == protocol &&
1924 c->u.port.low_port <= port &&
1925 c->u.port.high_port >= port)
1932 rc = sidtab_context_to_sid(&sidtab,
1938 *out_sid = c->sid[0];
1940 *out_sid = SECINITSID_PORT;
1944 read_unlock(&policy_rwlock);
1949 * security_netif_sid - Obtain the SID for a network interface.
1950 * @name: interface name
1951 * @if_sid: interface SID
1953 int security_netif_sid(char *name, u32 *if_sid)
1958 read_lock(&policy_rwlock);
1960 c = policydb.ocontexts[OCON_NETIF];
1962 if (strcmp(name, c->u.name) == 0)
1968 if (!c->sid[0] || !c->sid[1]) {
1969 rc = sidtab_context_to_sid(&sidtab,
1974 rc = sidtab_context_to_sid(&sidtab,
1980 *if_sid = c->sid[0];
1982 *if_sid = SECINITSID_NETIF;
1985 read_unlock(&policy_rwlock);
1989 static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask)
1993 for (i = 0; i < 4; i++)
1994 if (addr[i] != (input[i] & mask[i])) {
2003 * security_node_sid - Obtain the SID for a node (host).
2004 * @domain: communication domain aka address family
2006 * @addrlen: address length in bytes
2007 * @out_sid: security identifier
2009 int security_node_sid(u16 domain,
2017 read_lock(&policy_rwlock);
2023 if (addrlen != sizeof(u32)) {
2028 addr = *((u32 *)addrp);
2030 c = policydb.ocontexts[OCON_NODE];
2032 if (c->u.node.addr == (addr & c->u.node.mask))
2040 if (addrlen != sizeof(u64) * 2) {
2044 c = policydb.ocontexts[OCON_NODE6];
2046 if (match_ipv6_addrmask(addrp, c->u.node6.addr,
2054 *out_sid = SECINITSID_NODE;
2060 rc = sidtab_context_to_sid(&sidtab,
2066 *out_sid = c->sid[0];
2068 *out_sid = SECINITSID_NODE;
2072 read_unlock(&policy_rwlock);
2079 * security_get_user_sids - Obtain reachable SIDs for a user.
2080 * @fromsid: starting SID
2081 * @username: username
2082 * @sids: array of reachable SIDs for user
2083 * @nel: number of elements in @sids
2085 * Generate the set of SIDs for legal security contexts
2086 * for a given user that can be reached by @fromsid.
2087 * Set *@sids to point to a dynamically allocated
2088 * array containing the set of SIDs. Set *@nel to the
2089 * number of elements in the array.
2092 int security_get_user_sids(u32 fromsid,
2097 struct context *fromcon, usercon;
2098 u32 *mysids = NULL, *mysids2, sid;
2099 u32 mynel = 0, maxnel = SIDS_NEL;
2100 struct user_datum *user;
2101 struct role_datum *role;
2102 struct ebitmap_node *rnode, *tnode;
2108 if (!ss_initialized)
2111 read_lock(&policy_rwlock);
2113 context_init(&usercon);
2115 fromcon = sidtab_search(&sidtab, fromsid);
2121 user = hashtab_search(policydb.p_users.table, username);
2126 usercon.user = user->value;
2128 mysids = kcalloc(maxnel, sizeof(*mysids), GFP_ATOMIC);
2134 ebitmap_for_each_positive_bit(&user->roles, rnode, i) {
2135 role = policydb.role_val_to_struct[i];
2136 usercon.role = i + 1;
2137 ebitmap_for_each_positive_bit(&role->types, tnode, j) {
2138 usercon.type = j + 1;
2140 if (mls_setup_user_range(fromcon, user, &usercon))
2143 rc = sidtab_context_to_sid(&sidtab, &usercon, &sid);
2146 if (mynel < maxnel) {
2147 mysids[mynel++] = sid;
2150 mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
2155 memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
2158 mysids[mynel++] = sid;
2164 read_unlock(&policy_rwlock);
2170 mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);
2176 for (i = 0, j = 0; i < mynel; i++) {
2177 rc = avc_has_perm_noaudit(fromsid, mysids[i],
2178 SECCLASS_PROCESS, /* kernel value */
2179 PROCESS__TRANSITION, AVC_STRICT,
2182 mysids2[j++] = mysids[i];
2194 * security_genfs_sid - Obtain a SID for a file in a filesystem
2195 * @fstype: filesystem type
2196 * @path: path from root of mount
2197 * @sclass: file security class
2198 * @sid: SID for path
2200 * Obtain a SID to use for a file in a filesystem that
2201 * cannot support xattr or use a fixed labeling behavior like
2202 * transition SIDs or task SIDs.
2204 int security_genfs_sid(const char *fstype,
2211 struct genfs *genfs;
2213 int rc = 0, cmp = 0;
2215 while (path[0] == '/' && path[1] == '/')
2218 read_lock(&policy_rwlock);
2220 sclass = unmap_class(orig_sclass);
2222 for (genfs = policydb.genfs; genfs; genfs = genfs->next) {
2223 cmp = strcmp(fstype, genfs->fstype);
2228 if (!genfs || cmp) {
2229 *sid = SECINITSID_UNLABELED;
2234 for (c = genfs->head; c; c = c->next) {
2235 len = strlen(c->u.name);
2236 if ((!c->v.sclass || sclass == c->v.sclass) &&
2237 (strncmp(c->u.name, path, len) == 0))
2242 *sid = SECINITSID_UNLABELED;
2248 rc = sidtab_context_to_sid(&sidtab,
2257 read_unlock(&policy_rwlock);
2262 * security_fs_use - Determine how to handle labeling for a filesystem.
2263 * @fstype: filesystem type
2264 * @behavior: labeling behavior
2265 * @sid: SID for filesystem (superblock)
2267 int security_fs_use(
2269 unsigned int *behavior,
2275 read_lock(&policy_rwlock);
2277 c = policydb.ocontexts[OCON_FSUSE];
2279 if (strcmp(fstype, c->u.name) == 0)
2285 *behavior = c->v.behavior;
2287 rc = sidtab_context_to_sid(&sidtab,
2295 rc = security_genfs_sid(fstype, "/", SECCLASS_DIR, sid);
2297 *behavior = SECURITY_FS_USE_NONE;
2300 *behavior = SECURITY_FS_USE_GENFS;
2305 read_unlock(&policy_rwlock);
2309 int security_get_bools(int *len, char ***names, int **values)
2311 int i, rc = -ENOMEM;
2313 read_lock(&policy_rwlock);
2317 *len = policydb.p_bools.nprim;
2323 *names = kcalloc(*len, sizeof(char *), GFP_ATOMIC);
2327 *values = kcalloc(*len, sizeof(int), GFP_ATOMIC);
2331 for (i = 0; i < *len; i++) {
2333 (*values)[i] = policydb.bool_val_to_struct[i]->state;
2334 name_len = strlen(policydb.p_bool_val_to_name[i]) + 1;
2335 (*names)[i] = kmalloc(sizeof(char) * name_len, GFP_ATOMIC);
2338 strncpy((*names)[i], policydb.p_bool_val_to_name[i], name_len);
2339 (*names)[i][name_len - 1] = 0;
2343 read_unlock(&policy_rwlock);
2347 for (i = 0; i < *len; i++)
2355 int security_set_bools(int len, int *values)
2358 int lenp, seqno = 0;
2359 struct cond_node *cur;
2361 write_lock_irq(&policy_rwlock);
2363 lenp = policydb.p_bools.nprim;
2369 for (i = 0; i < len; i++) {
2370 if (!!values[i] != policydb.bool_val_to_struct[i]->state) {
2371 audit_log(current->audit_context, GFP_ATOMIC,
2372 AUDIT_MAC_CONFIG_CHANGE,
2373 "bool=%s val=%d old_val=%d auid=%u ses=%u",
2374 policydb.p_bool_val_to_name[i],
2376 policydb.bool_val_to_struct[i]->state,
2377 audit_get_loginuid(current),
2378 audit_get_sessionid(current));
2381 policydb.bool_val_to_struct[i]->state = 1;
2383 policydb.bool_val_to_struct[i]->state = 0;
2386 for (cur = policydb.cond_list; cur; cur = cur->next) {
2387 rc = evaluate_cond_node(&policydb, cur);
2392 seqno = ++latest_granting;
2395 write_unlock_irq(&policy_rwlock);
2397 avc_ss_reset(seqno);
2398 selnl_notify_policyload(seqno);
2399 selinux_status_update_policyload(seqno);
2400 selinux_xfrm_notify_policyload();
2405 int security_get_bool_value(int bool)
2410 read_lock(&policy_rwlock);
2412 len = policydb.p_bools.nprim;
2418 rc = policydb.bool_val_to_struct[bool]->state;
2420 read_unlock(&policy_rwlock);
2424 static int security_preserve_bools(struct policydb *p)
2426 int rc, nbools = 0, *bvalues = NULL, i;
2427 char **bnames = NULL;
2428 struct cond_bool_datum *booldatum;
2429 struct cond_node *cur;
2431 rc = security_get_bools(&nbools, &bnames, &bvalues);
2434 for (i = 0; i < nbools; i++) {
2435 booldatum = hashtab_search(p->p_bools.table, bnames[i]);
2437 booldatum->state = bvalues[i];
2439 for (cur = p->cond_list; cur; cur = cur->next) {
2440 rc = evaluate_cond_node(p, cur);
2447 for (i = 0; i < nbools; i++)
2456 * security_sid_mls_copy() - computes a new sid based on the given
2457 * sid and the mls portion of mls_sid.
2459 int security_sid_mls_copy(u32 sid, u32 mls_sid, u32 *new_sid)
2461 struct context *context1;
2462 struct context *context2;
2463 struct context newcon;
2468 if (!ss_initialized || !policydb.mls_enabled) {
2473 context_init(&newcon);
2475 read_lock(&policy_rwlock);
2476 context1 = sidtab_search(&sidtab, sid);
2478 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2484 context2 = sidtab_search(&sidtab, mls_sid);
2486 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2492 newcon.user = context1->user;
2493 newcon.role = context1->role;
2494 newcon.type = context1->type;
2495 rc = mls_context_cpy(&newcon, context2);
2499 /* Check the validity of the new context. */
2500 if (!policydb_context_isvalid(&policydb, &newcon)) {
2501 rc = convert_context_handle_invalid_context(&newcon);
2506 rc = sidtab_context_to_sid(&sidtab, &newcon, new_sid);
2510 if (!context_struct_to_string(&newcon, &s, &len)) {
2511 audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2512 "security_sid_mls_copy: invalid context %s", s);
2517 read_unlock(&policy_rwlock);
2518 context_destroy(&newcon);
2524 * security_net_peersid_resolve - Compare and resolve two network peer SIDs
2525 * @nlbl_sid: NetLabel SID
2526 * @nlbl_type: NetLabel labeling protocol type
2527 * @xfrm_sid: XFRM SID
2530 * Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be
2531 * resolved into a single SID it is returned via @peer_sid and the function
2532 * returns zero. Otherwise @peer_sid is set to SECSID_NULL and the function
2533 * returns a negative value. A table summarizing the behavior is below:
2535 * | function return | @sid
2536 * ------------------------------+-----------------+-----------------
2537 * no peer labels | 0 | SECSID_NULL
2538 * single peer label | 0 | <peer_label>
2539 * multiple, consistent labels | 0 | <peer_label>
2540 * multiple, inconsistent labels | -<errno> | SECSID_NULL
2543 int security_net_peersid_resolve(u32 nlbl_sid, u32 nlbl_type,
2548 struct context *nlbl_ctx;
2549 struct context *xfrm_ctx;
2551 /* handle the common (which also happens to be the set of easy) cases
2552 * right away, these two if statements catch everything involving a
2553 * single or absent peer SID/label */
2554 if (xfrm_sid == SECSID_NULL) {
2555 *peer_sid = nlbl_sid;
2558 /* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a "fallback" label
2559 * and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label
2561 if (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) {
2562 *peer_sid = xfrm_sid;
2566 /* we don't need to check ss_initialized here since the only way both
2567 * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the
2568 * security server was initialized and ss_initialized was true */
2569 if (!policydb.mls_enabled) {
2570 *peer_sid = SECSID_NULL;
2574 read_lock(&policy_rwlock);
2576 nlbl_ctx = sidtab_search(&sidtab, nlbl_sid);
2578 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2579 __func__, nlbl_sid);
2583 xfrm_ctx = sidtab_search(&sidtab, xfrm_sid);
2585 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2586 __func__, xfrm_sid);
2590 rc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES);
2593 read_unlock(&policy_rwlock);
2595 /* at present NetLabel SIDs/labels really only carry MLS
2596 * information so if the MLS portion of the NetLabel SID
2597 * matches the MLS portion of the labeled XFRM SID/label
2598 * then pass along the XFRM SID as it is the most
2600 *peer_sid = xfrm_sid;
2602 *peer_sid = SECSID_NULL;
2606 static int get_classes_callback(void *k, void *d, void *args)
2608 struct class_datum *datum = d;
2609 char *name = k, **classes = args;
2610 int value = datum->value - 1;
2612 classes[value] = kstrdup(name, GFP_ATOMIC);
2613 if (!classes[value])
2619 int security_get_classes(char ***classes, int *nclasses)
2623 read_lock(&policy_rwlock);
2625 *nclasses = policydb.p_classes.nprim;
2626 *classes = kcalloc(*nclasses, sizeof(**classes), GFP_ATOMIC);
2630 rc = hashtab_map(policydb.p_classes.table, get_classes_callback,
2634 for (i = 0; i < *nclasses; i++)
2635 kfree((*classes)[i]);
2640 read_unlock(&policy_rwlock);
2644 static int get_permissions_callback(void *k, void *d, void *args)
2646 struct perm_datum *datum = d;
2647 char *name = k, **perms = args;
2648 int value = datum->value - 1;
2650 perms[value] = kstrdup(name, GFP_ATOMIC);
2657 int security_get_permissions(char *class, char ***perms, int *nperms)
2659 int rc = -ENOMEM, i;
2660 struct class_datum *match;
2662 read_lock(&policy_rwlock);
2664 match = hashtab_search(policydb.p_classes.table, class);
2666 printk(KERN_ERR "SELinux: %s: unrecognized class %s\n",
2672 *nperms = match->permissions.nprim;
2673 *perms = kcalloc(*nperms, sizeof(**perms), GFP_ATOMIC);
2677 if (match->comdatum) {
2678 rc = hashtab_map(match->comdatum->permissions.table,
2679 get_permissions_callback, *perms);
2684 rc = hashtab_map(match->permissions.table, get_permissions_callback,
2690 read_unlock(&policy_rwlock);
2694 read_unlock(&policy_rwlock);
2695 for (i = 0; i < *nperms; i++)
2701 int security_get_reject_unknown(void)
2703 return policydb.reject_unknown;
2706 int security_get_allow_unknown(void)
2708 return policydb.allow_unknown;
2712 * security_policycap_supported - Check for a specific policy capability
2713 * @req_cap: capability
2716 * This function queries the currently loaded policy to see if it supports the
2717 * capability specified by @req_cap. Returns true (1) if the capability is
2718 * supported, false (0) if it isn't supported.
2721 int security_policycap_supported(unsigned int req_cap)
2725 read_lock(&policy_rwlock);
2726 rc = ebitmap_get_bit(&policydb.policycaps, req_cap);
2727 read_unlock(&policy_rwlock);
2732 struct selinux_audit_rule {
2734 struct context au_ctxt;
2737 void selinux_audit_rule_free(void *vrule)
2739 struct selinux_audit_rule *rule = vrule;
2742 context_destroy(&rule->au_ctxt);
2747 int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule)
2749 struct selinux_audit_rule *tmprule;
2750 struct role_datum *roledatum;
2751 struct type_datum *typedatum;
2752 struct user_datum *userdatum;
2753 struct selinux_audit_rule **rule = (struct selinux_audit_rule **)vrule;
2758 if (!ss_initialized)
2762 case AUDIT_SUBJ_USER:
2763 case AUDIT_SUBJ_ROLE:
2764 case AUDIT_SUBJ_TYPE:
2765 case AUDIT_OBJ_USER:
2766 case AUDIT_OBJ_ROLE:
2767 case AUDIT_OBJ_TYPE:
2768 /* only 'equals' and 'not equals' fit user, role, and type */
2769 if (op != Audit_equal && op != Audit_not_equal)
2772 case AUDIT_SUBJ_SEN:
2773 case AUDIT_SUBJ_CLR:
2774 case AUDIT_OBJ_LEV_LOW:
2775 case AUDIT_OBJ_LEV_HIGH:
2776 /* we do not allow a range, indicated by the presense of '-' */
2777 if (strchr(rulestr, '-'))
2781 /* only the above fields are valid */
2785 tmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL);
2789 context_init(&tmprule->au_ctxt);
2791 read_lock(&policy_rwlock);
2793 tmprule->au_seqno = latest_granting;
2796 case AUDIT_SUBJ_USER:
2797 case AUDIT_OBJ_USER:
2798 userdatum = hashtab_search(policydb.p_users.table, rulestr);
2802 tmprule->au_ctxt.user = userdatum->value;
2804 case AUDIT_SUBJ_ROLE:
2805 case AUDIT_OBJ_ROLE:
2806 roledatum = hashtab_search(policydb.p_roles.table, rulestr);
2810 tmprule->au_ctxt.role = roledatum->value;
2812 case AUDIT_SUBJ_TYPE:
2813 case AUDIT_OBJ_TYPE:
2814 typedatum = hashtab_search(policydb.p_types.table, rulestr);
2818 tmprule->au_ctxt.type = typedatum->value;
2820 case AUDIT_SUBJ_SEN:
2821 case AUDIT_SUBJ_CLR:
2822 case AUDIT_OBJ_LEV_LOW:
2823 case AUDIT_OBJ_LEV_HIGH:
2824 rc = mls_from_string(rulestr, &tmprule->au_ctxt, GFP_ATOMIC);
2828 read_unlock(&policy_rwlock);
2831 selinux_audit_rule_free(tmprule);
2840 /* Check to see if the rule contains any selinux fields */
2841 int selinux_audit_rule_known(struct audit_krule *rule)
2845 for (i = 0; i < rule->field_count; i++) {
2846 struct audit_field *f = &rule->fields[i];
2848 case AUDIT_SUBJ_USER:
2849 case AUDIT_SUBJ_ROLE:
2850 case AUDIT_SUBJ_TYPE:
2851 case AUDIT_SUBJ_SEN:
2852 case AUDIT_SUBJ_CLR:
2853 case AUDIT_OBJ_USER:
2854 case AUDIT_OBJ_ROLE:
2855 case AUDIT_OBJ_TYPE:
2856 case AUDIT_OBJ_LEV_LOW:
2857 case AUDIT_OBJ_LEV_HIGH:
2865 int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule,
2866 struct audit_context *actx)
2868 struct context *ctxt;
2869 struct mls_level *level;
2870 struct selinux_audit_rule *rule = vrule;
2874 audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2875 "selinux_audit_rule_match: missing rule\n");
2879 read_lock(&policy_rwlock);
2881 if (rule->au_seqno < latest_granting) {
2882 audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2883 "selinux_audit_rule_match: stale rule\n");
2888 ctxt = sidtab_search(&sidtab, sid);
2890 audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2891 "selinux_audit_rule_match: unrecognized SID %d\n",
2897 /* a field/op pair that is not caught here will simply fall through
2900 case AUDIT_SUBJ_USER:
2901 case AUDIT_OBJ_USER:
2904 match = (ctxt->user == rule->au_ctxt.user);
2906 case Audit_not_equal:
2907 match = (ctxt->user != rule->au_ctxt.user);
2911 case AUDIT_SUBJ_ROLE:
2912 case AUDIT_OBJ_ROLE:
2915 match = (ctxt->role == rule->au_ctxt.role);
2917 case Audit_not_equal:
2918 match = (ctxt->role != rule->au_ctxt.role);
2922 case AUDIT_SUBJ_TYPE:
2923 case AUDIT_OBJ_TYPE:
2926 match = (ctxt->type == rule->au_ctxt.type);
2928 case Audit_not_equal:
2929 match = (ctxt->type != rule->au_ctxt.type);
2933 case AUDIT_SUBJ_SEN:
2934 case AUDIT_SUBJ_CLR:
2935 case AUDIT_OBJ_LEV_LOW:
2936 case AUDIT_OBJ_LEV_HIGH:
2937 level = ((field == AUDIT_SUBJ_SEN ||
2938 field == AUDIT_OBJ_LEV_LOW) ?
2939 &ctxt->range.level[0] : &ctxt->range.level[1]);
2942 match = mls_level_eq(&rule->au_ctxt.range.level[0],
2945 case Audit_not_equal:
2946 match = !mls_level_eq(&rule->au_ctxt.range.level[0],
2950 match = (mls_level_dom(&rule->au_ctxt.range.level[0],
2952 !mls_level_eq(&rule->au_ctxt.range.level[0],
2956 match = mls_level_dom(&rule->au_ctxt.range.level[0],
2960 match = (mls_level_dom(level,
2961 &rule->au_ctxt.range.level[0]) &&
2962 !mls_level_eq(level,
2963 &rule->au_ctxt.range.level[0]));
2966 match = mls_level_dom(level,
2967 &rule->au_ctxt.range.level[0]);
2973 read_unlock(&policy_rwlock);
2977 static int (*aurule_callback)(void) = audit_update_lsm_rules;
2979 static int aurule_avc_callback(u32 event, u32 ssid, u32 tsid,
2980 u16 class, u32 perms, u32 *retained)
2984 if (event == AVC_CALLBACK_RESET && aurule_callback)
2985 err = aurule_callback();
2989 static int __init aurule_init(void)
2993 err = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET,
2994 SECSID_NULL, SECSID_NULL, SECCLASS_NULL, 0);
2996 panic("avc_add_callback() failed, error %d\n", err);
3000 __initcall(aurule_init);
3002 #ifdef CONFIG_NETLABEL
3004 * security_netlbl_cache_add - Add an entry to the NetLabel cache
3005 * @secattr: the NetLabel packet security attributes
3006 * @sid: the SELinux SID
3009 * Attempt to cache the context in @ctx, which was derived from the packet in
3010 * @skb, in the NetLabel subsystem cache. This function assumes @secattr has
3011 * already been initialized.
3014 static void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr,
3019 sid_cache = kmalloc(sizeof(*sid_cache), GFP_ATOMIC);
3020 if (sid_cache == NULL)
3022 secattr->cache = netlbl_secattr_cache_alloc(GFP_ATOMIC);
3023 if (secattr->cache == NULL) {
3029 secattr->cache->free = kfree;
3030 secattr->cache->data = sid_cache;
3031 secattr->flags |= NETLBL_SECATTR_CACHE;
3035 * security_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID
3036 * @secattr: the NetLabel packet security attributes
3037 * @sid: the SELinux SID
3040 * Convert the given NetLabel security attributes in @secattr into a
3041 * SELinux SID. If the @secattr field does not contain a full SELinux
3042 * SID/context then use SECINITSID_NETMSG as the foundation. If possibile the
3043 * 'cache' field of @secattr is set and the CACHE flag is set; this is to
3044 * allow the @secattr to be used by NetLabel to cache the secattr to SID
3045 * conversion for future lookups. Returns zero on success, negative values on
3049 int security_netlbl_secattr_to_sid(struct netlbl_lsm_secattr *secattr,
3053 struct context *ctx;
3054 struct context ctx_new;
3056 if (!ss_initialized) {
3061 read_lock(&policy_rwlock);
3063 if (secattr->flags & NETLBL_SECATTR_CACHE) {
3064 *sid = *(u32 *)secattr->cache->data;
3066 } else if (secattr->flags & NETLBL_SECATTR_SECID) {
3067 *sid = secattr->attr.secid;
3069 } else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) {
3070 ctx = sidtab_search(&sidtab, SECINITSID_NETMSG);
3072 goto netlbl_secattr_to_sid_return;
3074 context_init(&ctx_new);
3075 ctx_new.user = ctx->user;
3076 ctx_new.role = ctx->role;
3077 ctx_new.type = ctx->type;
3078 mls_import_netlbl_lvl(&ctx_new, secattr);
3079 if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
3080 if (ebitmap_netlbl_import(&ctx_new.range.level[0].cat,
3081 secattr->attr.mls.cat) != 0)
3082 goto netlbl_secattr_to_sid_return;
3083 memcpy(&ctx_new.range.level[1].cat,
3084 &ctx_new.range.level[0].cat,
3085 sizeof(ctx_new.range.level[0].cat));
3087 if (mls_context_isvalid(&policydb, &ctx_new) != 1)
3088 goto netlbl_secattr_to_sid_return_cleanup;
3090 rc = sidtab_context_to_sid(&sidtab, &ctx_new, sid);
3092 goto netlbl_secattr_to_sid_return_cleanup;
3094 security_netlbl_cache_add(secattr, *sid);
3096 ebitmap_destroy(&ctx_new.range.level[0].cat);
3102 netlbl_secattr_to_sid_return:
3103 read_unlock(&policy_rwlock);
3105 netlbl_secattr_to_sid_return_cleanup:
3106 ebitmap_destroy(&ctx_new.range.level[0].cat);
3107 goto netlbl_secattr_to_sid_return;
3111 * security_netlbl_sid_to_secattr - Convert a SELinux SID to a NetLabel secattr
3112 * @sid: the SELinux SID
3113 * @secattr: the NetLabel packet security attributes
3116 * Convert the given SELinux SID in @sid into a NetLabel security attribute.
3117 * Returns zero on success, negative values on failure.
3120 int security_netlbl_sid_to_secattr(u32 sid, struct netlbl_lsm_secattr *secattr)
3123 struct context *ctx;
3125 if (!ss_initialized)
3128 read_lock(&policy_rwlock);
3129 ctx = sidtab_search(&sidtab, sid);
3132 goto netlbl_sid_to_secattr_failure;
3134 secattr->domain = kstrdup(policydb.p_type_val_to_name[ctx->type - 1],
3136 if (secattr->domain == NULL) {
3138 goto netlbl_sid_to_secattr_failure;
3140 secattr->attr.secid = sid;
3141 secattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID;
3142 mls_export_netlbl_lvl(ctx, secattr);
3143 rc = mls_export_netlbl_cat(ctx, secattr);
3145 goto netlbl_sid_to_secattr_failure;
3146 read_unlock(&policy_rwlock);
3150 netlbl_sid_to_secattr_failure:
3151 read_unlock(&policy_rwlock);
3154 #endif /* CONFIG_NETLABEL */
3157 * security_read_policy - read the policy.
3158 * @data: binary policy data
3159 * @len: length of data in bytes
3162 int security_read_policy(void **data, ssize_t *len)
3165 struct policy_file fp;
3167 if (!ss_initialized)
3170 *len = security_policydb_len();
3172 *data = vmalloc_user(*len);
3179 read_lock(&policy_rwlock);
3180 rc = policydb_write(&policydb, &fp);
3181 read_unlock(&policy_rwlock);
3186 *len = (unsigned long)fp.data - (unsigned long)*data;