security_selinux.c 19.3 KB
Newer Older
1
/*
2
 * Copyright (C) 2008,2009 Red Hat, Inc.
3 4 5 6 7 8 9 10
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * Authors:
 *     James Morris <jmorris@namei.org>
11
 *     Dan Walsh <dwalsh@redhat.com>
12 13 14 15 16 17 18 19 20 21
 *
 * SELinux security driver.
 */
#include <config.h>
#include <selinux/selinux.h>
#include <selinux/context.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

22
#include "security_driver.h"
23 24 25 26
#include "security_selinux.h"
#include "virterror_internal.h"
#include "util.h"
#include "memory.h"
27
#include "logging.h"
28 29
#include "pci.h"
#include "hostusb.h"
30
#include "storage_file.h"
D
Daniel P. Berrange 已提交
31 32 33

#define VIR_FROM_THIS VIR_FROM_SECURITY

34
static char default_domain_context[1024];
35
static char default_content_context[1024];
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
static char default_image_context[1024];
#define SECURITY_SELINUX_VOID_DOI       "0"
#define SECURITY_SELINUX_NAME "selinux"

/* TODO
   The data struct of used mcs should be replaced with a better data structure in the future
*/

struct MCS {
    char *mcs;
    struct MCS *next;
};
static struct MCS *mcsList = NULL;

static int
mcsAdd(const char *mcs)
{
    struct MCS *ptr;

    for (ptr = mcsList; ptr; ptr = ptr->next) {
D
Daniel P. Berrange 已提交
56
        if (STREQ(ptr->mcs, mcs))
57 58
            return -1;
    }
D
Daniel P. Berrange 已提交
59 60
    if (VIR_ALLOC(ptr) < 0)
        return -1;
61 62 63 64 65 66 67 68 69 70 71 72 73
    ptr->mcs = strdup(mcs);
    ptr->next = mcsList;
    mcsList = ptr;
    return 0;
}

static int
mcsRemove(const char *mcs)
{
    struct MCS *prevptr = NULL;
    struct MCS *ptr = NULL;

    for (ptr = mcsList; ptr; ptr = ptr->next) {
D
Daniel P. Berrange 已提交
74
        if (STREQ(ptr->mcs, mcs)) {
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
            if (prevptr)
                prevptr->next = ptr->next;
            else {
                mcsList = ptr->next;
            }
            free(ptr->mcs);
            free(ptr);
            return 0;
        }
        prevptr = ptr;
    }
    return -1;
}

static char *
SELinuxGenNewContext(const char *oldcontext, const char *mcs)
{
    char *newcontext = NULL;
    char *scontext = strdup(oldcontext);
    if (!scontext) goto err;
    context_t con = context_new(scontext);
    if (!con) goto err;
    context_range_set(con, mcs);
    newcontext = strdup(context_str(con));
    context_free(con);
err:
    freecon(scontext);
    return (newcontext);
}

static int
SELinuxInitialize(virConnectPtr conn)
{
    char *ptr = NULL;
    int fd = 0;

    virRandomInitialize(time(NULL) ^ getpid());

    fd = open(selinux_virtual_domain_context_path(), O_RDONLY);
    if (fd < 0) {
115 116 117
        virReportSystemError(conn, errno,
                             _("cannot open SELinux virtual domain context file '%s'"),
                             selinux_virtual_domain_context_path());
118 119 120 121
        return -1;
    }

    if (saferead(fd, default_domain_context, sizeof(default_domain_context)) < 0) {
122 123 124
        virReportSystemError(conn, errno,
                             _("cannot read SELinux virtual domain context file %s"),
                             selinux_virtual_domain_context_path());
125 126 127 128 129 130 131 132 133
        close(fd);
        return -1;
    }
    close(fd);

    ptr = strchrnul(default_domain_context, '\n');
    *ptr = '\0';

    if ((fd = open(selinux_virtual_image_context_path(), O_RDONLY)) < 0) {
134 135 136
        virReportSystemError(conn, errno,
                             _("cannot open SELinux virtual image context file %s"),
                             selinux_virtual_image_context_path());
137 138 139 140
        return -1;
    }

    if (saferead(fd, default_image_context, sizeof(default_image_context)) < 0) {
141 142 143
        virReportSystemError(conn, errno,
                             _("cannot read SELinux virtual image context file %s"),
                             selinux_virtual_image_context_path());
144 145 146 147 148 149
        close(fd);
        return -1;
    }
    close(fd);

    ptr = strchrnul(default_image_context, '\n');
150 151 152 153 154 155 156
    if (*ptr == '\n') {
        *ptr = '\0';
        strcpy(default_content_context, ptr+1);
        ptr = strchrnul(default_content_context, '\n');
        if (*ptr == '\n')
            *ptr = '\0';
    }
157 158 159 160
    return 0;
}

