linux/security/selinux/ss/services.c
<<
>>
Prefs
   1/*
   2 * Implementation of the security services.
   3 *
   4 * Authors : Stephen Smalley, <sds@epoch.ncsc.mil>
   5 *           James Morris <jmorris@redhat.com>
   6 *
   7 * Updated: Trusted Computer Solutions, Inc. <dgoeddel@trustedcs.com>
   8 *
   9 *      Support for enhanced MLS infrastructure.
  10 *      Support for context based audit filters.
  11 *
  12 * Updated: Frank Mayer <mayerf@tresys.com> and Karl MacMillan <kmacmillan@tresys.com>
  13 *
  14 *      Added conditional policy language extensions
  15 *
  16 * Updated: Hewlett-Packard <paul@paul-moore.com>
  17 *
  18 *      Added support for NetLabel
  19 *      Added support for the policy capability bitmap
  20 *
  21 * Updated: Chad Sellers <csellers@tresys.com>
  22 *
  23 *  Added validation of kernel classes and permissions
  24 *
  25 * Updated: KaiGai Kohei <kaigai@ak.jp.nec.com>
  26 *
  27 *  Added support for bounds domain and audit messaged on masked permissions
  28 *
  29 * Updated: Guido Trentalancia <guido@trentalancia.com>
  30 *
  31 *  Added support for runtime switching of the policy type
  32 *
  33 * Copyright (C) 2008, 2009 NEC Corporation
  34 * Copyright (C) 2006, 2007 Hewlett-Packard Development Company, L.P.
  35 * Copyright (C) 2004-2006 Trusted Computer Solutions, Inc.
  36 * Copyright (C) 2003 - 2004, 2006 Tresys Technology, LLC
  37 * Copyright (C) 2003 Red Hat, Inc., James Morris <jmorris@redhat.com>
  38 *      This program is free software; you can redistribute it and/or modify
  39 *      it under the terms of the GNU General Public License as published by
  40 *      the Free Software Foundation, version 2.
  41 */
  42#include <linux/kernel.h>
  43#include <linux/slab.h>
  44#include <linux/string.h>
  45#include <linux/spinlock.h>
  46#include <linux/rcupdate.h>
  47#include <linux/errno.h>
  48#include <linux/in.h>
  49#include <linux/sched.h>
  50#include <linux/audit.h>
  51#include <linux/mutex.h>
  52#include <linux/selinux.h>
  53#include <linux/flex_array.h>
  54#include <linux/vmalloc.h>
  55#include <net/netlabel.h>
  56
  57#include "flask.h"
  58#include "avc.h"
  59#include "avc_ss.h"
  60#include "security.h"
  61#include "context.h"
  62#include "policydb.h"
  63#include "sidtab.h"
  64#include "services.h"
  65#include "conditional.h"
  66#include "mls.h"
  67#include "objsec.h"
  68#include "netlabel.h"
  69#include "xfrm.h"
  70#include "ebitmap.h"
  71#include "audit.h"
  72
  73int selinux_policycap_netpeer;
  74int selinux_policycap_openperm;
  75int selinux_policycap_cgroupseclabel;
  76int selinux_policycap_nnp_nosuid_transition;
  77
  78static DEFINE_RWLOCK(policy_rwlock);
  79
  80static struct sidtab *sidtab;
  81struct policydb policydb;
  82int ss_initialized;
  83
  84/*
  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
  88 * occurs.
  89 */
  90static u32 latest_granting;
  91
  92/* Forward declaration. */
  93static int context_struct_to_string(struct context *context, char **scontext,
  94                                    u32 *scontext_len);
  95
  96static void context_struct_compute_av(struct context *scontext,
  97                                        struct context *tcontext,
  98                                        u16 tclass,
  99                                        struct av_decision *avd,
 100                                        struct extended_perms *xperms);
 101
 102struct selinux_mapping {
 103        u16 value; /* policy value */
 104        unsigned num_perms;
 105        u32 perms[sizeof(u32) * 8];
 106};
 107
 108static struct selinux_mapping *current_mapping;
 109static u16 current_mapping_size;
 110
 111static int selinux_set_mapping(struct policydb *pol,
 112                               struct security_class_mapping *map,
 113                               struct selinux_mapping **out_map_p,
 114                               u16 *out_map_size)
 115{
 116        struct selinux_mapping *out_map = NULL;
 117        size_t size = sizeof(struct selinux_mapping);
 118        u16 i, j;
 119        unsigned k;
 120        bool print_unknown_handle = false;
 121
 122        /* Find number of classes in the input mapping */
 123        if (!map)
 124                return -EINVAL;
 125        i = 0;
 126        while (map[i].name)
 127                i++;
 128
 129        /* Allocate space for the class records, plus one for class zero */
 130        out_map = kcalloc(++i, size, GFP_ATOMIC);
 131        if (!out_map)
 132                return -ENOMEM;
 133
 134        /* Store the raw class and permission values */
 135        j = 0;
 136        while (map[j].name) {
 137                struct security_class_mapping *p_in = map + (j++);
 138                struct selinux_mapping *p_out = out_map + j;
 139
 140                /* An empty class string skips ahead */
 141                if (!strcmp(p_in->name, "")) {
 142                        p_out->num_perms = 0;
 143                        continue;
 144                }
 145
 146                p_out->value = string_to_security_class(pol, p_in->name);
 147                if (!p_out->value) {
 148                        printk(KERN_INFO
 149                               "SELinux:  Class %s not defined in policy.\n",
 150                               p_in->name);
 151                        if (pol->reject_unknown)
 152                                goto err;
 153                        p_out->num_perms = 0;
 154                        print_unknown_handle = true;
 155                        continue;
 156                }
 157
 158                k = 0;
 159                while (p_in->perms && p_in->perms[k]) {
 160                        /* An empty permission string skips ahead */
 161                        if (!*p_in->perms[k]) {
 162                                k++;
 163                                continue;
 164                        }
 165                        p_out->perms[k] = string_to_av_perm(pol, p_out->value,
 166                                                            p_in->perms[k]);
 167                        if (!p_out->perms[k]) {
 168                                printk(KERN_INFO
 169                                       "SELinux:  Permission %s in class %s not defined in policy.\n",
 170                                       p_in->perms[k], p_in->name);
 171                                if (pol->reject_unknown)
 172                                        goto err;
 173                                print_unknown_handle = true;
 174                        }
 175
 176                        k++;
 177                }
 178                p_out->num_perms = k;
 179        }
 180
 181        if (print_unknown_handle)
 182                printk(KERN_INFO "SELinux: the above unknown classes and permissions will be %s\n",
 183                       pol->allow_unknown ? "allowed" : "denied");
 184
 185        *out_map_p = out_map;
 186        *out_map_size = i;
 187        return 0;
 188err:
 189        kfree(out_map);
 190        return -EINVAL;
 191}
 192
 193/*
 194 * Get real, policy values from mapped values
 195 */
 196
 197static u16 unmap_class(u16 tclass)
 198{
 199        if (tclass < current_mapping_size)
 200                return current_mapping[tclass].value;
 201
 202        return tclass;
 203}
 204
 205/*
 206 * Get kernel value for class from its policy value
 207 */
 208static u16 map_class(u16 pol_value)
 209{
 210        u16 i;
 211
 212        for (i = 1; i < current_mapping_size; i++) {
 213                if (current_mapping[i].value == pol_value)
 214                        return i;
 215        }
 216
 217        return SECCLASS_NULL;
 218}
 219
 220static void map_decision(u16 tclass, struct av_decision *avd,
 221                         int allow_unknown)
 222{
 223        if (tclass < current_mapping_size) {
 224                unsigned i, n = current_mapping[tclass].num_perms;
 225                u32 result;
 226
 227                for (i = 0, result = 0; i < n; i++) {
 228                        if (avd->allowed & current_mapping[tclass].perms[i])
 229                                result |= 1<<i;
 230                        if (allow_unknown && !current_mapping[tclass].perms[i])
 231                                result |= 1<<i;
 232                }
 233                avd->allowed = result;
 234
 235                for (i = 0, result = 0; i < n; i++)
 236                        if (avd->auditallow & current_mapping[tclass].perms[i])
 237                                result |= 1<<i;
 238                avd->auditallow = result;
 239
 240                for (i = 0, result = 0; i < n; i++) {
 241                        if (avd->auditdeny & current_mapping[tclass].perms[i])
 242                                result |= 1<<i;
 243                        if (!allow_unknown && !current_mapping[tclass].perms[i])
 244                                result |= 1<<i;
 245                }
 246                /*
 247                 * In case the kernel has a bug and requests a permission
 248                 * between num_perms and the maximum permission number, we
 249                 * should audit that denial
 250                 */
 251                for (; i < (sizeof(u32)*8); i++)
 252                        result |= 1<<i;
 253                avd->auditdeny = result;
 254        }
 255}
 256
 257int security_mls_enabled(void)
 258{
 259        return policydb.mls_enabled;
 260}
 261
 262/*
 263 * Return the boolean value of a constraint expression
 264 * when it is applied to the specified source and target
 265 * security contexts.
 266 *
 267 * xcontext is a special beast...  It is used by the validatetrans rules
 268 * only.  For these rules, scontext is the context before the transition,
 269 * tcontext is the context after the transition, and xcontext is the context
 270 * of the process performing the transition.  All other callers of
 271 * constraint_expr_eval should pass in NULL for xcontext.
 272 */
 273static int constraint_expr_eval(struct context *scontext,
 274                                struct context *tcontext,
 275                                struct context *xcontext,
 276                                struct constraint_expr *cexpr)
 277{
 278        u32 val1, val2;
 279        struct context *c;
 280        struct role_datum *r1, *r2;
 281        struct mls_level *l1, *l2;
 282        struct constraint_expr *e;
 283        int s[CEXPR_MAXDEPTH];
 284        int sp = -1;
 285
 286        for (e = cexpr; e; e = e->next) {
 287                switch (e->expr_type) {
 288                case CEXPR_NOT:
 289                        BUG_ON(sp < 0);
 290                        s[sp] = !s[sp];
 291                        break;
 292                case CEXPR_AND:
 293                        BUG_ON(sp < 1);
 294                        sp--;
 295                        s[sp] &= s[sp + 1];
 296                        break;
 297                case CEXPR_OR:
 298                        BUG_ON(sp < 1);
 299                        sp--;
 300                        s[sp] |= s[sp + 1];
 301                        break;
 302                case CEXPR_ATTR:
 303                        if (sp == (CEXPR_MAXDEPTH - 1))
 304                                return 0;
 305                        switch (e->attr) {
 306                        case CEXPR_USER:
 307                                val1 = scontext->user;
 308                                val2 = tcontext->user;
 309                                break;
 310                        case CEXPR_TYPE:
 311                                val1 = scontext->type;
 312                                val2 = tcontext->type;
 313                                break;
 314                        case CEXPR_ROLE:
 315                                val1 = scontext->role;
 316                                val2 = tcontext->role;
 317                                r1 = policydb.role_val_to_struct[val1 - 1];
 318                                r2 = policydb.role_val_to_struct[val2 - 1];
 319                                switch (e->op) {
 320                                case CEXPR_DOM:
 321                                        s[++sp] = ebitmap_get_bit(&r1->dominates,
 322                                                                  val2 - 1);
 323                                        continue;
 324                                case CEXPR_DOMBY:
 325                                        s[++sp] = ebitmap_get_bit(&r2->dominates,
 326                                                                  val1 - 1);
 327                                        continue;
 328                                case CEXPR_INCOMP:
 329                                        s[++sp] = (!ebitmap_get_bit(&r1->dominates,
 330                                                                    val2 - 1) &&
 331                                                   !ebitmap_get_bit(&r2->dominates,
 332                                                                    val1 - 1));
 333                                        continue;
 334                                default:
 335                                        break;
 336                                }
 337                                break;
 338                        case CEXPR_L1L2:
 339                                l1 = &(scontext->range.level[0]);
 340                                l2 = &(tcontext->range.level[0]);
 341                                goto mls_ops;
 342                        case CEXPR_L1H2:
 343                                l1 = &(scontext->range.level[0]);
 344                                l2 = &(tcontext->range.level[1]);
 345                                goto mls_ops;
 346                        case CEXPR_H1L2:
 347                                l1 = &(scontext->range.level[1]);
 348                                l2 = &(tcontext->range.level[0]);
 349                                goto mls_ops;
 350                        case CEXPR_H1H2:
 351                                l1 = &(scontext->range.level[1]);
 352                                l2 = &(tcontext->range.level[1]);
 353                                goto mls_ops;
 354                        case CEXPR_L1H1:
 355                                l1 = &(scontext->range.level[0]);
 356                                l2 = &(scontext->range.level[1]);
 357                                goto mls_ops;
 358                        case CEXPR_L2H2:
 359                                l1 = &(tcontext->range.level[0]);
 360                                l2 = &(tcontext->range.level[1]);
 361                                goto mls_ops;
 362mls_ops:
 363                        switch (e->op) {
 364                        case CEXPR_EQ:
 365                                s[++sp] = mls_level_eq(l1, l2);
 366                                continue;
 367                        case CEXPR_NEQ:
 368                                s[++sp] = !mls_level_eq(l1, l2);
 369                                continue;
 370                        case CEXPR_DOM:
 371                                s[++sp] = mls_level_dom(l1, l2);
 372                                continue;
 373                        case CEXPR_DOMBY:
 374                                s[++sp] = mls_level_dom(l2, l1);
 375                                continue;
 376                        case CEXPR_INCOMP:
 377                                s[++sp] = mls_level_incomp(l2, l1);
 378                                continue;
 379                        default:
 380                                BUG();
 381                                return 0;
 382                        }
 383                        break;
 384                        default:
 385                                BUG();
 386                                return 0;
 387                        }
 388
 389                        switch (e->op) {
 390                        case CEXPR_EQ:
 391                                s[++sp] = (val1 == val2);
 392                                break;
 393                        case CEXPR_NEQ:
 394                                s[++sp] = (val1 != val2);
 395                                break;
 396                        default:
 397                                BUG();
 398                                return 0;
 399                        }
 400                        break;
 401                case CEXPR_NAMES:
 402                        if (sp == (CEXPR_MAXDEPTH-1))
 403                                return 0;
 404                        c = scontext;
 405                        if (e->attr & CEXPR_TARGET)
 406                                c = tcontext;
 407                        else if (e->attr & CEXPR_XTARGET) {
 408                                c = xcontext;
 409                                if (!c) {
 410                                        BUG();
 411                                        return 0;
 412                                }
 413                        }
 414                        if (e->attr & CEXPR_USER)
 415                                val1 = c->user;
 416                        else if (e->attr & CEXPR_ROLE)
 417                                val1 = c->role;
 418                        else if (e->attr & CEXPR_TYPE)
 419                                val1 = c->type;
 420                        else {
 421                                BUG();
 422                                return 0;
 423                        }
 424
 425                        switch (e->op) {
 426                        case CEXPR_EQ:
 427                                s[++sp] = ebitmap_get_bit(&e->names, val1 - 1);
 428                                break;
 429                        case CEXPR_NEQ:
 430                                s[++sp] = !ebitmap_get_bit(&e->names, val1 - 1);
 431                                break;
 432                        default:
 433                                BUG();
 434                                return 0;
 435                        }
 436                        break;
 437                default:
 438                        BUG();
 439                        return 0;
 440                }
 441        }
 442
 443        BUG_ON(sp != 0);
 444        return s[0];
 445}
 446
 447/*
 448 * security_dump_masked_av - dumps masked permissions during
 449 * security_compute_av due to RBAC, MLS/Constraint and Type bounds.
 450 */
 451static int dump_masked_av_helper(void *k, void *d, void *args)
 452{
 453        struct perm_datum *pdatum = d;
 454        char **permission_names = args;
 455
 456        BUG_ON(pdatum->value < 1 || pdatum->value > 32);
 457
 458        permission_names[pdatum->value - 1] = (char *)k;
 459
 460        return 0;
 461}
 462
 463static void security_dump_masked_av(struct context *scontext,
 464                                    struct context *tcontext,
 465                                    u16 tclass,
 466                                    u32 permissions,
 467                                    const char *reason)
 468{
 469        struct common_datum *common_dat;
 470        struct class_datum *tclass_dat;
 471        struct audit_buffer *ab;
 472        char *tclass_name;
 473        char *scontext_name = NULL;
 474        char *tcontext_name = NULL;
 475        char *permission_names[32];
 476        int index;
 477        u32 length;
 478        bool need_comma = false;
 479
 480        if (!permissions)
 481                return;
 482
 483        tclass_name = sym_name(&policydb, SYM_CLASSES, tclass - 1);
 484        tclass_dat = policydb.class_val_to_struct[tclass - 1];
 485        common_dat = tclass_dat->comdatum;
 486
 487        /* init permission_names */
 488        if (common_dat &&
 489            hashtab_map(common_dat->permissions.table,
 490                        dump_masked_av_helper, permission_names) < 0)
 491                goto out;
 492
 493        if (hashtab_map(tclass_dat->permissions.table,
 494                        dump_masked_av_helper, permission_names) < 0)
 495                goto out;
 496
 497        /* get scontext/tcontext in text form */
 498        if (context_struct_to_string(scontext,
 499                                     &scontext_name, &length) < 0)
 500                goto out;
 501
 502        if (context_struct_to_string(tcontext,
 503                                     &tcontext_name, &length) < 0)
 504                goto out;
 505
 506        /* audit a message */
 507        ab = audit_log_start(current->audit_context,
 508                             GFP_ATOMIC, AUDIT_SELINUX_ERR);
 509        if (!ab)
 510                goto out;
 511
 512        audit_log_format(ab, "op=security_compute_av reason=%s "
 513                         "scontext=%s tcontext=%s tclass=%s perms=",
 514                         reason, scontext_name, tcontext_name, tclass_name);
 515
 516        for (index = 0; index < 32; index++) {
 517                u32 mask = (1 << index);
 518
 519                if ((mask & permissions) == 0)
 520                        continue;
 521
 522                audit_log_format(ab, "%s%s",
 523                                 need_comma ? "," : "",
 524                                 permission_names[index]
 525                                 ? permission_names[index] : "????");
 526                need_comma = true;
 527        }
 528        audit_log_end(ab);
 529out:
 530        /* release scontext/tcontext */
 531        kfree(tcontext_name);
 532        kfree(scontext_name);
 533
 534        return;
 535}
 536
 537/*
 538 * security_boundary_permission - drops violated permissions
 539 * on boundary constraint.
 540 */
 541static void type_attribute_bounds_av(struct context *scontext,
 542                                     struct context *tcontext,
 543                                     u16 tclass,
 544                                     struct av_decision *avd)
 545{
 546        struct context lo_scontext;
 547        struct context lo_tcontext;
 548        struct av_decision lo_avd;
 549        struct type_datum *source;
 550        struct type_datum *target;
 551        u32 masked = 0;
 552
 553        source = flex_array_get_ptr(policydb.type_val_to_struct_array,
 554                                    scontext->type - 1);
 555        BUG_ON(!source);
 556
 557        target = flex_array_get_ptr(policydb.type_val_to_struct_array,
 558                                    tcontext->type - 1);
 559        BUG_ON(!target);
 560
 561        if (source->bounds) {
 562                memset(&lo_avd, 0, sizeof(lo_avd));
 563
 564                memcpy(&lo_scontext, scontext, sizeof(lo_scontext));
 565                lo_scontext.type = source->bounds;
 566
 567                context_struct_compute_av(&lo_scontext,
 568                                          tcontext,
 569                                          tclass,
 570                                          &lo_avd,
 571                                          NULL);
 572                if ((lo_avd.allowed & avd->allowed) == avd->allowed)
 573                        return;         /* no masked permission */
 574                masked = ~lo_avd.allowed & avd->allowed;
 575        }
 576
 577        if (target->bounds) {
 578                memset(&lo_avd, 0, sizeof(lo_avd));
 579
 580                memcpy(&lo_tcontext, tcontext, sizeof(lo_tcontext));
 581                lo_tcontext.type = target->bounds;
 582
 583                context_struct_compute_av(scontext,
 584                                          &lo_tcontext,
 585                                          tclass,
 586                                          &lo_avd,
 587                                          NULL);
 588                if ((lo_avd.allowed & avd->allowed) == avd->allowed)
 589                        return;         /* no masked permission */
 590                masked = ~lo_avd.allowed & avd->allowed;
 591        }
 592
 593        if (source->bounds && target->bounds) {
 594                memset(&lo_avd, 0, sizeof(lo_avd));
 595                /*
 596                 * lo_scontext and lo_tcontext are already
 597                 * set up.
 598                 */
 599
 600                context_struct_compute_av(&lo_scontext,
 601                                          &lo_tcontext,
 602                                          tclass,
 603                                          &lo_avd,
 604                                          NULL);
 605                if ((lo_avd.allowed & avd->allowed) == avd->allowed)
 606                        return;         /* no masked permission */
 607                masked = ~lo_avd.allowed & avd->allowed;
 608        }
 609
 610        if (masked) {
 611                /* mask violated permissions */
 612                avd->allowed &= ~masked;
 613
 614                /* audit masked permissions */
 615                security_dump_masked_av(scontext, tcontext,
 616                                        tclass, masked, "bounds");
 617        }
 618}
 619
 620/*
 621 * flag which drivers have permissions
 622 * only looking for ioctl based extended permssions
 623 */
 624void services_compute_xperms_drivers(
 625                struct extended_perms *xperms,
 626                struct avtab_node *node)
 627{
 628        unsigned int i;
 629
 630        if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
 631                /* if one or more driver has all permissions allowed */
 632                for (i = 0; i < ARRAY_SIZE(xperms->drivers.p); i++)
 633                        xperms->drivers.p[i] |= node->datum.u.xperms->perms.p[i];
 634        } else if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
 635                /* if allowing permissions within a driver */
 636                security_xperm_set(xperms->drivers.p,
 637                                        node->datum.u.xperms->driver);
 638        }
 639
 640        /* If no ioctl commands are allowed, ignore auditallow and auditdeny */
 641        if (node->key.specified & AVTAB_XPERMS_ALLOWED)
 642                xperms->len = 1;
 643}
 644
 645/*
 646 * Compute access vectors and extended permissions based on a context
 647 * structure pair for the permissions in a particular class.
 648 */
 649static void context_struct_compute_av(struct context *scontext,
 650                                        struct context *tcontext,
 651                                        u16 tclass,
 652                                        struct av_decision *avd,
 653                                        struct extended_perms *xperms)
 654{
 655        struct constraint_node *constraint;
 656        struct role_allow *ra;
 657        struct avtab_key avkey;
 658        struct avtab_node *node;
 659        struct class_datum *tclass_datum;
 660        struct ebitmap *sattr, *tattr;
 661        struct ebitmap_node *snode, *tnode;
 662        unsigned int i, j;
 663
 664        avd->allowed = 0;
 665        avd->auditallow = 0;
 666        avd->auditdeny = 0xffffffff;
 667        if (xperms) {
 668                memset(&xperms->drivers, 0, sizeof(xperms->drivers));
 669                xperms->len = 0;
 670        }
 671
 672        if (unlikely(!tclass || tclass > policydb.p_classes.nprim)) {
 673                if (printk_ratelimit())
 674                        printk(KERN_WARNING "SELinux:  Invalid class %hu\n", tclass);
 675                return;
 676        }
 677
 678        tclass_datum = policydb.class_val_to_struct[tclass - 1];
 679
 680        /*
 681         * If a specific type enforcement rule was defined for
 682         * this permission check, then use it.
 683         */
 684        avkey.target_class = tclass;
 685        avkey.specified = AVTAB_AV | AVTAB_XPERMS;
 686        sattr = flex_array_get(policydb.type_attr_map_array, scontext->type - 1);
 687        BUG_ON(!sattr);
 688        tattr = flex_array_get(policydb.type_attr_map_array, tcontext->type - 1);
 689        BUG_ON(!tattr);
 690        ebitmap_for_each_positive_bit(sattr, snode, i) {
 691                ebitmap_for_each_positive_bit(tattr, tnode, j) {
 692                        avkey.source_type = i + 1;
 693                        avkey.target_type = j + 1;
 694                        for (node = avtab_search_node(&policydb.te_avtab, &avkey);
 695                             node;
 696                             node = avtab_search_node_next(node, avkey.specified)) {
 697                                if (node->key.specified == AVTAB_ALLOWED)
 698                                        avd->allowed |= node->datum.u.data;
 699                                else if (node->key.specified == AVTAB_AUDITALLOW)
 700                                        avd->auditallow |= node->datum.u.data;
 701                                else if (node->key.specified == AVTAB_AUDITDENY)
 702                                        avd->auditdeny &= node->datum.u.data;
 703                                else if (xperms && (node->key.specified & AVTAB_XPERMS))
 704                                        services_compute_xperms_drivers(xperms, node);
 705                        }
 706
 707                        /* Check conditional av table for additional permissions */
 708                        cond_compute_av(&policydb.te_cond_avtab, &avkey,
 709                                        avd, xperms);
 710
 711                }
 712        }
 713
 714        /*
 715         * Remove any permissions prohibited by a constraint (this includes
 716         * the MLS policy).
 717         */
 718        constraint = tclass_datum->constraints;
 719        while (constraint) {
 720                if ((constraint->permissions & (avd->allowed)) &&
 721                    !constraint_expr_eval(scontext, tcontext, NULL,
 722                                          constraint->expr)) {
 723                        avd->allowed &= ~(constraint->permissions);
 724                }
 725                constraint = constraint->next;
 726        }
 727
 728        /*
 729         * If checking process transition permission and the
 730         * role is changing, then check the (current_role, new_role)
 731         * pair.
 732         */
 733        if (tclass == policydb.process_class &&
 734            (avd->allowed & policydb.process_trans_perms) &&
 735            scontext->role != tcontext->role) {
 736                for (ra = policydb.role_allow; ra; ra = ra->next) {
 737                        if (scontext->role == ra->role &&
 738                            tcontext->role == ra->new_role)
 739                                break;
 740                }
 741                if (!ra)
 742                        avd->allowed &= ~policydb.process_trans_perms;
 743        }
 744
 745        /*
 746         * If the given source and target types have boundary
 747         * constraint, lazy checks have to mask any violated
 748         * permission and notice it to userspace via audit.
 749         */
 750        type_attribute_bounds_av(scontext, tcontext,
 751                                 tclass, avd);
 752}
 753
 754static int security_validtrans_handle_fail(struct context *ocontext,
 755                                           struct context *ncontext,
 756                                           struct context *tcontext,
 757                                           u16 tclass)
 758{
 759        char *o = NULL, *n = NULL, *t = NULL;
 760        u32 olen, nlen, tlen;
 761
 762        if (context_struct_to_string(ocontext, &o, &olen))
 763                goto out;
 764        if (context_struct_to_string(ncontext, &n, &nlen))
 765                goto out;
 766        if (context_struct_to_string(tcontext, &t, &tlen))
 767                goto out;
 768        audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
 769                  "op=security_validate_transition seresult=denied"
 770                  " oldcontext=%s newcontext=%s taskcontext=%s tclass=%s",
 771                  o, n, t, sym_name(&policydb, SYM_CLASSES, tclass-1));
 772out:
 773        kfree(o);
 774        kfree(n);
 775        kfree(t);
 776
 777        if (!selinux_enforcing)
 778                return 0;
 779        return -EPERM;
 780}
 781
 782int security_validate_transition(u32 oldsid, u32 newsid, u32 tasksid,
 783                                 u16 orig_tclass)
 784{
 785        struct context *ocontext;
 786        struct context *ncontext;
 787        struct context *tcontext;
 788        struct class_datum *tclass_datum;
 789        struct constraint_node *constraint;
 790        u16 tclass;
 791        int rc = 0;
 792
 793        if (!ss_initialized)
 794                return 0;
 795
 796        read_lock(&policy_rwlock);
 797
 798        tclass = unmap_class(orig_tclass);
 799
 800        if (!tclass || tclass > policydb.p_classes.nprim) {
 801                printk(KERN_ERR "SELinux: %s:  unrecognized class %d\n",
 802                        __func__, tclass);
 803                rc = -EINVAL;
 804                goto out;
 805        }
 806        tclass_datum = policydb.class_val_to_struct[tclass - 1];
 807
 808        ocontext = sidtab_search(sidtab, oldsid);
 809        if (!ocontext) {
 810                printk(KERN_ERR "SELinux: %s:  unrecognized SID %d\n",
 811                        __func__, oldsid);
 812                rc = -EINVAL;
 813                goto out;
 814        }
 815
 816        ncontext = sidtab_search(sidtab, newsid);
 817        if (!ncontext) {
 818                printk(KERN_ERR "SELinux: %s:  unrecognized SID %d\n",
 819                        __func__, newsid);
 820                rc = -EINVAL;
 821                goto out;
 822        }
 823
 824        tcontext = sidtab_search(sidtab, tasksid);
 825        if (!tcontext) {
 826                printk(KERN_ERR "SELinux: %s:  unrecognized SID %d\n",
 827                        __func__, tasksid);
 828                rc = -EINVAL;
 829                goto out;
 830        }
 831
 832        constraint = tclass_datum->validatetrans;
 833        while (constraint) {
 834                if (!constraint_expr_eval(ocontext, ncontext, tcontext,
 835                                          constraint->expr)) {
 836                        rc = security_validtrans_handle_fail(ocontext, ncontext,
 837                                                             tcontext, tclass);
 838                        goto out;
 839                }
 840                constraint = constraint->next;
 841        }
 842
 843out:
 844        read_unlock(&policy_rwlock);
 845        return rc;
 846}
 847
 848/*
 849 * security_bounded_transition - check whether the given
 850 * transition is directed to bounded, or not.
 851 * It returns 0, if @newsid is bounded by @oldsid.
 852 * Otherwise, it returns error code.
 853 *
 854 * @oldsid : current security identifier
 855 * @newsid : destinated security identifier
 856 */
 857int security_bounded_transition(u32 old_sid, u32 new_sid)
 858{
 859        struct context *old_context, *new_context;
 860        struct type_datum *type;
 861        int index;
 862        int rc;
 863
 864        read_lock(&policy_rwlock);
 865
 866        rc = -EINVAL;
 867        old_context = sidtab_search(sidtab, old_sid);
 868        if (!old_context) {
 869                printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n",
 870                       __func__, old_sid);
 871                goto out;
 872        }
 873
 874        rc = -EINVAL;
 875        new_context = sidtab_search(sidtab, new_sid);
 876        if (!new_context) {
 877                printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n",
 878                       __func__, new_sid);
 879                goto out;
 880        }
 881
 882        rc = 0;
 883        /* type/domain unchanged */
 884        if (old_context->type == new_context->type)
 885                goto out;
 886
 887        index = new_context->type;
 888        while (true) {
 889                type = flex_array_get_ptr(policydb.type_val_to_struct_array,
 890                                          index - 1);
 891                BUG_ON(!type);
 892
 893                /* not bounded anymore */
 894                rc = -EPERM;
 895                if (!type->bounds)
 896                        break;
 897
 898                /* @newsid is bounded by @oldsid */
 899                rc = 0;
 900                if (type->bounds == old_context->type)
 901                        break;
 902
 903                index = type->bounds;
 904        }
 905
 906        if (rc) {
 907                char *old_name = NULL;
 908                char *new_name = NULL;
 909                u32 length;
 910
 911                if (!context_struct_to_string(old_context,
 912                                              &old_name, &length) &&
 913                    !context_struct_to_string(new_context,
 914                                              &new_name, &length)) {
 915                        audit_log(current->audit_context,
 916                                  GFP_ATOMIC, AUDIT_SELINUX_ERR,
 917                                  "op=security_bounded_transition "
 918                                  "seresult=denied "
 919                                  "oldcontext=%s newcontext=%s",
 920                                  old_name, new_name);
 921                }
 922                kfree(new_name);
 923                kfree(old_name);
 924        }
 925out:
 926        read_unlock(&policy_rwlock);
 927
 928        return rc;
 929}
 930
 931static void avd_init(struct av_decision *avd)
 932{
 933        avd->allowed = 0;
 934        avd->auditallow = 0;
 935        avd->auditdeny = 0xffffffff;
 936        avd->seqno = latest_granting;
 937        avd->flags = 0;
 938}
 939
 940void services_compute_xperms_decision(struct extended_perms_decision *xpermd,
 941                                        struct avtab_node *node)
 942{
 943        unsigned int i;
 944
 945        if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
 946                if (xpermd->driver != node->datum.u.xperms->driver)
 947                        return;
 948        } else if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
 949                if (!security_xperm_test(node->datum.u.xperms->perms.p,
 950                                        xpermd->driver))
 951                        return;
 952        } else {
 953                BUG();
 954        }
 955
 956        if (node->key.specified == AVTAB_XPERMS_ALLOWED) {
 957                xpermd->used |= XPERMS_ALLOWED;
 958                if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
 959                        memset(xpermd->allowed->p, 0xff,
 960                                        sizeof(xpermd->allowed->p));
 961                }
 962                if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
 963                        for (i = 0; i < ARRAY_SIZE(xpermd->allowed->p); i++)
 964                                xpermd->allowed->p[i] |=
 965                                        node->datum.u.xperms->perms.p[i];
 966                }
 967        } else if (node->key.specified == AVTAB_XPERMS_AUDITALLOW) {
 968                xpermd->used |= XPERMS_AUDITALLOW;
 969                if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
 970                        memset(xpermd->auditallow->p, 0xff,
 971                                        sizeof(xpermd->auditallow->p));
 972                }
 973                if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
 974                        for (i = 0; i < ARRAY_SIZE(xpermd->auditallow->p); i++)
 975                                xpermd->auditallow->p[i] |=
 976                                        node->datum.u.xperms->perms.p[i];
 977                }
 978        } else if (node->key.specified == AVTAB_XPERMS_DONTAUDIT) {
 979                xpermd->used |= XPERMS_DONTAUDIT;
 980                if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
 981                        memset(xpermd->dontaudit->p, 0xff,
 982                                        sizeof(xpermd->dontaudit->p));
 983                }
 984                if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
 985                        for (i = 0; i < ARRAY_SIZE(xpermd->dontaudit->p); i++)
 986                                xpermd->dontaudit->p[i] |=
 987                                        node->datum.u.xperms->perms.p[i];
 988                }
 989        } else {
 990                BUG();
 991        }
 992}
 993
 994void security_compute_xperms_decision(u32 ssid,
 995                                u32 tsid,
 996                                u16 orig_tclass,
 997                                u8 driver,
 998                                struct extended_perms_decision *xpermd)
 999{
1000        u16 tclass;
1001        struct context *scontext, *tcontext;
1002        struct avtab_key avkey;
1003        struct avtab_node *node;
1004        struct ebitmap *sattr, *tattr;
1005        struct ebitmap_node *snode, *tnode;
1006        unsigned int i, j;
1007
1008        xpermd->driver = driver;
1009        xpermd->used = 0;
1010        memset(xpermd->allowed->p, 0, sizeof(xpermd->allowed->p));
1011        memset(xpermd->auditallow->p, 0, sizeof(xpermd->auditallow->p));
1012        memset(xpermd->dontaudit->p, 0, sizeof(xpermd->dontaudit->p));
1013
1014        read_lock(&policy_rwlock);
1015        if (!ss_initialized)
1016                goto allow;
1017
1018        scontext = sidtab_search(sidtab, ssid);
1019        if (!scontext) {
1020                printk(KERN_ERR "SELinux: %s:  unrecognized SID %d\n",
1021                       __func__, ssid);
1022                goto out;
1023        }
1024
1025        tcontext = sidtab_search(sidtab, tsid);
1026        if (!tcontext) {
1027                printk(KERN_ERR "SELinux: %s:  unrecognized SID %d\n",
1028                       __func__, tsid);
1029                goto out;
1030        }
1031
1032        tclass = unmap_class(orig_tclass);
1033        if (unlikely(orig_tclass && !tclass)) {
1034                if (policydb.allow_unknown)
1035                        goto allow;
1036                goto out;
1037        }
1038
1039
1040        if (unlikely(!tclass || tclass > policydb.p_classes.nprim)) {
1041                pr_warn_ratelimited("SELinux:  Invalid class %hu\n", tclass);
1042                goto out;
1043        }
1044
1045        avkey.target_class = tclass;
1046        avkey.specified = AVTAB_XPERMS;
1047        sattr = flex_array_get(policydb.type_attr_map_array,
1048                                scontext->type - 1);
1049        BUG_ON(!sattr);
1050        tattr = flex_array_get(policydb.type_attr_map_array,
1051                                tcontext->type - 1);
1052        BUG_ON(!tattr);
1053        ebitmap_for_each_positive_bit(sattr, snode, i) {
1054                ebitmap_for_each_positive_bit(tattr, tnode, j) {
1055                        avkey.source_type = i + 1;
1056                        avkey.target_type = j + 1;
1057                        for (node = avtab_search_node(&policydb.te_avtab, &avkey);
1058                             node;
1059                             node = avtab_search_node_next(node, avkey.specified))
1060                                services_compute_xperms_decision(xpermd, node);
1061
1062                        cond_compute_xperms(&policydb.te_cond_avtab,
1063                                                &avkey, xpermd);
1064                }
1065        }
1066out:
1067        read_unlock(&policy_rwlock);
1068        return;
1069allow:
1070        memset(xpermd->allowed->p, 0xff, sizeof(xpermd->allowed->p));
1071        goto out;
1072}
1073
1074/**
1075 * security_compute_av - Compute access vector decisions.
1076 * @ssid: source security identifier
1077 * @tsid: target security identifier
1078 * @tclass: target security class
1079 * @avd: access vector decisions
1080 * @xperms: extended permissions
1081 *
1082 * Compute a set of access vector decisions based on the
1083 * SID pair (@ssid, @tsid) for the permissions in @tclass.
1084 */
1085void security_compute_av(u32 ssid,
1086                         u32 tsid,
1087                         u16 orig_tclass,
1088                         struct av_decision *avd,
1089                         struct extended_perms *xperms)
1090{
1091        u16 tclass;
1092        struct context *scontext = NULL, *tcontext = NULL;
1093
1094        read_lock(&policy_rwlock);
1095        avd_init(avd);
1096        xperms->len = 0;
1097        if (!ss_initialized)
1098                goto allow;
1099
1100        scontext = sidtab_search(sidtab, ssid);
1101        if (!scontext) {
1102                printk(KERN_ERR "SELinux: %s:  unrecognized SID %d\n",
1103                       __func__, ssid);
1104                goto out;
1105        }
1106
1107        /* permissive domain? */
1108        if (ebitmap_get_bit(&policydb.permissive_map, scontext->type))
1109                avd->flags |= AVD_FLAGS_PERMISSIVE;
1110
1111        tcontext = sidtab_search(sidtab, tsid);
1112        if (!tcontext) {
1113                printk(KERN_ERR "SELinux: %s:  unrecognized SID %d\n",
1114                       __func__, tsid);
1115                goto out;
1116        }
1117
1118        tclass = unmap_class(orig_tclass);
1119        if (unlikely(orig_tclass && !tclass)) {
1120                if (policydb.allow_unknown)
1121                        goto allow;
1122                goto out;
1123        }
1124        context_struct_compute_av(scontext, tcontext, tclass, avd, xperms);
1125        map_decision(orig_tclass, avd, policydb.allow_unknown);
1126out:
1127        read_unlock(&policy_rwlock);
1128        return;
1129allow:
1130        avd->allowed = 0xffffffff;
1131        goto out;
1132}
1133
1134void security_compute_av_user(u32 ssid,
1135                              u32 tsid,
1136                              u16 tclass,
1137                              struct av_decision *avd)
1138{
1139        struct context *scontext = NULL, *tcontext = NULL;
1140
1141        read_lock(&policy_rwlock);
1142        avd_init(avd);
1143        if (!ss_initialized)
1144                goto allow;
1145
1146        scontext = sidtab_search(sidtab, ssid);
1147        if (!scontext) {
1148                printk(KERN_ERR "SELinux: %s:  unrecognized SID %d\n",
1149                       __func__, ssid);
1150                goto out;
1151        }
1152
1153        /* permissive domain? */
1154        if (ebitmap_get_bit(&policydb.permissive_map, scontext->type))
1155                avd->flags |= AVD_FLAGS_PERMISSIVE;
1156
1157        tcontext = sidtab_search(sidtab, tsid);
1158        if (!tcontext) {
1159                printk(KERN_ERR "SELinux: %s:  unrecognized SID %d\n",
1160                       __func__, tsid);
1161                goto out;
1162        }
1163
1164        if (unlikely(!tclass)) {
1165                if (policydb.allow_unknown)
1166                        goto allow;
1167                goto out;
1168        }
1169
1170        context_struct_compute_av(scontext, tcontext, tclass, avd, NULL);
1171 out:
1172        read_unlock(&policy_rwlock);
1173        return;
1174allow:
1175        avd->allowed = 0xffffffff;
1176        goto out;
1177}
1178
1179/*
1180 * Write the security context string representation of
1181 * the context structure `context' into a dynamically
1182 * allocated string of the correct size.  Set `*scontext'
1183 * to point to this string and set `*scontext_len' to
1184 * the length of the string.
1185 */
1186static int context_struct_to_string(struct context *context, char **scontext, u32 *scontext_len)
1187{
1188        char *scontextp;
1189
1190        if (scontext)
1191                *scontext = NULL;
1192        *scontext_len = 0;
1193
1194        if (context->len) {
1195                *scontext_len = context->len;
1196                if (scontext) {
1197                        *scontext = kstrdup(context->str, GFP_ATOMIC);
1198                        if (!(*scontext))
1199                                return -ENOMEM;
1200                }
1201                return 0;
1202        }
1203
1204        /* Compute the size of the context. */
1205        *scontext_len += strlen(sym_name(&policydb, SYM_USERS, context->user - 1)) + 1;
1206        *scontext_len += strlen(sym_name(&policydb, SYM_ROLES, context->role - 1)) + 1;
1207        *scontext_len += strlen(sym_name(&policydb, SYM_TYPES, context->type - 1)) + 1;
1208        *scontext_len += mls_compute_context_len(context);
1209
1210        if (!scontext)
1211                return 0;
1212
1213        /* Allocate space for the context; caller must free this space. */
1214        scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
1215        if (!scontextp)
1216                return -ENOMEM;
1217        *scontext = scontextp;
1218
1219        /*
1220         * Copy the user name, role name and type name into the context.
1221         */
1222        sprintf(scontextp, "%s:%s:%s",
1223                sym_name(&policydb, SYM_USERS, context->user - 1),
1224                sym_name(&policydb, SYM_ROLES, context->role - 1),
1225                sym_name(&policydb, SYM_TYPES, context->type - 1));
1226        scontextp += strlen(sym_name(&policydb, SYM_USERS, context->user - 1)) +
1227                     1 + strlen(sym_name(&policydb, SYM_ROLES, context->role - 1)) +
1228                     1 + strlen(sym_name(&policydb, SYM_TYPES, context->type - 1));
1229
1230        mls_sid_to_context(context, &scontextp);
1231
1232        *scontextp = 0;
1233
1234        return 0;
1235}
1236
1237#include "initial_sid_to_string.h"
1238
1239const char *security_get_initial_sid_context(u32 sid)
1240{
1241        if (unlikely(sid > SECINITSID_NUM))
1242                return NULL;
1243        return initial_sid_to_string[sid];
1244}
1245
1246static int security_sid_to_context_core(u32 sid, char **scontext,
1247                                        u32 *scontext_len, int force)
1248{
1249        struct context *context;
1250        int rc = 0;
1251
1252        if (scontext)
1253                *scontext = NULL;
1254        *scontext_len  = 0;
1255
1256        if (!ss_initialized) {
1257                if (sid <= SECINITSID_NUM) {
1258                        char *scontextp;
1259
1260                        *scontext_len = strlen(initial_sid_to_string[sid]) + 1;
1261                        if (!scontext)
1262                                goto out;
1263                        scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
1264                        if (!scontextp) {
1265                                rc = -ENOMEM;
1266                                goto out;
1267                        }
1268                        strcpy(scontextp, initial_sid_to_string[sid]);
1269                        *scontext = scontextp;
1270                        goto out;
1271                }
1272                printk(KERN_ERR "SELinux: %s:  called before initial "
1273                       "load_policy on unknown SID %d\n", __func__, sid);
1274                rc = -EINVAL;
1275                goto out;
1276        }
1277        read_lock(&policy_rwlock);
1278        if (force)
1279                context = sidtab_search_force(sidtab, sid);
1280        else
1281                context = sidtab_search(sidtab, sid);
1282        if (!context) {
1283                printk(KERN_ERR "SELinux: %s:  unrecognized SID %d\n",
1284                        __func__, sid);
1285                rc = -EINVAL;
1286                goto out_unlock;
1287        }
1288        rc = context_struct_to_string(context, scontext, scontext_len);
1289out_unlock:
1290        read_unlock(&policy_rwlock);
1291out:
1292        return rc;
1293
1294}
1295
1296/**
1297 * security_sid_to_context - Obtain a context for a given SID.
1298 * @sid: security identifier, SID
1299 * @scontext: security context
1300 * @scontext_len: length in bytes
1301 *
1302 * Write the string representation of the context associated with @sid
1303 * into a dynamically allocated string of the correct size.  Set @scontext
1304 * to point to this string and set @scontext_len to the length of the string.
1305 */
1306int security_sid_to_context(u32 sid, char **scontext, u32 *scontext_len)
1307{
1308        return security_sid_to_context_core(sid, scontext, scontext_len, 0);
1309}
1310
1311int security_sid_to_context_force(u32 sid, char **scontext, u32 *scontext_len)
1312{
1313        return security_sid_to_context_core(sid, scontext, scontext_len, 1);
1314}
1315
1316/*
1317 * Caveat:  Mutates scontext.
1318 */
1319static int string_to_context_struct(struct policydb *pol,
1320                                    struct sidtab *sidtabp,
1321                                    char *scontext,
1322                                    u32 scontext_len,
1323                                    struct context *ctx,
1324                                    u32 def_sid)
1325{
1326        struct role_datum *role;
1327        struct type_datum *typdatum;
1328        struct user_datum *usrdatum;
1329        char *scontextp, *p, oldc;
1330        int rc = 0;
1331
1332        context_init(ctx);
1333
1334        /* Parse the security context. */
1335
1336        rc = -EINVAL;
1337        scontextp = (char *) scontext;
1338
1339        /* Extract the user. */
1340        p = scontextp;
1341        while (*p && *p != ':')
1342                p++;
1343
1344        if (*p == 0)
1345                goto out;
1346
1347        *p++ = 0;
1348
1349        usrdatum = hashtab_search(pol->p_users.table, scontextp);
1350        if (!usrdatum)
1351                goto out;
1352
1353        ctx->user = usrdatum->value;
1354
1355        /* Extract role. */
1356        scontextp = p;
1357        while (*p && *p != ':')
1358                p++;
1359
1360        if (*p == 0)
1361                goto out;
1362
1363        *p++ = 0;
1364
1365        role = hashtab_search(pol->p_roles.table, scontextp);
1366        if (!role)
1367                goto out;
1368        ctx->role = role->value;
1369
1370        /* Extract type. */
1371        scontextp = p;
1372        while (*p && *p != ':')
1373                p++;
1374        oldc = *p;
1375        *p++ = 0;
1376
1377        typdatum = hashtab_search(pol->p_types.table, scontextp);
1378        if (!typdatum || typdatum->attribute)
1379                goto out;
1380
1381        ctx->type = typdatum->value;
1382
1383        rc = mls_context_to_sid(pol, oldc, &p, ctx, sidtabp, def_sid);
1384        if (rc)
1385                goto out;
1386
1387        rc = -EINVAL;
1388        if ((p - scontext) < scontext_len)
1389                goto out;
1390
1391        /* Check the validity of the new context. */
1392        if (!policydb_context_isvalid(pol, ctx))
1393                goto out;
1394        rc = 0;
1395out:
1396        if (rc)
1397                context_destroy(ctx);
1398        return rc;
1399}
1400
1401static int security_context_to_sid_core(const char *scontext, u32 scontext_len,
1402                                        u32 *sid, u32 def_sid, gfp_t gfp_flags,
1403                                        int force)
1404{
1405        char *scontext2, *str = NULL;
1406        struct context context;
1407        int rc = 0;
1408
1409        /* An empty security context is never valid. */
1410        if (!scontext_len)
1411                return -EINVAL;
1412
1413        if (!ss_initialized) {
1414                int i;
1415
1416                for (i = 1; i < SECINITSID_NUM; i++) {
1417                        if (!strcmp(initial_sid_to_string[i], scontext)) {
1418                                *sid = i;
1419                                return 0;
1420                        }
1421                }
1422                *sid = SECINITSID_KERNEL;
1423                return 0;
1424        }
1425        *sid = SECSID_NULL;
1426
1427        /* Copy the string so that we can modify the copy as we parse it. */
1428        scontext2 = kmalloc(scontext_len + 1, gfp_flags);
1429        if (!scontext2)
1430                return -ENOMEM;
1431        memcpy(scontext2, scontext, scontext_len);
1432        scontext2[scontext_len] = 0;
1433
1434        if (force) {
1435                /* Save another copy for storing in uninterpreted form */
1436                rc = -ENOMEM;
1437                str = kstrdup(scontext2, gfp_flags);
1438                if (!str)
1439                        goto out;
1440        }
1441
1442        read_lock(&policy_rwlock);
1443        rc = string_to_context_struct(&policydb, sidtab, scontext2,
1444                                      scontext_len, &context, def_sid);
1445        if (rc == -EINVAL && force) {
1446                context.str = str;
1447                context.len = strlen(str) + 1;
1448                str = NULL;
1449        } else if (rc)
1450                goto out_unlock;
1451        rc = sidtab_context_to_sid(sidtab, &context, sid);
1452        context_destroy(&context);
1453out_unlock:
1454        read_unlock(&policy_rwlock);
1455out:
1456        kfree(scontext2);
1457        kfree(str);
1458        return rc;
1459}
1460
1461/**
1462 * security_context_to_sid - Obtain a SID for a given security context.
1463 * @scontext: security context
1464 * @scontext_len: length in bytes
1465 * @sid: security identifier, SID
1466 *
1467 * Obtains a SID associated with the security context that
1468 * has the string representation specified by @scontext.
1469 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1470 * memory is available, or 0 on success.
1471 */
1472int security_context_to_sid(const char *scontext, u32 scontext_len, u32 *sid)
1473{
1474        return security_context_to_sid_core(scontext, scontext_len,
1475                                            sid, SECSID_NULL, GFP_KERNEL, 0);
1476}
1477
1478/**
1479 * security_context_to_sid_default - Obtain a SID for a given security context,
1480 * falling back to specified default if needed.
1481 *
1482 * @scontext: security context
1483 * @scontext_len: length in bytes
1484 * @sid: security identifier, SID
1485 * @def_sid: default SID to assign on error
1486 *
1487 * Obtains a SID associated with the security context that
1488 * has the string representation specified by @scontext.
1489 * The default SID is passed to the MLS layer to be used to allow
1490 * kernel labeling of the MLS field if the MLS field is not present
1491 * (for upgrading to MLS without full relabel).
1492 * Implicitly forces adding of the context even if it cannot be mapped yet.
1493 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1494 * memory is available, or 0 on success.
1495 */
1496int security_context_to_sid_default(const char *scontext, u32 scontext_len,
1497                                    u32 *sid, u32 def_sid, gfp_t gfp_flags)
1498{
1499        return security_context_to_sid_core(scontext, scontext_len,
1500                                            sid, def_sid, gfp_flags, 1);
1501}
1502
1503int security_context_to_sid_force(const char *scontext, u32 scontext_len,
1504                                  u32 *sid)
1505{
1506        return security_context_to_sid_core(scontext, scontext_len,
1507                                            sid, SECSID_NULL, GFP_KERNEL, 1);
1508}
1509
1510static int compute_sid_handle_invalid_context(
1511        struct context *scontext,
1512        struct context *tcontext,
1513        u16 tclass,
1514        struct context *newcontext)
1515{
1516        char *s = NULL, *t = NULL, *n = NULL;
1517        u32 slen, tlen, nlen;
1518
1519        if (context_struct_to_string(scontext, &s, &slen))
1520                goto out;
1521        if (context_struct_to_string(tcontext, &t, &tlen))
1522                goto out;
1523        if (context_struct_to_string(newcontext, &n, &nlen))
1524                goto out;
1525        audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
1526                  "op=security_compute_sid invalid_context=%s"
1527                  " scontext=%s"
1528                  " tcontext=%s"
1529                  " tclass=%s",
1530                  n, s, t, sym_name(&policydb, SYM_CLASSES, tclass-1));
1531out:
1532        kfree(s);
1533        kfree(t);
1534        kfree(n);
1535        if (!selinux_enforcing)
1536                return 0;
1537        return -EACCES;
1538}
1539
1540static void filename_compute_type(struct policydb *p, struct context *newcontext,
1541                                  u32 stype, u32 ttype, u16 tclass,
1542                                  const char *objname)
1543{
1544        struct filename_trans ft;
1545        struct filename_trans_datum *otype;
1546
1547        /*
1548         * Most filename trans rules are going to live in specific directories
1549         * like /dev or /var/run.  This bitmap will quickly skip rule searches
1550         * if the ttype does not contain any rules.
1551         */
1552        if (!ebitmap_get_bit(&p->filename_trans_ttypes, ttype))
1553                return;
1554
1555        ft.stype = stype;
1556        ft.ttype = ttype;
1557        ft.tclass = tclass;
1558        ft.name = objname;
1559
1560        otype = hashtab_search(p->filename_trans, &ft);
1561        if (otype)
1562                newcontext->type = otype->otype;
1563}
1564
1565static int security_compute_sid(u32 ssid,
1566                                u32 tsid,
1567                                u16 orig_tclass,
1568                                u32 specified,
1569                                const char *objname,
1570                                u32 *out_sid,
1571                                bool kern)
1572{
1573        struct class_datum *cladatum = NULL;
1574        struct context *scontext = NULL, *tcontext = NULL, newcontext;
1575        struct role_trans *roletr = NULL;
1576        struct avtab_key avkey;
1577        struct avtab_datum *avdatum;
1578        struct avtab_node *node;
1579        u16 tclass;
1580        int rc = 0;
1581        bool sock;
1582
1583        if (!ss_initialized) {
1584                switch (orig_tclass) {
1585                case SECCLASS_PROCESS: /* kernel value */
1586                        *out_sid = ssid;
1587                        break;
1588                default:
1589                        *out_sid = tsid;
1590                        break;
1591                }
1592                goto out;
1593        }
1594
1595        context_init(&newcontext);
1596
1597        read_lock(&policy_rwlock);
1598
1599        if (kern) {
1600                tclass = unmap_class(orig_tclass);
1601                sock = security_is_socket_class(orig_tclass);
1602        } else {
1603                tclass = orig_tclass;
1604                sock = security_is_socket_class(map_class(tclass));
1605        }
1606
1607        scontext = sidtab_search(sidtab, ssid);
1608        if (!scontext) {
1609                printk(KERN_ERR "SELinux: %s:  unrecognized SID %d\n",
1610                       __func__, ssid);
1611                rc = -EINVAL;
1612                goto out_unlock;
1613        }
1614        tcontext = sidtab_search(sidtab, tsid);
1615        if (!tcontext) {
1616                printk(KERN_ERR "SELinux: %s:  unrecognized SID %d\n",
1617                       __func__, tsid);
1618                rc = -EINVAL;
1619                goto out_unlock;
1620        }
1621
1622        if (tclass && tclass <= policydb.p_classes.nprim)
1623                cladatum = policydb.class_val_to_struct[tclass - 1];
1624
1625        /* Set the user identity. */
1626        switch (specified) {
1627        case AVTAB_TRANSITION:
1628        case AVTAB_CHANGE:
1629                if (cladatum && cladatum->default_user == DEFAULT_TARGET) {
1630                        newcontext.user = tcontext->user;
1631                } else {
1632                        /* notice this gets both DEFAULT_SOURCE and unset */
1633                        /* Use the process user identity. */
1634                        newcontext.user = scontext->user;
1635                }
1636                break;
1637        case AVTAB_MEMBER:
1638                /* Use the related object owner. */
1639                newcontext.user = tcontext->user;
1640                break;
1641        }
1642
1643        /* Set the role to default values. */
1644        if (cladatum && cladatum->default_role == DEFAULT_SOURCE) {
1645                newcontext.role = scontext->role;
1646        } else if (cladatum && cladatum->default_role == DEFAULT_TARGET) {
1647                newcontext.role = tcontext->role;
1648        } else {
1649                if ((tclass == policydb.process_class) || (sock == true))
1650                        newcontext.role = scontext->role;
1651                else
1652                        newcontext.role = OBJECT_R_VAL;
1653        }
1654
1655        /* Set the type to default values. */
1656        if (cladatum && cladatum->default_type == DEFAULT_SOURCE) {
1657                newcontext.type = scontext->type;
1658        } else if (cladatum && cladatum->default_type == DEFAULT_TARGET) {
1659                newcontext.type = tcontext->type;
1660        } else {
1661                if ((tclass == policydb.process_class) || (sock == true)) {
1662                        /* Use the type of process. */
1663                        newcontext.type = scontext->type;
1664                } else {
1665                        /* Use the type of the related object. */
1666                        newcontext.type = tcontext->type;
1667                }
1668        }
1669
1670        /* Look for a type transition/member/change rule. */
1671        avkey.source_type = scontext->type;
1672        avkey.target_type = tcontext->type;
1673        avkey.target_class = tclass;
1674        avkey.specified = specified;
1675        avdatum = avtab_search(&policydb.te_avtab, &avkey);
1676
1677        /* If no permanent rule, also check for enabled conditional rules */
1678        if (!avdatum) {
1679                node = avtab_search_node(&policydb.te_cond_avtab, &avkey);
1680                for (; node; node = avtab_search_node_next(node, specified)) {
1681                        if (node->key.specified & AVTAB_ENABLED) {
1682                                avdatum = &node->datum;
1683                                break;
1684                        }
1685                }
1686        }
1687
1688        if (avdatum) {
1689                /* Use the type from the type transition/member/change rule. */
1690                newcontext.type = avdatum->u.data;
1691        }
1692
1693        /* if we have a objname this is a file trans check so check those rules */
1694        if (objname)
1695                filename_compute_type(&policydb, &newcontext, scontext->type,
1696                                      tcontext->type, tclass, objname);
1697
1698        /* Check for class-specific changes. */
1699        if (specified & AVTAB_TRANSITION) {
1700                /* Look for a role transition rule. */
1701                for (roletr = policydb.role_tr; roletr; roletr = roletr->next) {
1702                        if ((roletr->role == scontext->role) &&
1703                            (roletr->type == tcontext->type) &&
1704                            (roletr->tclass == tclass)) {
1705                                /* Use the role transition rule. */
1706                                newcontext.role = roletr->new_role;
1707                                break;
1708                        }
1709                }
1710        }
1711
1712        /* Set the MLS attributes.
1713           This is done last because it may allocate memory. */
1714        rc = mls_compute_sid(scontext, tcontext, tclass, specified,
1715                             &newcontext, sock);
1716        if (rc)
1717                goto out_unlock;
1718
1719        /* Check the validity of the context. */
1720        if (!policydb_context_isvalid(&policydb, &newcontext)) {
1721                rc = compute_sid_handle_invalid_context(scontext,
1722                                                        tcontext,
1723                                                        tclass,
1724                                                        &newcontext);
1725                if (rc)
1726                        goto out_unlock;
1727        }
1728        /* Obtain the sid for the context. */
1729        rc = sidtab_context_to_sid(sidtab, &newcontext, out_sid);
1730out_unlock:
1731        read_unlock(&policy_rwlock);
1732        context_destroy(&newcontext);
1733out:
1734        return rc;
1735}
1736
1737/**
1738 * security_transition_sid - Compute the SID for a new subject/object.
1739 * @ssid: source security identifier
1740 * @tsid: target security identifier
1741 * @tclass: target security class
1742 * @out_sid: security identifier for new subject/object
1743 *
1744 * Compute a SID to use for labeling a new subject or object in the
1745 * class @tclass based on a SID pair (@ssid, @tsid).
1746 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1747 * if insufficient memory is available, or %0 if the new SID was
1748 * computed successfully.
1749 */
1750int security_transition_sid(u32 ssid, u32 tsid, u16 tclass,
1751                            const struct qstr *qstr, u32 *out_sid)
1752{
1753        return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION,
1754                                    qstr ? qstr->name : NULL, out_sid, true);
1755}
1756
1757int security_transition_sid_user(u32 ssid, u32 tsid, u16 tclass,
1758                                 const char *objname, u32 *out_sid)
1759{
1760        return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION,
1761                                    objname, out_sid, false);
1762}
1763
1764/**
1765 * security_member_sid - Compute the SID for member selection.
1766 * @ssid: source security identifier
1767 * @tsid: target security identifier
1768 * @tclass: target security class
1769 * @out_sid: security identifier for selected member
1770 *
1771 * Compute a SID to use when selecting a member of a polyinstantiated
1772 * object of class @tclass based on a SID pair (@ssid, @tsid).
1773 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1774 * if insufficient memory is available, or %0 if the SID was
1775 * computed successfully.
1776 */
1777int security_member_sid(u32 ssid,
1778                        u32 tsid,
1779                        u16 tclass,
1780                        u32 *out_sid)
1781{
1782        return security_compute_sid(ssid, tsid, tclass, AVTAB_MEMBER, NULL,
1783                                    out_sid, false);
1784}
1785
1786/**
1787 * security_change_sid - Compute the SID for object relabeling.
1788 * @ssid: source security identifier
1789 * @tsid: target security identifier
1790 * @tclass: target security class
1791 * @out_sid: security identifier for selected member
1792 *
1793 * Compute a SID to use for relabeling an object of class @tclass
1794 * based on a SID pair (@ssid, @tsid).
1795 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1796 * if insufficient memory is available, or %0 if the SID was
1797 * computed successfully.
1798 */
1799int security_change_sid(u32 ssid,
1800                        u32 tsid,
1801                        u16 tclass,
1802                        u32 *out_sid)
1803{
1804        return security_compute_sid(ssid, tsid, tclass, AVTAB_CHANGE, NULL,
1805                                    out_sid, false);
1806}
1807
1808static inline int convert_context_handle_invalid_context(struct context *context)
1809{
1810        char *s;
1811        u32 len;
1812
1813        if (selinux_enforcing)
1814                return -EINVAL;
1815
1816        if (!context_struct_to_string(context, &s, &len)) {
1817                printk(KERN_WARNING "SELinux:  Context %s would be invalid if enforcing\n", s);
1818                kfree(s);
1819        }
1820        return 0;
1821}
1822
1823struct convert_context_args {
1824        struct policydb *oldp;
1825        struct policydb *newp;
1826};
1827
1828/*
1829 * Convert the values in the security context
1830 * structure `oldc' from the values specified
1831 * in the policy `p->oldp' to the values specified
1832 * in the policy `p->newp', storing the new context
1833 * in `newc'.  Verify that the context is valid
1834 * under the new policy.
1835 */
1836static int convert_context(struct context *oldc, struct context *newc, void *p)
1837{
1838        struct convert_context_args *args;
1839        struct ocontext *oc;
1840        struct role_datum *role;
1841        struct type_datum *typdatum;
1842        struct user_datum *usrdatum;
1843        char *s;
1844        u32 len;
1845        int rc;
1846
1847        args = p;
1848
1849        if (oldc->str) {
1850                s = kstrdup(oldc->str, GFP_KERNEL);
1851                if (!s)
1852                        return -ENOMEM;
1853
1854                rc = string_to_context_struct(args->newp, NULL, s,
1855                                              oldc->len, newc, SECSID_NULL);
1856                if (rc == -EINVAL) {
1857                        /* Retain string representation for later mapping. */
1858                        context_init(newc);
1859                        newc->str = s;
1860                        newc->len = oldc->len;
1861                        return 0;
1862                }
1863                kfree(s);
1864                if (rc) {
1865                        /* Other error condition, e.g. ENOMEM. */
1866                        printk(KERN_ERR "SELinux:   Unable to map context %s, rc = %d.\n",
1867                               oldc->str, -rc);
1868                        return rc;
1869                }
1870                pr_info("SELinux:  Context %s became valid (mapped).\n",
1871                        oldc->str);
1872                return 0;
1873        }
1874
1875        context_init(newc);
1876
1877        /* Convert the user. */
1878        rc = -EINVAL;
1879        usrdatum = hashtab_search(args->newp->p_users.table,
1880                                  sym_name(args->oldp,
1881                                           SYM_USERS, oldc->user - 1));
1882        if (!usrdatum)
1883                goto bad;
1884        newc->user = usrdatum->value;
1885
1886        /* Convert the role. */
1887        rc = -EINVAL;
1888        role = hashtab_search(args->newp->p_roles.table,
1889                              sym_name(args->oldp, SYM_ROLES, oldc->role - 1));
1890        if (!role)
1891                goto bad;
1892        newc->role = role->value;
1893
1894        /* Convert the type. */
1895        rc = -EINVAL;
1896        typdatum = hashtab_search(args->newp->p_types.table,
1897                                  sym_name(args->oldp,
1898                                           SYM_TYPES, oldc->type - 1));
1899        if (!typdatum)
1900                goto bad;
1901        newc->type = typdatum->value;
1902
1903        /* Convert the MLS fields if dealing with MLS policies */
1904        if (args->oldp->mls_enabled && args->newp->mls_enabled) {
1905                rc = mls_convert_context(args->oldp, args->newp, oldc, newc);
1906                if (rc)
1907                        goto bad;
1908        } else if (!args->oldp->mls_enabled && args->newp->mls_enabled) {
1909                /*
1910                 * Switching between non-MLS and MLS policy:
1911                 * ensure that the MLS fields of the context for all
1912                 * existing entries in the sidtab are filled in with a
1913                 * suitable default value, likely taken from one of the
1914                 * initial SIDs.
1915                 */
1916                oc = args->newp->ocontexts[OCON_ISID];
1917                while (oc && oc->sid[0] != SECINITSID_UNLABELED)
1918                        oc = oc->next;
1919                rc = -EINVAL;
1920                if (!oc) {
1921                        printk(KERN_ERR "SELinux:  unable to look up"
1922                                " the initial SIDs list\n");
1923                        goto bad;
1924                }
1925                rc = mls_range_set(newc, &oc->context[0].range);
1926                if (rc)
1927                        goto bad;
1928        }
1929
1930        /* Check the validity of the new context. */
1931        if (!policydb_context_isvalid(args->newp, newc)) {
1932                rc = convert_context_handle_invalid_context(oldc);
1933                if (rc)
1934                        goto bad;
1935        }
1936
1937        return 0;
1938bad:
1939        /* Map old representation to string and save it. */
1940        rc = context_struct_to_string(oldc, &s, &len);
1941        if (rc)
1942                return rc;
1943        context_destroy(newc);
1944        newc->str = s;
1945        newc->len = len;
1946        printk(KERN_INFO "SELinux:  Context %s became invalid (unmapped).\n",
1947               newc->str);
1948        return 0;
1949}
1950
1951static void security_load_policycaps(void)
1952{
1953        selinux_policycap_netpeer = ebitmap_get_bit(&policydb.policycaps,
1954                                                  POLICYDB_CAPABILITY_NETPEER);
1955        selinux_policycap_openperm = ebitmap_get_bit(&policydb.policycaps,
1956                                                  POLICYDB_CAPABILITY_OPENPERM);
1957        selinux_policycap_cgroupseclabel =
1958                ebitmap_get_bit(&policydb.policycaps,
1959                                POLICYDB_CAPABILITY_CGROUPSECLABEL);
1960        selinux_policycap_nnp_nosuid_transition =
1961                ebitmap_get_bit(&policydb.policycaps,
1962                                POLICYDB_CAPABILITY_NNP_NOSUID_TRANSITION);
1963}
1964
1965static int security_preserve_bools(struct policydb *p);
1966
1967/**
1968 * security_load_policy - Load a security policy configuration.
1969 * @data: binary policy data
1970 * @len: length of data in bytes
1971 *
1972 * Load a new set of security policy configuration data,
1973 * validate it and convert the SID table as necessary.
1974 * This function will flush the access vector cache after
1975 * loading the new policy.
1976 */
1977int security_load_policy(void *data, size_t len)
1978{
1979        struct sidtab *oldsidtab, *newsidtab;
1980        struct policydb *oldpolicydb, *newpolicydb;
1981        struct selinux_mapping *oldmap, *map = NULL;
1982        struct sidtab_convert_params convert_params;
1983        struct convert_context_args args;
1984        u32 seqno;
1985        u16 map_size;
1986        int rc = 0;
1987        struct policy_file file = { data, len }, *fp = &file;
1988
1989        oldpolicydb = kzalloc(2 * sizeof(*oldpolicydb), GFP_KERNEL);
1990        if (!oldpolicydb) {
1991                rc = -ENOMEM;
1992                goto out;
1993        }
1994        newpolicydb = oldpolicydb + 1;
1995
1996        newsidtab = kmalloc(sizeof(*newsidtab), GFP_KERNEL);
1997        if (!newsidtab) {
1998                rc = -ENOMEM;
1999                goto out;
2000        }
2001
2002        if (!ss_initialized) {
2003                avtab_cache_init();
2004                rc = policydb_read(&policydb, fp);
2005                if (rc) {
2006                        avtab_cache_destroy();
2007                        kfree(newsidtab);
2008                        goto out;
2009                }
2010
2011                policydb.len = len;
2012                rc = selinux_set_mapping(&policydb, secclass_map,
2013                                         &current_mapping,
2014                                         &current_mapping_size);
2015                if (rc) {
2016                        kfree(newsidtab);
2017                        policydb_destroy(&policydb);
2018                        avtab_cache_destroy();
2019                        goto out;
2020                }
2021
2022                rc = policydb_load_isids(&policydb, newsidtab);
2023                if (rc) {
2024                        kfree(newsidtab);
2025                        policydb_destroy(&policydb);
2026                        avtab_cache_destroy();
2027                        goto out;
2028                }
2029
2030                security_load_policycaps();
2031                ss_initialized = 1;
2032                seqno = ++latest_granting;
2033                sidtab = newsidtab;
2034                selinux_complete_init();
2035                avc_ss_reset(seqno);
2036                selnl_notify_policyload(seqno);
2037                selinux_status_update_policyload(seqno);
2038                selinux_netlbl_cache_invalidate();
2039                selinux_xfrm_notify_policyload();
2040                goto out;
2041        }
2042
2043        rc = policydb_read(newpolicydb, fp);
2044        if (rc) {
2045                kfree(newsidtab);
2046                goto out;
2047        }
2048
2049        newpolicydb->len = len;
2050        /* If switching between different policy types, log MLS status */
2051        if (policydb.mls_enabled && !newpolicydb->mls_enabled)
2052                printk(KERN_INFO "SELinux: Disabling MLS support...\n");
2053        else if (!policydb.mls_enabled && newpolicydb->mls_enabled)
2054                printk(KERN_INFO "SELinux: Enabling MLS support...\n");
2055
2056        rc = policydb_load_isids(newpolicydb, newsidtab);
2057        if (rc) {
2058                printk(KERN_ERR "SELinux:  unable to load the initial SIDs\n");
2059                policydb_destroy(newpolicydb);
2060                kfree(newsidtab);
2061                goto out;
2062        }
2063
2064        rc = selinux_set_mapping(newpolicydb, secclass_map, &map, &map_size);
2065        if (rc)
2066                goto err;
2067
2068        rc = security_preserve_bools(newpolicydb);
2069        if (rc) {
2070                printk(KERN_ERR "SELinux:  unable to preserve booleans\n");
2071                goto err;
2072        }
2073
2074        oldsidtab = sidtab;
2075
2076        /*
2077         * Convert the internal representations of contexts
2078         * in the new SID table.
2079         */
2080        args.oldp = &policydb;
2081        args.newp = newpolicydb;
2082
2083        convert_params.func = convert_context;
2084        convert_params.args = &args;
2085        convert_params.target = newsidtab;
2086
2087        rc = sidtab_convert(oldsidtab, &convert_params);
2088        if (rc) {
2089                printk(KERN_ERR "SELinux:  unable to convert the internal"
2090                        " representation of contexts in the new SID"
2091                        " table\n");
2092                goto err;
2093        }
2094
2095        /* Save the old policydb and SID table to free later. */
2096        memcpy(oldpolicydb, &policydb, sizeof(policydb));
2097
2098        /* Install the new policydb and SID table. */
2099        write_lock_irq(&policy_rwlock);
2100        memcpy(&policydb, newpolicydb, sizeof(policydb));
2101        sidtab = newsidtab;
2102        security_load_policycaps();
2103        oldmap = current_mapping;
2104        current_mapping = map;
2105        current_mapping_size = map_size;
2106        seqno = ++latest_granting;
2107        write_unlock_irq(&policy_rwlock);
2108
2109        /* Free the old policydb and SID table. */
2110        policydb_destroy(oldpolicydb);
2111        sidtab_destroy(oldsidtab);
2112        kfree(oldsidtab);
2113        kfree(oldmap);
2114
2115        avc_ss_reset(seqno);
2116        selnl_notify_policyload(seqno);
2117        selinux_status_update_policyload(seqno);
2118        selinux_netlbl_cache_invalidate();
2119        selinux_xfrm_notify_policyload();
2120
2121        rc = 0;
2122        goto out;
2123
2124err:
2125        kfree(map);
2126        sidtab_destroy(newsidtab);
2127        kfree(newsidtab);
2128        policydb_destroy(newpolicydb);
2129
2130out:
2131        kfree(oldpolicydb);
2132        return rc;
2133}
2134
2135size_t security_policydb_len(void)
2136{
2137        size_t len;
2138
2139        read_lock(&policy_rwlock);
2140        len = policydb.len;
2141        read_unlock(&policy_rwlock);
2142
2143        return len;
2144}
2145
2146/**
2147 * security_port_sid - Obtain the SID for a port.
2148 * @protocol: protocol number
2149 * @port: port number
2150 * @out_sid: security identifier
2151 */
2152int security_port_sid(u8 protocol, u16 port, u32 *out_sid)
2153{
2154        struct ocontext *c;
2155        int rc = 0;
2156
2157        read_lock(&policy_rwlock);
2158
2159        c = policydb.ocontexts[OCON_PORT];
2160        while (c) {
2161                if (c->u.port.protocol == protocol &&
2162                    c->u.port.low_port <= port &&
2163                    c->u.port.high_port >= port)
2164                        break;
2165                c = c->next;
2166        }
2167
2168        if (c) {
2169                if (!c->sid[0]) {
2170                        rc = sidtab_context_to_sid(sidtab,
2171                                                   &c->context[0],
2172                                                   &c->sid[0]);
2173                        if (rc)
2174                                goto out;
2175                }
2176                *out_sid = c->sid[0];
2177        } else {
2178                *out_sid = SECINITSID_PORT;
2179        }
2180
2181out:
2182        read_unlock(&policy_rwlock);
2183        return rc;
2184}
2185
2186/**
2187 * security_pkey_sid - Obtain the SID for a pkey.
2188 * @subnet_prefix: Subnet Prefix
2189 * @pkey_num: pkey number
2190 * @out_sid: security identifier
2191 */
2192int security_ib_pkey_sid(u64 subnet_prefix, u16 pkey_num, u32 *out_sid)
2193{
2194        struct ocontext *c;
2195        int rc = 0;
2196
2197        read_lock(&policy_rwlock);
2198
2199        c = policydb.ocontexts[OCON_IBPKEY];
2200        while (c) {
2201                if (c->u.ibpkey.low_pkey <= pkey_num &&
2202                    c->u.ibpkey.high_pkey >= pkey_num &&
2203                    c->u.ibpkey.subnet_prefix == subnet_prefix)
2204                        break;
2205
2206                c = c->next;
2207        }
2208
2209        if (c) {
2210                if (!c->sid[0]) {
2211                        rc = sidtab_context_to_sid(sidtab,
2212                                                   &c->context[0],
2213                                                   &c->sid[0]);
2214                        if (rc)
2215                                goto out;
2216                }
2217                *out_sid = c->sid[0];
2218        } else
2219                *out_sid = SECINITSID_UNLABELED;
2220
2221out:
2222        read_unlock(&policy_rwlock);
2223        return rc;
2224}
2225
2226/**
2227 * security_ib_endport_sid - Obtain the SID for a subnet management interface.
2228 * @dev_name: device name
2229 * @port: port number
2230 * @out_sid: security identifier
2231 */
2232int security_ib_endport_sid(const char *dev_name, u8 port_num, u32 *out_sid)
2233{
2234        struct ocontext *c;
2235        int rc = 0;
2236
2237        read_lock(&policy_rwlock);
2238
2239        c = policydb.ocontexts[OCON_IBENDPORT];
2240        while (c) {
2241                if (c->u.ibendport.port == port_num &&
2242                    !strncmp(c->u.ibendport.dev_name,
2243                             dev_name,
2244                             IB_DEVICE_NAME_MAX))
2245                        break;
2246
2247                c = c->next;
2248        }
2249
2250        if (c) {
2251                if (!c->sid[0]) {
2252                        rc = sidtab_context_to_sid(sidtab,
2253                                                   &c->context[0],
2254                                                   &c->sid[0]);
2255                        if (rc)
2256                                goto out;
2257                }
2258                *out_sid = c->sid[0];
2259        } else
2260                *out_sid = SECINITSID_UNLABELED;
2261
2262out:
2263        read_unlock(&policy_rwlock);
2264        return rc;
2265}
2266
2267/**
2268 * security_netif_sid - Obtain the SID for a network interface.
2269 * @name: interface name
2270 * @if_sid: interface SID
2271 */
2272int security_netif_sid(char *name, u32 *if_sid)
2273{
2274        int rc = 0;
2275        struct ocontext *c;
2276
2277        read_lock(&policy_rwlock);
2278
2279        c = policydb.ocontexts[OCON_NETIF];
2280        while (c) {
2281                if (strcmp(name, c->u.name) == 0)
2282                        break;
2283                c = c->next;
2284        }
2285
2286        if (c) {
2287                if (!c->sid[0] || !c->sid[1]) {
2288                        rc = sidtab_context_to_sid(sidtab,
2289                                                  &c->context[0],
2290                                                  &c->sid[0]);
2291                        if (rc)
2292                                goto out;
2293                        rc = sidtab_context_to_sid(sidtab,
2294                                                   &c->context[1],
2295                                                   &c->sid[1]);
2296                        if (rc)
2297                                goto out;
2298                }
2299                *if_sid = c->sid[0];
2300        } else
2301                *if_sid = SECINITSID_NETIF;
2302
2303out:
2304        read_unlock(&policy_rwlock);
2305        return rc;
2306}
2307
2308static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask)
2309{
2310        int i, fail = 0;
2311
2312        for (i = 0; i < 4; i++)
2313                if (addr[i] != (input[i] & mask[i])) {
2314                        fail = 1;
2315                        break;
2316                }
2317
2318        return !fail;
2319}
2320
2321/**
2322 * security_node_sid - Obtain the SID for a node (host).
2323 * @domain: communication domain aka address family
2324 * @addrp: address
2325 * @addrlen: address length in bytes
2326 * @out_sid: security identifier
2327 */
2328int security_node_sid(u16 domain,
2329                      void *addrp,
2330                      u32 addrlen,
2331                      u32 *out_sid)
2332{
2333        int rc;
2334        struct ocontext *c;
2335
2336        read_lock(&policy_rwlock);
2337
2338        switch (domain) {
2339        case AF_INET: {
2340                u32 addr;
2341
2342                rc = -EINVAL;
2343                if (addrlen != sizeof(u32))
2344                        goto out;
2345
2346                addr = *((u32 *)addrp);
2347
2348                c = policydb.ocontexts[OCON_NODE];
2349                while (c) {
2350                        if (c->u.node.addr == (addr & c->u.node.mask))
2351                                break;
2352                        c = c->next;
2353                }
2354                break;
2355        }
2356
2357        case AF_INET6:
2358                rc = -EINVAL;
2359                if (addrlen != sizeof(u64) * 2)
2360                        goto out;
2361                c = policydb.ocontexts[OCON_NODE6];
2362                while (c) {
2363                        if (match_ipv6_addrmask(addrp, c->u.node6.addr,
2364                                                c->u.node6.mask))
2365                                break;
2366                        c = c->next;
2367                }
2368                break;
2369
2370        default:
2371                rc = 0;
2372                *out_sid = SECINITSID_NODE;
2373                goto out;
2374        }
2375
2376        if (c) {
2377                if (!c->sid[0]) {
2378                        rc = sidtab_context_to_sid(sidtab,
2379                                                   &c->context[0],
2380                                                   &c->sid[0]);
2381                        if (rc)
2382                                goto out;
2383                }
2384                *out_sid = c->sid[0];
2385        } else {
2386                *out_sid = SECINITSID_NODE;
2387        }
2388
2389        rc = 0;
2390out:
2391        read_unlock(&policy_rwlock);
2392        return rc;
2393}
2394
2395#define SIDS_NEL 25
2396
2397/**
2398 * security_get_user_sids - Obtain reachable SIDs for a user.
2399 * @fromsid: starting SID
2400 * @username: username
2401 * @sids: array of reachable SIDs for user
2402 * @nel: number of elements in @sids
2403 *
2404 * Generate the set of SIDs for legal security contexts
2405 * for a given user that can be reached by @fromsid.
2406 * Set *@sids to point to a dynamically allocated
2407 * array containing the set of SIDs.  Set *@nel to the
2408 * number of elements in the array.
2409 */
2410
2411int security_get_user_sids(u32 fromsid,
2412                           char *username,
2413                           u32 **sids,
2414                           u32 *nel)
2415{
2416        struct context *fromcon, usercon;
2417        u32 *mysids = NULL, *mysids2, sid;
2418        u32 mynel = 0, maxnel = SIDS_NEL;
2419        struct user_datum *user;
2420        struct role_datum *role;
2421        struct ebitmap_node *rnode, *tnode;
2422        int rc = 0, i, j;
2423
2424        *sids = NULL;
2425        *nel = 0;
2426
2427        if (!ss_initialized)
2428                goto out;
2429
2430        read_lock(&policy_rwlock);
2431
2432        context_init(&usercon);
2433
2434        rc = -EINVAL;
2435        fromcon = sidtab_search(sidtab, fromsid);
2436        if (!fromcon)
2437                goto out_unlock;
2438
2439        rc = -EINVAL;
2440        user = hashtab_search(policydb.p_users.table, username);
2441        if (!user)
2442                goto out_unlock;
2443
2444        usercon.user = user->value;
2445
2446        rc = -ENOMEM;
2447        mysids = kcalloc(maxnel, sizeof(*mysids), GFP_ATOMIC);
2448        if (!mysids)
2449                goto out_unlock;
2450
2451        ebitmap_for_each_positive_bit(&user->roles, rnode, i) {
2452                role = policydb.role_val_to_struct[i];
2453                usercon.role = i + 1;
2454                ebitmap_for_each_positive_bit(&role->types, tnode, j) {
2455                        usercon.type = j + 1;
2456
2457                        if (mls_setup_user_range(fromcon, user, &usercon))
2458                                continue;
2459
2460                        rc = sidtab_context_to_sid(sidtab, &usercon, &sid);
2461                        if (rc)
2462                                goto out_unlock;
2463                        if (mynel < maxnel) {
2464                                mysids[mynel++] = sid;
2465                        } else {
2466                                rc = -ENOMEM;
2467                                maxnel += SIDS_NEL;
2468                                mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
2469                                if (!mysids2)
2470                                        goto out_unlock;
2471                                memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
2472                                kfree(mysids);
2473                                mysids = mysids2;
2474                                mysids[mynel++] = sid;
2475                        }
2476                }
2477        }
2478        rc = 0;
2479out_unlock:
2480        read_unlock(&policy_rwlock);
2481        if (rc || !mynel) {
2482                kfree(mysids);
2483                goto out;
2484        }
2485
2486        rc = -ENOMEM;
2487        mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);
2488        if (!mysids2) {
2489                kfree(mysids);
2490                goto out;
2491        }
2492        for (i = 0, j = 0; i < mynel; i++) {
2493                struct av_decision dummy_avd;
2494                rc = avc_has_perm_noaudit(fromsid, mysids[i],
2495                                          SECCLASS_PROCESS, /* kernel value */
2496                                          PROCESS__TRANSITION, AVC_STRICT,
2497                                          &dummy_avd);
2498                if (!rc)
2499                        mysids2[j++] = mysids[i];
2500                cond_resched();
2501        }
2502        rc = 0;
2503        kfree(mysids);
2504        *sids = mysids2;
2505        *nel = j;
2506out:
2507        return rc;
2508}
2509
2510/**
2511 * security_genfs_sid - Obtain a SID for a file in a filesystem
2512 * @fstype: filesystem type
2513 * @path: path from root of mount
2514 * @sclass: file security class
2515 * @sid: SID for path
2516 *
2517 * Obtain a SID to use for a file in a filesystem that
2518 * cannot support xattr or use a fixed labeling behavior like
2519 * transition SIDs or task SIDs.
2520 */
2521int security_genfs_sid(const char *fstype,
2522                       char *path,
2523                       u16 orig_sclass,
2524                       u32 *sid)
2525{
2526        int len;
2527        u16 sclass;
2528        struct genfs *genfs;
2529        struct ocontext *c;
2530        int rc, cmp = 0;
2531
2532        while (path[0] == '/' && path[1] == '/')
2533                path++;
2534
2535        read_lock(&policy_rwlock);
2536
2537        sclass = unmap_class(orig_sclass);
2538        *sid = SECINITSID_UNLABELED;
2539
2540        for (genfs = policydb.genfs; genfs; genfs = genfs->next) {
2541                cmp = strcmp(fstype, genfs->fstype);
2542                if (cmp <= 0)
2543                        break;
2544        }
2545
2546        rc = -ENOENT;
2547        if (!genfs || cmp)
2548                goto out;
2549
2550        for (c = genfs->head; c; c = c->next) {
2551                len = strlen(c->u.name);
2552                if ((!c->v.sclass || sclass == c->v.sclass) &&
2553                    (strncmp(c->u.name, path, len) == 0))
2554                        break;
2555        }
2556
2557        rc = -ENOENT;
2558        if (!c)
2559                goto out;
2560
2561        if (!c->sid[0]) {
2562                rc = sidtab_context_to_sid(sidtab, &c->context[0], &c->sid[0]);
2563                if (rc)
2564                        goto out;
2565        }
2566
2567        *sid = c->sid[0];
2568        rc = 0;
2569out:
2570        read_unlock(&policy_rwlock);
2571        return rc;
2572}
2573
2574/**
2575 * security_fs_use - Determine how to handle labeling for a filesystem.
2576 * @fstype: filesystem type
2577 * @behavior: labeling behavior
2578 * @sid: SID for filesystem (superblock)
2579 */
2580int security_fs_use(
2581        const char *fstype,
2582        unsigned int *behavior,
2583        u32 *sid)
2584{
2585        int rc = 0;
2586        struct ocontext *c;
2587
2588        read_lock(&policy_rwlock);
2589
2590        c = policydb.ocontexts[OCON_FSUSE];
2591        while (c) {
2592                if (strcmp(fstype, c->u.name) == 0)
2593                        break;
2594                c = c->next;
2595        }
2596
2597        if (c) {
2598                *behavior = c->v.behavior;
2599                if (!c->sid[0]) {
2600                        rc = sidtab_context_to_sid(sidtab, &c->context[0],
2601                                                   &c->sid[0]);
2602                        if (rc)
2603                                goto out;
2604                }
2605                *sid = c->sid[0];
2606        } else {
2607                rc = security_genfs_sid(fstype, "/", SECCLASS_DIR, sid);
2608                if (rc) {
2609                        *behavior = SECURITY_FS_USE_NONE;
2610                        rc = 0;
2611                } else {
2612                        *behavior = SECURITY_FS_USE_GENFS;
2613                }
2614        }
2615
2616out:
2617        read_unlock(&policy_rwlock);
2618        return rc;
2619}
2620
2621int security_get_bools(int *len, char ***names, int **values)
2622{
2623        int i, rc;
2624
2625        read_lock(&policy_rwlock);
2626        *names = NULL;
2627        *values = NULL;
2628
2629        rc = 0;
2630        *len = policydb.p_bools.nprim;
2631        if (!*len)
2632                goto out;
2633
2634        rc = -ENOMEM;
2635        *names = kcalloc(*len, sizeof(char *), GFP_ATOMIC);
2636        if (!*names)
2637                goto err;
2638
2639        rc = -ENOMEM;
2640        *values = kcalloc(*len, sizeof(int), GFP_ATOMIC);
2641        if (!*values)
2642                goto err;
2643
2644        for (i = 0; i < *len; i++) {
2645                size_t name_len;
2646
2647                (*values)[i] = policydb.bool_val_to_struct[i]->state;
2648                name_len = strlen(sym_name(&policydb, SYM_BOOLS, i)) + 1;
2649
2650                rc = -ENOMEM;
2651                (*names)[i] = kmalloc(sizeof(char) * name_len, GFP_ATOMIC);
2652                if (!(*names)[i])
2653                        goto err;
2654
2655                strncpy((*names)[i], sym_name(&policydb, SYM_BOOLS, i), name_len);
2656                (*names)[i][name_len - 1] = 0;
2657        }
2658        rc = 0;
2659out:
2660        read_unlock(&policy_rwlock);
2661        return rc;
2662err:
2663        if (*names) {
2664                for (i = 0; i < *len; i++)
2665                        kfree((*names)[i]);
2666        }
2667        kfree(*values);
2668        goto out;
2669}
2670
2671
2672int security_set_bools(int len, int *values)
2673{
2674        int i, rc;
2675        int lenp, seqno = 0;
2676        struct cond_node *cur;
2677
2678        write_lock_irq(&policy_rwlock);
2679
2680        rc = -EFAULT;
2681        lenp = policydb.p_bools.nprim;
2682        if (len != lenp)
2683                goto out;
2684
2685        for (i = 0; i < len; i++) {
2686                if (!!values[i] != policydb.bool_val_to_struct[i]->state) {
2687                        audit_log(current->audit_context, GFP_ATOMIC,
2688                                AUDIT_MAC_CONFIG_CHANGE,
2689                                "bool=%s val=%d old_val=%d auid=%u ses=%u",
2690                                sym_name(&policydb, SYM_BOOLS, i),
2691                                !!values[i],
2692                                policydb.bool_val_to_struct[i]->state,
2693                                from_kuid(&init_user_ns, audit_get_loginuid(current)),
2694                                audit_get_sessionid(current));
2695                }
2696                if (values[i])
2697                        policydb.bool_val_to_struct[i]->state = 1;
2698                else
2699                        policydb.bool_val_to_struct[i]->state = 0;
2700        }
2701
2702        for (cur = policydb.cond_list; cur; cur = cur->next) {
2703                rc = evaluate_cond_node(&policydb, cur);
2704                if (rc)
2705                        goto out;
2706        }
2707
2708        seqno = ++latest_granting;
2709        rc = 0;
2710out:
2711        write_unlock_irq(&policy_rwlock);
2712        if (!rc) {
2713                avc_ss_reset(seqno);
2714                selnl_notify_policyload(seqno);
2715                selinux_status_update_policyload(seqno);
2716                selinux_xfrm_notify_policyload();
2717        }
2718        return rc;
2719}
2720
2721int security_get_bool_value(int bool)
2722{
2723        int rc;
2724        int len;
2725
2726        read_lock(&policy_rwlock);
2727
2728        rc = -EFAULT;
2729        len = policydb.p_bools.nprim;
2730        if (bool >= len)
2731                goto out;
2732
2733        rc = policydb.bool_val_to_struct[bool]->state;
2734out:
2735        read_unlock(&policy_rwlock);
2736        return rc;
2737}
2738
2739static int security_preserve_bools(struct policydb *p)
2740{
2741        int rc, nbools = 0, *bvalues = NULL, i;
2742        char **bnames = NULL;
2743        struct cond_bool_datum *booldatum;
2744        struct cond_node *cur;
2745
2746        rc = security_get_bools(&nbools, &bnames, &bvalues);
2747        if (rc)
2748                goto out;
2749        for (i = 0; i < nbools; i++) {
2750                booldatum = hashtab_search(p->p_bools.table, bnames[i]);
2751                if (booldatum)
2752                        booldatum->state = bvalues[i];
2753        }
2754        for (cur = p->cond_list; cur; cur = cur->next) {
2755                rc = evaluate_cond_node(p, cur);
2756                if (rc)
2757                        goto out;
2758        }
2759
2760out:
2761        if (bnames) {
2762                for (i = 0; i < nbools; i++)
2763                        kfree(bnames[i]);
2764        }
2765        kfree(bnames);
2766        kfree(bvalues);
2767        return rc;
2768}
2769
2770/*
2771 * security_sid_mls_copy() - computes a new sid based on the given
2772 * sid and the mls portion of mls_sid.
2773 */
2774int security_sid_mls_copy(u32 sid, u32 mls_sid, u32 *new_sid)
2775{
2776        struct context *context1;
2777        struct context *context2;
2778        struct context newcon;
2779        char *s;
2780        u32 len;
2781        int rc;
2782
2783        rc = 0;
2784        if (!ss_initialized || !policydb.mls_enabled) {
2785                *new_sid = sid;
2786                goto out;
2787        }
2788
2789        context_init(&newcon);
2790
2791        read_lock(&policy_rwlock);
2792
2793        rc = -EINVAL;
2794        context1 = sidtab_search(sidtab, sid);
2795        if (!context1) {
2796                printk(KERN_ERR "SELinux: %s:  unrecognized SID %d\n",
2797                        __func__, sid);
2798                goto out_unlock;
2799        }
2800
2801        rc = -EINVAL;
2802        context2 = sidtab_search(sidtab, mls_sid);
2803        if (!context2) {
2804                printk(KERN_ERR "SELinux: %s:  unrecognized SID %d\n",
2805                        __func__, mls_sid);
2806                goto out_unlock;
2807        }
2808
2809        newcon.user = context1->user;
2810        newcon.role = context1->role;
2811        newcon.type = context1->type;
2812        rc = mls_context_cpy(&newcon, context2);
2813        if (rc)
2814                goto out_unlock;
2815
2816        /* Check the validity of the new context. */
2817        if (!policydb_context_isvalid(&policydb, &newcon)) {
2818                rc = convert_context_handle_invalid_context(&newcon);
2819                if (rc) {
2820                        if (!context_struct_to_string(&newcon, &s, &len)) {
2821                                audit_log(current->audit_context,
2822                                          GFP_ATOMIC, AUDIT_SELINUX_ERR,
2823                                          "op=security_sid_mls_copy "
2824                                          "invalid_context=%s", s);
2825                                kfree(s);
2826                        }
2827                        goto out_unlock;
2828                }
2829        }
2830
2831        rc = sidtab_context_to_sid(sidtab, &newcon, new_sid);
2832out_unlock:
2833        read_unlock(&policy_rwlock);
2834        context_destroy(&newcon);
2835out:
2836        return rc;
2837}
2838
2839/**
2840 * security_net_peersid_resolve - Compare and resolve two network peer SIDs
2841 * @nlbl_sid: NetLabel SID
2842 * @nlbl_type: NetLabel labeling protocol type
2843 * @xfrm_sid: XFRM SID
2844 *
2845 * Description:
2846 * Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be
2847 * resolved into a single SID it is returned via @peer_sid and the function
2848 * returns zero.  Otherwise @peer_sid is set to SECSID_NULL and the function
2849 * returns a negative value.  A table summarizing the behavior is below:
2850 *
2851 *                                 | function return |      @sid
2852 *   ------------------------------+-----------------+-----------------
2853 *   no peer labels                |        0        |    SECSID_NULL
2854 *   single peer label             |        0        |    <peer_label>
2855 *   multiple, consistent labels   |        0        |    <peer_label>
2856 *   multiple, inconsistent labels |    -<errno>     |    SECSID_NULL
2857 *
2858 */
2859int security_net_peersid_resolve(u32 nlbl_sid, u32 nlbl_type,
2860                                 u32 xfrm_sid,
2861                                 u32 *peer_sid)
2862{
2863        int rc;
2864        struct context *nlbl_ctx;
2865        struct context *xfrm_ctx;
2866
2867        *peer_sid = SECSID_NULL;
2868
2869        /* handle the common (which also happens to be the set of easy) cases
2870         * right away, these two if statements catch everything involving a
2871         * single or absent peer SID/label */
2872        if (xfrm_sid == SECSID_NULL) {
2873                *peer_sid = nlbl_sid;
2874                return 0;
2875        }
2876        /* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a "fallback" label
2877         * and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label
2878         * is present */
2879        if (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) {
2880                *peer_sid = xfrm_sid;
2881                return 0;
2882        }
2883
2884        /* we don't need to check ss_initialized here since the only way both
2885         * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the
2886         * security server was initialized and ss_initialized was true */
2887        if (!policydb.mls_enabled)
2888                return 0;
2889
2890        read_lock(&policy_rwlock);
2891
2892        rc = -EINVAL;
2893        nlbl_ctx = sidtab_search(sidtab, nlbl_sid);
2894        if (!nlbl_ctx) {
2895                printk(KERN_ERR "SELinux: %s:  unrecognized SID %d\n",
2896                       __func__, nlbl_sid);
2897                goto out;
2898        }
2899        rc = -EINVAL;
2900        xfrm_ctx = sidtab_search(sidtab, xfrm_sid);
2901        if (!xfrm_ctx) {
2902                printk(KERN_ERR "SELinux: %s:  unrecognized SID %d\n",
2903                       __func__, xfrm_sid);
2904                goto out;
2905        }
2906        rc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES);
2907        if (rc)
2908                goto out;
2909
2910        /* at present NetLabel SIDs/labels really only carry MLS
2911         * information so if the MLS portion of the NetLabel SID
2912         * matches the MLS portion of the labeled XFRM SID/label
2913         * then pass along the XFRM SID as it is the most
2914         * expressive */
2915        *peer_sid = xfrm_sid;
2916out:
2917        read_unlock(&policy_rwlock);
2918        return rc;
2919}
2920
2921static int get_classes_callback(void *k, void *d, void *args)
2922{
2923        struct class_datum *datum = d;
2924        char *name = k, **classes = args;
2925        int value = datum->value - 1;
2926
2927        classes[value] = kstrdup(name, GFP_ATOMIC);
2928        if (!classes[value])
2929                return -ENOMEM;
2930
2931        return 0;
2932}
2933
2934int security_get_classes(char ***classes, int *nclasses)
2935{
2936        int rc;
2937
2938        read_lock(&policy_rwlock);
2939
2940        rc = -ENOMEM;
2941        *nclasses = policydb.p_classes.nprim;
2942        *classes = kcalloc(*nclasses, sizeof(**classes), GFP_ATOMIC);
2943        if (!*classes)
2944                goto out;
2945
2946        rc = hashtab_map(policydb.p_classes.table, get_classes_callback,
2947                        *classes);
2948        if (rc) {
2949                int i;
2950                for (i = 0; i < *nclasses; i++)
2951                        kfree((*classes)[i]);
2952                kfree(*classes);
2953        }
2954
2955out:
2956        read_unlock(&policy_rwlock);
2957        return rc;
2958}
2959
2960static int get_permissions_callback(void *k, void *d, void *args)
2961{
2962        struct perm_datum *datum = d;
2963        char *name = k, **perms = args;
2964        int value = datum->value - 1;
2965
2966        perms[value] = kstrdup(name, GFP_ATOMIC);
2967        if (!perms[value])
2968                return -ENOMEM;
2969
2970        return 0;
2971}
2972
2973int security_get_permissions(char *class, char ***perms, int *nperms)
2974{
2975        int rc, i;
2976        struct class_datum *match;
2977
2978        read_lock(&policy_rwlock);
2979
2980        rc = -EINVAL;
2981        match = hashtab_search(policydb.p_classes.table, class);
2982        if (!match) {
2983                printk(KERN_ERR "SELinux: %s:  unrecognized class %s\n",
2984                        __func__, class);
2985                goto out;
2986        }
2987
2988        rc = -ENOMEM;
2989        *nperms = match->permissions.nprim;
2990        *perms = kcalloc(*nperms, sizeof(**perms), GFP_ATOMIC);
2991        if (!*perms)
2992                goto out;
2993
2994        if (match->comdatum) {
2995                rc = hashtab_map(match->comdatum->permissions.table,
2996                                get_permissions_callback, *perms);
2997                if (rc)
2998                        goto err;
2999        }
3000
3001        rc = hashtab_map(match->permissions.table, get_permissions_callback,
3002                        *perms);
3003        if (rc)
3004                goto err;
3005
3006out:
3007        read_unlock(&policy_rwlock);
3008        return rc;
3009
3010err:
3011        read_unlock(&policy_rwlock);
3012        for (i = 0; i < *nperms; i++)
3013                kfree((*perms)[i]);
3014        kfree(*perms);
3015        return rc;
3016}
3017
3018int security_get_reject_unknown(void)
3019{
3020        return policydb.reject_unknown;
3021}
3022
3023int security_get_allow_unknown(void)
3024{
3025        return policydb.allow_unknown;
3026}
3027
3028/**
3029 * security_policycap_supported - Check for a specific policy capability
3030 * @req_cap: capability
3031 *
3032 * Description:
3033 * This function queries the currently loaded policy to see if it supports the
3034 * capability specified by @req_cap.  Returns true (1) if the capability is
3035 * supported, false (0) if it isn't supported.
3036 *
3037 */
3038int security_policycap_supported(unsigned int req_cap)
3039{
3040        int rc;
3041
3042        read_lock(&policy_rwlock);
3043        rc = ebitmap_get_bit(&policydb.policycaps, req_cap);
3044        read_unlock(&policy_rwlock);
3045
3046        return rc;
3047}
3048
3049struct selinux_audit_rule {
3050        u32 au_seqno;
3051        struct context au_ctxt;
3052};
3053
3054void selinux_audit_rule_free(void *vrule)
3055{
3056        struct selinux_audit_rule *rule = vrule;
3057
3058        if (rule) {
3059                context_destroy(&rule->au_ctxt);
3060                kfree(rule);
3061        }
3062}
3063
3064int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule)
3065{
3066        struct selinux_audit_rule *tmprule;
3067        struct role_datum *roledatum;
3068        struct type_datum *typedatum;
3069        struct user_datum *userdatum;
3070        struct selinux_audit_rule **rule = (struct selinux_audit_rule **)vrule;
3071        int rc = 0;
3072
3073        *rule = NULL;
3074
3075        if (!ss_initialized)
3076                return -EOPNOTSUPP;
3077
3078        switch (field) {
3079        case AUDIT_SUBJ_USER:
3080        case AUDIT_SUBJ_ROLE:
3081        case AUDIT_SUBJ_TYPE:
3082        case AUDIT_OBJ_USER:
3083        case AUDIT_OBJ_ROLE:
3084        case AUDIT_OBJ_TYPE:
3085                /* only 'equals' and 'not equals' fit user, role, and type */
3086                if (op != Audit_equal && op != Audit_not_equal)
3087                        return -EINVAL;
3088                break;
3089        case AUDIT_SUBJ_SEN:
3090        case AUDIT_SUBJ_CLR:
3091        case AUDIT_OBJ_LEV_LOW:
3092        case AUDIT_OBJ_LEV_HIGH:
3093                /* we do not allow a range, indicated by the presence of '-' */
3094                if (strchr(rulestr, '-'))
3095                        return -EINVAL;
3096                break;
3097        default:
3098                /* only the above fields are valid */
3099                return -EINVAL;
3100        }
3101
3102        tmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL);
3103        if (!tmprule)
3104                return -ENOMEM;
3105
3106        context_init(&tmprule->au_ctxt);
3107
3108        read_lock(&policy_rwlock);
3109
3110        tmprule->au_seqno = latest_granting;
3111
3112        switch (field) {
3113        case AUDIT_SUBJ_USER:
3114        case AUDIT_OBJ_USER:
3115                rc = -EINVAL;
3116                userdatum = hashtab_search(policydb.p_users.table, rulestr);
3117                if (!userdatum)
3118                        goto out;
3119                tmprule->au_ctxt.user = userdatum->value;
3120                break;
3121        case AUDIT_SUBJ_ROLE:
3122        case AUDIT_OBJ_ROLE:
3123                rc = -EINVAL;
3124                roledatum = hashtab_search(policydb.p_roles.table, rulestr);
3125                if (!roledatum)
3126                        goto out;
3127                tmprule->au_ctxt.role = roledatum->value;
3128                break;
3129        case AUDIT_SUBJ_TYPE:
3130        case AUDIT_OBJ_TYPE:
3131                rc = -EINVAL;
3132                typedatum = hashtab_search(policydb.p_types.table, rulestr);
3133                if (!typedatum)
3134                        goto out;
3135                tmprule->au_ctxt.type = typedatum->value;
3136                break;
3137        case AUDIT_SUBJ_SEN:
3138        case AUDIT_SUBJ_CLR:
3139        case AUDIT_OBJ_LEV_LOW:
3140        case AUDIT_OBJ_LEV_HIGH:
3141                rc = mls_from_string(rulestr, &tmprule->au_ctxt, GFP_ATOMIC);
3142                if (rc)
3143                        goto out;
3144                break;
3145        }
3146        rc = 0;
3147out:
3148        read_unlock(&policy_rwlock);
3149
3150        if (rc) {
3151                selinux_audit_rule_free(tmprule);
3152                tmprule = NULL;
3153        }
3154
3155        *rule = tmprule;
3156
3157        return rc;
3158}
3159
3160/* Check to see if the rule contains any selinux fields */
3161int selinux_audit_rule_known(struct audit_krule *rule)
3162{
3163        int i;
3164
3165        for (i = 0; i < rule->field_count; i++) {
3166                struct audit_field *f = &rule->fields[i];
3167                switch (f->type) {
3168                case AUDIT_SUBJ_USER:
3169                case AUDIT_SUBJ_ROLE:
3170                case AUDIT_SUBJ_TYPE:
3171                case AUDIT_SUBJ_SEN:
3172                case AUDIT_SUBJ_CLR:
3173                case AUDIT_OBJ_USER:
3174                case AUDIT_OBJ_ROLE:
3175                case AUDIT_OBJ_TYPE:
3176                case AUDIT_OBJ_LEV_LOW:
3177                case AUDIT_OBJ_LEV_HIGH:
3178                        return 1;
3179                }
3180        }
3181
3182        return 0;
3183}
3184
3185int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule,
3186                             struct audit_context *actx)
3187{
3188        struct context *ctxt;
3189        struct mls_level *level;
3190        struct selinux_audit_rule *rule = vrule;
3191        int match = 0;
3192
3193        if (unlikely(!rule)) {
3194                WARN_ONCE(1, "selinux_audit_rule_match: missing rule\n");
3195                return -ENOENT;
3196        }
3197
3198        read_lock(&policy_rwlock);
3199
3200        if (rule->au_seqno < latest_granting) {
3201                match = -ESTALE;
3202                goto out;
3203        }
3204
3205        ctxt = sidtab_search(sidtab, sid);
3206        if (unlikely(!ctxt)) {
3207                WARN_ONCE(1, "selinux_audit_rule_match: unrecognized SID %d\n",
3208                          sid);
3209                match = -ENOENT;
3210                goto out;
3211        }
3212
3213        /* a field/op pair that is not caught here will simply fall through
3214           without a match */
3215        switch (field) {
3216        case AUDIT_SUBJ_USER:
3217        case AUDIT_OBJ_USER:
3218                switch (op) {
3219                case Audit_equal:
3220                        match = (ctxt->user == rule->au_ctxt.user);
3221                        break;
3222                case Audit_not_equal:
3223                        match = (ctxt->user != rule->au_ctxt.user);
3224                        break;
3225                }
3226                break;
3227        case AUDIT_SUBJ_ROLE:
3228        case AUDIT_OBJ_ROLE:
3229                switch (op) {
3230                case Audit_equal:
3231                        match = (ctxt->role == rule->au_ctxt.role);
3232                        break;
3233                case Audit_not_equal:
3234                        match = (ctxt->role != rule->au_ctxt.role);
3235                        break;
3236                }
3237                break;
3238        case AUDIT_SUBJ_TYPE:
3239        case AUDIT_OBJ_TYPE:
3240                switch (op) {
3241                case Audit_equal:
3242                        match = (ctxt->type == rule->au_ctxt.type);
3243                        break;
3244                case Audit_not_equal:
3245                        match = (ctxt->type != rule->au_ctxt.type);
3246                        break;
3247                }
3248                break;
3249        case AUDIT_SUBJ_SEN:
3250        case AUDIT_SUBJ_CLR:
3251        case AUDIT_OBJ_LEV_LOW:
3252        case AUDIT_OBJ_LEV_HIGH:
3253                level = ((field == AUDIT_SUBJ_SEN ||
3254                          field == AUDIT_OBJ_LEV_LOW) ?
3255                         &ctxt->range.level[0] : &ctxt->range.level[1]);
3256                switch (op) {
3257                case Audit_equal:
3258                        match = mls_level_eq(&rule->au_ctxt.range.level[0],
3259                                             level);
3260                        break;
3261                case Audit_not_equal:
3262                        match = !mls_level_eq(&rule->au_ctxt.range.level[0],
3263                                              level);
3264                        break;
3265                case Audit_lt:
3266                        match = (mls_level_dom(&rule->au_ctxt.range.level[0],
3267                                               level) &&
3268                                 !mls_level_eq(&rule->au_ctxt.range.level[0],
3269                                               level));
3270                        break;
3271                case Audit_le:
3272                        match = mls_level_dom(&rule->au_ctxt.range.level[0],
3273                                              level);
3274                        break;
3275                case Audit_gt:
3276                        match = (mls_level_dom(level,
3277                                              &rule->au_ctxt.range.level[0]) &&
3278                                 !mls_level_eq(level,
3279                                               &rule->au_ctxt.range.level[0]));
3280                        break;
3281                case Audit_ge:
3282                        match = mls_level_dom(level,
3283                                              &rule->au_ctxt.range.level[0]);
3284                        break;
3285                }
3286        }
3287
3288out:
3289        read_unlock(&policy_rwlock);
3290        return match;
3291}
3292
3293static int (*aurule_callback)(void) = audit_update_lsm_rules;
3294
3295static int aurule_avc_callback(u32 event)
3296{
3297        int err = 0;
3298
3299        if (event == AVC_CALLBACK_RESET && aurule_callback)
3300                err = aurule_callback();
3301        return err;
3302}
3303
3304static int __init aurule_init(void)
3305{
3306        int err;
3307
3308        err = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET);
3309        if (err)
3310                panic("avc_add_callback() failed, error %d\n", err);
3311
3312        return err;
3313}
3314__initcall(aurule_init);
3315
3316#ifdef CONFIG_NETLABEL
3317/**
3318 * security_netlbl_cache_add - Add an entry to the NetLabel cache
3319 * @secattr: the NetLabel packet security attributes
3320 * @sid: the SELinux SID
3321 *
3322 * Description:
3323 * Attempt to cache the context in @ctx, which was derived from the packet in
3324 * @skb, in the NetLabel subsystem cache.  This function assumes @secattr has
3325 * already been initialized.
3326 *
3327 */
3328static void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr,
3329                                      u32 sid)
3330{
3331        u32 *sid_cache;
3332
3333        sid_cache = kmalloc(sizeof(*sid_cache), GFP_ATOMIC);
3334        if (sid_cache == NULL)
3335                return;
3336        secattr->cache = netlbl_secattr_cache_alloc(GFP_ATOMIC);
3337        if (secattr->cache == NULL) {
3338                kfree(sid_cache);
3339                return;
3340        }
3341
3342        *sid_cache = sid;
3343        secattr->cache->free = kfree;
3344        secattr->cache->data = sid_cache;
3345        secattr->flags |= NETLBL_SECATTR_CACHE;
3346}
3347
3348/**
3349 * security_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID
3350 * @secattr: the NetLabel packet security attributes
3351 * @sid: the SELinux SID
3352 *
3353 * Description:
3354 * Convert the given NetLabel security attributes in @secattr into a
3355 * SELinux SID.  If the @secattr field does not contain a full SELinux
3356 * SID/context then use SECINITSID_NETMSG as the foundation.  If possible the
3357 * 'cache' field of @secattr is set and the CACHE flag is set; this is to
3358 * allow the @secattr to be used by NetLabel to cache the secattr to SID
3359 * conversion for future lookups.  Returns zero on success, negative values on
3360 * failure.
3361 *
3362 */
3363int security_netlbl_secattr_to_sid(struct netlbl_lsm_secattr *secattr,
3364                                   u32 *sid)
3365{
3366        int rc;
3367        struct context *ctx;
3368        struct context ctx_new;
3369
3370        if (!ss_initialized) {
3371                *sid = SECSID_NULL;
3372                return 0;
3373        }
3374
3375        read_lock(&policy_rwlock);
3376
3377        if (secattr->flags & NETLBL_SECATTR_CACHE)
3378                *sid = *(u32 *)secattr->cache->data;
3379        else if (secattr->flags & NETLBL_SECATTR_SECID)
3380                *sid = secattr->attr.secid;
3381        else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) {
3382                rc = -EIDRM;
3383                ctx = sidtab_search(sidtab, SECINITSID_NETMSG);
3384                if (ctx == NULL)
3385                        goto out;
3386
3387                context_init(&ctx_new);
3388                ctx_new.user = ctx->user;
3389                ctx_new.role = ctx->role;
3390                ctx_new.type = ctx->type;
3391                mls_import_netlbl_lvl(&ctx_new, secattr);
3392                if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
3393                        rc = ebitmap_netlbl_import(&ctx_new.range.level[0].cat,
3394                                                   secattr->attr.mls.cat);
3395                        if (rc)
3396                                goto out;
3397                        memcpy(&ctx_new.range.level[1].cat,
3398                               &ctx_new.range.level[0].cat,
3399                               sizeof(ctx_new.range.level[0].cat));
3400                }
3401                rc = -EIDRM;
3402                if (!mls_context_isvalid(&policydb, &ctx_new))
3403                        goto out_free;
3404
3405                rc = sidtab_context_to_sid(sidtab, &ctx_new, sid);
3406                if (rc)
3407                        goto out_free;
3408
3409                security_netlbl_cache_add(secattr, *sid);
3410
3411                ebitmap_destroy(&ctx_new.range.level[0].cat);
3412        } else
3413                *sid = SECSID_NULL;
3414
3415        read_unlock(&policy_rwlock);
3416        return 0;
3417out_free:
3418        ebitmap_destroy(&ctx_new.range.level[0].cat);
3419out:
3420        read_unlock(&policy_rwlock);
3421        return rc;
3422}
3423
3424/**
3425 * security_netlbl_sid_to_secattr - Convert a SELinux SID to a NetLabel secattr
3426 * @sid: the SELinux SID
3427 * @secattr: the NetLabel packet security attributes
3428 *
3429 * Description:
3430 * Convert the given SELinux SID in @sid into a NetLabel security attribute.
3431 * Returns zero on success, negative values on failure.
3432 *
3433 */
3434int security_netlbl_sid_to_secattr(u32 sid, struct netlbl_lsm_secattr *secattr)
3435{
3436        int rc;
3437        struct context *ctx;
3438
3439        if (!ss_initialized)
3440                return 0;
3441
3442        read_lock(&policy_rwlock);
3443
3444        rc = -ENOENT;
3445        ctx = sidtab_search(sidtab, sid);
3446        if (ctx == NULL)
3447                goto out;
3448
3449        rc = -ENOMEM;
3450        secattr->domain = kstrdup(sym_name(&policydb, SYM_TYPES, ctx->type - 1),
3451                                  GFP_ATOMIC);
3452        if (secattr->domain == NULL)
3453                goto out;
3454
3455        secattr->attr.secid = sid;
3456        secattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID;
3457        mls_export_netlbl_lvl(ctx, secattr);
3458        rc = mls_export_netlbl_cat(ctx, secattr);
3459out:
3460        read_unlock(&policy_rwlock);
3461        return rc;
3462}
3463#endif /* CONFIG_NETLABEL */
3464
3465/**
3466 * security_read_policy - read the policy.
3467 * @data: binary policy data
3468 * @len: length of data in bytes
3469 *
3470 */
3471int security_read_policy(void **data, size_t *len)
3472{
3473        int rc;
3474        struct policy_file fp;
3475
3476        if (!ss_initialized)
3477                return -EINVAL;
3478
3479        *len = security_policydb_len();
3480
3481        *data = vmalloc_user(*len);
3482        if (!*data)
3483                return -ENOMEM;
3484
3485        fp.data = *data;
3486        fp.len = *len;
3487
3488        read_lock(&policy_rwlock);
3489        rc = policydb_write(&policydb, &fp);
3490        read_unlock(&policy_rwlock);
3491
3492        if (rc)
3493                return rc;
3494
3495        *len = (unsigned long)fp.data - (unsigned long)*data;
3496        return 0;
3497
3498}
3499