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 * Copyright (C) 2006, 2007 Hewlett-Packard Development Company, L.P.
26 * Copyright (C) 2004-2006 Trusted Computer Solutions, Inc.
27 * Copyright (C) 2003 - 2004, 2006 Tresys Technology, LLC
28 * Copyright (C) 2003 Red Hat, Inc., James Morris <jmorris@redhat.com>
29 * This program is free software; you can redistribute it and/or modify
30 * it under the terms of the GNU General Public License as published by
31 * the Free Software Foundation, version 2.
33 #include <linux/kernel.h>
34 #include <linux/slab.h>
35 #include <linux/string.h>
36 #include <linux/spinlock.h>
37 #include <linux/rcupdate.h>
38 #include <linux/errno.h>
40 #include <linux/sched.h>
41 #include <linux/audit.h>
42 #include <linux/mutex.h>
43 #include <linux/selinux.h>
44 #include <net/netlabel.h>
54 #include "conditional.h"
62 extern void selnl_notify_policyload(u32 seqno);
63 unsigned int policydb_loaded_version;
65 int selinux_policycap_netpeer;
66 int selinux_policycap_openperm;
69 * This is declared in avc.c
71 extern const struct selinux_class_perm selinux_class_perm;
73 static DEFINE_RWLOCK(policy_rwlock);
75 static struct sidtab sidtab;
76 struct policydb policydb;
80 * The largest sequence number that has been used when
81 * providing an access decision to the access vector cache.
82 * The sequence number only changes when a policy change
85 static u32 latest_granting;
87 /* Forward declaration. */
88 static int context_struct_to_string(struct context *context, char **scontext,
91 static int context_struct_compute_av(struct context *scontext,
92 struct context *tcontext,
95 struct av_decision *avd);
97 * Return the boolean value of a constraint expression
98 * when it is applied to the specified source and target
101 * xcontext is a special beast... It is used by the validatetrans rules
102 * only. For these rules, scontext is the context before the transition,
103 * tcontext is the context after the transition, and xcontext is the context
104 * of the process performing the transition. All other callers of
105 * constraint_expr_eval should pass in NULL for xcontext.
107 static int constraint_expr_eval(struct context *scontext,
108 struct context *tcontext,
109 struct context *xcontext,
110 struct constraint_expr *cexpr)
114 struct role_datum *r1, *r2;
115 struct mls_level *l1, *l2;
116 struct constraint_expr *e;
117 int s[CEXPR_MAXDEPTH];
120 for (e = cexpr; e; e = e->next) {
121 switch (e->expr_type) {
137 if (sp == (CEXPR_MAXDEPTH-1))
141 val1 = scontext->user;
142 val2 = tcontext->user;
145 val1 = scontext->type;
146 val2 = tcontext->type;
149 val1 = scontext->role;
150 val2 = tcontext->role;
151 r1 = policydb.role_val_to_struct[val1 - 1];
152 r2 = policydb.role_val_to_struct[val2 - 1];
155 s[++sp] = ebitmap_get_bit(&r1->dominates,
159 s[++sp] = ebitmap_get_bit(&r2->dominates,
163 s[++sp] = (!ebitmap_get_bit(&r1->dominates,
165 !ebitmap_get_bit(&r2->dominates,
173 l1 = &(scontext->range.level[0]);
174 l2 = &(tcontext->range.level[0]);
177 l1 = &(scontext->range.level[0]);
178 l2 = &(tcontext->range.level[1]);
181 l1 = &(scontext->range.level[1]);
182 l2 = &(tcontext->range.level[0]);
185 l1 = &(scontext->range.level[1]);
186 l2 = &(tcontext->range.level[1]);
189 l1 = &(scontext->range.level[0]);
190 l2 = &(scontext->range.level[1]);
193 l1 = &(tcontext->range.level[0]);
194 l2 = &(tcontext->range.level[1]);
199 s[++sp] = mls_level_eq(l1, l2);
202 s[++sp] = !mls_level_eq(l1, l2);
205 s[++sp] = mls_level_dom(l1, l2);
208 s[++sp] = mls_level_dom(l2, l1);
211 s[++sp] = mls_level_incomp(l2, l1);
225 s[++sp] = (val1 == val2);
228 s[++sp] = (val1 != val2);
236 if (sp == (CEXPR_MAXDEPTH-1))
239 if (e->attr & CEXPR_TARGET)
241 else if (e->attr & CEXPR_XTARGET) {
248 if (e->attr & CEXPR_USER)
250 else if (e->attr & CEXPR_ROLE)
252 else if (e->attr & CEXPR_TYPE)
261 s[++sp] = ebitmap_get_bit(&e->names, val1 - 1);
264 s[++sp] = !ebitmap_get_bit(&e->names, val1 - 1);
282 * security_boundary_permission - drops violated permissions
283 * on boundary constraint.
285 static void type_attribute_bounds_av(struct context *scontext,
286 struct context *tcontext,
289 struct av_decision *avd)
291 struct context lo_scontext;
292 struct context lo_tcontext;
293 struct av_decision lo_avd;
294 struct type_datum *source
295 = policydb.type_val_to_struct[scontext->type - 1];
296 struct type_datum *target
297 = policydb.type_val_to_struct[tcontext->type - 1];
300 if (source->bounds) {
301 memset(&lo_avd, 0, sizeof(lo_avd));
303 memcpy(&lo_scontext, scontext, sizeof(lo_scontext));
304 lo_scontext.type = source->bounds;
306 context_struct_compute_av(&lo_scontext,
311 if ((lo_avd.allowed & avd->allowed) == avd->allowed)
312 return; /* no masked permission */
313 masked = ~lo_avd.allowed & avd->allowed;
316 if (target->bounds) {
317 memset(&lo_avd, 0, sizeof(lo_avd));
319 memcpy(&lo_tcontext, tcontext, sizeof(lo_tcontext));
320 lo_tcontext.type = target->bounds;
322 context_struct_compute_av(scontext,
327 if ((lo_avd.allowed & avd->allowed) == avd->allowed)
328 return; /* no masked permission */
329 masked = ~lo_avd.allowed & avd->allowed;
332 if (source->bounds && target->bounds) {
333 memset(&lo_avd, 0, sizeof(lo_avd));
335 * lo_scontext and lo_tcontext are already
339 context_struct_compute_av(&lo_scontext,
344 if ((lo_avd.allowed & avd->allowed) == avd->allowed)
345 return; /* no masked permission */
346 masked = ~lo_avd.allowed & avd->allowed;
350 struct audit_buffer *ab;
352 = policydb.p_type_val_to_name[source->value - 1];
354 = policydb.p_type_val_to_name[target->value - 1];
356 = policydb.p_class_val_to_name[tclass - 1];
358 /* mask violated permissions */
359 avd->allowed &= ~masked;
361 /* notice to userspace via audit message */
362 ab = audit_log_start(current->audit_context,
363 GFP_ATOMIC, AUDIT_SELINUX_ERR);
367 audit_log_format(ab, "av boundary violation: "
368 "source=%s target=%s tclass=%s",
369 stype_name, ttype_name, tclass_name);
370 avc_dump_av(ab, tclass, masked);
376 * Compute access vectors based on a context structure pair for
377 * the permissions in a particular class.
379 static int context_struct_compute_av(struct context *scontext,
380 struct context *tcontext,
383 struct av_decision *avd)
385 struct constraint_node *constraint;
386 struct role_allow *ra;
387 struct avtab_key avkey;
388 struct avtab_node *node;
389 struct class_datum *tclass_datum;
390 struct ebitmap *sattr, *tattr;
391 struct ebitmap_node *snode, *tnode;
392 const struct selinux_class_perm *kdefs = &selinux_class_perm;
396 * Remap extended Netlink classes for old policy versions.
397 * Do this here rather than socket_type_to_security_class()
398 * in case a newer policy version is loaded, allowing sockets
399 * to remain in the correct class.
401 if (policydb_loaded_version < POLICYDB_VERSION_NLCLASS)
402 if (tclass >= SECCLASS_NETLINK_ROUTE_SOCKET &&
403 tclass <= SECCLASS_NETLINK_DNRT_SOCKET)
404 tclass = SECCLASS_NETLINK_SOCKET;
407 * Initialize the access vectors to the default values.
410 avd->decided = 0xffffffff;
412 avd->auditdeny = 0xffffffff;
413 avd->seqno = latest_granting;
416 * Check for all the invalid cases.
418 * - tclass > policy and > kernel
419 * - tclass > policy but is a userspace class
420 * - tclass > policy but we do not allow unknowns
422 if (unlikely(!tclass))
424 if (unlikely(tclass > policydb.p_classes.nprim))
425 if (tclass > kdefs->cts_len ||
426 !kdefs->class_to_string[tclass] ||
427 !policydb.allow_unknown)
431 * Kernel class and we allow unknown so pad the allow decision
432 * the pad will be all 1 for unknown classes.
434 if (tclass <= kdefs->cts_len && policydb.allow_unknown)
435 avd->allowed = policydb.undefined_perms[tclass - 1];
438 * Not in policy. Since decision is completed (all 1 or all 0) return.
440 if (unlikely(tclass > policydb.p_classes.nprim))
443 tclass_datum = policydb.class_val_to_struct[tclass - 1];
446 * If a specific type enforcement rule was defined for
447 * this permission check, then use it.
449 avkey.target_class = tclass;
450 avkey.specified = AVTAB_AV;
451 sattr = &policydb.type_attr_map[scontext->type - 1];
452 tattr = &policydb.type_attr_map[tcontext->type - 1];
453 ebitmap_for_each_positive_bit(sattr, snode, i) {
454 ebitmap_for_each_positive_bit(tattr, tnode, j) {
455 avkey.source_type = i + 1;
456 avkey.target_type = j + 1;
457 for (node = avtab_search_node(&policydb.te_avtab, &avkey);
459 node = avtab_search_node_next(node, avkey.specified)) {
460 if (node->key.specified == AVTAB_ALLOWED)
461 avd->allowed |= node->datum.data;
462 else if (node->key.specified == AVTAB_AUDITALLOW)
463 avd->auditallow |= node->datum.data;
464 else if (node->key.specified == AVTAB_AUDITDENY)
465 avd->auditdeny &= node->datum.data;
468 /* Check conditional av table for additional permissions */
469 cond_compute_av(&policydb.te_cond_avtab, &avkey, avd);
475 * Remove any permissions prohibited by a constraint (this includes
478 constraint = tclass_datum->constraints;
480 if ((constraint->permissions & (avd->allowed)) &&
481 !constraint_expr_eval(scontext, tcontext, NULL,
483 avd->allowed = (avd->allowed) & ~(constraint->permissions);
485 constraint = constraint->next;
489 * If checking process transition permission and the
490 * role is changing, then check the (current_role, new_role)
493 if (tclass == SECCLASS_PROCESS &&
494 (avd->allowed & (PROCESS__TRANSITION | PROCESS__DYNTRANSITION)) &&
495 scontext->role != tcontext->role) {
496 for (ra = policydb.role_allow; ra; ra = ra->next) {
497 if (scontext->role == ra->role &&
498 tcontext->role == ra->new_role)
502 avd->allowed = (avd->allowed) & ~(PROCESS__TRANSITION |
503 PROCESS__DYNTRANSITION);
507 * If the given source and target types have boundary
508 * constraint, lazy checks have to mask any violated
509 * permission and notice it to userspace via audit.
511 type_attribute_bounds_av(scontext, tcontext,
512 tclass, requested, avd);
517 if (!tclass || tclass > kdefs->cts_len ||
518 !kdefs->class_to_string[tclass]) {
519 if (printk_ratelimit())
520 printk(KERN_ERR "SELinux: %s: unrecognized class %d\n",
526 * Known to the kernel, but not to the policy.
527 * Handle as a denial (allowed is 0).
533 * Given a sid find if the type has the permissive flag set
535 int security_permissive_sid(u32 sid)
537 struct context *context;
541 read_lock(&policy_rwlock);
543 context = sidtab_search(&sidtab, sid);
546 type = context->type;
548 * we are intentionally using type here, not type-1, the 0th bit may
549 * someday indicate that we are globally setting permissive in policy.
551 rc = ebitmap_get_bit(&policydb.permissive_map, type);
553 read_unlock(&policy_rwlock);
557 static int security_validtrans_handle_fail(struct context *ocontext,
558 struct context *ncontext,
559 struct context *tcontext,
562 char *o = NULL, *n = NULL, *t = NULL;
563 u32 olen, nlen, tlen;
565 if (context_struct_to_string(ocontext, &o, &olen) < 0)
567 if (context_struct_to_string(ncontext, &n, &nlen) < 0)
569 if (context_struct_to_string(tcontext, &t, &tlen) < 0)
571 audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
572 "security_validate_transition: denied for"
573 " oldcontext=%s newcontext=%s taskcontext=%s tclass=%s",
574 o, n, t, policydb.p_class_val_to_name[tclass-1]);
580 if (!selinux_enforcing)
585 int security_validate_transition(u32 oldsid, u32 newsid, u32 tasksid,
588 struct context *ocontext;
589 struct context *ncontext;
590 struct context *tcontext;
591 struct class_datum *tclass_datum;
592 struct constraint_node *constraint;
598 read_lock(&policy_rwlock);
601 * Remap extended Netlink classes for old policy versions.
602 * Do this here rather than socket_type_to_security_class()
603 * in case a newer policy version is loaded, allowing sockets
604 * to remain in the correct class.
606 if (policydb_loaded_version < POLICYDB_VERSION_NLCLASS)
607 if (tclass >= SECCLASS_NETLINK_ROUTE_SOCKET &&
608 tclass <= SECCLASS_NETLINK_DNRT_SOCKET)
609 tclass = SECCLASS_NETLINK_SOCKET;
611 if (!tclass || tclass > policydb.p_classes.nprim) {
612 printk(KERN_ERR "SELinux: %s: unrecognized class %d\n",
617 tclass_datum = policydb.class_val_to_struct[tclass - 1];
619 ocontext = sidtab_search(&sidtab, oldsid);
621 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
627 ncontext = sidtab_search(&sidtab, newsid);
629 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
635 tcontext = sidtab_search(&sidtab, tasksid);
637 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
643 constraint = tclass_datum->validatetrans;
645 if (!constraint_expr_eval(ocontext, ncontext, tcontext,
647 rc = security_validtrans_handle_fail(ocontext, ncontext,
651 constraint = constraint->next;
655 read_unlock(&policy_rwlock);
660 * security_bounded_transition - check whether the given
661 * transition is directed to bounded, or not.
662 * It returns 0, if @newsid is bounded by @oldsid.
663 * Otherwise, it returns error code.
665 * @oldsid : current security identifier
666 * @newsid : destinated security identifier
668 int security_bounded_transition(u32 old_sid, u32 new_sid)
670 struct context *old_context, *new_context;
671 struct type_datum *type;
675 read_lock(&policy_rwlock);
677 old_context = sidtab_search(&sidtab, old_sid);
679 printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n",
684 new_context = sidtab_search(&sidtab, new_sid);
686 printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n",
691 /* type/domain unchaned */
692 if (old_context->type == new_context->type) {
697 index = new_context->type;
699 type = policydb.type_val_to_struct[index - 1];
702 /* not bounded anymore */
708 /* @newsid is bounded by @oldsid */
709 if (type->bounds == old_context->type) {
713 index = type->bounds;
716 read_unlock(&policy_rwlock);
723 * security_compute_av - Compute access vector decisions.
724 * @ssid: source security identifier
725 * @tsid: target security identifier
726 * @tclass: target security class
727 * @requested: requested permissions
728 * @avd: access vector decisions
730 * Compute a set of access vector decisions based on the
731 * SID pair (@ssid, @tsid) for the permissions in @tclass.
732 * Return -%EINVAL if any of the parameters are invalid or %0
733 * if the access vector decisions were computed successfully.
735 int security_compute_av(u32 ssid,
739 struct av_decision *avd)
741 struct context *scontext = NULL, *tcontext = NULL;
744 if (!ss_initialized) {
745 avd->allowed = 0xffffffff;
746 avd->decided = 0xffffffff;
748 avd->auditdeny = 0xffffffff;
749 avd->seqno = latest_granting;
753 read_lock(&policy_rwlock);
755 scontext = sidtab_search(&sidtab, ssid);
757 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
762 tcontext = sidtab_search(&sidtab, tsid);
764 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
770 rc = context_struct_compute_av(scontext, tcontext, tclass,
773 read_unlock(&policy_rwlock);
778 * Write the security context string representation of
779 * the context structure `context' into a dynamically
780 * allocated string of the correct size. Set `*scontext'
781 * to point to this string and set `*scontext_len' to
782 * the length of the string.
784 static int context_struct_to_string(struct context *context, char **scontext, u32 *scontext_len)
792 *scontext_len = context->len;
793 *scontext = kstrdup(context->str, GFP_ATOMIC);
799 /* Compute the size of the context. */
800 *scontext_len += strlen(policydb.p_user_val_to_name[context->user - 1]) + 1;
801 *scontext_len += strlen(policydb.p_role_val_to_name[context->role - 1]) + 1;
802 *scontext_len += strlen(policydb.p_type_val_to_name[context->type - 1]) + 1;
803 *scontext_len += mls_compute_context_len(context);
805 /* Allocate space for the context; caller must free this space. */
806 scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
809 *scontext = scontextp;
812 * Copy the user name, role name and type name into the context.
814 sprintf(scontextp, "%s:%s:%s",
815 policydb.p_user_val_to_name[context->user - 1],
816 policydb.p_role_val_to_name[context->role - 1],
817 policydb.p_type_val_to_name[context->type - 1]);
818 scontextp += strlen(policydb.p_user_val_to_name[context->user - 1]) +
819 1 + strlen(policydb.p_role_val_to_name[context->role - 1]) +
820 1 + strlen(policydb.p_type_val_to_name[context->type - 1]);
822 mls_sid_to_context(context, &scontextp);
829 #include "initial_sid_to_string.h"
831 const char *security_get_initial_sid_context(u32 sid)
833 if (unlikely(sid > SECINITSID_NUM))
835 return initial_sid_to_string[sid];
838 static int security_sid_to_context_core(u32 sid, char **scontext,
839 u32 *scontext_len, int force)
841 struct context *context;
847 if (!ss_initialized) {
848 if (sid <= SECINITSID_NUM) {
851 *scontext_len = strlen(initial_sid_to_string[sid]) + 1;
852 scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
857 strcpy(scontextp, initial_sid_to_string[sid]);
858 *scontext = scontextp;
861 printk(KERN_ERR "SELinux: %s: called before initial "
862 "load_policy on unknown SID %d\n", __func__, sid);
866 read_lock(&policy_rwlock);
868 context = sidtab_search_force(&sidtab, sid);
870 context = sidtab_search(&sidtab, sid);
872 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
877 rc = context_struct_to_string(context, scontext, scontext_len);
879 read_unlock(&policy_rwlock);
886 * security_sid_to_context - Obtain a context for a given SID.
887 * @sid: security identifier, SID
888 * @scontext: security context
889 * @scontext_len: length in bytes
891 * Write the string representation of the context associated with @sid
892 * into a dynamically allocated string of the correct size. Set @scontext
893 * to point to this string and set @scontext_len to the length of the string.
895 int security_sid_to_context(u32 sid, char **scontext, u32 *scontext_len)
897 return security_sid_to_context_core(sid, scontext, scontext_len, 0);
900 int security_sid_to_context_force(u32 sid, char **scontext, u32 *scontext_len)
902 return security_sid_to_context_core(sid, scontext, scontext_len, 1);
906 * Caveat: Mutates scontext.
908 static int string_to_context_struct(struct policydb *pol,
909 struct sidtab *sidtabp,
915 struct role_datum *role;
916 struct type_datum *typdatum;
917 struct user_datum *usrdatum;
918 char *scontextp, *p, oldc;
923 /* Parse the security context. */
926 scontextp = (char *) scontext;
928 /* Extract the user. */
930 while (*p && *p != ':')
938 usrdatum = hashtab_search(pol->p_users.table, scontextp);
942 ctx->user = usrdatum->value;
946 while (*p && *p != ':')
954 role = hashtab_search(pol->p_roles.table, scontextp);
957 ctx->role = role->value;
961 while (*p && *p != ':')
966 typdatum = hashtab_search(pol->p_types.table, scontextp);
967 if (!typdatum || typdatum->attribute)
970 ctx->type = typdatum->value;
972 rc = mls_context_to_sid(pol, oldc, &p, ctx, sidtabp, def_sid);
976 if ((p - scontext) < scontext_len) {
981 /* Check the validity of the new context. */
982 if (!policydb_context_isvalid(pol, ctx)) {
989 context_destroy(ctx);
993 static int security_context_to_sid_core(const char *scontext, u32 scontext_len,
994 u32 *sid, u32 def_sid, gfp_t gfp_flags,
997 char *scontext2, *str = NULL;
998 struct context context;
1001 if (!ss_initialized) {
1004 for (i = 1; i < SECINITSID_NUM; i++) {
1005 if (!strcmp(initial_sid_to_string[i], scontext)) {
1010 *sid = SECINITSID_KERNEL;
1015 /* Copy the string so that we can modify the copy as we parse it. */
1016 scontext2 = kmalloc(scontext_len+1, gfp_flags);
1019 memcpy(scontext2, scontext, scontext_len);
1020 scontext2[scontext_len] = 0;
1023 /* Save another copy for storing in uninterpreted form */
1024 str = kstrdup(scontext2, gfp_flags);
1031 read_lock(&policy_rwlock);
1032 rc = string_to_context_struct(&policydb, &sidtab,
1033 scontext2, scontext_len,
1035 if (rc == -EINVAL && force) {
1037 context.len = scontext_len;
1041 rc = sidtab_context_to_sid(&sidtab, &context, sid);
1042 context_destroy(&context);
1044 read_unlock(&policy_rwlock);
1051 * security_context_to_sid - Obtain a SID for a given security context.
1052 * @scontext: security context
1053 * @scontext_len: length in bytes
1054 * @sid: security identifier, SID
1056 * Obtains a SID associated with the security context that
1057 * has the string representation specified by @scontext.
1058 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1059 * memory is available, or 0 on success.
1061 int security_context_to_sid(const char *scontext, u32 scontext_len, u32 *sid)
1063 return security_context_to_sid_core(scontext, scontext_len,
1064 sid, SECSID_NULL, GFP_KERNEL, 0);
1068 * security_context_to_sid_default - Obtain a SID for a given security context,
1069 * falling back to specified default if needed.
1071 * @scontext: security context
1072 * @scontext_len: length in bytes
1073 * @sid: security identifier, SID
1074 * @def_sid: default SID to assign on error
1076 * Obtains a SID associated with the security context that
1077 * has the string representation specified by @scontext.
1078 * The default SID is passed to the MLS layer to be used to allow
1079 * kernel labeling of the MLS field if the MLS field is not present
1080 * (for upgrading to MLS without full relabel).
1081 * Implicitly forces adding of the context even if it cannot be mapped yet.
1082 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1083 * memory is available, or 0 on success.
1085 int security_context_to_sid_default(const char *scontext, u32 scontext_len,
1086 u32 *sid, u32 def_sid, gfp_t gfp_flags)
1088 return security_context_to_sid_core(scontext, scontext_len,
1089 sid, def_sid, gfp_flags, 1);
1092 int security_context_to_sid_force(const char *scontext, u32 scontext_len,
1095 return security_context_to_sid_core(scontext, scontext_len,
1096 sid, SECSID_NULL, GFP_KERNEL, 1);
1099 static int compute_sid_handle_invalid_context(
1100 struct context *scontext,
1101 struct context *tcontext,
1103 struct context *newcontext)
1105 char *s = NULL, *t = NULL, *n = NULL;
1106 u32 slen, tlen, nlen;
1108 if (context_struct_to_string(scontext, &s, &slen) < 0)
1110 if (context_struct_to_string(tcontext, &t, &tlen) < 0)
1112 if (context_struct_to_string(newcontext, &n, &nlen) < 0)
1114 audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
1115 "security_compute_sid: invalid context %s"
1119 n, s, t, policydb.p_class_val_to_name[tclass-1]);
1124 if (!selinux_enforcing)
1129 static int security_compute_sid(u32 ssid,
1135 struct context *scontext = NULL, *tcontext = NULL, newcontext;
1136 struct role_trans *roletr = NULL;
1137 struct avtab_key avkey;
1138 struct avtab_datum *avdatum;
1139 struct avtab_node *node;
1142 if (!ss_initialized) {
1144 case SECCLASS_PROCESS:
1154 context_init(&newcontext);
1156 read_lock(&policy_rwlock);
1158 scontext = sidtab_search(&sidtab, ssid);
1160 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
1165 tcontext = sidtab_search(&sidtab, tsid);
1167 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
1173 /* Set the user identity. */
1174 switch (specified) {
1175 case AVTAB_TRANSITION:
1177 /* Use the process user identity. */
1178 newcontext.user = scontext->user;
1181 /* Use the related object owner. */
1182 newcontext.user = tcontext->user;
1186 /* Set the role and type to default values. */
1188 case SECCLASS_PROCESS:
1189 /* Use the current role and type of process. */
1190 newcontext.role = scontext->role;
1191 newcontext.type = scontext->type;
1194 /* Use the well-defined object role. */
1195 newcontext.role = OBJECT_R_VAL;
1196 /* Use the type of the related object. */
1197 newcontext.type = tcontext->type;
1200 /* Look for a type transition/member/change rule. */
1201 avkey.source_type = scontext->type;
1202 avkey.target_type = tcontext->type;
1203 avkey.target_class = tclass;
1204 avkey.specified = specified;
1205 avdatum = avtab_search(&policydb.te_avtab, &avkey);
1207 /* If no permanent rule, also check for enabled conditional rules */
1209 node = avtab_search_node(&policydb.te_cond_avtab, &avkey);
1210 for (; node; node = avtab_search_node_next(node, specified)) {
1211 if (node->key.specified & AVTAB_ENABLED) {
1212 avdatum = &node->datum;
1219 /* Use the type from the type transition/member/change rule. */
1220 newcontext.type = avdatum->data;
1223 /* Check for class-specific changes. */
1225 case SECCLASS_PROCESS:
1226 if (specified & AVTAB_TRANSITION) {
1227 /* Look for a role transition rule. */
1228 for (roletr = policydb.role_tr; roletr;
1229 roletr = roletr->next) {
1230 if (roletr->role == scontext->role &&
1231 roletr->type == tcontext->type) {
1232 /* Use the role transition rule. */
1233 newcontext.role = roletr->new_role;
1243 /* Set the MLS attributes.
1244 This is done last because it may allocate memory. */
1245 rc = mls_compute_sid(scontext, tcontext, tclass, specified, &newcontext);
1249 /* Check the validity of the context. */
1250 if (!policydb_context_isvalid(&policydb, &newcontext)) {
1251 rc = compute_sid_handle_invalid_context(scontext,
1258 /* Obtain the sid for the context. */
1259 rc = sidtab_context_to_sid(&sidtab, &newcontext, out_sid);
1261 read_unlock(&policy_rwlock);
1262 context_destroy(&newcontext);
1268 * security_transition_sid - Compute the SID for a new subject/object.
1269 * @ssid: source security identifier
1270 * @tsid: target security identifier
1271 * @tclass: target security class
1272 * @out_sid: security identifier for new subject/object
1274 * Compute a SID to use for labeling a new subject or object in the
1275 * class @tclass based on a SID pair (@ssid, @tsid).
1276 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1277 * if insufficient memory is available, or %0 if the new SID was
1278 * computed successfully.
1280 int security_transition_sid(u32 ssid,
1285 return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION, out_sid);
1289 * security_member_sid - Compute the SID for member selection.
1290 * @ssid: source security identifier
1291 * @tsid: target security identifier
1292 * @tclass: target security class
1293 * @out_sid: security identifier for selected member
1295 * Compute a SID to use when selecting a member of a polyinstantiated
1296 * object of class @tclass based on a SID pair (@ssid, @tsid).
1297 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1298 * if insufficient memory is available, or %0 if the SID was
1299 * computed successfully.
1301 int security_member_sid(u32 ssid,
1306 return security_compute_sid(ssid, tsid, tclass, AVTAB_MEMBER, out_sid);
1310 * security_change_sid - Compute the SID for object relabeling.
1311 * @ssid: source security identifier
1312 * @tsid: target security identifier
1313 * @tclass: target security class
1314 * @out_sid: security identifier for selected member
1316 * Compute a SID to use for relabeling an object of class @tclass
1317 * based on a SID pair (@ssid, @tsid).
1318 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1319 * if insufficient memory is available, or %0 if the SID was
1320 * computed successfully.
1322 int security_change_sid(u32 ssid,
1327 return security_compute_sid(ssid, tsid, tclass, AVTAB_CHANGE, out_sid);
1331 * Verify that each kernel class that is defined in the
1334 static int validate_classes(struct policydb *p)
1337 struct class_datum *cladatum;
1338 struct perm_datum *perdatum;
1339 u32 nprim, tmp, common_pts_len, perm_val, pol_val;
1341 const struct selinux_class_perm *kdefs = &selinux_class_perm;
1342 const char *def_class, *def_perm, *pol_class;
1343 struct symtab *perms;
1344 bool print_unknown_handle = 0;
1346 if (p->allow_unknown) {
1347 u32 num_classes = kdefs->cts_len;
1348 p->undefined_perms = kcalloc(num_classes, sizeof(u32), GFP_KERNEL);
1349 if (!p->undefined_perms)
1353 for (i = 1; i < kdefs->cts_len; i++) {
1354 def_class = kdefs->class_to_string[i];
1357 if (i > p->p_classes.nprim) {
1359 "SELinux: class %s not defined in policy\n",
1361 if (p->reject_unknown)
1363 if (p->allow_unknown)
1364 p->undefined_perms[i-1] = ~0U;
1365 print_unknown_handle = 1;
1368 pol_class = p->p_class_val_to_name[i-1];
1369 if (strcmp(pol_class, def_class)) {
1371 "SELinux: class %d is incorrect, found %s but should be %s\n",
1372 i, pol_class, def_class);
1376 for (i = 0; i < kdefs->av_pts_len; i++) {
1377 class_val = kdefs->av_perm_to_string[i].tclass;
1378 perm_val = kdefs->av_perm_to_string[i].value;
1379 def_perm = kdefs->av_perm_to_string[i].name;
1380 if (class_val > p->p_classes.nprim)
1382 pol_class = p->p_class_val_to_name[class_val-1];
1383 cladatum = hashtab_search(p->p_classes.table, pol_class);
1385 perms = &cladatum->permissions;
1386 nprim = 1 << (perms->nprim - 1);
1387 if (perm_val > nprim) {
1389 "SELinux: permission %s in class %s not defined in policy\n",
1390 def_perm, pol_class);
1391 if (p->reject_unknown)
1393 if (p->allow_unknown)
1394 p->undefined_perms[class_val-1] |= perm_val;
1395 print_unknown_handle = 1;
1398 perdatum = hashtab_search(perms->table, def_perm);
1399 if (perdatum == NULL) {
1401 "SELinux: permission %s in class %s not found in policy, bad policy\n",
1402 def_perm, pol_class);
1405 pol_val = 1 << (perdatum->value - 1);
1406 if (pol_val != perm_val) {
1408 "SELinux: permission %s in class %s has incorrect value\n",
1409 def_perm, pol_class);
1413 for (i = 0; i < kdefs->av_inherit_len; i++) {
1414 class_val = kdefs->av_inherit[i].tclass;
1415 if (class_val > p->p_classes.nprim)
1417 pol_class = p->p_class_val_to_name[class_val-1];
1418 cladatum = hashtab_search(p->p_classes.table, pol_class);
1420 if (!cladatum->comdatum) {
1422 "SELinux: class %s should have an inherits clause but does not\n",
1426 tmp = kdefs->av_inherit[i].common_base;
1428 while (!(tmp & 0x01)) {
1432 perms = &cladatum->comdatum->permissions;
1433 for (j = 0; j < common_pts_len; j++) {
1434 def_perm = kdefs->av_inherit[i].common_pts[j];
1435 if (j >= perms->nprim) {
1437 "SELinux: permission %s in class %s not defined in policy\n",
1438 def_perm, pol_class);
1439 if (p->reject_unknown)
1441 if (p->allow_unknown)
1442 p->undefined_perms[class_val-1] |= (1 << j);
1443 print_unknown_handle = 1;
1446 perdatum = hashtab_search(perms->table, def_perm);
1447 if (perdatum == NULL) {
1449 "SELinux: permission %s in class %s not found in policy, bad policy\n",
1450 def_perm, pol_class);
1453 if (perdatum->value != j + 1) {
1455 "SELinux: permission %s in class %s has incorrect value\n",
1456 def_perm, pol_class);
1461 if (print_unknown_handle)
1462 printk(KERN_INFO "SELinux: the above unknown classes and permissions will be %s\n",
1463 (security_get_allow_unknown() ? "allowed" : "denied"));
1467 /* Clone the SID into the new SID table. */
1468 static int clone_sid(u32 sid,
1469 struct context *context,
1472 struct sidtab *s = arg;
1474 return sidtab_insert(s, sid, context);
1477 static inline int convert_context_handle_invalid_context(struct context *context)
1481 if (selinux_enforcing) {
1487 if (!context_struct_to_string(context, &s, &len)) {
1489 "SELinux: Context %s would be invalid if enforcing\n",
1497 struct convert_context_args {
1498 struct policydb *oldp;
1499 struct policydb *newp;
1503 * Convert the values in the security context
1504 * structure `c' from the values specified
1505 * in the policy `p->oldp' to the values specified
1506 * in the policy `p->newp'. Verify that the
1507 * context is valid under the new policy.
1509 static int convert_context(u32 key,
1513 struct convert_context_args *args;
1514 struct context oldc;
1515 struct role_datum *role;
1516 struct type_datum *typdatum;
1517 struct user_datum *usrdatum;
1526 s = kstrdup(c->str, GFP_KERNEL);
1531 rc = string_to_context_struct(args->newp, NULL, s,
1532 c->len, &ctx, SECSID_NULL);
1536 "SELinux: Context %s became valid (mapped).\n",
1538 /* Replace string with mapped representation. */
1540 memcpy(c, &ctx, sizeof(*c));
1542 } else if (rc == -EINVAL) {
1543 /* Retain string representation for later mapping. */
1547 /* Other error condition, e.g. ENOMEM. */
1549 "SELinux: Unable to map context %s, rc = %d.\n",
1555 rc = context_cpy(&oldc, c);
1561 /* Convert the user. */
1562 usrdatum = hashtab_search(args->newp->p_users.table,
1563 args->oldp->p_user_val_to_name[c->user - 1]);
1566 c->user = usrdatum->value;
1568 /* Convert the role. */
1569 role = hashtab_search(args->newp->p_roles.table,
1570 args->oldp->p_role_val_to_name[c->role - 1]);
1573 c->role = role->value;
1575 /* Convert the type. */
1576 typdatum = hashtab_search(args->newp->p_types.table,
1577 args->oldp->p_type_val_to_name[c->type - 1]);
1580 c->type = typdatum->value;
1582 rc = mls_convert_context(args->oldp, args->newp, c);
1586 /* Check the validity of the new context. */
1587 if (!policydb_context_isvalid(args->newp, c)) {
1588 rc = convert_context_handle_invalid_context(&oldc);
1593 context_destroy(&oldc);
1598 /* Map old representation to string and save it. */
1599 if (context_struct_to_string(&oldc, &s, &len))
1601 context_destroy(&oldc);
1606 "SELinux: Context %s became invalid (unmapped).\n",
1612 static void security_load_policycaps(void)
1614 selinux_policycap_netpeer = ebitmap_get_bit(&policydb.policycaps,
1615 POLICYDB_CAPABILITY_NETPEER);
1616 selinux_policycap_openperm = ebitmap_get_bit(&policydb.policycaps,
1617 POLICYDB_CAPABILITY_OPENPERM);
1620 extern void selinux_complete_init(void);
1621 static int security_preserve_bools(struct policydb *p);
1624 * security_load_policy - Load a security policy configuration.
1625 * @data: binary policy data
1626 * @len: length of data in bytes
1628 * Load a new set of security policy configuration data,
1629 * validate it and convert the SID table as necessary.
1630 * This function will flush the access vector cache after
1631 * loading the new policy.
1633 int security_load_policy(void *data, size_t len)
1635 struct policydb oldpolicydb, newpolicydb;
1636 struct sidtab oldsidtab, newsidtab;
1637 struct convert_context_args args;
1640 struct policy_file file = { data, len }, *fp = &file;
1642 if (!ss_initialized) {
1644 if (policydb_read(&policydb, fp)) {
1645 avtab_cache_destroy();
1648 if (policydb_load_isids(&policydb, &sidtab)) {
1649 policydb_destroy(&policydb);
1650 avtab_cache_destroy();
1653 /* Verify that the kernel defined classes are correct. */
1654 if (validate_classes(&policydb)) {
1656 "SELinux: the definition of a class is incorrect\n");
1657 sidtab_destroy(&sidtab);
1658 policydb_destroy(&policydb);
1659 avtab_cache_destroy();
1662 security_load_policycaps();
1663 policydb_loaded_version = policydb.policyvers;
1665 seqno = ++latest_granting;
1666 selinux_complete_init();
1667 avc_ss_reset(seqno);
1668 selnl_notify_policyload(seqno);
1669 selinux_netlbl_cache_invalidate();
1670 selinux_xfrm_notify_policyload();
1675 sidtab_hash_eval(&sidtab, "sids");
1678 if (policydb_read(&newpolicydb, fp))
1681 if (sidtab_init(&newsidtab)) {
1682 policydb_destroy(&newpolicydb);
1686 /* Verify that the kernel defined classes are correct. */
1687 if (validate_classes(&newpolicydb)) {
1689 "SELinux: the definition of a class is incorrect\n");
1694 rc = security_preserve_bools(&newpolicydb);
1696 printk(KERN_ERR "SELinux: unable to preserve booleans\n");
1700 /* Clone the SID table. */
1701 sidtab_shutdown(&sidtab);
1702 if (sidtab_map(&sidtab, clone_sid, &newsidtab)) {
1708 * Convert the internal representations of contexts
1709 * in the new SID table.
1711 args.oldp = &policydb;
1712 args.newp = &newpolicydb;
1713 rc = sidtab_map(&newsidtab, convert_context, &args);
1717 /* Save the old policydb and SID table to free later. */
1718 memcpy(&oldpolicydb, &policydb, sizeof policydb);
1719 sidtab_set(&oldsidtab, &sidtab);
1721 /* Install the new policydb and SID table. */
1722 write_lock_irq(&policy_rwlock);
1723 memcpy(&policydb, &newpolicydb, sizeof policydb);
1724 sidtab_set(&sidtab, &newsidtab);
1725 security_load_policycaps();
1726 seqno = ++latest_granting;
1727 policydb_loaded_version = policydb.policyvers;
1728 write_unlock_irq(&policy_rwlock);
1730 /* Free the old policydb and SID table. */
1731 policydb_destroy(&oldpolicydb);
1732 sidtab_destroy(&oldsidtab);
1734 avc_ss_reset(seqno);
1735 selnl_notify_policyload(seqno);
1736 selinux_netlbl_cache_invalidate();
1737 selinux_xfrm_notify_policyload();
1742 sidtab_destroy(&newsidtab);
1743 policydb_destroy(&newpolicydb);
1749 * security_port_sid - Obtain the SID for a port.
1750 * @protocol: protocol number
1751 * @port: port number
1752 * @out_sid: security identifier
1754 int security_port_sid(u8 protocol, u16 port, u32 *out_sid)
1759 read_lock(&policy_rwlock);
1761 c = policydb.ocontexts[OCON_PORT];
1763 if (c->u.port.protocol == protocol &&
1764 c->u.port.low_port <= port &&
1765 c->u.port.high_port >= port)
1772 rc = sidtab_context_to_sid(&sidtab,
1778 *out_sid = c->sid[0];
1780 *out_sid = SECINITSID_PORT;
1784 read_unlock(&policy_rwlock);
1789 * security_netif_sid - Obtain the SID for a network interface.
1790 * @name: interface name
1791 * @if_sid: interface SID
1793 int security_netif_sid(char *name, u32 *if_sid)
1798 read_lock(&policy_rwlock);
1800 c = policydb.ocontexts[OCON_NETIF];
1802 if (strcmp(name, c->u.name) == 0)
1808 if (!c->sid[0] || !c->sid[1]) {
1809 rc = sidtab_context_to_sid(&sidtab,
1814 rc = sidtab_context_to_sid(&sidtab,
1820 *if_sid = c->sid[0];
1822 *if_sid = SECINITSID_NETIF;
1825 read_unlock(&policy_rwlock);
1829 static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask)
1833 for (i = 0; i < 4; i++)
1834 if (addr[i] != (input[i] & mask[i])) {
1843 * security_node_sid - Obtain the SID for a node (host).
1844 * @domain: communication domain aka address family
1846 * @addrlen: address length in bytes
1847 * @out_sid: security identifier
1849 int security_node_sid(u16 domain,
1857 read_lock(&policy_rwlock);
1863 if (addrlen != sizeof(u32)) {
1868 addr = *((u32 *)addrp);
1870 c = policydb.ocontexts[OCON_NODE];
1872 if (c->u.node.addr == (addr & c->u.node.mask))
1880 if (addrlen != sizeof(u64) * 2) {
1884 c = policydb.ocontexts[OCON_NODE6];
1886 if (match_ipv6_addrmask(addrp, c->u.node6.addr,
1894 *out_sid = SECINITSID_NODE;
1900 rc = sidtab_context_to_sid(&sidtab,
1906 *out_sid = c->sid[0];
1908 *out_sid = SECINITSID_NODE;
1912 read_unlock(&policy_rwlock);
1919 * security_get_user_sids - Obtain reachable SIDs for a user.
1920 * @fromsid: starting SID
1921 * @username: username
1922 * @sids: array of reachable SIDs for user
1923 * @nel: number of elements in @sids
1925 * Generate the set of SIDs for legal security contexts
1926 * for a given user that can be reached by @fromsid.
1927 * Set *@sids to point to a dynamically allocated
1928 * array containing the set of SIDs. Set *@nel to the
1929 * number of elements in the array.
1932 int security_get_user_sids(u32 fromsid,
1937 struct context *fromcon, usercon;
1938 u32 *mysids = NULL, *mysids2, sid;
1939 u32 mynel = 0, maxnel = SIDS_NEL;
1940 struct user_datum *user;
1941 struct role_datum *role;
1942 struct ebitmap_node *rnode, *tnode;
1948 if (!ss_initialized)
1951 read_lock(&policy_rwlock);
1953 context_init(&usercon);
1955 fromcon = sidtab_search(&sidtab, fromsid);
1961 user = hashtab_search(policydb.p_users.table, username);
1966 usercon.user = user->value;
1968 mysids = kcalloc(maxnel, sizeof(*mysids), GFP_ATOMIC);
1974 ebitmap_for_each_positive_bit(&user->roles, rnode, i) {
1975 role = policydb.role_val_to_struct[i];
1977 ebitmap_for_each_positive_bit(&role->types, tnode, j) {
1980 if (mls_setup_user_range(fromcon, user, &usercon))
1983 rc = sidtab_context_to_sid(&sidtab, &usercon, &sid);
1986 if (mynel < maxnel) {
1987 mysids[mynel++] = sid;
1990 mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
1995 memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
1998 mysids[mynel++] = sid;
2004 read_unlock(&policy_rwlock);
2010 mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);
2016 for (i = 0, j = 0; i < mynel; i++) {
2017 rc = avc_has_perm_noaudit(fromsid, mysids[i],
2019 PROCESS__TRANSITION, AVC_STRICT,
2022 mysids2[j++] = mysids[i];
2034 * security_genfs_sid - Obtain a SID for a file in a filesystem
2035 * @fstype: filesystem type
2036 * @path: path from root of mount
2037 * @sclass: file security class
2038 * @sid: SID for path
2040 * Obtain a SID to use for a file in a filesystem that
2041 * cannot support xattr or use a fixed labeling behavior like
2042 * transition SIDs or task SIDs.
2044 int security_genfs_sid(const char *fstype,
2050 struct genfs *genfs;
2052 int rc = 0, cmp = 0;
2054 while (path[0] == '/' && path[1] == '/')
2057 read_lock(&policy_rwlock);
2059 for (genfs = policydb.genfs; genfs; genfs = genfs->next) {
2060 cmp = strcmp(fstype, genfs->fstype);
2065 if (!genfs || cmp) {
2066 *sid = SECINITSID_UNLABELED;
2071 for (c = genfs->head; c; c = c->next) {
2072 len = strlen(c->u.name);
2073 if ((!c->v.sclass || sclass == c->v.sclass) &&
2074 (strncmp(c->u.name, path, len) == 0))
2079 *sid = SECINITSID_UNLABELED;
2085 rc = sidtab_context_to_sid(&sidtab,
2094 read_unlock(&policy_rwlock);
2099 * security_fs_use - Determine how to handle labeling for a filesystem.
2100 * @fstype: filesystem type
2101 * @behavior: labeling behavior
2102 * @sid: SID for filesystem (superblock)
2104 int security_fs_use(
2106 unsigned int *behavior,
2112 read_lock(&policy_rwlock);
2114 c = policydb.ocontexts[OCON_FSUSE];
2116 if (strcmp(fstype, c->u.name) == 0)
2122 *behavior = c->v.behavior;
2124 rc = sidtab_context_to_sid(&sidtab,
2132 rc = security_genfs_sid(fstype, "/", SECCLASS_DIR, sid);
2134 *behavior = SECURITY_FS_USE_NONE;
2137 *behavior = SECURITY_FS_USE_GENFS;
2142 read_unlock(&policy_rwlock);
2146 int security_get_bools(int *len, char ***names, int **values)
2148 int i, rc = -ENOMEM;
2150 read_lock(&policy_rwlock);
2154 *len = policydb.p_bools.nprim;
2160 *names = kcalloc(*len, sizeof(char *), GFP_ATOMIC);
2164 *values = kcalloc(*len, sizeof(int), GFP_ATOMIC);
2168 for (i = 0; i < *len; i++) {
2170 (*values)[i] = policydb.bool_val_to_struct[i]->state;
2171 name_len = strlen(policydb.p_bool_val_to_name[i]) + 1;
2172 (*names)[i] = kmalloc(sizeof(char) * name_len, GFP_ATOMIC);
2175 strncpy((*names)[i], policydb.p_bool_val_to_name[i], name_len);
2176 (*names)[i][name_len - 1] = 0;
2180 read_unlock(&policy_rwlock);
2184 for (i = 0; i < *len; i++)
2192 int security_set_bools(int len, int *values)
2195 int lenp, seqno = 0;
2196 struct cond_node *cur;
2198 write_lock_irq(&policy_rwlock);
2200 lenp = policydb.p_bools.nprim;
2206 for (i = 0; i < len; i++) {
2207 if (!!values[i] != policydb.bool_val_to_struct[i]->state) {
2208 audit_log(current->audit_context, GFP_ATOMIC,
2209 AUDIT_MAC_CONFIG_CHANGE,
2210 "bool=%s val=%d old_val=%d auid=%u ses=%u",
2211 policydb.p_bool_val_to_name[i],
2213 policydb.bool_val_to_struct[i]->state,
2214 audit_get_loginuid(current),
2215 audit_get_sessionid(current));
2218 policydb.bool_val_to_struct[i]->state = 1;
2220 policydb.bool_val_to_struct[i]->state = 0;
2223 for (cur = policydb.cond_list; cur; cur = cur->next) {
2224 rc = evaluate_cond_node(&policydb, cur);
2229 seqno = ++latest_granting;
2232 write_unlock_irq(&policy_rwlock);
2234 avc_ss_reset(seqno);
2235 selnl_notify_policyload(seqno);
2236 selinux_xfrm_notify_policyload();
2241 int security_get_bool_value(int bool)
2246 read_lock(&policy_rwlock);
2248 len = policydb.p_bools.nprim;
2254 rc = policydb.bool_val_to_struct[bool]->state;
2256 read_unlock(&policy_rwlock);
2260 static int security_preserve_bools(struct policydb *p)
2262 int rc, nbools = 0, *bvalues = NULL, i;
2263 char **bnames = NULL;
2264 struct cond_bool_datum *booldatum;
2265 struct cond_node *cur;
2267 rc = security_get_bools(&nbools, &bnames, &bvalues);
2270 for (i = 0; i < nbools; i++) {
2271 booldatum = hashtab_search(p->p_bools.table, bnames[i]);
2273 booldatum->state = bvalues[i];
2275 for (cur = p->cond_list; cur; cur = cur->next) {
2276 rc = evaluate_cond_node(p, cur);
2283 for (i = 0; i < nbools; i++)
2292 * security_sid_mls_copy() - computes a new sid based on the given
2293 * sid and the mls portion of mls_sid.
2295 int security_sid_mls_copy(u32 sid, u32 mls_sid, u32 *new_sid)
2297 struct context *context1;
2298 struct context *context2;
2299 struct context newcon;
2304 if (!ss_initialized || !selinux_mls_enabled) {
2309 context_init(&newcon);
2311 read_lock(&policy_rwlock);
2312 context1 = sidtab_search(&sidtab, sid);
2314 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2320 context2 = sidtab_search(&sidtab, mls_sid);
2322 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2328 newcon.user = context1->user;
2329 newcon.role = context1->role;
2330 newcon.type = context1->type;
2331 rc = mls_context_cpy(&newcon, context2);
2335 /* Check the validity of the new context. */
2336 if (!policydb_context_isvalid(&policydb, &newcon)) {
2337 rc = convert_context_handle_invalid_context(&newcon);
2342 rc = sidtab_context_to_sid(&sidtab, &newcon, new_sid);
2346 if (!context_struct_to_string(&newcon, &s, &len)) {
2347 audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2348 "security_sid_mls_copy: invalid context %s", s);
2353 read_unlock(&policy_rwlock);
2354 context_destroy(&newcon);
2360 * security_net_peersid_resolve - Compare and resolve two network peer SIDs
2361 * @nlbl_sid: NetLabel SID
2362 * @nlbl_type: NetLabel labeling protocol type
2363 * @xfrm_sid: XFRM SID
2366 * Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be
2367 * resolved into a single SID it is returned via @peer_sid and the function
2368 * returns zero. Otherwise @peer_sid is set to SECSID_NULL and the function
2369 * returns a negative value. A table summarizing the behavior is below:
2371 * | function return | @sid
2372 * ------------------------------+-----------------+-----------------
2373 * no peer labels | 0 | SECSID_NULL
2374 * single peer label | 0 | <peer_label>
2375 * multiple, consistent labels | 0 | <peer_label>
2376 * multiple, inconsistent labels | -<errno> | SECSID_NULL
2379 int security_net_peersid_resolve(u32 nlbl_sid, u32 nlbl_type,
2384 struct context *nlbl_ctx;
2385 struct context *xfrm_ctx;
2387 /* handle the common (which also happens to be the set of easy) cases
2388 * right away, these two if statements catch everything involving a
2389 * single or absent peer SID/label */
2390 if (xfrm_sid == SECSID_NULL) {
2391 *peer_sid = nlbl_sid;
2394 /* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a "fallback" label
2395 * and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label
2397 if (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) {
2398 *peer_sid = xfrm_sid;
2402 /* we don't need to check ss_initialized here since the only way both
2403 * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the
2404 * security server was initialized and ss_initialized was true */
2405 if (!selinux_mls_enabled) {
2406 *peer_sid = SECSID_NULL;
2410 read_lock(&policy_rwlock);
2412 nlbl_ctx = sidtab_search(&sidtab, nlbl_sid);
2414 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2415 __func__, nlbl_sid);
2419 xfrm_ctx = sidtab_search(&sidtab, xfrm_sid);
2421 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2422 __func__, xfrm_sid);
2426 rc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES);
2429 read_unlock(&policy_rwlock);
2431 /* at present NetLabel SIDs/labels really only carry MLS
2432 * information so if the MLS portion of the NetLabel SID
2433 * matches the MLS portion of the labeled XFRM SID/label
2434 * then pass along the XFRM SID as it is the most
2436 *peer_sid = xfrm_sid;
2438 *peer_sid = SECSID_NULL;
2442 static int get_classes_callback(void *k, void *d, void *args)
2444 struct class_datum *datum = d;
2445 char *name = k, **classes = args;
2446 int value = datum->value - 1;
2448 classes[value] = kstrdup(name, GFP_ATOMIC);
2449 if (!classes[value])
2455 int security_get_classes(char ***classes, int *nclasses)
2459 read_lock(&policy_rwlock);
2461 *nclasses = policydb.p_classes.nprim;
2462 *classes = kcalloc(*nclasses, sizeof(*classes), GFP_ATOMIC);
2466 rc = hashtab_map(policydb.p_classes.table, get_classes_callback,
2470 for (i = 0; i < *nclasses; i++)
2471 kfree((*classes)[i]);
2476 read_unlock(&policy_rwlock);
2480 static int get_permissions_callback(void *k, void *d, void *args)
2482 struct perm_datum *datum = d;
2483 char *name = k, **perms = args;
2484 int value = datum->value - 1;
2486 perms[value] = kstrdup(name, GFP_ATOMIC);
2493 int security_get_permissions(char *class, char ***perms, int *nperms)
2495 int rc = -ENOMEM, i;
2496 struct class_datum *match;
2498 read_lock(&policy_rwlock);
2500 match = hashtab_search(policydb.p_classes.table, class);
2502 printk(KERN_ERR "SELinux: %s: unrecognized class %s\n",
2508 *nperms = match->permissions.nprim;
2509 *perms = kcalloc(*nperms, sizeof(*perms), GFP_ATOMIC);
2513 if (match->comdatum) {
2514 rc = hashtab_map(match->comdatum->permissions.table,
2515 get_permissions_callback, *perms);
2520 rc = hashtab_map(match->permissions.table, get_permissions_callback,
2526 read_unlock(&policy_rwlock);
2530 read_unlock(&policy_rwlock);
2531 for (i = 0; i < *nperms; i++)
2537 int security_get_reject_unknown(void)
2539 return policydb.reject_unknown;
2542 int security_get_allow_unknown(void)
2544 return policydb.allow_unknown;
2548 * security_policycap_supported - Check for a specific policy capability
2549 * @req_cap: capability
2552 * This function queries the currently loaded policy to see if it supports the
2553 * capability specified by @req_cap. Returns true (1) if the capability is
2554 * supported, false (0) if it isn't supported.
2557 int security_policycap_supported(unsigned int req_cap)
2561 read_lock(&policy_rwlock);
2562 rc = ebitmap_get_bit(&policydb.policycaps, req_cap);
2563 read_unlock(&policy_rwlock);
2568 struct selinux_audit_rule {
2570 struct context au_ctxt;
2573 void selinux_audit_rule_free(void *vrule)
2575 struct selinux_audit_rule *rule = vrule;
2578 context_destroy(&rule->au_ctxt);
2583 int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule)
2585 struct selinux_audit_rule *tmprule;
2586 struct role_datum *roledatum;
2587 struct type_datum *typedatum;
2588 struct user_datum *userdatum;
2589 struct selinux_audit_rule **rule = (struct selinux_audit_rule **)vrule;
2594 if (!ss_initialized)
2598 case AUDIT_SUBJ_USER:
2599 case AUDIT_SUBJ_ROLE:
2600 case AUDIT_SUBJ_TYPE:
2601 case AUDIT_OBJ_USER:
2602 case AUDIT_OBJ_ROLE:
2603 case AUDIT_OBJ_TYPE:
2604 /* only 'equals' and 'not equals' fit user, role, and type */
2605 if (op != AUDIT_EQUAL && op != AUDIT_NOT_EQUAL)
2608 case AUDIT_SUBJ_SEN:
2609 case AUDIT_SUBJ_CLR:
2610 case AUDIT_OBJ_LEV_LOW:
2611 case AUDIT_OBJ_LEV_HIGH:
2612 /* we do not allow a range, indicated by the presense of '-' */
2613 if (strchr(rulestr, '-'))
2617 /* only the above fields are valid */
2621 tmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL);
2625 context_init(&tmprule->au_ctxt);
2627 read_lock(&policy_rwlock);
2629 tmprule->au_seqno = latest_granting;
2632 case AUDIT_SUBJ_USER:
2633 case AUDIT_OBJ_USER:
2634 userdatum = hashtab_search(policydb.p_users.table, rulestr);
2638 tmprule->au_ctxt.user = userdatum->value;
2640 case AUDIT_SUBJ_ROLE:
2641 case AUDIT_OBJ_ROLE:
2642 roledatum = hashtab_search(policydb.p_roles.table, rulestr);
2646 tmprule->au_ctxt.role = roledatum->value;
2648 case AUDIT_SUBJ_TYPE:
2649 case AUDIT_OBJ_TYPE:
2650 typedatum = hashtab_search(policydb.p_types.table, rulestr);
2654 tmprule->au_ctxt.type = typedatum->value;
2656 case AUDIT_SUBJ_SEN:
2657 case AUDIT_SUBJ_CLR:
2658 case AUDIT_OBJ_LEV_LOW:
2659 case AUDIT_OBJ_LEV_HIGH:
2660 rc = mls_from_string(rulestr, &tmprule->au_ctxt, GFP_ATOMIC);
2664 read_unlock(&policy_rwlock);
2667 selinux_audit_rule_free(tmprule);
2676 /* Check to see if the rule contains any selinux fields */
2677 int selinux_audit_rule_known(struct audit_krule *rule)
2681 for (i = 0; i < rule->field_count; i++) {
2682 struct audit_field *f = &rule->fields[i];
2684 case AUDIT_SUBJ_USER:
2685 case AUDIT_SUBJ_ROLE:
2686 case AUDIT_SUBJ_TYPE:
2687 case AUDIT_SUBJ_SEN:
2688 case AUDIT_SUBJ_CLR:
2689 case AUDIT_OBJ_USER:
2690 case AUDIT_OBJ_ROLE:
2691 case AUDIT_OBJ_TYPE:
2692 case AUDIT_OBJ_LEV_LOW:
2693 case AUDIT_OBJ_LEV_HIGH:
2701 int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule,
2702 struct audit_context *actx)
2704 struct context *ctxt;
2705 struct mls_level *level;
2706 struct selinux_audit_rule *rule = vrule;
2710 audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2711 "selinux_audit_rule_match: missing rule\n");
2715 read_lock(&policy_rwlock);
2717 if (rule->au_seqno < latest_granting) {
2718 audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2719 "selinux_audit_rule_match: stale rule\n");
2724 ctxt = sidtab_search(&sidtab, sid);
2726 audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2727 "selinux_audit_rule_match: unrecognized SID %d\n",
2733 /* a field/op pair that is not caught here will simply fall through
2736 case AUDIT_SUBJ_USER:
2737 case AUDIT_OBJ_USER:
2740 match = (ctxt->user == rule->au_ctxt.user);
2742 case AUDIT_NOT_EQUAL:
2743 match = (ctxt->user != rule->au_ctxt.user);
2747 case AUDIT_SUBJ_ROLE:
2748 case AUDIT_OBJ_ROLE:
2751 match = (ctxt->role == rule->au_ctxt.role);
2753 case AUDIT_NOT_EQUAL:
2754 match = (ctxt->role != rule->au_ctxt.role);
2758 case AUDIT_SUBJ_TYPE:
2759 case AUDIT_OBJ_TYPE:
2762 match = (ctxt->type == rule->au_ctxt.type);
2764 case AUDIT_NOT_EQUAL:
2765 match = (ctxt->type != rule->au_ctxt.type);
2769 case AUDIT_SUBJ_SEN:
2770 case AUDIT_SUBJ_CLR:
2771 case AUDIT_OBJ_LEV_LOW:
2772 case AUDIT_OBJ_LEV_HIGH:
2773 level = ((field == AUDIT_SUBJ_SEN ||
2774 field == AUDIT_OBJ_LEV_LOW) ?
2775 &ctxt->range.level[0] : &ctxt->range.level[1]);
2778 match = mls_level_eq(&rule->au_ctxt.range.level[0],
2781 case AUDIT_NOT_EQUAL:
2782 match = !mls_level_eq(&rule->au_ctxt.range.level[0],
2785 case AUDIT_LESS_THAN:
2786 match = (mls_level_dom(&rule->au_ctxt.range.level[0],
2788 !mls_level_eq(&rule->au_ctxt.range.level[0],
2791 case AUDIT_LESS_THAN_OR_EQUAL:
2792 match = mls_level_dom(&rule->au_ctxt.range.level[0],
2795 case AUDIT_GREATER_THAN:
2796 match = (mls_level_dom(level,
2797 &rule->au_ctxt.range.level[0]) &&
2798 !mls_level_eq(level,
2799 &rule->au_ctxt.range.level[0]));
2801 case AUDIT_GREATER_THAN_OR_EQUAL:
2802 match = mls_level_dom(level,
2803 &rule->au_ctxt.range.level[0]);
2809 read_unlock(&policy_rwlock);
2813 static int (*aurule_callback)(void) = audit_update_lsm_rules;
2815 static int aurule_avc_callback(u32 event, u32 ssid, u32 tsid,
2816 u16 class, u32 perms, u32 *retained)
2820 if (event == AVC_CALLBACK_RESET && aurule_callback)
2821 err = aurule_callback();
2825 static int __init aurule_init(void)
2829 err = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET,
2830 SECSID_NULL, SECSID_NULL, SECCLASS_NULL, 0);
2832 panic("avc_add_callback() failed, error %d\n", err);
2836 __initcall(aurule_init);
2838 #ifdef CONFIG_NETLABEL
2840 * security_netlbl_cache_add - Add an entry to the NetLabel cache
2841 * @secattr: the NetLabel packet security attributes
2842 * @sid: the SELinux SID
2845 * Attempt to cache the context in @ctx, which was derived from the packet in
2846 * @skb, in the NetLabel subsystem cache. This function assumes @secattr has
2847 * already been initialized.
2850 static void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr,
2855 sid_cache = kmalloc(sizeof(*sid_cache), GFP_ATOMIC);
2856 if (sid_cache == NULL)
2858 secattr->cache = netlbl_secattr_cache_alloc(GFP_ATOMIC);
2859 if (secattr->cache == NULL) {
2865 secattr->cache->free = kfree;
2866 secattr->cache->data = sid_cache;
2867 secattr->flags |= NETLBL_SECATTR_CACHE;
2871 * security_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID
2872 * @secattr: the NetLabel packet security attributes
2873 * @sid: the SELinux SID
2876 * Convert the given NetLabel security attributes in @secattr into a
2877 * SELinux SID. If the @secattr field does not contain a full SELinux
2878 * SID/context then use SECINITSID_NETMSG as the foundation. If possibile the
2879 * 'cache' field of @secattr is set and the CACHE flag is set; this is to
2880 * allow the @secattr to be used by NetLabel to cache the secattr to SID
2881 * conversion for future lookups. Returns zero on success, negative values on
2885 int security_netlbl_secattr_to_sid(struct netlbl_lsm_secattr *secattr,
2889 struct context *ctx;
2890 struct context ctx_new;
2892 if (!ss_initialized) {
2897 read_lock(&policy_rwlock);
2899 if (secattr->flags & NETLBL_SECATTR_CACHE) {
2900 *sid = *(u32 *)secattr->cache->data;
2902 } else if (secattr->flags & NETLBL_SECATTR_SECID) {
2903 *sid = secattr->attr.secid;
2905 } else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) {
2906 ctx = sidtab_search(&sidtab, SECINITSID_NETMSG);
2908 goto netlbl_secattr_to_sid_return;
2910 context_init(&ctx_new);
2911 ctx_new.user = ctx->user;
2912 ctx_new.role = ctx->role;
2913 ctx_new.type = ctx->type;
2914 mls_import_netlbl_lvl(&ctx_new, secattr);
2915 if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
2916 if (ebitmap_netlbl_import(&ctx_new.range.level[0].cat,
2917 secattr->attr.mls.cat) != 0)
2918 goto netlbl_secattr_to_sid_return;
2919 memcpy(&ctx_new.range.level[1].cat,
2920 &ctx_new.range.level[0].cat,
2921 sizeof(ctx_new.range.level[0].cat));
2923 if (mls_context_isvalid(&policydb, &ctx_new) != 1)
2924 goto netlbl_secattr_to_sid_return_cleanup;
2926 rc = sidtab_context_to_sid(&sidtab, &ctx_new, sid);
2928 goto netlbl_secattr_to_sid_return_cleanup;
2930 security_netlbl_cache_add(secattr, *sid);
2932 ebitmap_destroy(&ctx_new.range.level[0].cat);
2938 netlbl_secattr_to_sid_return:
2939 read_unlock(&policy_rwlock);
2941 netlbl_secattr_to_sid_return_cleanup:
2942 ebitmap_destroy(&ctx_new.range.level[0].cat);
2943 goto netlbl_secattr_to_sid_return;
2947 * security_netlbl_sid_to_secattr - Convert a SELinux SID to a NetLabel secattr
2948 * @sid: the SELinux SID
2949 * @secattr: the NetLabel packet security attributes
2952 * Convert the given SELinux SID in @sid into a NetLabel security attribute.
2953 * Returns zero on success, negative values on failure.
2956 int security_netlbl_sid_to_secattr(u32 sid, struct netlbl_lsm_secattr *secattr)
2959 struct context *ctx;
2961 if (!ss_initialized)
2964 read_lock(&policy_rwlock);
2965 ctx = sidtab_search(&sidtab, sid);
2968 goto netlbl_sid_to_secattr_failure;
2970 secattr->domain = kstrdup(policydb.p_type_val_to_name[ctx->type - 1],
2972 if (secattr->domain == NULL) {
2974 goto netlbl_sid_to_secattr_failure;
2976 secattr->attr.secid = sid;
2977 secattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID;
2978 mls_export_netlbl_lvl(ctx, secattr);
2979 rc = mls_export_netlbl_cat(ctx, secattr);
2981 goto netlbl_sid_to_secattr_failure;
2982 read_unlock(&policy_rwlock);
2986 netlbl_sid_to_secattr_failure:
2987 read_unlock(&policy_rwlock);
2990 #endif /* CONFIG_NETLABEL */