static int
D
Daniel P. Berrange 已提交
161 162
SELinuxGenSecurityLabel(virConnectPtr conn,
                        virDomainObjPtr vm)
163 164 165 166 167 168
{
    int rc = -1;
    char mcs[1024];
    char *scontext = NULL;
    int c1 = 0;
    int c2 = 0;
169 170 171 172 173 174

    if (vm->def->seclabel.label ||
        vm->def->seclabel.model ||
        vm->def->seclabel.imagelabel) {
        virSecurityReportError(conn, VIR_ERR_INTERNAL_ERROR,
                               "%s", _("security label already defined for VM"));
175
        return rc;
D
Daniel P. Berrange 已提交
176
    }
177 178 179 180 181 182 183 184

    do {
        c1 = virRandom(1024);
        c2 = virRandom(1024);

        if ( c1 == c2 ) {
            sprintf(mcs, "s0:c%d", c1);
        } else {
D
Daniel P. Berrange 已提交
185
            if ( c1 < c2 )
186 187 188 189 190 191 192
                sprintf(mcs, "s0:c%d,c%d", c1, c2);
            else
                sprintf(mcs, "s0:c%d,c%d", c2, c1);
        }
    } while(mcsAdd(mcs) == -1);

    vm->def->seclabel.label = SELinuxGenNewContext(default_domain_context, mcs);
D
Daniel P. Berrange 已提交
193 194 195 196 197
    if (! vm->def->seclabel.label)  {
        virSecurityReportError(conn, VIR_ERR_ERROR,
                               _("cannot generate selinux context for %s"), mcs);
        goto err;
    }
198
    vm->def->seclabel.imagelabel = SELinuxGenNewContext(default_image_context, mcs);
D
Daniel P. Berrange 已提交
199 200 201 202 203
    if (! vm->def->seclabel.imagelabel)  {
        virSecurityReportError(conn, VIR_ERR_ERROR,
                               _("cannot generate selinux context for %s"), mcs);
        goto err;
    }
204
    vm->def->seclabel.model = strdup(SECURITY_SELINUX_NAME);
205
    if (!vm->def->seclabel.model) {
D
Daniel P. Berrange 已提交
206 207 208 209
        virReportOOMError(conn);
        goto err;
    }

210 211 212 213

    rc = 0;
    goto done;
err:
D
Daniel P. Berrange 已提交
214 215 216
    VIR_FREE(vm->def->seclabel.label);
    VIR_FREE(vm->def->seclabel.imagelabel);
    VIR_FREE(vm->def->seclabel.model);
217
done:
D
Daniel P. Berrange 已提交
218
    VIR_FREE(scontext);
219 220 221
    return rc;
}

222 223 224 225 226 227 228 229 230
static int
SELinuxReserveSecurityLabel(virConnectPtr conn,
                            virDomainObjPtr vm)
{
    security_context_t pctx;
    context_t ctx = NULL;
    const char *mcs;

    if (getpidcon(vm->pid, &pctx) == -1) {
231 232
        virReportSystemError(conn, errno,
                             _("unable to get PID %d security context"), vm->pid);
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
        return -1;
    }

    ctx = context_new(pctx);
    VIR_FREE(pctx);
    if (!ctx)
        goto err;

    mcs = context_range_get(ctx);
    if (!mcs)
        goto err;

    mcsAdd(mcs);

    context_free(ctx);

    return 0;

err:
    context_free(ctx);
    return -1;
}



258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
static int
SELinuxSecurityDriverProbe(void)
{
    return is_selinux_enabled() ? SECURITY_DRIVER_ENABLE : SECURITY_DRIVER_DISABLE;
}

static int
SELinuxSecurityDriverOpen(virConnectPtr conn, virSecurityDriverPtr drv)
{
    /*
     * Where will the DOI come from?  SELinux configuration, or qemu
     * configuration? For the moment, we'll just set it to "0".
     */
    virSecurityDriverSetDOI(conn, drv, SECURITY_SELINUX_VOID_DOI);
    return SELinuxInitialize(conn);
}

