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;
74 * This is declared in avc.c
76 extern const struct selinux_class_perm selinux_class_perm;
78 static DEFINE_RWLOCK(policy_rwlock);
80 static struct sidtab sidtab;
81 struct policydb policydb;
85 * The largest sequence number that has been used when
86 * providing an access decision to the access vector cache.
87 * The sequence number only changes when a policy change
90 static u32 latest_granting;
92 /* Forward declaration. */
93 static int context_struct_to_string(struct context *context, char **scontext,
96 static int context_struct_compute_av(struct context *scontext,
97 struct context *tcontext,
100 struct av_decision *avd);
102 * Return the boolean value of a constraint expression
103 * when it is applied to the specified source and target
106 * xcontext is a special beast... It is used by the validatetrans rules
107 * only. For these rules, scontext is the context before the transition,
108 * tcontext is the context after the transition, and xcontext is the context
109 * of the process performing the transition. All other callers of
110 * constraint_expr_eval should pass in NULL for xcontext.
112 static int constraint_expr_eval(struct context *scontext,
113 struct context *tcontext,
114 struct context *xcontext,
115 struct constraint_expr *cexpr)
119 struct role_datum *r1, *r2;
120 struct mls_level *l1, *l2;
121 struct constraint_expr *e;
122 int s[CEXPR_MAXDEPTH];
125 for (e = cexpr; e; e = e->next) {
126 switch (e->expr_type) {
142 if (sp == (CEXPR_MAXDEPTH-1))
146 val1 = scontext->user;
147 val2 = tcontext->user;
150 val1 = scontext->type;
151 val2 = tcontext->type;
154 val1 = scontext->role;
155 val2 = tcontext->role;
156 r1 = policydb.role_val_to_struct[val1 - 1];
157 r2 = policydb.role_val_to_struct[val2 - 1];
160 s[++sp] = ebitmap_get_bit(&r1->dominates,
164 s[++sp] = ebitmap_get_bit(&r2->dominates,
168 s[++sp] = (!ebitmap_get_bit(&r1->dominates,
170 !ebitmap_get_bit(&r2->dominates,
178 l1 = &(scontext->range.level[0]);
179 l2 = &(tcontext->range.level[0]);
182 l1 = &(scontext->range.level[0]);
183 l2 = &(tcontext->range.level[1]);
186 l1 = &(scontext->range.level[1]);
187 l2 = &(tcontext->range.level[0]);
190 l1 = &(scontext->range.level[1]);
191 l2 = &(tcontext->range.level[1]);
194 l1 = &(scontext->range.level[0]);
195 l2 = &(scontext->range.level[1]);
198 l1 = &(tcontext->range.level[0]);
199 l2 = &(tcontext->range.level[1]);
204 s[++sp] = mls_level_eq(l1, l2);
207 s[++sp] = !mls_level_eq(l1, l2);
210 s[++sp] = mls_level_dom(l1, l2);
213 s[++sp] = mls_level_dom(l2, l1);
216 s[++sp] = mls_level_incomp(l2, l1);
230 s[++sp] = (val1 == val2);
233 s[++sp] = (val1 != val2);
241 if (sp == (CEXPR_MAXDEPTH-1))
244 if (e->attr & CEXPR_TARGET)
246 else if (e->attr & CEXPR_XTARGET) {
253 if (e->attr & CEXPR_USER)
255 else if (e->attr & CEXPR_ROLE)
257 else if (e->attr & CEXPR_TYPE)
266 s[++sp] = ebitmap_get_bit(&e->names, val1 - 1);
269 s[++sp] = !ebitmap_get_bit(&e->names, val1 - 1);
287 * security_dump_masked_av - dumps masked permissions during
288 * security_compute_av due to RBAC, MLS/Constraint and Type bounds.
290 static int dump_masked_av_helper(void *k, void *d, void *args)
292 struct perm_datum *pdatum = d;
293 char **permission_names = args;
295 BUG_ON(pdatum->value < 1 || pdatum->value > 32);
297 permission_names[pdatum->value - 1] = (char *)k;
302 static void security_dump_masked_av(struct context *scontext,
303 struct context *tcontext,
308 struct common_datum *common_dat;
309 struct class_datum *tclass_dat;
310 struct audit_buffer *ab;
312 char *scontext_name = NULL;
313 char *tcontext_name = NULL;
314 char *permission_names[32];
316 bool need_comma = false;
321 tclass_name = policydb.p_class_val_to_name[tclass - 1];
322 tclass_dat = policydb.class_val_to_struct[tclass - 1];
323 common_dat = tclass_dat->comdatum;
325 /* init permission_names */
327 hashtab_map(common_dat->permissions.table,
328 dump_masked_av_helper, permission_names) < 0)
331 if (hashtab_map(tclass_dat->permissions.table,
332 dump_masked_av_helper, permission_names) < 0)
335 /* get scontext/tcontext in text form */
336 if (context_struct_to_string(scontext,
337 &scontext_name, &length) < 0)
340 if (context_struct_to_string(tcontext,
341 &tcontext_name, &length) < 0)
344 /* audit a message */
345 ab = audit_log_start(current->audit_context,
346 GFP_ATOMIC, AUDIT_SELINUX_ERR);
350 audit_log_format(ab, "op=security_compute_av reason=%s "
351 "scontext=%s tcontext=%s tclass=%s perms=",
352 reason, scontext_name, tcontext_name, tclass_name);
354 for (index = 0; index < 32; index++) {
355 u32 mask = (1 << index);
357 if ((mask & permissions) == 0)
360 audit_log_format(ab, "%s%s",
361 need_comma ? "," : "",
362 permission_names[index]
363 ? permission_names[index] : "????");
368 /* release scontext/tcontext */
369 kfree(tcontext_name);
370 kfree(scontext_name);
376 * security_boundary_permission - drops violated permissions
377 * on boundary constraint.
379 static void type_attribute_bounds_av(struct context *scontext,
380 struct context *tcontext,
383 struct av_decision *avd)
385 struct context lo_scontext;
386 struct context lo_tcontext;
387 struct av_decision lo_avd;
388 struct type_datum *source
389 = policydb.type_val_to_struct[scontext->type - 1];
390 struct type_datum *target
391 = policydb.type_val_to_struct[tcontext->type - 1];
394 if (source->bounds) {
395 memset(&lo_avd, 0, sizeof(lo_avd));
397 memcpy(&lo_scontext, scontext, sizeof(lo_scontext));
398 lo_scontext.type = source->bounds;
400 context_struct_compute_av(&lo_scontext,
405 if ((lo_avd.allowed & avd->allowed) == avd->allowed)
406 return; /* no masked permission */
407 masked = ~lo_avd.allowed & avd->allowed;
410 if (target->bounds) {
411 memset(&lo_avd, 0, sizeof(lo_avd));
413 memcpy(&lo_tcontext, tcontext, sizeof(lo_tcontext));
414 lo_tcontext.type = target->bounds;
416 context_struct_compute_av(scontext,
421 if ((lo_avd.allowed & avd->allowed) == avd->allowed)
422 return; /* no masked permission */
423 masked = ~lo_avd.allowed & avd->allowed;
426 if (source->bounds && target->bounds) {
427 memset(&lo_avd, 0, sizeof(lo_avd));
429 * lo_scontext and lo_tcontext are already
433 context_struct_compute_av(&lo_scontext,
438 if ((lo_avd.allowed & avd->allowed) == avd->allowed)
439 return; /* no masked permission */
440 masked = ~lo_avd.allowed & avd->allowed;
444 /* mask violated permissions */
445 avd->allowed &= ~masked;
447 /* audit masked permissions */
448 security_dump_masked_av(scontext, tcontext,
449 tclass, masked, "bounds");
454 * Compute access vectors based on a context structure pair for
455 * the permissions in a particular class.
457 static int context_struct_compute_av(struct context *scontext,
458 struct context *tcontext,
461 struct av_decision *avd)
463 struct constraint_node *constraint;
464 struct role_allow *ra;
465 struct avtab_key avkey;
466 struct avtab_node *node;
467 struct class_datum *tclass_datum;
468 struct ebitmap *sattr, *tattr;
469 struct ebitmap_node *snode, *tnode;
470 const struct selinux_class_perm *kdefs = &selinux_class_perm;
474 * Remap extended Netlink classes for old policy versions.
475 * Do this here rather than socket_type_to_security_class()
476 * in case a newer policy version is loaded, allowing sockets
477 * to remain in the correct class.
479 if (policydb_loaded_version < POLICYDB_VERSION_NLCLASS)
480 if (tclass >= SECCLASS_NETLINK_ROUTE_SOCKET &&
481 tclass <= SECCLASS_NETLINK_DNRT_SOCKET)
482 tclass = SECCLASS_NETLINK_SOCKET;
485 * Initialize the access vectors to the default values.
489 avd->auditdeny = 0xffffffff;
490 avd->seqno = latest_granting;
494 * Check for all the invalid cases.
496 * - tclass > policy and > kernel
497 * - tclass > policy but is a userspace class
498 * - tclass > policy but we do not allow unknowns
500 if (unlikely(!tclass))
502 if (unlikely(tclass > policydb.p_classes.nprim))
503 if (tclass > kdefs->cts_len ||
504 !kdefs->class_to_string[tclass] ||
505 !policydb.allow_unknown)
509 * Kernel class and we allow unknown so pad the allow decision
510 * the pad will be all 1 for unknown classes.
512 if (tclass <= kdefs->cts_len && policydb.allow_unknown)
513 avd->allowed = policydb.undefined_perms[tclass - 1];
516 * Not in policy. Since decision is completed (all 1 or all 0) return.
518 if (unlikely(tclass > policydb.p_classes.nprim))
521 tclass_datum = policydb.class_val_to_struct[tclass - 1];
524 * If a specific type enforcement rule was defined for
525 * this permission check, then use it.
527 avkey.target_class = tclass;
528 avkey.specified = AVTAB_AV;
529 sattr = &policydb.type_attr_map[scontext->type - 1];
530 tattr = &policydb.type_attr_map[tcontext->type - 1];
531 ebitmap_for_each_positive_bit(sattr, snode, i) {
532 ebitmap_for_each_positive_bit(tattr, tnode, j) {
533 avkey.source_type = i + 1;
534 avkey.target_type = j + 1;
535 for (node = avtab_search_node(&policydb.te_avtab, &avkey);
537 node = avtab_search_node_next(node, avkey.specified)) {
538 if (node->key.specified == AVTAB_ALLOWED)
539 avd->allowed |= node->datum.data;
540 else if (node->key.specified == AVTAB_AUDITALLOW)
541 avd->auditallow |= node->datum.data;
542 else if (node->key.specified == AVTAB_AUDITDENY)
543 avd->auditdeny &= node->datum.data;
546 /* Check conditional av table for additional permissions */
547 cond_compute_av(&policydb.te_cond_avtab, &avkey, avd);
553 * Remove any permissions prohibited by a constraint (this includes
556 constraint = tclass_datum->constraints;
558 if ((constraint->permissions & (avd->allowed)) &&
559 !constraint_expr_eval(scontext, tcontext, NULL,
561 avd->allowed &= ~(constraint->permissions);
563 constraint = constraint->next;
567 * If checking process transition permission and the
568 * role is changing, then check the (current_role, new_role)
571 if (tclass == SECCLASS_PROCESS &&
572 (avd->allowed & (PROCESS__TRANSITION | PROCESS__DYNTRANSITION)) &&
573 scontext->role != tcontext->role) {
574 for (ra = policydb.role_allow; ra; ra = ra->next) {
575 if (scontext->role == ra->role &&
576 tcontext->role == ra->new_role)
580 avd->allowed &= ~(PROCESS__TRANSITION |
581 PROCESS__DYNTRANSITION);
585 * If the given source and target types have boundary
586 * constraint, lazy checks have to mask any violated
587 * permission and notice it to userspace via audit.
589 type_attribute_bounds_av(scontext, tcontext,
590 tclass, requested, avd);
595 if (!tclass || tclass > kdefs->cts_len ||
596 !kdefs->class_to_string[tclass]) {
597 if (printk_ratelimit())
598 printk(KERN_ERR "SELinux: %s: unrecognized class %d\n",
604 * Known to the kernel, but not to the policy.
605 * Handle as a denial (allowed is 0).
610 static int security_validtrans_handle_fail(struct context *ocontext,
611 struct context *ncontext,
612 struct context *tcontext,
615 char *o = NULL, *n = NULL, *t = NULL;
616 u32 olen, nlen, tlen;
618 if (context_struct_to_string(ocontext, &o, &olen) < 0)
620 if (context_struct_to_string(ncontext, &n, &nlen) < 0)
622 if (context_struct_to_string(tcontext, &t, &tlen) < 0)
624 audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
625 "security_validate_transition: denied for"
626 " oldcontext=%s newcontext=%s taskcontext=%s tclass=%s",
627 o, n, t, policydb.p_class_val_to_name[tclass-1]);
633 if (!selinux_enforcing)
638 int security_validate_transition(u32 oldsid, u32 newsid, u32 tasksid,
641 struct context *ocontext;
642 struct context *ncontext;
643 struct context *tcontext;
644 struct class_datum *tclass_datum;
645 struct constraint_node *constraint;
651 read_lock(&policy_rwlock);
654 * Remap extended Netlink classes for old policy versions.
655 * Do this here rather than socket_type_to_security_class()
656 * in case a newer policy version is loaded, allowing sockets
657 * to remain in the correct class.
659 if (policydb_loaded_version < POLICYDB_VERSION_NLCLASS)
660 if (tclass >= SECCLASS_NETLINK_ROUTE_SOCKET &&
661 tclass <= SECCLASS_NETLINK_DNRT_SOCKET)
662 tclass = SECCLASS_NETLINK_SOCKET;
664 if (!tclass || tclass > policydb.p_classes.nprim) {
665 printk(KERN_ERR "SELinux: %s: unrecognized class %d\n",
670 tclass_datum = policydb.class_val_to_struct[tclass - 1];
672 ocontext = sidtab_search(&sidtab, oldsid);
674 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
680 ncontext = sidtab_search(&sidtab, newsid);
682 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
688 tcontext = sidtab_search(&sidtab, tasksid);
690 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
696 constraint = tclass_datum->validatetrans;
698 if (!constraint_expr_eval(ocontext, ncontext, tcontext,
700 rc = security_validtrans_handle_fail(ocontext, ncontext,
704 constraint = constraint->next;
708 read_unlock(&policy_rwlock);
713 * security_bounded_transition - check whether the given
714 * transition is directed to bounded, or not.
715 * It returns 0, if @newsid is bounded by @oldsid.
716 * Otherwise, it returns error code.
718 * @oldsid : current security identifier
719 * @newsid : destinated security identifier
721 int security_bounded_transition(u32 old_sid, u32 new_sid)
723 struct context *old_context, *new_context;
724 struct type_datum *type;
728 read_lock(&policy_rwlock);
730 old_context = sidtab_search(&sidtab, old_sid);
732 printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n",
737 new_context = sidtab_search(&sidtab, new_sid);
739 printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n",
744 /* type/domain unchanged */
745 if (old_context->type == new_context->type) {
750 index = new_context->type;
752 type = policydb.type_val_to_struct[index - 1];
755 /* not bounded anymore */
761 /* @newsid is bounded by @oldsid */
762 if (type->bounds == old_context->type) {
766 index = type->bounds;
770 char *old_name = NULL;
771 char *new_name = NULL;
774 if (!context_struct_to_string(old_context,
775 &old_name, &length) &&
776 !context_struct_to_string(new_context,
777 &new_name, &length)) {
778 audit_log(current->audit_context,
779 GFP_ATOMIC, AUDIT_SELINUX_ERR,
780 "op=security_bounded_transition "
782 "oldcontext=%s newcontext=%s",
789 read_unlock(&policy_rwlock);
796 * security_compute_av - Compute access vector decisions.
797 * @ssid: source security identifier
798 * @tsid: target security identifier
799 * @tclass: target security class
800 * @requested: requested permissions
801 * @avd: access vector decisions
803 * Compute a set of access vector decisions based on the
804 * SID pair (@ssid, @tsid) for the permissions in @tclass.
805 * Return -%EINVAL if any of the parameters are invalid or %0
806 * if the access vector decisions were computed successfully.
808 int security_compute_av(u32 ssid,
812 struct av_decision *avd)
814 struct context *scontext = NULL, *tcontext = NULL;
817 if (!ss_initialized) {
818 avd->allowed = 0xffffffff;
820 avd->auditdeny = 0xffffffff;
821 avd->seqno = latest_granting;
825 read_lock(&policy_rwlock);
827 scontext = sidtab_search(&sidtab, ssid);
829 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
834 tcontext = sidtab_search(&sidtab, tsid);
836 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
842 rc = context_struct_compute_av(scontext, tcontext, tclass,
845 /* permissive domain? */
846 if (ebitmap_get_bit(&policydb.permissive_map, scontext->type))
847 avd->flags |= AVD_FLAGS_PERMISSIVE;
849 read_unlock(&policy_rwlock);
854 * Write the security context string representation of
855 * the context structure `context' into a dynamically
856 * allocated string of the correct size. Set `*scontext'
857 * to point to this string and set `*scontext_len' to
858 * the length of the string.
860 static int context_struct_to_string(struct context *context, char **scontext, u32 *scontext_len)
868 *scontext_len = context->len;
869 *scontext = kstrdup(context->str, GFP_ATOMIC);
875 /* Compute the size of the context. */
876 *scontext_len += strlen(policydb.p_user_val_to_name[context->user - 1]) + 1;
877 *scontext_len += strlen(policydb.p_role_val_to_name[context->role - 1]) + 1;
878 *scontext_len += strlen(policydb.p_type_val_to_name[context->type - 1]) + 1;
879 *scontext_len += mls_compute_context_len(context);
881 /* Allocate space for the context; caller must free this space. */
882 scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
885 *scontext = scontextp;
888 * Copy the user name, role name and type name into the context.
890 sprintf(scontextp, "%s:%s:%s",
891 policydb.p_user_val_to_name[context->user - 1],
892 policydb.p_role_val_to_name[context->role - 1],
893 policydb.p_type_val_to_name[context->type - 1]);
894 scontextp += strlen(policydb.p_user_val_to_name[context->user - 1]) +
895 1 + strlen(policydb.p_role_val_to_name[context->role - 1]) +
896 1 + strlen(policydb.p_type_val_to_name[context->type - 1]);
898 mls_sid_to_context(context, &scontextp);
905 #include "initial_sid_to_string.h"
907 const char *security_get_initial_sid_context(u32 sid)
909 if (unlikely(sid > SECINITSID_NUM))
911 return initial_sid_to_string[sid];
914 static int security_sid_to_context_core(u32 sid, char **scontext,
915 u32 *scontext_len, int force)
917 struct context *context;
923 if (!ss_initialized) {
924 if (sid <= SECINITSID_NUM) {
927 *scontext_len = strlen(initial_sid_to_string[sid]) + 1;
928 scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
933 strcpy(scontextp, initial_sid_to_string[sid]);
934 *scontext = scontextp;
937 printk(KERN_ERR "SELinux: %s: called before initial "
938 "load_policy on unknown SID %d\n", __func__, sid);
942 read_lock(&policy_rwlock);
944 context = sidtab_search_force(&sidtab, sid);
946 context = sidtab_search(&sidtab, sid);
948 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
953 rc = context_struct_to_string(context, scontext, scontext_len);
955 read_unlock(&policy_rwlock);
962 * security_sid_to_context - Obtain a context for a given SID.
963 * @sid: security identifier, SID
964 * @scontext: security context
965 * @scontext_len: length in bytes
967 * Write the string representation of the context associated with @sid
968 * into a dynamically allocated string of the correct size. Set @scontext
969 * to point to this string and set @scontext_len to the length of the string.
971 int security_sid_to_context(u32 sid, char **scontext, u32 *scontext_len)
973 return security_sid_to_context_core(sid, scontext, scontext_len, 0);
976 int security_sid_to_context_force(u32 sid, char **scontext, u32 *scontext_len)
978 return security_sid_to_context_core(sid, scontext, scontext_len, 1);
982 * Caveat: Mutates scontext.
984 static int string_to_context_struct(struct policydb *pol,
985 struct sidtab *sidtabp,
991 struct role_datum *role;
992 struct type_datum *typdatum;
993 struct user_datum *usrdatum;
994 char *scontextp, *p, oldc;
999 /* Parse the security context. */
1002 scontextp = (char *) scontext;
1004 /* Extract the user. */
1006 while (*p && *p != ':')
1014 usrdatum = hashtab_search(pol->p_users.table, scontextp);
1018 ctx->user = usrdatum->value;
1022 while (*p && *p != ':')
1030 role = hashtab_search(pol->p_roles.table, scontextp);
1033 ctx->role = role->value;
1037 while (*p && *p != ':')
1042 typdatum = hashtab_search(pol->p_types.table, scontextp);
1043 if (!typdatum || typdatum->attribute)
1046 ctx->type = typdatum->value;
1048 rc = mls_context_to_sid(pol, oldc, &p, ctx, sidtabp, def_sid);
1052 if ((p - scontext) < scontext_len) {
1057 /* Check the validity of the new context. */
1058 if (!policydb_context_isvalid(pol, ctx)) {
1065 context_destroy(ctx);
1069 static int security_context_to_sid_core(const char *scontext, u32 scontext_len,
1070 u32 *sid, u32 def_sid, gfp_t gfp_flags,
1073 char *scontext2, *str = NULL;
1074 struct context context;
1077 if (!ss_initialized) {
1080 for (i = 1; i < SECINITSID_NUM; i++) {
1081 if (!strcmp(initial_sid_to_string[i], scontext)) {
1086 *sid = SECINITSID_KERNEL;
1091 /* Copy the string so that we can modify the copy as we parse it. */
1092 scontext2 = kmalloc(scontext_len+1, gfp_flags);
1095 memcpy(scontext2, scontext, scontext_len);
1096 scontext2[scontext_len] = 0;
1099 /* Save another copy for storing in uninterpreted form */
1100 str = kstrdup(scontext2, gfp_flags);
1107 read_lock(&policy_rwlock);
1108 rc = string_to_context_struct(&policydb, &sidtab,
1109 scontext2, scontext_len,
1111 if (rc == -EINVAL && force) {
1113 context.len = scontext_len;
1117 rc = sidtab_context_to_sid(&sidtab, &context, sid);
1118 context_destroy(&context);
1120 read_unlock(&policy_rwlock);
1127 * security_context_to_sid - Obtain a SID for a given security context.
1128 * @scontext: security context
1129 * @scontext_len: length in bytes
1130 * @sid: security identifier, SID
1132 * Obtains a SID associated with the security context that
1133 * has the string representation specified by @scontext.
1134 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1135 * memory is available, or 0 on success.
1137 int security_context_to_sid(const char *scontext, u32 scontext_len, u32 *sid)
1139 return security_context_to_sid_core(scontext, scontext_len,
1140 sid, SECSID_NULL, GFP_KERNEL, 0);
1144 * security_context_to_sid_default - Obtain a SID for a given security context,
1145 * falling back to specified default if needed.
1147 * @scontext: security context
1148 * @scontext_len: length in bytes
1149 * @sid: security identifier, SID
1150 * @def_sid: default SID to assign on error
1152 * Obtains a SID associated with the security context that
1153 * has the string representation specified by @scontext.
1154 * The default SID is passed to the MLS layer to be used to allow
1155 * kernel labeling of the MLS field if the MLS field is not present
1156 * (for upgrading to MLS without full relabel).
1157 * Implicitly forces adding of the context even if it cannot be mapped yet.
1158 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1159 * memory is available, or 0 on success.
1161 int security_context_to_sid_default(const char *scontext, u32 scontext_len,
1162 u32 *sid, u32 def_sid, gfp_t gfp_flags)
1164 return security_context_to_sid_core(scontext, scontext_len,
1165 sid, def_sid, gfp_flags, 1);
1168 int security_context_to_sid_force(const char *scontext, u32 scontext_len,
1171 return security_context_to_sid_core(scontext, scontext_len,
1172 sid, SECSID_NULL, GFP_KERNEL, 1);
1175 static int compute_sid_handle_invalid_context(
1176 struct context *scontext,
1177 struct context *tcontext,
1179 struct context *newcontext)
1181 char *s = NULL, *t = NULL, *n = NULL;
1182 u32 slen, tlen, nlen;
1184 if (context_struct_to_string(scontext, &s, &slen) < 0)
1186 if (context_struct_to_string(tcontext, &t, &tlen) < 0)
1188 if (context_struct_to_string(newcontext, &n, &nlen) < 0)
1190 audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
1191 "security_compute_sid: invalid context %s"
1195 n, s, t, policydb.p_class_val_to_name[tclass-1]);
1200 if (!selinux_enforcing)
1205 static int security_compute_sid(u32 ssid,
1211 struct context *scontext = NULL, *tcontext = NULL, newcontext;
1212 struct role_trans *roletr = NULL;
1213 struct avtab_key avkey;
1214 struct avtab_datum *avdatum;
1215 struct avtab_node *node;
1218 if (!ss_initialized) {
1220 case SECCLASS_PROCESS:
1230 context_init(&newcontext);
1232 read_lock(&policy_rwlock);
1234 scontext = sidtab_search(&sidtab, ssid);
1236 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
1241 tcontext = sidtab_search(&sidtab, tsid);
1243 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
1249 /* Set the user identity. */
1250 switch (specified) {
1251 case AVTAB_TRANSITION:
1253 /* Use the process user identity. */
1254 newcontext.user = scontext->user;
1257 /* Use the related object owner. */
1258 newcontext.user = tcontext->user;
1262 /* Set the role and type to default values. */
1264 case SECCLASS_PROCESS:
1265 /* Use the current role and type of process. */
1266 newcontext.role = scontext->role;
1267 newcontext.type = scontext->type;
1270 /* Use the well-defined object role. */
1271 newcontext.role = OBJECT_R_VAL;
1272 /* Use the type of the related object. */
1273 newcontext.type = tcontext->type;
1276 /* Look for a type transition/member/change rule. */
1277 avkey.source_type = scontext->type;
1278 avkey.target_type = tcontext->type;
1279 avkey.target_class = tclass;
1280 avkey.specified = specified;
1281 avdatum = avtab_search(&policydb.te_avtab, &avkey);
1283 /* If no permanent rule, also check for enabled conditional rules */
1285 node = avtab_search_node(&policydb.te_cond_avtab, &avkey);
1286 for (; node; node = avtab_search_node_next(node, specified)) {
1287 if (node->key.specified & AVTAB_ENABLED) {
1288 avdatum = &node->datum;
1295 /* Use the type from the type transition/member/change rule. */
1296 newcontext.type = avdatum->data;
1299 /* Check for class-specific changes. */
1301 case SECCLASS_PROCESS:
1302 if (specified & AVTAB_TRANSITION) {
1303 /* Look for a role transition rule. */
1304 for (roletr = policydb.role_tr; roletr;
1305 roletr = roletr->next) {
1306 if (roletr->role == scontext->role &&
1307 roletr->type == tcontext->type) {
1308 /* Use the role transition rule. */
1309 newcontext.role = roletr->new_role;
1319 /* Set the MLS attributes.
1320 This is done last because it may allocate memory. */
1321 rc = mls_compute_sid(scontext, tcontext, tclass, specified, &newcontext);
1325 /* Check the validity of the context. */
1326 if (!policydb_context_isvalid(&policydb, &newcontext)) {
1327 rc = compute_sid_handle_invalid_context(scontext,
1334 /* Obtain the sid for the context. */
1335 rc = sidtab_context_to_sid(&sidtab, &newcontext, out_sid);
1337 read_unlock(&policy_rwlock);
1338 context_destroy(&newcontext);
1344 * security_transition_sid - Compute the SID for a new subject/object.
1345 * @ssid: source security identifier
1346 * @tsid: target security identifier
1347 * @tclass: target security class
1348 * @out_sid: security identifier for new subject/object
1350 * Compute a SID to use for labeling a new subject or object in the
1351 * class @tclass based on a SID pair (@ssid, @tsid).
1352 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1353 * if insufficient memory is available, or %0 if the new SID was
1354 * computed successfully.
1356 int security_transition_sid(u32 ssid,
1361 return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION, out_sid);
1365 * security_member_sid - Compute the SID for member selection.
1366 * @ssid: source security identifier
1367 * @tsid: target security identifier
1368 * @tclass: target security class
1369 * @out_sid: security identifier for selected member
1371 * Compute a SID to use when selecting a member of a polyinstantiated
1372 * object of class @tclass based on a SID pair (@ssid, @tsid).
1373 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1374 * if insufficient memory is available, or %0 if the SID was
1375 * computed successfully.
1377 int security_member_sid(u32 ssid,
1382 return security_compute_sid(ssid, tsid, tclass, AVTAB_MEMBER, out_sid);
1386 * security_change_sid - Compute the SID for object relabeling.
1387 * @ssid: source security identifier
1388 * @tsid: target security identifier
1389 * @tclass: target security class
1390 * @out_sid: security identifier for selected member
1392 * Compute a SID to use for relabeling an object of class @tclass
1393 * based on a SID pair (@ssid, @tsid).
1394 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1395 * if insufficient memory is available, or %0 if the SID was
1396 * computed successfully.
1398 int security_change_sid(u32 ssid,
1403 return security_compute_sid(ssid, tsid, tclass, AVTAB_CHANGE, out_sid);
1407 * Verify that each kernel class that is defined in the
1410 static int validate_classes(struct policydb *p)
1413 struct class_datum *cladatum;
1414 struct perm_datum *perdatum;
1415 u32 nprim, tmp, common_pts_len, perm_val, pol_val;
1417 const struct selinux_class_perm *kdefs = &selinux_class_perm;
1418 const char *def_class, *def_perm, *pol_class;
1419 struct symtab *perms;
1420 bool print_unknown_handle = 0;
1422 if (p->allow_unknown) {
1423 u32 num_classes = kdefs->cts_len;
1424 p->undefined_perms = kcalloc(num_classes, sizeof(u32), GFP_KERNEL);
1425 if (!p->undefined_perms)
1429 for (i = 1; i < kdefs->cts_len; i++) {
1430 def_class = kdefs->class_to_string[i];
1433 if (i > p->p_classes.nprim) {
1435 "SELinux: class %s not defined in policy\n",
1437 if (p->reject_unknown)
1439 if (p->allow_unknown)
1440 p->undefined_perms[i-1] = ~0U;
1441 print_unknown_handle = 1;
1444 pol_class = p->p_class_val_to_name[i-1];
1445 if (strcmp(pol_class, def_class)) {
1447 "SELinux: class %d is incorrect, found %s but should be %s\n",
1448 i, pol_class, def_class);
1452 for (i = 0; i < kdefs->av_pts_len; i++) {
1453 class_val = kdefs->av_perm_to_string[i].tclass;
1454 perm_val = kdefs->av_perm_to_string[i].value;
1455 def_perm = kdefs->av_perm_to_string[i].name;
1456 if (class_val > p->p_classes.nprim)
1458 pol_class = p->p_class_val_to_name[class_val-1];
1459 cladatum = hashtab_search(p->p_classes.table, pol_class);
1461 perms = &cladatum->permissions;
1462 nprim = 1 << (perms->nprim - 1);
1463 if (perm_val > nprim) {
1465 "SELinux: permission %s in class %s not defined in policy\n",
1466 def_perm, pol_class);
1467 if (p->reject_unknown)
1469 if (p->allow_unknown)
1470 p->undefined_perms[class_val-1] |= perm_val;
1471 print_unknown_handle = 1;
1474 perdatum = hashtab_search(perms->table, def_perm);
1475 if (perdatum == NULL) {
1477 "SELinux: permission %s in class %s not found in policy, bad policy\n",
1478 def_perm, pol_class);
1481 pol_val = 1 << (perdatum->value - 1);
1482 if (pol_val != perm_val) {
1484 "SELinux: permission %s in class %s has incorrect value\n",
1485 def_perm, pol_class);
1489 for (i = 0; i < kdefs->av_inherit_len; i++) {
1490 class_val = kdefs->av_inherit[i].tclass;
1491 if (class_val > p->p_classes.nprim)
1493 pol_class = p->p_class_val_to_name[class_val-1];
1494 cladatum = hashtab_search(p->p_classes.table, pol_class);
1496 if (!cladatum->comdatum) {
1498 "SELinux: class %s should have an inherits clause but does not\n",
1502 tmp = kdefs->av_inherit[i].common_base;
1504 while (!(tmp & 0x01)) {
1508 perms = &cladatum->comdatum->permissions;
1509 for (j = 0; j < common_pts_len; j++) {
1510 def_perm = kdefs->av_inherit[i].common_pts[j];
1511 if (j >= perms->nprim) {
1513 "SELinux: permission %s in class %s not defined in policy\n",
1514 def_perm, pol_class);
1515 if (p->reject_unknown)
1517 if (p->allow_unknown)
1518 p->undefined_perms[class_val-1] |= (1 << j);
1519 print_unknown_handle = 1;
1522 perdatum = hashtab_search(perms->table, def_perm);
1523 if (perdatum == NULL) {
1525 "SELinux: permission %s in class %s not found in policy, bad policy\n",
1526 def_perm, pol_class);
1529 if (perdatum->value != j + 1) {
1531 "SELinux: permission %s in class %s has incorrect value\n",
1532 def_perm, pol_class);
1537 if (print_unknown_handle)
1538 printk(KERN_INFO "SELinux: the above unknown classes and permissions will be %s\n",
1539 (security_get_allow_unknown() ? "allowed" : "denied"));
1543 /* Clone the SID into the new SID table. */
1544 static int clone_sid(u32 sid,
1545 struct context *context,
1548 struct sidtab *s = arg;
1550 return sidtab_insert(s, sid, context);
1553 static inline int convert_context_handle_invalid_context(struct context *context)
1557 if (selinux_enforcing) {
1563 if (!context_struct_to_string(context, &s, &len)) {
1565 "SELinux: Context %s would be invalid if enforcing\n",
1573 struct convert_context_args {
1574 struct policydb *oldp;
1575 struct policydb *newp;
1579 * Convert the values in the security context
1580 * structure `c' from the values specified
1581 * in the policy `p->oldp' to the values specified
1582 * in the policy `p->newp'. Verify that the
1583 * context is valid under the new policy.
1585 static int convert_context(u32 key,
1589 struct convert_context_args *args;
1590 struct context oldc;
1591 struct role_datum *role;
1592 struct type_datum *typdatum;
1593 struct user_datum *usrdatum;
1602 s = kstrdup(c->str, GFP_KERNEL);
1607 rc = string_to_context_struct(args->newp, NULL, s,
1608 c->len, &ctx, SECSID_NULL);
1612 "SELinux: Context %s became valid (mapped).\n",
1614 /* Replace string with mapped representation. */
1616 memcpy(c, &ctx, sizeof(*c));
1618 } else if (rc == -EINVAL) {
1619 /* Retain string representation for later mapping. */
1623 /* Other error condition, e.g. ENOMEM. */
1625 "SELinux: Unable to map context %s, rc = %d.\n",
1631 rc = context_cpy(&oldc, c);
1637 /* Convert the user. */
1638 usrdatum = hashtab_search(args->newp->p_users.table,
1639 args->oldp->p_user_val_to_name[c->user - 1]);
1642 c->user = usrdatum->value;
1644 /* Convert the role. */
1645 role = hashtab_search(args->newp->p_roles.table,
1646 args->oldp->p_role_val_to_name[c->role - 1]);
1649 c->role = role->value;
1651 /* Convert the type. */
1652 typdatum = hashtab_search(args->newp->p_types.table,
1653 args->oldp->p_type_val_to_name[c->type - 1]);
1656 c->type = typdatum->value;
1658 rc = mls_convert_context(args->oldp, args->newp, c);
1662 /* Check the validity of the new context. */
1663 if (!policydb_context_isvalid(args->newp, c)) {
1664 rc = convert_context_handle_invalid_context(&oldc);
1669 context_destroy(&oldc);
1674 /* Map old representation to string and save it. */
1675 if (context_struct_to_string(&oldc, &s, &len))
1677 context_destroy(&oldc);
1682 "SELinux: Context %s became invalid (unmapped).\n",
1688 static void security_load_policycaps(void)
1690 selinux_policycap_netpeer = ebitmap_get_bit(&policydb.policycaps,
1691 POLICYDB_CAPABILITY_NETPEER);
1692 selinux_policycap_openperm = ebitmap_get_bit(&policydb.policycaps,
1693 POLICYDB_CAPABILITY_OPENPERM);
1696 extern void selinux_complete_init(void);
1697 static int security_preserve_bools(struct policydb *p);
1700 * security_load_policy - Load a security policy configuration.
1701 * @data: binary policy data
1702 * @len: length of data in bytes
1704 * Load a new set of security policy configuration data,
1705 * validate it and convert the SID table as necessary.
1706 * This function will flush the access vector cache after
1707 * loading the new policy.
1709 int security_load_policy(void *data, size_t len)
1711 struct policydb oldpolicydb, newpolicydb;
1712 struct sidtab oldsidtab, newsidtab;
1713 struct convert_context_args args;
1716 struct policy_file file = { data, len }, *fp = &file;
1718 if (!ss_initialized) {
1720 if (policydb_read(&policydb, fp)) {
1721 avtab_cache_destroy();
1724 if (policydb_load_isids(&policydb, &sidtab)) {
1725 policydb_destroy(&policydb);
1726 avtab_cache_destroy();
1729 /* Verify that the kernel defined classes are correct. */
1730 if (validate_classes(&policydb)) {
1732 "SELinux: the definition of a class is incorrect\n");
1733 sidtab_destroy(&sidtab);
1734 policydb_destroy(&policydb);
1735 avtab_cache_destroy();
1738 security_load_policycaps();
1739 policydb_loaded_version = policydb.policyvers;
1741 seqno = ++latest_granting;
1742 selinux_complete_init();
1743 avc_ss_reset(seqno);
1744 selnl_notify_policyload(seqno);
1745 selinux_netlbl_cache_invalidate();
1746 selinux_xfrm_notify_policyload();
1751 sidtab_hash_eval(&sidtab, "sids");
1754 if (policydb_read(&newpolicydb, fp))
1757 if (sidtab_init(&newsidtab)) {
1758 policydb_destroy(&newpolicydb);
1762 /* Verify that the kernel defined classes are correct. */
1763 if (validate_classes(&newpolicydb)) {
1765 "SELinux: the definition of a class is incorrect\n");
1770 rc = security_preserve_bools(&newpolicydb);
1772 printk(KERN_ERR "SELinux: unable to preserve booleans\n");
1776 /* Clone the SID table. */
1777 sidtab_shutdown(&sidtab);
1778 if (sidtab_map(&sidtab, clone_sid, &newsidtab)) {
1784 * Convert the internal representations of contexts
1785 * in the new SID table.
1787 args.oldp = &policydb;
1788 args.newp = &newpolicydb;
1789 rc = sidtab_map(&newsidtab, convert_context, &args);
1793 /* Save the old policydb and SID table to free later. */
1794 memcpy(&oldpolicydb, &policydb, sizeof policydb);
1795 sidtab_set(&oldsidtab, &sidtab);
1797 /* Install the new policydb and SID table. */
1798 write_lock_irq(&policy_rwlock);
1799 memcpy(&policydb, &newpolicydb, sizeof policydb);
1800 sidtab_set(&sidtab, &newsidtab);
1801 security_load_policycaps();
1802 seqno = ++latest_granting;
1803 policydb_loaded_version = policydb.policyvers;
1804 write_unlock_irq(&policy_rwlock);
1806 /* Free the old policydb and SID table. */
1807 policydb_destroy(&oldpolicydb);
1808 sidtab_destroy(&oldsidtab);
1810 avc_ss_reset(seqno);
1811 selnl_notify_policyload(seqno);
1812 selinux_netlbl_cache_invalidate();
1813 selinux_xfrm_notify_policyload();
1818 sidtab_destroy(&newsidtab);
1819 policydb_destroy(&newpolicydb);
1825 * security_port_sid - Obtain the SID for a port.
1826 * @protocol: protocol number
1827 * @port: port number
1828 * @out_sid: security identifier
1830 int security_port_sid(u8 protocol, u16 port, u32 *out_sid)
1835 read_lock(&policy_rwlock);
1837 c = policydb.ocontexts[OCON_PORT];
1839 if (c->u.port.protocol == protocol &&
1840 c->u.port.low_port <= port &&
1841 c->u.port.high_port >= port)
1848 rc = sidtab_context_to_sid(&sidtab,
1854 *out_sid = c->sid[0];
1856 *out_sid = SECINITSID_PORT;
1860 read_unlock(&policy_rwlock);
1865 * security_netif_sid - Obtain the SID for a network interface.
1866 * @name: interface name
1867 * @if_sid: interface SID
1869 int security_netif_sid(char *name, u32 *if_sid)
1874 read_lock(&policy_rwlock);
1876 c = policydb.ocontexts[OCON_NETIF];
1878 if (strcmp(name, c->u.name) == 0)
1884 if (!c->sid[0] || !c->sid[1]) {
1885 rc = sidtab_context_to_sid(&sidtab,
1890 rc = sidtab_context_to_sid(&sidtab,
1896 *if_sid = c->sid[0];
1898 *if_sid = SECINITSID_NETIF;
1901 read_unlock(&policy_rwlock);
1905 static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask)
1909 for (i = 0; i < 4; i++)
1910 if (addr[i] != (input[i] & mask[i])) {
1919 * security_node_sid - Obtain the SID for a node (host).
1920 * @domain: communication domain aka address family
1922 * @addrlen: address length in bytes
1923 * @out_sid: security identifier
1925 int security_node_sid(u16 domain,
1933 read_lock(&policy_rwlock);
1939 if (addrlen != sizeof(u32)) {
1944 addr = *((u32 *)addrp);
1946 c = policydb.ocontexts[OCON_NODE];
1948 if (c->u.node.addr == (addr & c->u.node.mask))
1956 if (addrlen != sizeof(u64) * 2) {
1960 c = policydb.ocontexts[OCON_NODE6];
1962 if (match_ipv6_addrmask(addrp, c->u.node6.addr,
1970 *out_sid = SECINITSID_NODE;
1976 rc = sidtab_context_to_sid(&sidtab,
1982 *out_sid = c->sid[0];
1984 *out_sid = SECINITSID_NODE;
1988 read_unlock(&policy_rwlock);
1995 * security_get_user_sids - Obtain reachable SIDs for a user.
1996 * @fromsid: starting SID
1997 * @username: username
1998 * @sids: array of reachable SIDs for user
1999 * @nel: number of elements in @sids
2001 * Generate the set of SIDs for legal security contexts
2002 * for a given user that can be reached by @fromsid.
2003 * Set *@sids to point to a dynamically allocated
2004 * array containing the set of SIDs. Set *@nel to the
2005 * number of elements in the array.
2008 int security_get_user_sids(u32 fromsid,
2013 struct context *fromcon, usercon;
2014 u32 *mysids = NULL, *mysids2, sid;
2015 u32 mynel = 0, maxnel = SIDS_NEL;
2016 struct user_datum *user;
2017 struct role_datum *role;
2018 struct ebitmap_node *rnode, *tnode;
2024 if (!ss_initialized)
2027 read_lock(&policy_rwlock);
2029 context_init(&usercon);
2031 fromcon = sidtab_search(&sidtab, fromsid);
2037 user = hashtab_search(policydb.p_users.table, username);
2042 usercon.user = user->value;
2044 mysids = kcalloc(maxnel, sizeof(*mysids), GFP_ATOMIC);
2050 ebitmap_for_each_positive_bit(&user->roles, rnode, i) {
2051 role = policydb.role_val_to_struct[i];
2053 ebitmap_for_each_positive_bit(&role->types, tnode, j) {
2056 if (mls_setup_user_range(fromcon, user, &usercon))
2059 rc = sidtab_context_to_sid(&sidtab, &usercon, &sid);
2062 if (mynel < maxnel) {
2063 mysids[mynel++] = sid;
2066 mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
2071 memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
2074 mysids[mynel++] = sid;
2080 read_unlock(&policy_rwlock);
2086 mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);
2092 for (i = 0, j = 0; i < mynel; i++) {
2093 rc = avc_has_perm_noaudit(fromsid, mysids[i],
2095 PROCESS__TRANSITION, AVC_STRICT,
2098 mysids2[j++] = mysids[i];
2110 * security_genfs_sid - Obtain a SID for a file in a filesystem
2111 * @fstype: filesystem type
2112 * @path: path from root of mount
2113 * @sclass: file security class
2114 * @sid: SID for path
2116 * Obtain a SID to use for a file in a filesystem that
2117 * cannot support xattr or use a fixed labeling behavior like
2118 * transition SIDs or task SIDs.
2120 int security_genfs_sid(const char *fstype,
2126 struct genfs *genfs;
2128 int rc = 0, cmp = 0;
2130 while (path[0] == '/' && path[1] == '/')
2133 read_lock(&policy_rwlock);
2135 for (genfs = policydb.genfs; genfs; genfs = genfs->next) {
2136 cmp = strcmp(fstype, genfs->fstype);
2141 if (!genfs || cmp) {
2142 *sid = SECINITSID_UNLABELED;
2147 for (c = genfs->head; c; c = c->next) {
2148 len = strlen(c->u.name);
2149 if ((!c->v.sclass || sclass == c->v.sclass) &&
2150 (strncmp(c->u.name, path, len) == 0))
2155 *sid = SECINITSID_UNLABELED;
2161 rc = sidtab_context_to_sid(&sidtab,
2170 read_unlock(&policy_rwlock);
2175 * security_fs_use - Determine how to handle labeling for a filesystem.
2176 * @fstype: filesystem type
2177 * @behavior: labeling behavior
2178 * @sid: SID for filesystem (superblock)
2180 int security_fs_use(
2182 unsigned int *behavior,
2188 read_lock(&policy_rwlock);
2190 c = policydb.ocontexts[OCON_FSUSE];
2192 if (strcmp(fstype, c->u.name) == 0)
2198 *behavior = c->v.behavior;
2200 rc = sidtab_context_to_sid(&sidtab,
2208 rc = security_genfs_sid(fstype, "/", SECCLASS_DIR, sid);
2210 *behavior = SECURITY_FS_USE_NONE;
2213 *behavior = SECURITY_FS_USE_GENFS;
2218 read_unlock(&policy_rwlock);
2222 int security_get_bools(int *len, char ***names, int **values)
2224 int i, rc = -ENOMEM;
2226 read_lock(&policy_rwlock);
2230 *len = policydb.p_bools.nprim;
2236 *names = kcalloc(*len, sizeof(char *), GFP_ATOMIC);
2240 *values = kcalloc(*len, sizeof(int), GFP_ATOMIC);
2244 for (i = 0; i < *len; i++) {
2246 (*values)[i] = policydb.bool_val_to_struct[i]->state;
2247 name_len = strlen(policydb.p_bool_val_to_name[i]) + 1;
2248 (*names)[i] = kmalloc(sizeof(char) * name_len, GFP_ATOMIC);
2251 strncpy((*names)[i], policydb.p_bool_val_to_name[i], name_len);
2252 (*names)[i][name_len - 1] = 0;
2256 read_unlock(&policy_rwlock);
2260 for (i = 0; i < *len; i++)
2268 int security_set_bools(int len, int *values)
2271 int lenp, seqno = 0;
2272 struct cond_node *cur;
2274 write_lock_irq(&policy_rwlock);
2276 lenp = policydb.p_bools.nprim;
2282 for (i = 0; i < len; i++) {
2283 if (!!values[i] != policydb.bool_val_to_struct[i]->state) {
2284 audit_log(current->audit_context, GFP_ATOMIC,
2285 AUDIT_MAC_CONFIG_CHANGE,
2286 "bool=%s val=%d old_val=%d auid=%u ses=%u",
2287 policydb.p_bool_val_to_name[i],
2289 policydb.bool_val_to_struct[i]->state,
2290 audit_get_loginuid(current),
2291 audit_get_sessionid(current));
2294 policydb.bool_val_to_struct[i]->state = 1;
2296 policydb.bool_val_to_struct[i]->state = 0;
2299 for (cur = policydb.cond_list; cur; cur = cur->next) {
2300 rc = evaluate_cond_node(&policydb, cur);
2305 seqno = ++latest_granting;
2308 write_unlock_irq(&policy_rwlock);
2310 avc_ss_reset(seqno);
2311 selnl_notify_policyload(seqno);
2312 selinux_xfrm_notify_policyload();
2317 int security_get_bool_value(int bool)
2322 read_lock(&policy_rwlock);
2324 len = policydb.p_bools.nprim;
2330 rc = policydb.bool_val_to_struct[bool]->state;
2332 read_unlock(&policy_rwlock);
2336 static int security_preserve_bools(struct policydb *p)
2338 int rc, nbools = 0, *bvalues = NULL, i;
2339 char **bnames = NULL;
2340 struct cond_bool_datum *booldatum;
2341 struct cond_node *cur;
2343 rc = security_get_bools(&nbools, &bnames, &bvalues);
2346 for (i = 0; i < nbools; i++) {
2347 booldatum = hashtab_search(p->p_bools.table, bnames[i]);
2349 booldatum->state = bvalues[i];
2351 for (cur = p->cond_list; cur; cur = cur->next) {
2352 rc = evaluate_cond_node(p, cur);
2359 for (i = 0; i < nbools; i++)
2368 * security_sid_mls_copy() - computes a new sid based on the given
2369 * sid and the mls portion of mls_sid.
2371 int security_sid_mls_copy(u32 sid, u32 mls_sid, u32 *new_sid)
2373 struct context *context1;
2374 struct context *context2;
2375 struct context newcon;
2380 if (!ss_initialized || !selinux_mls_enabled) {
2385 context_init(&newcon);
2387 read_lock(&policy_rwlock);
2388 context1 = sidtab_search(&sidtab, sid);
2390 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2396 context2 = sidtab_search(&sidtab, mls_sid);
2398 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2404 newcon.user = context1->user;
2405 newcon.role = context1->role;
2406 newcon.type = context1->type;
2407 rc = mls_context_cpy(&newcon, context2);
2411 /* Check the validity of the new context. */
2412 if (!policydb_context_isvalid(&policydb, &newcon)) {
2413 rc = convert_context_handle_invalid_context(&newcon);
2418 rc = sidtab_context_to_sid(&sidtab, &newcon, new_sid);
2422 if (!context_struct_to_string(&newcon, &s, &len)) {
2423 audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2424 "security_sid_mls_copy: invalid context %s", s);
2429 read_unlock(&policy_rwlock);
2430 context_destroy(&newcon);
2436 * security_net_peersid_resolve - Compare and resolve two network peer SIDs
2437 * @nlbl_sid: NetLabel SID
2438 * @nlbl_type: NetLabel labeling protocol type
2439 * @xfrm_sid: XFRM SID
2442 * Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be
2443 * resolved into a single SID it is returned via @peer_sid and the function
2444 * returns zero. Otherwise @peer_sid is set to SECSID_NULL and the function
2445 * returns a negative value. A table summarizing the behavior is below:
2447 * | function return | @sid
2448 * ------------------------------+-----------------+-----------------
2449 * no peer labels | 0 | SECSID_NULL
2450 * single peer label | 0 | <peer_label>
2451 * multiple, consistent labels | 0 | <peer_label>
2452 * multiple, inconsistent labels | -<errno> | SECSID_NULL
2455 int security_net_peersid_resolve(u32 nlbl_sid, u32 nlbl_type,
2460 struct context *nlbl_ctx;
2461 struct context *xfrm_ctx;
2463 /* handle the common (which also happens to be the set of easy) cases
2464 * right away, these two if statements catch everything involving a
2465 * single or absent peer SID/label */
2466 if (xfrm_sid == SECSID_NULL) {
2467 *peer_sid = nlbl_sid;
2470 /* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a "fallback" label
2471 * and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label
2473 if (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) {
2474 *peer_sid = xfrm_sid;
2478 /* we don't need to check ss_initialized here since the only way both
2479 * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the
2480 * security server was initialized and ss_initialized was true */
2481 if (!selinux_mls_enabled) {
2482 *peer_sid = SECSID_NULL;
2486 read_lock(&policy_rwlock);
2488 nlbl_ctx = sidtab_search(&sidtab, nlbl_sid);
2490 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2491 __func__, nlbl_sid);
2495 xfrm_ctx = sidtab_search(&sidtab, xfrm_sid);
2497 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2498 __func__, xfrm_sid);
2502 rc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES);
2505 read_unlock(&policy_rwlock);
2507 /* at present NetLabel SIDs/labels really only carry MLS
2508 * information so if the MLS portion of the NetLabel SID
2509 * matches the MLS portion of the labeled XFRM SID/label
2510 * then pass along the XFRM SID as it is the most
2512 *peer_sid = xfrm_sid;
2514 *peer_sid = SECSID_NULL;
2518 static int get_classes_callback(void *k, void *d, void *args)
2520 struct class_datum *datum = d;
2521 char *name = k, **classes = args;
2522 int value = datum->value - 1;
2524 classes[value] = kstrdup(name, GFP_ATOMIC);
2525 if (!classes[value])
2531 int security_get_classes(char ***classes, int *nclasses)
2535 read_lock(&policy_rwlock);
2537 *nclasses = policydb.p_classes.nprim;
2538 *classes = kcalloc(*nclasses, sizeof(*classes), GFP_ATOMIC);
2542 rc = hashtab_map(policydb.p_classes.table, get_classes_callback,
2546 for (i = 0; i < *nclasses; i++)
2547 kfree((*classes)[i]);
2552 read_unlock(&policy_rwlock);
2556 static int get_permissions_callback(void *k, void *d, void *args)
2558 struct perm_datum *datum = d;
2559 char *name = k, **perms = args;
2560 int value = datum->value - 1;
2562 perms[value] = kstrdup(name, GFP_ATOMIC);
2569 int security_get_permissions(char *class, char ***perms, int *nperms)
2571 int rc = -ENOMEM, i;
2572 struct class_datum *match;
2574 read_lock(&policy_rwlock);
2576 match = hashtab_search(policydb.p_classes.table, class);
2578 printk(KERN_ERR "SELinux: %s: unrecognized class %s\n",
2584 *nperms = match->permissions.nprim;
2585 *perms = kcalloc(*nperms, sizeof(*perms), GFP_ATOMIC);
2589 if (match->comdatum) {
2590 rc = hashtab_map(match->comdatum->permissions.table,
2591 get_permissions_callback, *perms);
2596 rc = hashtab_map(match->permissions.table, get_permissions_callback,
2602 read_unlock(&policy_rwlock);
2606 read_unlock(&policy_rwlock);
2607 for (i = 0; i < *nperms; i++)
2613 int security_get_reject_unknown(void)
2615 return policydb.reject_unknown;
2618 int security_get_allow_unknown(void)
2620 return policydb.allow_unknown;
2624 * security_policycap_supported - Check for a specific policy capability
2625 * @req_cap: capability
2628 * This function queries the currently loaded policy to see if it supports the
2629 * capability specified by @req_cap. Returns true (1) if the capability is
2630 * supported, false (0) if it isn't supported.
2633 int security_policycap_supported(unsigned int req_cap)
2637 read_lock(&policy_rwlock);
2638 rc = ebitmap_get_bit(&policydb.policycaps, req_cap);
2639 read_unlock(&policy_rwlock);
2644 struct selinux_audit_rule {
2646 struct context au_ctxt;
2649 void selinux_audit_rule_free(void *vrule)
2651 struct selinux_audit_rule *rule = vrule;
2654 context_destroy(&rule->au_ctxt);
2659 int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule)
2661 struct selinux_audit_rule *tmprule;
2662 struct role_datum *roledatum;
2663 struct type_datum *typedatum;
2664 struct user_datum *userdatum;
2665 struct selinux_audit_rule **rule = (struct selinux_audit_rule **)vrule;
2670 if (!ss_initialized)
2674 case AUDIT_SUBJ_USER:
2675 case AUDIT_SUBJ_ROLE:
2676 case AUDIT_SUBJ_TYPE:
2677 case AUDIT_OBJ_USER:
2678 case AUDIT_OBJ_ROLE:
2679 case AUDIT_OBJ_TYPE:
2680 /* only 'equals' and 'not equals' fit user, role, and type */
2681 if (op != Audit_equal && op != Audit_not_equal)
2684 case AUDIT_SUBJ_SEN:
2685 case AUDIT_SUBJ_CLR:
2686 case AUDIT_OBJ_LEV_LOW:
2687 case AUDIT_OBJ_LEV_HIGH:
2688 /* we do not allow a range, indicated by the presense of '-' */
2689 if (strchr(rulestr, '-'))
2693 /* only the above fields are valid */
2697 tmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL);
2701 context_init(&tmprule->au_ctxt);
2703 read_lock(&policy_rwlock);
2705 tmprule->au_seqno = latest_granting;
2708 case AUDIT_SUBJ_USER:
2709 case AUDIT_OBJ_USER:
2710 userdatum = hashtab_search(policydb.p_users.table, rulestr);
2714 tmprule->au_ctxt.user = userdatum->value;
2716 case AUDIT_SUBJ_ROLE:
2717 case AUDIT_OBJ_ROLE:
2718 roledatum = hashtab_search(policydb.p_roles.table, rulestr);
2722 tmprule->au_ctxt.role = roledatum->value;
2724 case AUDIT_SUBJ_TYPE:
2725 case AUDIT_OBJ_TYPE:
2726 typedatum = hashtab_search(policydb.p_types.table, rulestr);
2730 tmprule->au_ctxt.type = typedatum->value;
2732 case AUDIT_SUBJ_SEN:
2733 case AUDIT_SUBJ_CLR:
2734 case AUDIT_OBJ_LEV_LOW:
2735 case AUDIT_OBJ_LEV_HIGH:
2736 rc = mls_from_string(rulestr, &tmprule->au_ctxt, GFP_ATOMIC);
2740 read_unlock(&policy_rwlock);
2743 selinux_audit_rule_free(tmprule);
2752 /* Check to see if the rule contains any selinux fields */
2753 int selinux_audit_rule_known(struct audit_krule *rule)
2757 for (i = 0; i < rule->field_count; i++) {
2758 struct audit_field *f = &rule->fields[i];
2760 case AUDIT_SUBJ_USER:
2761 case AUDIT_SUBJ_ROLE:
2762 case AUDIT_SUBJ_TYPE:
2763 case AUDIT_SUBJ_SEN:
2764 case AUDIT_SUBJ_CLR:
2765 case AUDIT_OBJ_USER:
2766 case AUDIT_OBJ_ROLE:
2767 case AUDIT_OBJ_TYPE:
2768 case AUDIT_OBJ_LEV_LOW:
2769 case AUDIT_OBJ_LEV_HIGH:
2777 int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule,
2778 struct audit_context *actx)
2780 struct context *ctxt;
2781 struct mls_level *level;
2782 struct selinux_audit_rule *rule = vrule;
2786 audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2787 "selinux_audit_rule_match: missing rule\n");
2791 read_lock(&policy_rwlock);
2793 if (rule->au_seqno < latest_granting) {
2794 audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2795 "selinux_audit_rule_match: stale rule\n");
2800 ctxt = sidtab_search(&sidtab, sid);
2802 audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2803 "selinux_audit_rule_match: unrecognized SID %d\n",
2809 /* a field/op pair that is not caught here will simply fall through
2812 case AUDIT_SUBJ_USER:
2813 case AUDIT_OBJ_USER:
2816 match = (ctxt->user == rule->au_ctxt.user);
2818 case Audit_not_equal:
2819 match = (ctxt->user != rule->au_ctxt.user);
2823 case AUDIT_SUBJ_ROLE:
2824 case AUDIT_OBJ_ROLE:
2827 match = (ctxt->role == rule->au_ctxt.role);
2829 case Audit_not_equal:
2830 match = (ctxt->role != rule->au_ctxt.role);
2834 case AUDIT_SUBJ_TYPE:
2835 case AUDIT_OBJ_TYPE:
2838 match = (ctxt->type == rule->au_ctxt.type);
2840 case Audit_not_equal:
2841 match = (ctxt->type != rule->au_ctxt.type);
2845 case AUDIT_SUBJ_SEN:
2846 case AUDIT_SUBJ_CLR:
2847 case AUDIT_OBJ_LEV_LOW:
2848 case AUDIT_OBJ_LEV_HIGH:
2849 level = ((field == AUDIT_SUBJ_SEN ||
2850 field == AUDIT_OBJ_LEV_LOW) ?
2851 &ctxt->range.level[0] : &ctxt->range.level[1]);
2854 match = mls_level_eq(&rule->au_ctxt.range.level[0],
2857 case Audit_not_equal:
2858 match = !mls_level_eq(&rule->au_ctxt.range.level[0],
2862 match = (mls_level_dom(&rule->au_ctxt.range.level[0],
2864 !mls_level_eq(&rule->au_ctxt.range.level[0],
2868 match = mls_level_dom(&rule->au_ctxt.range.level[0],
2872 match = (mls_level_dom(level,
2873 &rule->au_ctxt.range.level[0]) &&
2874 !mls_level_eq(level,
2875 &rule->au_ctxt.range.level[0]));
2878 match = mls_level_dom(level,
2879 &rule->au_ctxt.range.level[0]);
2885 read_unlock(&policy_rwlock);
2889 static int (*aurule_callback)(void) = audit_update_lsm_rules;
2891 static int aurule_avc_callback(u32 event, u32 ssid, u32 tsid,
2892 u16 class, u32 perms, u32 *retained)
2896 if (event == AVC_CALLBACK_RESET && aurule_callback)
2897 err = aurule_callback();
2901 static int __init aurule_init(void)
2905 err = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET,
2906 SECSID_NULL, SECSID_NULL, SECCLASS_NULL, 0);
2908 panic("avc_add_callback() failed, error %d\n", err);
2912 __initcall(aurule_init);
2914 #ifdef CONFIG_NETLABEL
2916 * security_netlbl_cache_add - Add an entry to the NetLabel cache
2917 * @secattr: the NetLabel packet security attributes
2918 * @sid: the SELinux SID
2921 * Attempt to cache the context in @ctx, which was derived from the packet in
2922 * @skb, in the NetLabel subsystem cache. This function assumes @secattr has
2923 * already been initialized.
2926 static void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr,
2931 sid_cache = kmalloc(sizeof(*sid_cache), GFP_ATOMIC);
2932 if (sid_cache == NULL)
2934 secattr->cache = netlbl_secattr_cache_alloc(GFP_ATOMIC);
2935 if (secattr->cache == NULL) {
2941 secattr->cache->free = kfree;
2942 secattr->cache->data = sid_cache;
2943 secattr->flags |= NETLBL_SECATTR_CACHE;
2947 * security_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID
2948 * @secattr: the NetLabel packet security attributes
2949 * @sid: the SELinux SID
2952 * Convert the given NetLabel security attributes in @secattr into a
2953 * SELinux SID. If the @secattr field does not contain a full SELinux
2954 * SID/context then use SECINITSID_NETMSG as the foundation. If possibile the
2955 * 'cache' field of @secattr is set and the CACHE flag is set; this is to
2956 * allow the @secattr to be used by NetLabel to cache the secattr to SID
2957 * conversion for future lookups. Returns zero on success, negative values on
2961 int security_netlbl_secattr_to_sid(struct netlbl_lsm_secattr *secattr,
2965 struct context *ctx;
2966 struct context ctx_new;
2968 if (!ss_initialized) {
2973 read_lock(&policy_rwlock);
2975 if (secattr->flags & NETLBL_SECATTR_CACHE) {
2976 *sid = *(u32 *)secattr->cache->data;
2978 } else if (secattr->flags & NETLBL_SECATTR_SECID) {
2979 *sid = secattr->attr.secid;
2981 } else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) {
2982 ctx = sidtab_search(&sidtab, SECINITSID_NETMSG);
2984 goto netlbl_secattr_to_sid_return;
2986 context_init(&ctx_new);
2987 ctx_new.user = ctx->user;
2988 ctx_new.role = ctx->role;
2989 ctx_new.type = ctx->type;
2990 mls_import_netlbl_lvl(&ctx_new, secattr);
2991 if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
2992 if (ebitmap_netlbl_import(&ctx_new.range.level[0].cat,
2993 secattr->attr.mls.cat) != 0)
2994 goto netlbl_secattr_to_sid_return;
2995 memcpy(&ctx_new.range.level[1].cat,
2996 &ctx_new.range.level[0].cat,
2997 sizeof(ctx_new.range.level[0].cat));
2999 if (mls_context_isvalid(&policydb, &ctx_new) != 1)
3000 goto netlbl_secattr_to_sid_return_cleanup;
3002 rc = sidtab_context_to_sid(&sidtab, &ctx_new, sid);
3004 goto netlbl_secattr_to_sid_return_cleanup;
3006 security_netlbl_cache_add(secattr, *sid);
3008 ebitmap_destroy(&ctx_new.range.level[0].cat);
3014 netlbl_secattr_to_sid_return:
3015 read_unlock(&policy_rwlock);
3017 netlbl_secattr_to_sid_return_cleanup:
3018 ebitmap_destroy(&ctx_new.range.level[0].cat);
3019 goto netlbl_secattr_to_sid_return;
3023 * security_netlbl_sid_to_secattr - Convert a SELinux SID to a NetLabel secattr
3024 * @sid: the SELinux SID
3025 * @secattr: the NetLabel packet security attributes
3028 * Convert the given SELinux SID in @sid into a NetLabel security attribute.
3029 * Returns zero on success, negative values on failure.
3032 int security_netlbl_sid_to_secattr(u32 sid, struct netlbl_lsm_secattr *secattr)
3035 struct context *ctx;
3037 if (!ss_initialized)
3040 read_lock(&policy_rwlock);
3041 ctx = sidtab_search(&sidtab, sid);
3044 goto netlbl_sid_to_secattr_failure;
3046 secattr->domain = kstrdup(policydb.p_type_val_to_name[ctx->type - 1],
3048 if (secattr->domain == NULL) {
3050 goto netlbl_sid_to_secattr_failure;
3052 secattr->attr.secid = sid;
3053 secattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID;
3054 mls_export_netlbl_lvl(ctx, secattr);
3055 rc = mls_export_netlbl_cat(ctx, secattr);
3057 goto netlbl_sid_to_secattr_failure;
3058 read_unlock(&policy_rwlock);
3062 netlbl_sid_to_secattr_failure:
3063 read_unlock(&policy_rwlock);
3066 #endif /* CONFIG_NETLABEL */