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