static int
SELinuxGetSecurityLabel(virConnectPtr conn,
                        virDomainObjPtr vm,
                        virSecurityLabelPtr sec)
{
    security_context_t ctx;

    if (getpidcon(vm->pid, &ctx) == -1) {
283 284 285
        virReportSystemError(conn, errno,
                             _("unable to get PID %d security context"),
                             vm->pid);
286 287 288 289 290
        return -1;
    }

    if (strlen((char *) ctx) >= VIR_SECURITY_LABEL_BUFLEN) {
        virSecurityReportError(conn, VIR_ERR_ERROR,
291 292
                               _("security label exceeds "
                                 "maximum lenth: %d"),
293 294 295 296 297 298 299 300 301
                               VIR_SECURITY_LABEL_BUFLEN - 1);
        return -1;
    }

    strcpy(sec->label, (char *) ctx);
    free(ctx);

    sec->enforcing = security_getenforce();
    if (sec->enforcing == -1) {
302 303
        virReportSystemError(conn, errno, "%s",
                             _("error calling security_getenforce()"));
304 305 306 307 308 309 310
        return -1;
    }

    return 0;
}

static int
311
SELinuxSetFilecon(virConnectPtr conn, const char *path, char *tcon)
312
{
313
    security_context_t econ;
314

315 316
    VIR_INFO("Setting SELinux context on '%s' to '%s'", path, tcon);

317
    if (setfilecon(path, tcon) < 0) {
318 319
        int setfilecon_errno = errno;

320 321 322 323 324 325 326 327
        if (getfilecon(path, &econ) >= 0) {
            if (STREQ(tcon, econ)) {
                freecon(econ);
                /* It's alright, there's nothing to change anyway. */
                return 0;
            }
            freecon(econ);
        }
328 329

        /* if the error complaint is related to an image hosted on
330 331 332 333
         * an nfs mount, or a usbfs/sysfs filesystem not supporting
         * labelling, then just ignore it & hope for the best.
         * The user hopefully set one of the neccessary SELinux
         * virt_use_{nfs,usb,pci}  boolean tunables to allow it...
334 335
         */
        if (setfilecon_errno != EOPNOTSUPP) {
336 337 338
            virReportSystemError(conn, setfilecon_errno,
                                 _("unable to set security context '%s' on '%s'"),
                                 tcon, path);
339 340
            if (security_getenforce() == 1)
                return -1;
341 342 343
        } else {
            VIR_INFO("Setting security context '%s' on '%s' not supported",
                     tcon, path);
344
        }
345 346 347 348 349
    }
    return 0;
}

static int
350 351
SELinuxRestoreSecurityFileLabel(virConnectPtr conn,
                                const char *path)
352
{
353 354 355
    struct stat buf;
    security_context_t fcon = NULL;
    int rc = -1;
D
Daniel P. Berrange 已提交
356
    int err;
357
    char *newpath = NULL;
358

359 360
    VIR_INFO("Restoring SELinux context on '%s'", path);

D
Daniel P. Berrange 已提交
361 362 363 364
    if ((err = virFileResolveLink(path, &newpath)) < 0) {
        virReportSystemError(conn, err,
                             _("cannot resolve symlink %s"), path);
        goto err;
365
    }
366

D
Daniel P. Berrange 已提交
367 368 369 370 371
    if (stat(newpath, &buf) != 0)
        goto err;

    if (matchpathcon(newpath, buf.st_mode, &fcon) == 0)  {
        rc = SELinuxSetFilecon(conn, newpath, fcon);
372 373 374 375 376
    }
err:
    VIR_FREE(fcon);
    VIR_FREE(newpath);
    return rc;
377 378
}

379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
static int
SELinuxRestoreSecurityImageLabel(virConnectPtr conn,
                                 virDomainDiskDefPtr disk)
{
    /* Don't restore labels on readoly/shared disks, because
     * other VMs may still be accessing these
     * Alternatively we could iterate over all running
     * domains and try to figure out if it is in use, but
     * this would not work for clustered filesystems, since
     * we can't see running VMs using the file on other nodes
     * Safest bet is thus to skip the restore step.
     */
    if (disk->readonly || disk->shared)
        return 0;

    if (!disk->src)
        return 0;

    return SELinuxRestoreSecurityFileLabel(conn, disk->src);
}

400 401 402
static int
SELinuxSetSecurityImageLabel(virConnectPtr conn,
                             virDomainObjPtr vm,
403
                             virDomainDiskDefPtr disk)
404 405 406

{
    const virSecurityLabelDefPtr secdef = &vm->def->seclabel;
407
    const char *path;
408

409 410 411
    if (!disk->src)
        return 0;

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
    path = disk->src;
    do {
        virStorageFileMetadata meta;
        int ret;

        memset(&meta, 0, sizeof(meta));

        ret = virStorageFileGetMetadata(conn, path, &meta);

        if (path != disk->src)
            VIR_FREE(path);
        path = NULL;

        if (ret < 0)
            return -1;

        if (meta.backingStore != NULL &&
            SELinuxSetFilecon(conn, meta.backingStore,
                              default_content_context) < 0) {
            VIR_FREE(meta.backingStore);
            return -1;
        }

        path = meta.backingStore;
    } while (path != NULL);

438 439 440 441 442
    if (disk->shared) {
        return SELinuxSetFilecon(conn, disk->src, default_image_context);
    } else if (disk->readonly) {
        return SELinuxSetFilecon(conn, disk->src, default_content_context);
    } else if (secdef->imagelabel) {
443
        return SELinuxSetFilecon(conn, disk->src, secdef->imagelabel);
444
    }
445

446 447 448
    return 0;
}

449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595

static int
SELinuxSetSecurityPCILabel(virConnectPtr conn,
                           pciDevice *dev ATTRIBUTE_UNUSED,
                           const char *file, void *opaque)
{
    virDomainObjPtr vm = opaque;
    const virSecurityLabelDefPtr secdef = &vm->def->seclabel;

    return SELinuxSetFilecon(conn, file, secdef->imagelabel);
}

static int
SELinuxSetSecurityUSBLabel(virConnectPtr conn,
                           usbDevice *dev ATTRIBUTE_UNUSED,
                           const char *file, void *opaque)
{
    virDomainObjPtr vm = opaque;
    const virSecurityLabelDefPtr secdef = &vm->def->seclabel;

    return SELinuxSetFilecon(conn, file, secdef->imagelabel);
}

static int
SELinuxSetSecurityHostdevLabel(virConnectPtr conn,
                               virDomainObjPtr vm,
                               virDomainHostdevDefPtr dev)

{
    int ret = -1;

    if (dev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS)
        return 0;

    switch (dev->source.subsys.type) {
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB: {
        if (dev->source.subsys.u.usb.bus && dev->source.subsys.u.usb.device) {
            usbDevice *usb = usbGetDevice(conn,
                                          dev->source.subsys.u.usb.bus,
                                          dev->source.subsys.u.usb.device);

            if (!usb)
                goto done;

            ret = usbDeviceFileIterate(conn, usb, SELinuxSetSecurityUSBLabel, vm);
            usbFreeDevice(conn, usb);

            break;
        } else {
            /* XXX deal with product/vendor better */
            ret = 0;
        }
    }

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI: {
        pciDevice *pci = pciGetDevice(conn,
                                      dev->source.subsys.u.pci.domain,
                                      dev->source.subsys.u.pci.bus,
                                      dev->source.subsys.u.pci.slot,
                                      dev->source.subsys.u.pci.function);

        if (!pci)
            goto done;

        ret = pciDeviceFileIterate(conn, pci, SELinuxSetSecurityPCILabel, vm);
        pciFreeDevice(conn, pci);

        break;
    }

    default:
        ret = 0;
        break;
    }

done:
    return ret;
}

static int
SELinuxRestoreSecurityPCILabel(virConnectPtr conn,
                               pciDevice *dev ATTRIBUTE_UNUSED,
                               const char *file,
                               void *opaque ATTRIBUTE_UNUSED)
{
    return SELinuxRestoreSecurityFileLabel(conn, file);
}

static int
SELinuxRestoreSecurityUSBLabel(virConnectPtr conn,
                               usbDevice *dev ATTRIBUTE_UNUSED,
                               const char *file,
                               void *opaque ATTRIBUTE_UNUSED)
{
    return SELinuxRestoreSecurityFileLabel(conn, file);
}

static int
SELinuxRestoreSecurityHostdevLabel(virConnectPtr conn,
                                   virDomainHostdevDefPtr dev)

{
    int ret = -1;

    if (dev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS)
        return 0;

    switch (dev->source.subsys.type) {
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB: {
        usbDevice *usb = usbGetDevice(conn,
                                      dev->source.subsys.u.usb.bus,
                                      dev->source.subsys.u.usb.device);

        if (!usb)
            goto done;

        ret = usbDeviceFileIterate(conn, usb, SELinuxRestoreSecurityUSBLabel, NULL);
        usbFreeDevice(conn, usb);

        break;
    }

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI: {
        pciDevice *pci = pciGetDevice(conn,
                                      dev->source.subsys.u.pci.domain,
                                      dev->source.subsys.u.pci.bus,
                                      dev->source.subsys.u.pci.slot,
                                      dev->source.subsys.u.pci.function);

        if (!pci)
            goto done;

        ret = pciDeviceFileIterate(conn, pci, SELinuxRestoreSecurityPCILabel, NULL);
        pciFreeDevice(conn, pci);

        break;
    }

    default:
        ret = 0;
        break;
    }

done:
    return ret;
}

596 597 598 599 600 601 602
static int
SELinuxRestoreSecurityLabel(virConnectPtr conn,
                            virDomainObjPtr vm)
{
    const virSecurityLabelDefPtr secdef = &vm->def->seclabel;
    int i;
    int rc = 0;
603 604 605

    VIR_DEBUG("Restoring security label on %s", vm->def->name);

606
    if (secdef->imagelabel) {
607 608 609 610
        for (i = 0 ; i < vm->def->nhostdevs ; i++) {
            if (SELinuxRestoreSecurityHostdevLabel(conn, vm->def->hostdevs[i]) < 0)
                rc = -1;
        }
611
        for (i = 0 ; i < vm->def->ndisks ; i++) {
612
            if (SELinuxRestoreSecurityImageLabel(conn, vm->def->disks[i]) < 0)
613 614 615 616 617 618 619 620 621 622 623 624 625 626
                rc = -1;
        }
        VIR_FREE(secdef->model);
        VIR_FREE(secdef->label);
        context_t con = context_new(secdef->imagelabel);
        if (con) {
            mcsRemove(context_range_get(con));
            context_free(con);
        }
        VIR_FREE(secdef->imagelabel);
    }
    return rc;
}

627 628 629 630 631 632 633 634 635 636 637 638 639 640
static int
SELinuxSecurityVerify(virConnectPtr conn, virDomainDefPtr def)
{
    const virSecurityLabelDefPtr secdef = &def->seclabel;
    if (secdef->type == VIR_DOMAIN_SECLABEL_STATIC) {
        if (security_check_context(secdef->label) != 0) {
            virSecurityReportError(conn, VIR_ERR_XML_ERROR,
                                   _("Invalid security label %s"), secdef->label);
            return -1;
        }
    }
    return 0;
}

641 642 643 644 645 646 647 648 649 650 651
static int
SELinuxSetSecurityLabel(virConnectPtr conn,
                        virSecurityDriverPtr drv,
                        virDomainObjPtr vm)
{
    /* TODO: verify DOI */
    const virSecurityLabelDefPtr secdef = &vm->def->seclabel;
    int i;

    if (!STREQ(drv->name, secdef->model)) {
        virSecurityReportError(conn, VIR_ERR_ERROR,
652 653 654 655
                               _("security label driver mismatch: "
                                 "'%s' model configured for domain, but "
                                 "hypervisor driver is '%s'."),
                               secdef->model, drv->name);
656
        if (security_getenforce() == 1)
657
            return -1;
658 659 660
    }

    if (setexeccon(secdef->label) == -1) {
661 662 663
        virReportSystemError(conn, errno,
                             _("unable to set security context '%s'"),
                             secdef->label);
664
        if (security_getenforce() == 1)
665
            return -1;
666 667 668 669
    }

    if (secdef->imagelabel) {
        for (i = 0 ; i < vm->def->ndisks ; i++) {
670 671
            if (SELinuxSetSecurityImageLabel(conn, vm, vm->def->disks[i]) < 0)
                return -1;
672
        }
673 674 675 676
        for (i = 0 ; i < vm->def->nhostdevs ; i++) {
            if (SELinuxSetSecurityHostdevLabel(conn, vm, vm->def->hostdevs[i]) < 0)
                return -1;
        }
677 678 679 680 681 682 683 684 685
    }

    return 0;
}

virSecurityDriver virSELinuxSecurityDriver = {
    .name                       = SECURITY_SELINUX_NAME,
    .probe                      = SELinuxSecurityDriverProbe,
    .open                       = SELinuxSecurityDriverOpen,
686
    .domainSecurityVerify       = SELinuxSecurityVerify,
687 688 689
    .domainSetSecurityImageLabel = SELinuxSetSecurityImageLabel,
    .domainRestoreSecurityImageLabel = SELinuxRestoreSecurityImageLabel,
    .domainGenSecurityLabel     = SELinuxGenSecurityLabel,
690
    .domainReserveSecurityLabel     = SELinuxReserveSecurityLabel,
691 692 693
    .domainGetSecurityLabel     = SELinuxGetSecurityLabel,
    .domainRestoreSecurityLabel = SELinuxRestoreSecurityLabel,
    .domainSetSecurityLabel     = SELinuxSetSecurityLabel,
694 695
    .domainSetSecurityHostdevLabel = SELinuxSetSecurityHostdevLabel,
    .domainRestoreSecurityHostdevLabel = SELinuxRestoreSecurityHostdevLabel,
696
};