security_selinux.c 73.1 KB
Newer Older
1
/*
2
 * Copyright (C) 2008-2013 Red Hat, Inc.
3 4 5 6 7 8
 *
 * 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.
 *
O
Osier Yang 已提交
9 10 11 12 13 14
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
15
 * License along with this library.  If not, see
O
Osier Yang 已提交
16 17
 * <http://www.gnu.org/licenses/>.
 *
18 19
 * Authors:
 *     James Morris <jmorris@namei.org>
20
 *     Dan Walsh <dwalsh@redhat.com>
21 22 23 24 25 26 27 28 29
 *
 * 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>
E
Eric Blake 已提交
30 31 32
#if HAVE_SELINUX_LABEL_H
# include <selinux/label.h>
#endif
33

34
#include "security_driver.h"
35
#include "security_selinux.h"
36
#include "virerror.h"
37
#include "virutil.h"
38
#include "viralloc.h"
39
#include "virlog.h"
40
#include "virpci.h"
41
#include "virusb.h"
42
#include "virstoragefile.h"
E
Eric Blake 已提交
43
#include "virfile.h"
44
#include "virhash.h"
45
#include "virrandom.h"
46
#include "virconf.h"
47
#include "virtpm.h"
D
Daniel P. Berrange 已提交
48 49 50

#define VIR_FROM_THIS VIR_FROM_SECURITY

51 52 53 54 55 56 57 58 59 60
#define MAX_CONTEXT 1024

typedef struct _virSecuritySELinuxData virSecuritySELinuxData;
typedef virSecuritySELinuxData *virSecuritySELinuxDataPtr;

typedef struct _virSecuritySELinuxCallbackData virSecuritySELinuxCallbackData;
typedef virSecuritySELinuxCallbackData *virSecuritySELinuxCallbackDataPtr;

struct _virSecuritySELinuxData {
    char *domain_context;
61
    char *alt_domain_context;
62 63
    char *file_context;
    char *content_context;
64
    virHashTablePtr mcs;
65
    bool skipAllLabel;
66 67 68
#if HAVE_SELINUX_LABEL_H
    struct selabel_handle *label_handle;
#endif
69 70 71 72 73 74 75
};

struct _virSecuritySELinuxCallbackData {
    virSecurityManagerPtr manager;
    virSecurityLabelDefPtr secdef;
};

76 77 78
#define SECURITY_SELINUX_VOID_DOI       "0"
#define SECURITY_SELINUX_NAME "selinux"

79 80 81 82 83 84
static int
virSecuritySELinuxRestoreSecurityTPMFileLabelInt(virSecurityManagerPtr mgr,
                                                 virDomainDefPtr def,
                                                 virDomainTPMDefPtr tpm);


85 86 87
/*
 * Returns 0 on success, 1 if already reserved, or -1 on fatal error
 */
88
static int
89 90
virSecuritySELinuxMCSAdd(virSecurityManagerPtr mgr,
                         const char *mcs)
91
{
92
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
93

94 95 96 97
    if (virHashLookup(data->mcs, mcs))
        return 1;

    if (virHashAddEntry(data->mcs, mcs, (void*)0x1) < 0)
98
        return -1;
99

100 101 102
    return 0;
}

103 104 105
static void
virSecuritySELinuxMCSRemove(virSecurityManagerPtr mgr,
                            const char *mcs)
106
{
107 108 109
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);

    virHashRemoveEntry(data->mcs, mcs);
110 111
}

112 113

static char *
114 115 116 117
virSecuritySELinuxMCSFind(virSecurityManagerPtr mgr,
                          const char *sens,
                          int catMin,
                          int catMax)
118 119
{
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
120
    int catRange;
121
    char *mcs = NULL;
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167

    /* +1 since virRandomInt range is exclusive of the upper bound */
    catRange = (catMax - catMin) + 1;

    if (catRange < 8) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Category range c%d-c%d too small"),
                       catMin, catMax);
        return NULL;
    }

    VIR_DEBUG("Using sensitivity level '%s' cat min %d max %d range %d",
              sens, catMin, catMax, catRange);

    for (;;) {
        int c1 = virRandomInt(catRange);
        int c2 = virRandomInt(catRange);

        VIR_DEBUG("Try cat %s:c%d,c%d", sens, c1 + catMin, c2 + catMin);

        if (c1 == c2) {
            if (virAsprintf(&mcs, "%s:c%d", sens, catMin + c1) < 0) {
                virReportOOMError();
                return NULL;
            }
        } else {
            if (c1 > c2) {
                int t = c1;
                c1 = c2;
                c2 = t;
            }
            if (virAsprintf(&mcs, "%s:c%d,c%d", sens, catMin + c1, catMin + c2) < 0) {
                virReportOOMError();
                return NULL;
            }
        }

        if (virHashLookup(data->mcs, mcs) == NULL)
            break;

        VIR_FREE(mcs);
    }

    return mcs;
}

168 169 170 171 172 173 174 175 176 177 178 179 180 181

/*
 * This needs to cope with several styles of range
 *
 * system_u:system_r:virtd_t:s0
 * system_u:system_r:virtd_t:s0-s0
 * system_u:system_r:virtd_t:s0-s0:c0.c1023
 *
 * In the first two cases, we'll assume c0.c1023 for
 * the category part, since that's what we're really
 * interested in. This won't work in Enforcing mode,
 * but will prevent libvirtd breaking in Permissive
 * mode when run with a wierd process label.
 */
182 183 184 185 186
static int
virSecuritySELinuxMCSGetProcessRange(char **sens,
                                     int *catMin,
                                     int *catMax)
{
187 188
    security_context_t ourSecContext = NULL;
    context_t ourContext = NULL;
189 190
    char *cat = NULL;
    char *tmp;
191
    int ret = -1;
192

M
Martin Kletzander 已提交
193
    if (getcon_raw(&ourSecContext) < 0) {
194 195 196 197 198 199 200 201 202 203 204
        virReportSystemError(errno, "%s",
                             _("Unable to get current process SELinux context"));
        goto cleanup;
    }
    if (!(ourContext = context_new(ourSecContext))) {
        virReportSystemError(errno,
                             _("Unable to parse current SELinux context '%s'"),
                             ourSecContext);
        goto cleanup;
    }

205
    if (!(*sens = strdup(context_range_get(ourContext)))) {
206 207 208 209
        virReportOOMError();
        goto cleanup;
    }

210 211 212 213 214
    /* Find and blank out the category part (if any) */
    tmp = strchr(*sens, ':');
    if (tmp) {
        *tmp = '\0';
        cat = tmp + 1;
215 216
    }
    /* Find and blank out the sensitivity upper bound */
217
    if ((tmp = strchr(*sens, '-')))
218 219 220
        *tmp = '\0';
    /* sens now just contains the sensitivity lower bound */

221 222 223 224 225 226 227 228
    /* If there was no category part, just assume c0.c1024 */
    if (!cat) {
        *catMin = 0;
        *catMax = 1024;
        ret = 0;
        goto cleanup;
    }

229 230 231 232 233 234 235 236 237
    /* Find & extract category min */
    tmp = cat;
    if (tmp[0] != 'c') {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot parse category in %s"),
                       cat);
        goto cleanup;
    }
    tmp++;
238
    if (virStrToLong_i(tmp, &tmp, 10, catMin) < 0) {
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot parse category in %s"),
                       cat);
        goto cleanup;
    }

    /* We *must* have a pair of categories otherwise
     * there's no range to allocate VM categories from */
    if (!tmp[0]) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("No category range available"));
        goto cleanup;
    }

    /* Find & extract category max (if any) */
    if (tmp[0] != '.') {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot parse category in %s"),
                       cat);
        goto cleanup;
    }
    tmp++;
    if (tmp[0] != 'c') {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot parse category in %s"),
                       cat);
        goto cleanup;
    }
    tmp++;
268
    if (virStrToLong_i(tmp, &tmp, 10, catMax) < 0) {
269 270 271 272 273 274
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot parse category in %s"),
                       cat);
        goto cleanup;
    }

275
    ret = 0;
276 277

cleanup:
278 279
    if (ret < 0)
        VIR_FREE(*sens);
280 281
    freecon(ourSecContext);
    context_free(ourContext);
282
    return ret;
283 284
}

285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
static char *
virSecuritySELinuxContextAddRange(security_context_t src,
                                  security_context_t dst)
{
    char *str = NULL;
    char *ret = NULL;
    context_t srccon = NULL;
    context_t dstcon = NULL;

    if (!src || !dst)
        return ret;

    if (!(srccon = context_new(src)) || !(dstcon = context_new(dst))) {
        virReportSystemError(errno, "%s",
                             _("unable to allocate security context"));
        goto cleanup;
    }

    if (context_range_set(dstcon, context_range_get(srccon)) == -1) {
        virReportSystemError(errno,
                             _("unable to set security context range '%s'"), dst);
        goto cleanup;
    }

    if (!(str = context_str(dstcon))) {
        virReportSystemError(errno, "%s",
                             _("Unable to format SELinux context"));
        goto cleanup;
    }

    if (!(ret = strdup(str))) {
        virReportOOMError();
        goto cleanup;
    }

cleanup:
    if (srccon) context_free(srccon);
    if (dstcon) context_free(dstcon);
    return ret;
}
325

326
static char *
327 328 329
virSecuritySELinuxGenNewContext(const char *basecontext,
                                const char *mcs,
                                bool isObjectContext)
330
{
331
    context_t context = NULL;
332 333
    char *ret = NULL;
    char *str;
334 335 336
    security_context_t ourSecContext = NULL;
    context_t ourContext = NULL;

337 338 339
    VIR_DEBUG("basecontext=%s mcs=%s isObjectContext=%d",
              basecontext, mcs, isObjectContext);

M
Martin Kletzander 已提交
340
    if (getcon_raw(&ourSecContext) < 0) {
341 342 343 344 345 346 347 348 349 350
        virReportSystemError(errno, "%s",
                             _("Unable to get current process SELinux context"));
        goto cleanup;
    }
    if (!(ourContext = context_new(ourSecContext))) {
        virReportSystemError(errno,
                             _("Unable to parse current SELinux context '%s'"),
                             ourSecContext);
        goto cleanup;
    }
351
    VIR_DEBUG("process=%s", ourSecContext);
352 353 354 355 356 357 358 359

    if (!(context = context_new(basecontext))) {
        virReportSystemError(errno,
                             _("Unable to parse base SELinux context '%s'"),
                             basecontext);
        goto cleanup;
    }

360 361 362 363 364 365 366 367
    if (context_user_set(context,
                         context_user_get(ourContext)) != 0) {
        virReportSystemError(errno,
                             _("Unable to set SELinux context user '%s'"),
                             context_user_get(ourContext));
        goto cleanup;
    }

368 369
    if (!isObjectContext &&
        context_role_set(context,
370 371
                         context_role_get(ourContext)) != 0) {
        virReportSystemError(errno,
372
                             _("Unable to set SELinux context role '%s'"),
373 374 375 376
                             context_role_get(ourContext));
        goto cleanup;
    }

377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
    if (context_range_set(context, mcs) != 0) {
        virReportSystemError(errno,
                             _("Unable to set SELinux context MCS '%s'"),
                             mcs);
        goto cleanup;
    }
    if (!(str = context_str(context))) {
        virReportSystemError(errno, "%s",
                             _("Unable to format SELinux context"));
        goto cleanup;
    }
    if (!(ret = strdup(str))) {
        virReportOOMError();
        goto cleanup;
    }
392
    VIR_DEBUG("Generated context '%s'",  ret);
393
cleanup:
394 395
    freecon(ourSecContext);
    context_free(ourContext);
396 397
    context_free(context);
    return ret;
398 399
}

400

401
#ifdef HAVE_SELINUX_LXC_CONTEXTS_PATH
402
static int
403
virSecuritySELinuxLXCInitialize(virSecurityManagerPtr mgr)
404 405 406 407 408 409 410
{
    virConfValuePtr scon = NULL;
    virConfValuePtr tcon = NULL;
    virConfValuePtr dcon = NULL;
    virConfPtr selinux_conf;
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);

411 412
    data->skipAllLabel = true;

413
# if HAVE_SELINUX_LABEL_H
414 415 416 417 418 419
    data->label_handle = selabel_open(SELABEL_CTX_FILE, NULL, 0);
    if (!data->label_handle) {
        virReportSystemError(errno, "%s",
                             _("cannot open SELinux label_handle"));
        return -1;
    }
420
# endif
421

422 423 424 425 426
    selinux_conf = virConfReadFile(selinux_lxc_contexts_path(), 0);
    if (!selinux_conf) {
        virReportSystemError(errno,
                             _("cannot open SELinux lxc contexts file '%s'"),
                             selinux_lxc_contexts_path());
427
        goto error;
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
    }

    scon = virConfGetValue(selinux_conf, "process");
    if (! scon || scon->type != VIR_CONF_STRING || (! scon->str)) {
        virReportSystemError(errno,
                             _("cannot read 'process' value from selinux lxc contexts file '%s'"),
                             selinux_lxc_contexts_path());
        goto error;
    }

    tcon = virConfGetValue(selinux_conf, "file");
    if (! tcon || tcon->type != VIR_CONF_STRING || (! tcon->str)) {
        virReportSystemError(errno,
                             _("cannot read 'file' value from selinux lxc contexts file '%s'"),
                             selinux_lxc_contexts_path());
        goto error;
    }

    dcon = virConfGetValue(selinux_conf, "content");
    if (! dcon || dcon->type != VIR_CONF_STRING || (! dcon->str)) {
        virReportSystemError(errno,
                             _("cannot read 'file' value from selinux lxc contexts file '%s'"),
                             selinux_lxc_contexts_path());
        goto error;
    }

    data->domain_context = strdup(scon->str);
    data->file_context = strdup(tcon->str);
    data->content_context = strdup(dcon->str);
    if (!data->domain_context ||
        !data->file_context ||
        !data->content_context) {
        virReportSystemError(errno,
                             _("cannot allocate memory for LXC SELinux contexts '%s'"),
                             selinux_lxc_contexts_path());
        goto error;
    }
465 466 467 468

    if (!(data->mcs = virHashCreate(10, NULL)))
        goto error;

469 470 471 472
    virConfFree(selinux_conf);
    return 0;

error:
473
# if HAVE_SELINUX_LABEL_H
474
    selabel_close(data->label_handle);
475
# endif
476 477 478 479
    virConfFree(selinux_conf);
    VIR_FREE(data->domain_context);
    VIR_FREE(data->file_context);
    VIR_FREE(data->content_context);
480
    virHashFree(data->mcs);
481 482
    return -1;
}
483 484
#else
static int
485
virSecuritySELinuxLXCInitialize(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED)
486 487 488 489 490 491
{
    virReportSystemError(ENOSYS, "%s",
                         _("libselinux does not support LXC contexts path"));
    return -1;
}
#endif
492 493 494


static int
495
virSecuritySELinuxQEMUInitialize(virSecurityManagerPtr mgr)
496
{
497 498
    char *ptr;
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
499

500 501
    data->skipAllLabel = false;

502 503 504 505 506 507 508 509 510
#if HAVE_SELINUX_LABEL_H
    data->label_handle = selabel_open(SELABEL_CTX_FILE, NULL, 0);
    if (!data->label_handle) {
        virReportSystemError(errno, "%s",
                             _("cannot open SELinux label_handle"));
        return -1;
    }
#endif

511
    if (virFileReadAll(selinux_virtual_domain_context_path(), MAX_CONTEXT, &(data->domain_context)) < 0) {
512
        virReportSystemError(errno,
513
                             _("cannot read SELinux virtual domain context file '%s'"),
514
                             selinux_virtual_domain_context_path());
515
        goto error;
516 517
    }

518
    ptr = strchrnul(data->domain_context, '\n');
519
    if (ptr && *ptr == '\n') {
520
        *ptr = '\0';
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
        ptr++;
        if (*ptr != '\0') {
            data->alt_domain_context = strdup(ptr);
            if (!data->alt_domain_context) {
                virReportOOMError();
                goto error;
            }
            ptr = strchrnul(data->alt_domain_context, '\n');
            if (ptr && *ptr == '\n')
                *ptr = '\0';
        }
    }
    VIR_DEBUG("Loaded domain context '%s', alt domain context '%s'",
              data->domain_context, NULLSTR(data->alt_domain_context));

536

537
    if (virFileReadAll(selinux_virtual_image_context_path(), 2*MAX_CONTEXT, &(data->file_context)) < 0) {
538
        virReportSystemError(errno,
539 540
                             _("cannot read SELinux virtual image context file %s"),
                             selinux_virtual_image_context_path());
541
        goto error;
542 543
    }

544 545
    ptr = strchrnul(data->file_context, '\n');
    if (ptr && *ptr == '\n') {
546
        *ptr = '\0';
547 548 549 550 551 552 553
        data->content_context = strdup(ptr+1);
        if (!data->content_context) {
            virReportOOMError();
            goto error;
        }
        ptr = strchrnul(data->content_context, '\n');
        if (ptr && *ptr == '\n')
554 555
            *ptr = '\0';
    }
556

557 558 559
    VIR_DEBUG("Loaded file context '%s', content context '%s'",
              data->file_context, data->content_context);

560 561 562
    if (!(data->mcs = virHashCreate(10, NULL)))
        goto error;

563
    return 0;
564 565

error:
566 567 568
#if HAVE_SELINUX_LABEL_H
    selabel_close(data->label_handle);
#endif
569
    VIR_FREE(data->domain_context);
570
    VIR_FREE(data->alt_domain_context);
571 572
    VIR_FREE(data->file_context);
    VIR_FREE(data->content_context);
573
    virHashFree(data->mcs);
574
    return -1;
575 576
}

577 578

static int
579
virSecuritySELinuxInitialize(virSecurityManagerPtr mgr)
580 581 582
{
    VIR_DEBUG("SELinuxInitialize %s", virSecurityManagerGetDriver(mgr));
    if (STREQ(virSecurityManagerGetDriver(mgr),  "LXC")) {
583
        return virSecuritySELinuxLXCInitialize(mgr);
584
    } else {
585
        return virSecuritySELinuxQEMUInitialize(mgr);
586 587 588 589
    }
}


590
static int
591 592
virSecuritySELinuxGenSecurityLabel(virSecurityManagerPtr mgr,
                                   virDomainDefPtr def)
593 594
{
    int rc = -1;
595
    char *mcs = NULL;
596
    char *scontext = NULL;
597
    context_t ctx = NULL;
598
    const char *range;
599 600
    virSecurityLabelDefPtr seclabel;
    virSecuritySELinuxDataPtr data;
601
    const char *baselabel;
602 603
    char *sens = NULL;
    int catMin, catMax;
604

605 606 607 608 609 610 611 612 613 614
    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (seclabel == NULL) {
        return rc;
    }

    data = virSecurityManagerGetPrivateData(mgr);

    VIR_DEBUG("label=%s", virSecurityManagerGetDriver(mgr));
    if (seclabel->type == VIR_DOMAIN_SECLABEL_DYNAMIC &&
        seclabel->label) {
615 616
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("security label already defined for VM"));
617
        return rc;
D
Daniel P. Berrange 已提交
618
    }
619

620
    if (seclabel->imagelabel) {
621 622
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("security image label already defined for VM"));
623 624 625
        return rc;
    }

626 627
    if (seclabel->model &&
        STRNEQ(seclabel->model, SECURITY_SELINUX_NAME)) {
628 629
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label model %s is not supported with selinux"),
630
                       seclabel->model);
631 632 633
        return rc;
    }

634
    VIR_DEBUG("type=%d", seclabel->type);
635

636
    switch (seclabel->type) {
637
    case VIR_DOMAIN_SECLABEL_STATIC:
638
        if (!(ctx = context_new(seclabel->label))) {
639 640
            virReportSystemError(errno,
                                 _("unable to allocate socket security context '%s'"),
641
                                 seclabel->label);
642
            return rc;
643 644
        }

645
        range = context_range_get(ctx);
646 647 648 649 650
        if (!range ||
            !(mcs = strdup(range))) {
            virReportOOMError();
            goto cleanup;
        }
651 652 653
        break;

    case VIR_DOMAIN_SECLABEL_DYNAMIC:
654 655 656 657 658 659 660 661 662
        if (virSecuritySELinuxMCSGetProcessRange(&sens,
                                                 &catMin,
                                                 &catMax) < 0)
            goto cleanup;

        if (!(mcs = virSecuritySELinuxMCSFind(mgr,
                                              sens,
                                              catMin,
                                              catMax)))
663 664 665 666
            goto cleanup;

        if (virSecuritySELinuxMCSAdd(mgr, mcs) < 0)
            goto cleanup;
667

668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
        baselabel = seclabel->baselabel;
        if (!baselabel) {
            if (def->virtType == VIR_DOMAIN_VIRT_QEMU) {
                if (data->alt_domain_context == NULL) {
                    static bool warned = false;
                    if (!warned) {
                        VIR_WARN("SELinux policy does not define a domain type for QEMU TCG. "
                                 "Guest startup may be denied due to missing 'execmem' privilege "
                                 "unless the 'virt_use_execmem' policy boolean is enabled");
                        warned = true;
                    }
                    baselabel = data->domain_context;
                } else {
                    baselabel = data->alt_domain_context;
                }
            } else {
                baselabel = data->domain_context;
            }
        }

688 689
        seclabel->label = virSecuritySELinuxGenNewContext(baselabel, mcs, false);
        if (!seclabel->label)
690
            goto cleanup;
691

692 693 694 695 696 697 698
        break;

    case VIR_DOMAIN_SECLABEL_NONE:
        /* no op */
        break;

    default:
699 700
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected security label type '%s'"),
701
                       virDomainSeclabelTypeToString(seclabel->type));
702
        goto cleanup;
D
Daniel P. Berrange 已提交
703
    }
704

705
    if (!seclabel->norelabel) {
706
        seclabel->imagelabel = virSecuritySELinuxGenNewContext(data->file_context,
707 708
                                                               mcs,
                                                               true);
709
        if (!seclabel->imagelabel)
710 711 712
            goto cleanup;
    }

713 714
    if (!seclabel->model &&
        !(seclabel->model = strdup(SECURITY_SELINUX_NAME))) {
715
        virReportOOMError();
716
        goto cleanup;
D
Daniel P. Berrange 已提交
717 718
    }

719
    rc = 0;
720 721 722

cleanup:
    if (rc != 0) {
723 724 725 726 727 728
        if (seclabel->type == VIR_DOMAIN_SECLABEL_DYNAMIC)
            VIR_FREE(seclabel->label);
        VIR_FREE(seclabel->imagelabel);
        if (seclabel->type == VIR_DOMAIN_SECLABEL_DYNAMIC &&
            !seclabel->baselabel)
            VIR_FREE(seclabel->model);
729 730 731 732
    }

    if (ctx)
        context_free(ctx);
D
Daniel P. Berrange 已提交
733
    VIR_FREE(scontext);
734
    VIR_FREE(mcs);
735
    VIR_FREE(sens);
736 737

    VIR_DEBUG("model=%s label=%s imagelabel=%s baselabel=%s",
738 739 740 741
              NULLSTR(seclabel->model),
              NULLSTR(seclabel->label),
              NULLSTR(seclabel->imagelabel),
              NULLSTR(seclabel->baselabel));
742

743 744 745
    return rc;
}

746
static int
747
virSecuritySELinuxReserveSecurityLabel(virSecurityManagerPtr mgr,
748 749
                                       virDomainDefPtr def,
                                       pid_t pid)
750 751 752 753
{
    security_context_t pctx;
    context_t ctx = NULL;
    const char *mcs;
754
    int rv;
755
    virSecurityLabelDefPtr seclabel;
756

757 758 759 760 761 762
    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (seclabel == NULL) {
        return -1;
    }

    if (seclabel->type == VIR_DOMAIN_SECLABEL_STATIC)
763 764
        return 0;

M
Martin Kletzander 已提交
765
    if (getpidcon_raw(pid, &pctx) == -1) {
766
        virReportSystemError(errno,
767
                             _("unable to get PID %d security context"), pid);
768 769 770 771
        return -1;
    }

    ctx = context_new(pctx);
772
    freecon(pctx);
773
    if (!ctx)
774
        goto error;
775 776 777

    mcs = context_range_get(ctx);
    if (!mcs)
778 779
        goto error;

780
    if ((rv = virSecuritySELinuxMCSAdd(mgr, mcs)) < 0)
781
        goto error;
782

783 784 785 786 787 788
    if (rv == 1) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("MCS level for existing domain label %s already reserved"),
                       (char*)pctx);
        goto error;
    }
789 790 791 792 793

    context_free(ctx);

    return 0;

794
error:
795 796 797 798 799
    context_free(ctx);
    return -1;
}


800
static int
801
virSecuritySELinuxSecurityDriverProbe(const char *virtDriver)
802
{
803 804 805
    if (!is_selinux_enabled())
        return SECURITY_DRIVER_DISABLE;

806 807 808 809 810 811
    if (virtDriver && STREQ(virtDriver, "LXC")) {
#if HAVE_SELINUX_LXC_CONTEXTS_PATH
        if (!virFileExists(selinux_lxc_contexts_path()))
#endif
            return SECURITY_DRIVER_DISABLE;
    }
812 813

    return SECURITY_DRIVER_ENABLE;
814 815
}

816

817
static int
818
virSecuritySELinuxSecurityDriverOpen(virSecurityManagerPtr mgr)
819
{
820
    return virSecuritySELinuxInitialize(mgr);
821 822
}

823

824
static int
825
virSecuritySELinuxSecurityDriverClose(virSecurityManagerPtr mgr)
826
{
827 828 829 830 831
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);

    if (!data)
        return 0;

832 833 834 835
#if HAVE_SELINUX_LABEL_H
    selabel_close(data->label_handle);
#endif

836 837
    virHashFree(data->mcs);

838
    VIR_FREE(data->domain_context);
839
    VIR_FREE(data->alt_domain_context);
840 841 842
    VIR_FREE(data->file_context);
    VIR_FREE(data->content_context);

843 844 845 846
    return 0;
}


847 848
static const char *
virSecuritySELinuxSecurityGetModel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED)
849 850 851 852
{
    return SECURITY_SELINUX_NAME;
}

853 854
static const char *
virSecuritySELinuxSecurityGetDOI(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED)
855 856 857 858 859
{
    /*
     * Where will the DOI come from?  SELinux configuration, or qemu
     * configuration? For the moment, we'll just set it to "0".
     */
860
    return SECURITY_SELINUX_VOID_DOI;
861 862 863
}

static int
864 865 866 867
virSecuritySELinuxGetSecurityProcessLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                          virDomainDefPtr def ATTRIBUTE_UNUSED,
                                          pid_t pid,
                                          virSecurityLabelPtr sec)
868 869 870
{
    security_context_t ctx;

M
Martin Kletzander 已提交
871
    if (getpidcon_raw(pid, &ctx) == -1) {
872
        virReportSystemError(errno,
873
                             _("unable to get PID %d security context"),
874
                             pid);
875 876 877 878
        return -1;
    }

    if (strlen((char *) ctx) >= VIR_SECURITY_LABEL_BUFLEN) {
879 880 881 882
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label exceeds "
                         "maximum length: %d"),
                       VIR_SECURITY_LABEL_BUFLEN - 1);
883
        freecon(ctx);
884 885 886 887
        return -1;
    }

    strcpy(sec->label, (char *) ctx);
888
    freecon(ctx);
889

890
    VIR_DEBUG("label=%s", sec->label);
891 892
    sec->enforcing = security_getenforce();
    if (sec->enforcing == -1) {
893
        virReportSystemError(errno, "%s",
894
                             _("error calling security_getenforce()"));
895 896 897 898 899 900
        return -1;
    }

    return 0;
}

901 902 903
/* Attempt to change the label of PATH to TCON.  If OPTIONAL is true,
 * return 1 if labelling was not possible.  Otherwise, require a label
 * change, and return 0 for success, -1 for failure.  */
904
static int
905
virSecuritySELinuxSetFileconHelper(const char *path, char *tcon, bool optional)
906
{
907
    security_context_t econ;
908

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

M
Martin Kletzander 已提交
911
    if (setfilecon_raw(path, tcon) < 0) {
912 913
        int setfilecon_errno = errno;

M
Martin Kletzander 已提交
914
        if (getfilecon_raw(path, &econ) >= 0) {
915 916 917
            if (STREQ(tcon, econ)) {
                freecon(econ);
                /* It's alright, there's nothing to change anyway. */
918
                return optional ? 1 : 0;
919 920 921
            }
            freecon(econ);
        }
922 923

        /* if the error complaint is related to an image hosted on
924 925
         * an nfs mount, or a usbfs/sysfs filesystem not supporting
         * labelling, then just ignore it & hope for the best.
926
         * The user hopefully set one of the necessary SELinux
927
         * virt_use_{nfs,usb,pci}  boolean tunables to allow it...
928
         */
929
        if (setfilecon_errno != EOPNOTSUPP && setfilecon_errno != ENOTSUP) {
930
            virReportSystemError(setfilecon_errno,
931
                                 _("unable to set security context '%s' on '%s'"),
932
                                 tcon, path);
933 934
            if (security_getenforce() == 1)
                return -1;
935
        } else {
936 937 938 939 940 941 942 943 944 945 946 947 948 949
            const char *msg;
            if ((virStorageFileIsSharedFSType(path,
                                              VIR_STORAGE_FILE_SHFS_NFS) == 1) &&
                security_get_boolean_active("virt_use_nfs") != 1) {
                msg = _("Setting security context '%s' on '%s' not supported. "
                        "Consider setting virt_use_nfs");
               if (security_getenforce() == 1)
                   VIR_WARN(msg, tcon, path);
               else
                   VIR_INFO(msg, tcon, path);
            } else {
                VIR_INFO("Setting security context '%s' on '%s' not supported",
                         tcon, path);
            }
950 951
            if (optional)
                return 1;
952
        }
953 954 955 956
    }
    return 0;
}

957
static int
958
virSecuritySELinuxSetFileconOptional(const char *path, char *tcon)
959
{
960
    return virSecuritySELinuxSetFileconHelper(path, tcon, true);
961 962 963
}

static int
964
virSecuritySELinuxSetFilecon(const char *path, char *tcon)
965
{
966
    return virSecuritySELinuxSetFileconHelper(path, tcon, false);
967 968
}

969
static int
970
virSecuritySELinuxFSetFilecon(int fd, char *tcon)
971 972 973 974 975
{
    security_context_t econ;

    VIR_INFO("Setting SELinux context on fd %d to '%s'", fd, tcon);

M
Martin Kletzander 已提交
976
    if (fsetfilecon_raw(fd, tcon) < 0) {
977 978
        int fsetfilecon_errno = errno;

M
Martin Kletzander 已提交
979
        if (fgetfilecon_raw(fd, &econ) >= 0) {
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
            if (STREQ(tcon, econ)) {
                freecon(econ);
                /* It's alright, there's nothing to change anyway. */
                return 0;
            }
            freecon(econ);
        }

        /* if the error complaint is related to an image hosted on
         * 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 necessary SELinux
         * virt_use_{nfs,usb,pci}  boolean tunables to allow it...
         */
        if (fsetfilecon_errno != EOPNOTSUPP) {
            virReportSystemError(fsetfilecon_errno,
                                 _("unable to set security context '%s' on fd %d"),
                                 tcon, fd);
            if (security_getenforce() == 1)
                return -1;
        } else {
            VIR_INFO("Setting security context '%s' on fd %d not supported",
                     tcon, fd);
        }
    }
    return 0;
}

E
Eric Blake 已提交
1008 1009
/* Set fcon to the appropriate label for path and mode, or return -1.  */
static int
1010
getContext(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
1011
           const char *newpath, mode_t mode, security_context_t *fcon)
E
Eric Blake 已提交
1012 1013
{
#if HAVE_SELINUX_LABEL_H
1014
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
E
Eric Blake 已提交
1015

1016
    return selabel_lookup_raw(data->label_handle, fcon, newpath, mode);
E
Eric Blake 已提交
1017 1018 1019 1020 1021
#else
    return matchpathcon(newpath, mode, fcon);
#endif
}

1022 1023 1024

/* This method shouldn't raise errors, since they'll overwrite
 * errors that the caller(s) are already dealing with */
1025
static int
1026 1027
virSecuritySELinuxRestoreSecurityFileLabel(virSecurityManagerPtr mgr,
                                           const char *path)
1028
{
1029 1030 1031 1032
    struct stat buf;
    security_context_t fcon = NULL;
    int rc = -1;
    char *newpath = NULL;
1033
    char ebuf[1024];
1034

1035 1036
    VIR_INFO("Restoring SELinux context on '%s'", path);

1037
    if (virFileResolveLink(path, &newpath) < 0) {
1038 1039
        VIR_WARN("cannot resolve symlink %s: %s", path,
                 virStrerror(errno, ebuf, sizeof(ebuf)));
D
Daniel P. Berrange 已提交
1040
        goto err;
1041
    }
1042

1043
    if (stat(newpath, &buf) != 0) {
1044 1045
        VIR_WARN("cannot stat %s: %s", newpath,
                 virStrerror(errno, ebuf, sizeof(ebuf)));
D
Daniel P. Berrange 已提交
1046
        goto err;
1047
    }
D
Daniel P. Berrange 已提交
1048

1049
    if (getContext(mgr, newpath, buf.st_mode, &fcon) < 0) {
1050 1051 1052
        /* Any user created path likely does not have a default label,
         * which makes this an expected non error
         */
1053
        VIR_WARN("cannot lookup default selinux label for %s", newpath);
1054
        rc = 0;
1055
    } else {
1056
        rc = virSecuritySELinuxSetFilecon(newpath, fcon);
1057
    }
1058

1059
err:
1060
    freecon(fcon);
1061 1062
    VIR_FREE(newpath);
    return rc;
1063 1064
}

1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141

static int
virSecuritySELinuxSetSecurityTPMFileLabel(virSecurityManagerPtr mgr,
                                          virDomainDefPtr def,
                                          virDomainTPMDefPtr tpm)
{
    int rc;
    virSecurityLabelDefPtr seclabel;
    char *cancel_path;
    const char *tpmdev;

    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (seclabel == NULL)
        return -1;

    switch (tpm->type) {
    case VIR_DOMAIN_TPM_TYPE_PASSTHROUGH:
        tpmdev = tpm->data.passthrough.source.data.file.path;
        rc = virSecuritySELinuxSetFilecon(tpmdev, seclabel->imagelabel);
        if (rc < 0)
            return -1;

        if ((cancel_path = virTPMCreateCancelPath(tpmdev)) != NULL) {
            rc = virSecuritySELinuxSetFilecon(cancel_path,
                                              seclabel->imagelabel);
            VIR_FREE(cancel_path);
            if (rc < 0) {
                virSecuritySELinuxRestoreSecurityTPMFileLabelInt(mgr, def,
                                                                 tpm);
                return -1;
            }
        } else {
            return -1;
        }
        break;
    case VIR_DOMAIN_TPM_TYPE_LAST:
        break;
    }

    return 0;
}


static int
virSecuritySELinuxRestoreSecurityTPMFileLabelInt(virSecurityManagerPtr mgr,
                                                 virDomainDefPtr def,
                                                 virDomainTPMDefPtr tpm)
{
    int rc = 0;
    virSecurityLabelDefPtr seclabel;
    char *cancel_path;
    const char *tpmdev;

    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (seclabel == NULL)
        return -1;

    switch (tpm->type) {
    case VIR_DOMAIN_TPM_TYPE_PASSTHROUGH:
        tpmdev = tpm->data.passthrough.source.data.file.path;
        rc = virSecuritySELinuxRestoreSecurityFileLabel(mgr, tpmdev);

        if ((cancel_path = virTPMCreateCancelPath(tpmdev)) != NULL) {
            if (virSecuritySELinuxRestoreSecurityFileLabel(mgr,
                                  cancel_path) < 0)
                rc = -1;
            VIR_FREE(cancel_path);
        }
        break;
    case VIR_DOMAIN_TPM_TYPE_LAST:
        break;
    }

    return rc;
}


1142
static int
1143
virSecuritySELinuxRestoreSecurityImageLabelInt(virSecurityManagerPtr mgr,
1144 1145 1146
                                               virDomainDefPtr def,
                                               virDomainDiskDefPtr disk,
                                               int migrated)
1147
{
1148 1149 1150 1151 1152 1153
    virSecurityLabelDefPtr seclabel;
    virSecurityDeviceLabelDefPtr disk_seclabel;

    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (seclabel == NULL)
        return -1;
1154

1155 1156 1157
    disk_seclabel = virDomainDiskDefGetSecurityLabelDef(disk,
                                                        SECURITY_SELINUX_NAME);
    if (seclabel->norelabel || (disk_seclabel && disk_seclabel->norelabel))
1158 1159
        return 0;

1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
    /* 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;

1171
    if (!disk->src || disk->type == VIR_DOMAIN_DISK_TYPE_NETWORK)
1172 1173
        return 0;

1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
    /* If we have a shared FS & doing migrated, we must not
     * change ownership, because that kills access on the
     * destination host which is sub-optimal for the guest
     * VM's I/O attempts :-)
     */
    if (migrated) {
        int rc = virStorageFileIsSharedFS(disk->src);
        if (rc < 0)
            return -1;
        if (rc == 1) {
            VIR_DEBUG("Skipping image label restore on %s because FS is shared",
                      disk->src);
            return 0;
        }
    }

1190
    return virSecuritySELinuxRestoreSecurityFileLabel(mgr, disk->src);
1191 1192
}

1193 1194

static int
1195 1196 1197
virSecuritySELinuxRestoreSecurityImageLabel(virSecurityManagerPtr mgr,
                                            virDomainDefPtr def,
                                            virDomainDiskDefPtr disk)
1198
{
1199
    return virSecuritySELinuxRestoreSecurityImageLabelInt(mgr, def, disk, 0);
1200 1201 1202
}


1203
static int
1204 1205 1206 1207
virSecuritySELinuxSetSecurityFileLabel(virDomainDiskDefPtr disk,
                                       const char *path,
                                       size_t depth,
                                       void *opaque)
1208
{
1209 1210
    int ret;
    virSecurityDeviceLabelDefPtr disk_seclabel;
1211 1212 1213
    virSecuritySELinuxCallbackDataPtr cbdata = opaque;
    const virSecurityLabelDefPtr secdef = cbdata->secdef;
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(cbdata->manager);
1214

1215 1216 1217 1218
    disk_seclabel = virDomainDiskDefGetSecurityLabelDef(disk,
                                                        SECURITY_SELINUX_NAME);

    if (disk_seclabel && disk_seclabel->norelabel)
1219 1220
        return 0;

1221 1222 1223
    if (disk_seclabel && !disk_seclabel->norelabel &&
        disk_seclabel->label) {
        ret = virSecuritySELinuxSetFilecon(path, disk_seclabel->label);
1224
    } else if (depth == 0) {
1225

1226
        if (disk->shared) {
1227
            ret = virSecuritySELinuxSetFileconOptional(path, data->file_context);
1228
        } else if (disk->readonly) {
1229
            ret = virSecuritySELinuxSetFileconOptional(path, data->content_context);
1230
        } else if (secdef->imagelabel) {
1231
            ret = virSecuritySELinuxSetFileconOptional(path, secdef->imagelabel);
1232
        } else {
1233
            ret = 0;
1234 1235
        }
    } else {
1236
        ret = virSecuritySELinuxSetFileconOptional(path, data->content_context);
1237
    }
1238
    if (ret == 1 && !disk_seclabel) {
1239 1240
        /* If we failed to set a label, but virt_use_nfs let us
         * proceed anyway, then we don't need to relabel later.  */
1241
        disk_seclabel = virDomainDiskDefGenSecurityLabelDef(SECURITY_SELINUX_NAME);
1242
        if (!disk_seclabel)
1243
            return -1;
1244
        disk_seclabel->norelabel = true;
1245 1246 1247 1248 1249
        if (VIR_APPEND_ELEMENT(disk->seclabels, disk->nseclabels, disk_seclabel) < 0) {
            virReportOOMError();
            virSecurityDeviceLabelDefFree(disk_seclabel);
            return -1;
        }
1250
        ret = 0;
1251
    }
1252
    return ret;
1253 1254
}

1255
static int
1256 1257 1258
virSecuritySELinuxSetSecurityImageLabel(virSecurityManagerPtr mgr,
                                        virDomainDefPtr def,
                                        virDomainDiskDefPtr disk)
1259 1260

{
1261 1262
    virSecuritySELinuxCallbackData cbdata;
    cbdata.manager = mgr;
1263
    cbdata.secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
1264

1265 1266
    if (cbdata.secdef == NULL)
        return -1;
1267

1268
    if (cbdata.secdef->norelabel)
1269 1270
        return 0;

1271 1272 1273
    if (disk->type == VIR_DOMAIN_DISK_TYPE_NETWORK)
        return 0;

1274
    return virDomainDiskDefForeachPath(disk,
1275
                                       true,
1276
                                       virSecuritySELinuxSetSecurityFileLabel,
1277
                                       &cbdata);
1278 1279
}

1280 1281

static int
1282
virSecuritySELinuxSetSecurityPCILabel(virPCIDevicePtr dev ATTRIBUTE_UNUSED,
1283
                                      const char *file, void *opaque)
1284
{
1285
    virSecurityLabelDefPtr secdef;
1286
    virDomainDefPtr def = opaque;
1287

1288 1289 1290
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        return -1;
1291
    return virSecuritySELinuxSetFilecon(file, secdef->imagelabel);
1292 1293 1294
}

static int
1295
virSecuritySELinuxSetSecurityUSBLabel(virUSBDevicePtr dev ATTRIBUTE_UNUSED,
1296
                                      const char *file, void *opaque)
1297
{
1298
    virSecurityLabelDefPtr secdef;
1299
    virDomainDefPtr def = opaque;
1300 1301 1302 1303

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        return -1;
1304

1305
    return virSecuritySELinuxSetFilecon(file, secdef->imagelabel);
1306 1307
}

1308

1309
static int
1310 1311 1312
virSecuritySELinuxSetSecurityHostdevSubsysLabel(virDomainDefPtr def,
                                                virDomainHostdevDefPtr dev,
                                                const char *vroot)
1313 1314 1315 1316 1317 1318

{
    int ret = -1;

    switch (dev->source.subsys.type) {
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB: {
1319
        virUSBDevicePtr usb;
1320

1321 1322 1323
        if (dev->missing)
            return 0;

1324 1325 1326
        usb = virUSBDeviceNew(dev->source.subsys.u.usb.bus,
                              dev->source.subsys.u.usb.device,
                              vroot);
1327 1328
        if (!usb)
            goto done;
1329

1330 1331
        ret = virUSBDeviceFileIterate(usb, virSecuritySELinuxSetSecurityUSBLabel, def);
        virUSBDeviceFree(usb);
M
Mark McLoughlin 已提交
1332
        break;
1333 1334 1335
    }

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI: {
1336
        virPCIDevicePtr pci =
1337 1338 1339 1340
            virPCIDeviceNew(dev->source.subsys.u.pci.addr.domain,
                            dev->source.subsys.u.pci.addr.bus,
                            dev->source.subsys.u.pci.addr.slot,
                            dev->source.subsys.u.pci.addr.function);
1341 1342 1343 1344

        if (!pci)
            goto done;

1345 1346
        ret = virPCIDeviceFileIterate(pci, virSecuritySELinuxSetSecurityPCILabel, def);
        virPCIDeviceFree(pci);
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359

        break;
    }

    default:
        ret = 0;
        break;
    }

done:
    return ret;
}

1360

1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
static int
virSecuritySELinuxSetSecurityHostdevCapsLabel(virDomainDefPtr def,
                                              virDomainHostdevDefPtr dev,
                                              const char *vroot)
{
    int ret = -1;
    virSecurityLabelDefPtr secdef;
    char *path;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        return -1;

    switch (dev->source.caps.type) {
    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_STORAGE: {
        if (vroot) {
            if (virAsprintf(&path, "%s/%s", vroot,
                            dev->source.caps.u.storage.block) < 0) {
                virReportOOMError();
                return -1;
            }
        } else {
            if (!(path = strdup(dev->source.caps.u.storage.block))) {
                virReportOOMError();
                return -1;
            }
        }
        ret = virSecuritySELinuxSetFilecon(path, secdef->imagelabel);
        VIR_FREE(path);
        break;
    }

    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_MISC: {
        if (vroot) {
            if (virAsprintf(&path, "%s/%s", vroot,
                            dev->source.caps.u.misc.chardev) < 0) {
                virReportOOMError();
                return -1;
            }
        } else {
            if (!(path = strdup(dev->source.caps.u.misc.chardev))) {
                virReportOOMError();
                return -1;
            }
        }
        ret = virSecuritySELinuxSetFilecon(path, secdef->imagelabel);
        VIR_FREE(path);
        break;
    }

    default:
        ret = 0;
        break;
    }

    return ret;
}


1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
static int
virSecuritySELinuxSetSecurityHostdevLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                          virDomainDefPtr def,
                                          virDomainHostdevDefPtr dev,
                                          const char *vroot)

{
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        return -1;

    if (secdef->norelabel)
        return 0;

    switch (dev->mode) {
    case VIR_DOMAIN_HOSTDEV_MODE_SUBSYS:
        return virSecuritySELinuxSetSecurityHostdevSubsysLabel(def, dev, vroot);

1440 1441 1442
    case VIR_DOMAIN_HOSTDEV_MODE_CAPABILITIES:
        return virSecuritySELinuxSetSecurityHostdevCapsLabel(def, dev, vroot);

1443 1444 1445 1446 1447 1448
    default:
        return 0;
    }
}


1449
static int
1450
virSecuritySELinuxRestoreSecurityPCILabel(virPCIDevicePtr dev ATTRIBUTE_UNUSED,
1451
                                          const char *file,
1452
                                          void *opaque)
1453
{
1454 1455 1456
    virSecurityManagerPtr mgr = opaque;

    return virSecuritySELinuxRestoreSecurityFileLabel(mgr, file);
1457 1458 1459
}

static int
1460
virSecuritySELinuxRestoreSecurityUSBLabel(virUSBDevicePtr dev ATTRIBUTE_UNUSED,
1461
                                          const char *file,
1462
                                          void *opaque)
1463
{
1464 1465 1466
    virSecurityManagerPtr mgr = opaque;

    return virSecuritySELinuxRestoreSecurityFileLabel(mgr, file);
1467 1468
}

1469

1470
static int
1471 1472
virSecuritySELinuxRestoreSecurityHostdevSubsysLabel(virSecurityManagerPtr mgr,
                                                    virDomainHostdevDefPtr dev,
1473
                                                    const char *vroot)
1474 1475 1476 1477 1478 1479

{
    int ret = -1;

    switch (dev->source.subsys.type) {
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB: {
1480
        virUSBDevicePtr usb;
1481 1482 1483

        if (dev->missing)
            return 0;
1484

1485 1486 1487
        usb = virUSBDeviceNew(dev->source.subsys.u.usb.bus,
                              dev->source.subsys.u.usb.device,
                              vroot);
1488 1489 1490
        if (!usb)
            goto done;

1491 1492
        ret = virUSBDeviceFileIterate(usb, virSecuritySELinuxRestoreSecurityUSBLabel, mgr);
        virUSBDeviceFree(usb);
1493 1494 1495 1496 1497

        break;
    }

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI: {
1498
        virPCIDevicePtr pci =
1499 1500 1501 1502
            virPCIDeviceNew(dev->source.subsys.u.pci.addr.domain,
                            dev->source.subsys.u.pci.addr.bus,
                            dev->source.subsys.u.pci.addr.slot,
                            dev->source.subsys.u.pci.addr.function);
1503 1504 1505 1506

        if (!pci)
            goto done;

1507 1508
        ret = virPCIDeviceFileIterate(pci, virSecuritySELinuxRestoreSecurityPCILabel, mgr);
        virPCIDeviceFree(pci);
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521

        break;
    }

    default:
        ret = 0;
        break;
    }

done:
    return ret;
}

1522

1523
static int
1524 1525
virSecuritySELinuxRestoreSecurityHostdevCapsLabel(virSecurityManagerPtr mgr,
                                                  virDomainHostdevDefPtr dev,
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
                                                  const char *vroot)
{
    int ret = -1;
    char *path;

    switch (dev->source.caps.type) {
    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_STORAGE: {
        if (vroot) {
            if (virAsprintf(&path, "%s/%s", vroot,
                            dev->source.caps.u.storage.block) < 0) {
                virReportOOMError();
                return -1;
            }
        } else {
            if (!(path = strdup(dev->source.caps.u.storage.block))) {
                virReportOOMError();
                return -1;
            }
        }
1545
        ret = virSecuritySELinuxRestoreSecurityFileLabel(mgr, path);
1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
        VIR_FREE(path);
        break;
    }

    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_MISC: {
        if (vroot) {
            if (virAsprintf(&path, "%s/%s", vroot,
                            dev->source.caps.u.misc.chardev) < 0) {
                virReportOOMError();
                return -1;
            }
        } else {
            if (!(path = strdup(dev->source.caps.u.misc.chardev))) {
                virReportOOMError();
                return -1;
            }
        }
1563
        ret = virSecuritySELinuxRestoreSecurityFileLabel(mgr, path);
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
        VIR_FREE(path);
        break;
    }

    default:
        ret = 0;
        break;
    }

    return ret;
}


1577
static int
1578
virSecuritySELinuxRestoreSecurityHostdevLabel(virSecurityManagerPtr mgr,
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
                                              virDomainDefPtr def,
                                              virDomainHostdevDefPtr dev,
                                              const char *vroot)

{
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        return -1;

    if (secdef->norelabel)
        return 0;

    switch (dev->mode) {
    case VIR_DOMAIN_HOSTDEV_MODE_SUBSYS:
1595
        return virSecuritySELinuxRestoreSecurityHostdevSubsysLabel(mgr, dev, vroot);
1596

1597
    case VIR_DOMAIN_HOSTDEV_MODE_CAPABILITIES:
1598
        return virSecuritySELinuxRestoreSecurityHostdevCapsLabel(mgr, dev, vroot);
1599

1600 1601 1602 1603 1604 1605
    default:
        return 0;
    }
}


1606
static int
1607
virSecuritySELinuxSetSecurityChardevLabel(virDomainDefPtr def,
1608 1609
                                          virDomainChrDefPtr dev,
                                          virDomainChrSourceDefPtr dev_source)
1610 1611

{
1612 1613 1614
    virSecurityLabelDefPtr seclabel;
    virSecurityDeviceLabelDefPtr chr_seclabel = NULL;
    char *imagelabel = NULL;
1615 1616 1617
    char *in = NULL, *out = NULL;
    int ret = -1;

1618 1619
    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (seclabel == NULL)
1620 1621
        return -1;

1622 1623 1624 1625 1626
    if (dev)
        chr_seclabel = virDomainChrDefGetSecurityLabelDef(dev,
                                                          SECURITY_SELINUX_NAME);

    if (seclabel->norelabel || (chr_seclabel && chr_seclabel->norelabel))
1627 1628
        return 0;

1629 1630 1631 1632 1633 1634
    if (chr_seclabel)
        imagelabel = chr_seclabel->label;
    if (!imagelabel)
        imagelabel = seclabel->imagelabel;

    switch (dev_source->type) {
1635 1636
    case VIR_DOMAIN_CHR_TYPE_DEV:
    case VIR_DOMAIN_CHR_TYPE_FILE:
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
        ret = virSecuritySELinuxSetFilecon(dev_source->data.file.path,
                                           imagelabel);
        break;

    case VIR_DOMAIN_CHR_TYPE_UNIX:
        if (!dev_source->data.nix.listen) {
            if (virSecuritySELinuxSetFilecon(dev_source->data.file.path,
                                             imagelabel) < 0)
                goto done;
        }
        ret = 0;
1648 1649 1650
        break;

    case VIR_DOMAIN_CHR_TYPE_PIPE:
1651 1652
        if ((virAsprintf(&in, "%s.in", dev_source->data.file.path) < 0) ||
            (virAsprintf(&out, "%s.out", dev_source->data.file.path) < 0)) {
1653 1654 1655 1656
            virReportOOMError();
            goto done;
        }
        if (virFileExists(in) && virFileExists(out)) {
1657 1658
            if ((virSecuritySELinuxSetFilecon(in, imagelabel) < 0) ||
                (virSecuritySELinuxSetFilecon(out, imagelabel) < 0)) {
1659
                goto done;
1660
            }
1661 1662
        } else if (virSecuritySELinuxSetFilecon(dev_source->data.file.path,
                                                imagelabel) < 0) {
1663
            goto done;
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
        }
        ret = 0;
        break;

    default:
        ret = 0;
        break;
    }

done:
    VIR_FREE(in);
    VIR_FREE(out);
    return ret;
}

static int
1680 1681
virSecuritySELinuxRestoreSecurityChardevLabel(virSecurityManagerPtr mgr,
                                              virDomainDefPtr def,
1682 1683
                                              virDomainChrDefPtr dev,
                                              virDomainChrSourceDefPtr dev_source)
1684 1685

{
1686 1687
    virSecurityLabelDefPtr seclabel;
    virSecurityDeviceLabelDefPtr chr_seclabel = NULL;
1688 1689 1690
    char *in = NULL, *out = NULL;
    int ret = -1;

1691 1692
    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (seclabel == NULL)
1693 1694
        return -1;

1695 1696 1697 1698
    if (dev)
        chr_seclabel = virDomainChrDefGetSecurityLabelDef(dev,
                                                          SECURITY_SELINUX_NAME);
    if (seclabel->norelabel || (chr_seclabel && chr_seclabel->norelabel))
1699 1700
        return 0;

1701
    switch (dev_source->type) {
1702 1703
    case VIR_DOMAIN_CHR_TYPE_DEV:
    case VIR_DOMAIN_CHR_TYPE_FILE:
1704
        if (virSecuritySELinuxRestoreSecurityFileLabel(mgr, dev_source->data.file.path) < 0)
1705 1706
            goto done;
        ret = 0;
1707
        break;
1708 1709 1710

    case VIR_DOMAIN_CHR_TYPE_UNIX:
        if (!dev_source->data.nix.listen) {
1711
            if (virSecuritySELinuxRestoreSecurityFileLabel(mgr, dev_source->data.file.path) < 0)
1712 1713 1714 1715 1716
                goto done;
        }
        ret = 0;
        break;

1717
    case VIR_DOMAIN_CHR_TYPE_PIPE:
1718 1719
        if ((virAsprintf(&out, "%s.out", dev_source->data.file.path) < 0) ||
            (virAsprintf(&in, "%s.in", dev_source->data.file.path) < 0)) {
1720 1721 1722
            virReportOOMError();
            goto done;
        }
1723
        if (virFileExists(in) && virFileExists(out)) {
1724 1725
            if ((virSecuritySELinuxRestoreSecurityFileLabel(mgr, out) < 0) ||
                (virSecuritySELinuxRestoreSecurityFileLabel(mgr, in) < 0)) {
1726 1727
                goto done;
            }
1728
        } else if (virSecuritySELinuxRestoreSecurityFileLabel(mgr, dev_source->data.file.path) < 0) {
1729
            goto done;
1730
        }
1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
        ret = 0;
        break;

    default:
        ret = 0;
        break;
    }

done:
    VIR_FREE(in);
    VIR_FREE(out);
    return ret;
}


static int
1747 1748
virSecuritySELinuxRestoreSecurityChardevCallback(virDomainDefPtr def,
                                                 virDomainChrDefPtr dev,
1749
                                                 void *opaque)
1750
{
1751 1752
    virSecurityManagerPtr mgr = opaque;

1753 1754 1755 1756 1757
    /* This is taken care of by processing of def->serials */
    if (dev->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE &&
        dev->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL)
        return 0;

1758
    return virSecuritySELinuxRestoreSecurityChardevLabel(mgr, def, dev,
1759
                                                         &dev->source);
1760 1761 1762
}


E
Eric Blake 已提交
1763
static int
1764 1765
virSecuritySELinuxRestoreSecuritySmartcardCallback(virDomainDefPtr def,
                                                   virDomainSmartcardDefPtr dev,
1766
                                                   void *opaque)
E
Eric Blake 已提交
1767
{
1768
    virSecurityManagerPtr mgr = opaque;
E
Eric Blake 已提交
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778
    const char *database;

    switch (dev->type) {
    case VIR_DOMAIN_SMARTCARD_TYPE_HOST:
        break;

    case VIR_DOMAIN_SMARTCARD_TYPE_HOST_CERTIFICATES:
        database = dev->data.cert.database;
        if (!database)
            database = VIR_DOMAIN_SMARTCARD_DEFAULT_DATABASE;
1779
        return virSecuritySELinuxRestoreSecurityFileLabel(mgr, database);
E
Eric Blake 已提交
1780 1781

    case VIR_DOMAIN_SMARTCARD_TYPE_PASSTHROUGH:
1782
        return virSecuritySELinuxRestoreSecurityChardevLabel(mgr, def, NULL, &dev->data.passthru);
E
Eric Blake 已提交
1783 1784

    default:
1785 1786 1787
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown smartcard type %d"),
                       dev->type);
E
Eric Blake 已提交
1788 1789 1790 1791 1792 1793 1794
        return -1;
    }

    return 0;
}


1795
static int
1796
virSecuritySELinuxRestoreSecurityAllLabel(virSecurityManagerPtr mgr,
1797 1798
                                          virDomainDefPtr def,
                                          int migrated ATTRIBUTE_UNUSED)
1799
{
1800
    virSecurityLabelDefPtr secdef;
1801
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
1802 1803
    int i;
    int rc = 0;
1804

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

1807 1808 1809 1810
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        return -1;

1811
    if (secdef->norelabel || data->skipAllLabel)
1812 1813
        return 0;

1814 1815 1816 1817 1818 1819
    if (def->tpm) {
        if (virSecuritySELinuxRestoreSecurityTPMFileLabelInt(mgr, def,
                                                             def->tpm) < 0)
            rc = -1;
    }

1820
    for (i = 0 ; i < def->nhostdevs ; i++) {
1821 1822
        if (virSecuritySELinuxRestoreSecurityHostdevLabel(mgr,
                                                          def,
1823 1824
                                                          def->hostdevs[i],
                                                          NULL) < 0)
1825
            rc = -1;
1826
    }
1827
    for (i = 0 ; i < def->ndisks ; i++) {
1828 1829 1830 1831
        if (virSecuritySELinuxRestoreSecurityImageLabelInt(mgr,
                                                           def,
                                                           def->disks[i],
                                                           migrated) < 0)
1832 1833
            rc = -1;
    }
1834

1835
    if (virDomainChrDefForeach(def,
1836
                               false,
1837
                               virSecuritySELinuxRestoreSecurityChardevCallback,
1838
                               mgr) < 0)
1839 1840
        rc = -1;

1841
    if (virDomainSmartcardDefForeach(def,
E
Eric Blake 已提交
1842
                                     false,
1843
                                     virSecuritySELinuxRestoreSecuritySmartcardCallback,
1844
                                     mgr) < 0)
E
Eric Blake 已提交
1845 1846
        rc = -1;

1847
    if (def->os.kernel &&
1848
        virSecuritySELinuxRestoreSecurityFileLabel(mgr, def->os.kernel) < 0)
1849 1850
        rc = -1;

1851
    if (def->os.initrd &&
1852
        virSecuritySELinuxRestoreSecurityFileLabel(mgr, def->os.initrd) < 0)
1853 1854
        rc = -1;

O
Olivia Yin 已提交
1855 1856 1857 1858
    if (def->os.dtb &&
        virSecuritySELinuxRestoreSecurityFileLabel(mgr, def->os.dtb) < 0)
        rc = -1;

1859 1860 1861 1862
    return rc;
}

static int
1863
virSecuritySELinuxReleaseSecurityLabel(virSecurityManagerPtr mgr,
1864
                                       virDomainDefPtr def)
1865
{
1866 1867 1868 1869 1870
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        return -1;
1871

1872 1873 1874 1875
    if (secdef->type == VIR_DOMAIN_SECLABEL_DYNAMIC) {
        if (secdef->label != NULL) {
            context_t con = context_new(secdef->label);
            if (con) {
1876
                virSecuritySELinuxMCSRemove(mgr, context_range_get(con));
1877 1878 1879 1880 1881 1882
                context_free(con);
            }
        }
        VIR_FREE(secdef->label);
        if (!secdef->baselabel)
            VIR_FREE(secdef->model);
1883 1884 1885
    }
    VIR_FREE(secdef->imagelabel);

1886
    return 0;
1887 1888
}

1889 1890

static int
1891 1892 1893
virSecuritySELinuxSetSavedStateLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                     virDomainDefPtr def,
                                     const char *savefile)
1894
{
1895 1896 1897 1898 1899
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        return -1;
1900

1901
    if (secdef->norelabel)
1902 1903
        return 0;

1904
    return virSecuritySELinuxSetFilecon(savefile, secdef->imagelabel);
1905 1906 1907 1908
}


static int
1909
virSecuritySELinuxRestoreSavedStateLabel(virSecurityManagerPtr mgr,
1910 1911
                                         virDomainDefPtr def,
                                         const char *savefile)
1912
{
1913 1914 1915 1916 1917
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        return -1;
1918

1919
    if (secdef->norelabel)
1920 1921
        return 0;

1922
    return virSecuritySELinuxRestoreSecurityFileLabel(mgr, savefile);
1923 1924 1925
}


1926
static int
1927 1928
virSecuritySELinuxSecurityVerify(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                 virDomainDefPtr def)
1929
{
1930 1931 1932 1933 1934 1935
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        return -1;

1936
    if (!STREQ(SECURITY_SELINUX_NAME, secdef->model)) {
1937 1938 1939 1940
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "'%s' model configured for domain, but "
                         "hypervisor driver is '%s'."),
1941
                       secdef->model, SECURITY_SELINUX_NAME);
1942 1943 1944
        return -1;
    }

1945 1946
    if (secdef->type == VIR_DOMAIN_SECLABEL_STATIC) {
        if (security_check_context(secdef->label) != 0) {
1947 1948
            virReportError(VIR_ERR_XML_ERROR,
                           _("Invalid security label %s"), secdef->label);
1949 1950 1951 1952 1953 1954
            return -1;
        }
    }
    return 0;
}

1955
static int
1956
virSecuritySELinuxSetSecurityProcessLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
1957
                                          virDomainDefPtr def)
1958 1959
{
    /* TODO: verify DOI */
1960 1961 1962 1963 1964
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        return -1;
1965

1966
    if (secdef->label == NULL)
1967 1968
        return 0;

1969
    VIR_DEBUG("label=%s", secdef->label);
1970
    if (!STREQ(SECURITY_SELINUX_NAME, secdef->model)) {
1971 1972 1973 1974
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "'%s' model configured for domain, but "
                         "hypervisor driver is '%s'."),
1975
                       secdef->model, SECURITY_SELINUX_NAME);
1976
        if (security_getenforce() == 1)
1977
            return -1;
1978 1979
    }

M
Martin Kletzander 已提交
1980
    if (setexeccon_raw(secdef->label) == -1) {
1981
        virReportSystemError(errno,
1982 1983
                             _("unable to set security context '%s'"),
                             secdef->label);
1984
        if (security_getenforce() == 1)
1985
            return -1;
1986 1987
    }

1988 1989 1990
    return 0;
}

1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021
static int
virSecuritySELinuxSetSecurityChildProcessLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                               virDomainDefPtr def,
                                               virCommandPtr cmd)
{
    /* TODO: verify DOI */
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        return -1;

    if (secdef->label == NULL)
        return 0;

    VIR_DEBUG("label=%s", secdef->label);
    if (!STREQ(SECURITY_SELINUX_NAME, secdef->model)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "'%s' model configured for domain, but "
                         "hypervisor driver is '%s'."),
                       secdef->model, SECURITY_SELINUX_NAME);
        if (security_getenforce() == 1)
            return -1;
    }

    /* save in cmd to be set after fork/before child process is exec'ed */
    virCommandSetSELinuxLabel(cmd, secdef->label);
    return 0;
}

2022
static int
2023
virSecuritySELinuxSetSecurityDaemonSocketLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
2024
                                               virDomainDefPtr def)
2025 2026
{
    /* TODO: verify DOI */
2027
    virSecurityLabelDefPtr secdef;
2028
    security_context_t scon = NULL;
2029
    char *str = NULL;
2030 2031
    int rc = -1;

2032 2033 2034 2035 2036
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        return -1;

    if (secdef->label == NULL)
2037 2038
        return 0;

2039
    if (!STREQ(SECURITY_SELINUX_NAME, secdef->model)) {
2040 2041 2042 2043
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "'%s' model configured for domain, but "
                         "hypervisor driver is '%s'."),
2044
                       secdef->model, SECURITY_SELINUX_NAME);
2045 2046 2047
        goto done;
    }

M
Martin Kletzander 已提交
2048
    if (getcon_raw(&scon) == -1) {
2049 2050 2051 2052 2053 2054
        virReportSystemError(errno,
                             _("unable to get current process context '%s'"),
                             secdef->label);
        goto done;
    }

2055
    if (!(str = virSecuritySELinuxContextAddRange(secdef->label, scon)))
2056 2057
        goto done;

2058 2059
    VIR_DEBUG("Setting VM %s socket context %s", def->name, str);
    if (setsockcreatecon_raw(str) == -1) {
2060
        virReportSystemError(errno,
2061
                             _("unable to set socket security context '%s'"), str);
2062 2063 2064 2065 2066 2067 2068 2069 2070
        goto done;
    }

    rc = 0;
done:

    if (security_getenforce() != 1)
        rc = 0;
    freecon(scon);
2071
    VIR_FREE(str);
2072 2073 2074
    return rc;
}

2075
static int
2076
virSecuritySELinuxSetSecuritySocketLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
2077
                                         virDomainDefPtr vm)
2078
{
2079
    virSecurityLabelDefPtr secdef;
2080 2081
    int rc = -1;

2082 2083 2084 2085
    secdef = virDomainDefGetSecurityLabelDef(vm, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        return -1;

2086 2087 2088
    if (secdef->label == NULL)
        return 0;

2089
    if (!STREQ(SECURITY_SELINUX_NAME, secdef->model)) {
2090 2091 2092 2093
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "'%s' model configured for domain, but "
                         "hypervisor driver is '%s'."),
2094
                       secdef->model, SECURITY_SELINUX_NAME);
2095 2096 2097 2098
        goto done;
    }

    VIR_DEBUG("Setting VM %s socket context %s",
2099
              vm->name, secdef->label);
M
Martin Kletzander 已提交
2100
    if (setsockcreatecon_raw(secdef->label) == -1) {
2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115
        virReportSystemError(errno,
                             _("unable to set socket security context '%s'"),
                             secdef->label);
        goto done;
    }

    rc = 0;

done:
    if (security_getenforce() != 1)
        rc = 0;

    return rc;
}

2116
static int
2117
virSecuritySELinuxClearSecuritySocketLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
2118
                                           virDomainDefPtr def)
2119 2120
{
    /* TODO: verify DOI */
2121 2122 2123 2124 2125
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        return -1;
2126

2127
    if (secdef->label == NULL)
2128 2129
        return 0;

2130
    if (!STREQ(SECURITY_SELINUX_NAME, secdef->model)) {
2131 2132 2133 2134
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "'%s' model configured for domain, but "
                         "hypervisor driver is '%s'."),
2135
                       secdef->model, SECURITY_SELINUX_NAME);
2136 2137 2138 2139
        if (security_getenforce() == 1)
            return -1;
    }

M
Martin Kletzander 已提交
2140
    if (setsockcreatecon_raw(NULL) == -1) {
2141 2142 2143 2144 2145 2146 2147 2148 2149
        virReportSystemError(errno,
                             _("unable to clear socket security context '%s'"),
                             secdef->label);
        if (security_getenforce() == 1)
            return -1;
    }
    return 0;
}

2150 2151

static int
2152 2153 2154
virSecuritySELinuxSetSecurityChardevCallback(virDomainDefPtr def,
                                             virDomainChrDefPtr dev,
                                             void *opaque ATTRIBUTE_UNUSED)
2155
{
2156 2157 2158 2159 2160
    /* This is taken care of by processing of def->serials */
    if (dev->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE &&
        dev->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL)
        return 0;

2161
    return virSecuritySELinuxSetSecurityChardevLabel(def, dev, &dev->source);
2162 2163 2164
}


E
Eric Blake 已提交
2165
static int
2166 2167 2168
virSecuritySELinuxSetSecuritySmartcardCallback(virDomainDefPtr def,
                                               virDomainSmartcardDefPtr dev,
                                               void *opaque)
E
Eric Blake 已提交
2169 2170
{
    const char *database;
2171 2172
    virSecurityManagerPtr mgr = opaque;
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
E
Eric Blake 已提交
2173 2174 2175 2176 2177 2178 2179 2180 2181

    switch (dev->type) {
    case VIR_DOMAIN_SMARTCARD_TYPE_HOST:
        break;

    case VIR_DOMAIN_SMARTCARD_TYPE_HOST_CERTIFICATES:
        database = dev->data.cert.database;
        if (!database)
            database = VIR_DOMAIN_SMARTCARD_DEFAULT_DATABASE;
2182
        return virSecuritySELinuxSetFilecon(database, data->content_context);
E
Eric Blake 已提交
2183 2184

    case VIR_DOMAIN_SMARTCARD_TYPE_PASSTHROUGH:
2185
        return virSecuritySELinuxSetSecurityChardevLabel(def, NULL, &dev->data.passthru);
E
Eric Blake 已提交
2186 2187

    default:
2188 2189 2190
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown smartcard type %d"),
                       dev->type);
E
Eric Blake 已提交
2191 2192 2193 2194 2195 2196 2197
        return -1;
    }

    return 0;
}


2198
static int
2199 2200 2201
virSecuritySELinuxSetSecurityAllLabel(virSecurityManagerPtr mgr,
                                      virDomainDefPtr def,
                                      const char *stdin_path)
2202 2203
{
    int i;
2204 2205 2206 2207 2208 2209
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        return -1;
2210

2211
    if (secdef->norelabel || data->skipAllLabel)
2212 2213
        return 0;

2214
    for (i = 0 ; i < def->ndisks ; i++) {
2215
        /* XXX fixme - we need to recursively label the entire tree :-( */
2216
        if (def->disks[i]->type == VIR_DOMAIN_DISK_TYPE_DIR) {
2217
            VIR_WARN("Unable to relabel directory tree %s for disk %s",
2218
                     def->disks[i]->src, def->disks[i]->dst);
2219
            continue;
2220
        }
2221
        if (virSecuritySELinuxSetSecurityImageLabel(mgr,
2222
                                         def, def->disks[i]) < 0)
2223 2224
            return -1;
    }
2225
    /* XXX fixme process  def->fss if relabel == true */
2226

2227
    for (i = 0 ; i < def->nhostdevs ; i++) {
2228
        if (virSecuritySELinuxSetSecurityHostdevLabel(mgr,
2229 2230 2231
                                                      def,
                                                      def->hostdevs[i],
                                                      NULL) < 0)
2232
            return -1;
2233
    }
2234 2235 2236 2237 2238
    if (def->tpm) {
        if (virSecuritySELinuxSetSecurityTPMFileLabel(mgr, def,
                                                      def->tpm) < 0)
            return -1;
    }
2239

2240
    if (virDomainChrDefForeach(def,
2241
                               true,
2242
                               virSecuritySELinuxSetSecurityChardevCallback,
2243
                               NULL) < 0)
2244 2245
        return -1;

2246
    if (virDomainSmartcardDefForeach(def,
E
Eric Blake 已提交
2247
                                     true,
2248
                                     virSecuritySELinuxSetSecuritySmartcardCallback,
2249
                                     mgr) < 0)
E
Eric Blake 已提交
2250 2251
        return -1;

2252
    if (def->os.kernel &&
2253
        virSecuritySELinuxSetFilecon(def->os.kernel, data->content_context) < 0)
2254 2255
        return -1;

2256
    if (def->os.initrd &&
2257
        virSecuritySELinuxSetFilecon(def->os.initrd, data->content_context) < 0)
2258 2259
        return -1;

O
Olivia Yin 已提交
2260 2261 2262 2263
    if (def->os.dtb &&
        virSecuritySELinuxSetFilecon(def->os.dtb, data->content_context) < 0)
        return -1;

2264
    if (stdin_path) {
2265
        if (virSecuritySELinuxSetFilecon(stdin_path, data->content_context) < 0 &&
2266 2267 2268 2269
            virStorageFileIsSharedFSType(stdin_path,
                                         VIR_STORAGE_FILE_SHFS_NFS) != 1)
            return -1;
    }
2270

2271 2272 2273
    return 0;
}

2274
static int
2275 2276 2277
virSecuritySELinuxSetImageFDLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                  virDomainDefPtr def,
                                  int fd)
2278
{
2279 2280 2281 2282 2283
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        return -1;
2284 2285 2286 2287

    if (secdef->imagelabel == NULL)
        return 0;

2288
    return virSecuritySELinuxFSetFilecon(fd, secdef->imagelabel);
2289 2290
}

2291
static int
2292
virSecuritySELinuxSetTapFDLabel(virSecurityManagerPtr mgr,
2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319
                                virDomainDefPtr def,
                                int fd)
{
    struct stat buf;
    security_context_t fcon = NULL;
    virSecurityLabelDefPtr secdef;
    char *str = NULL;
    int rc = -1;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        return rc;

    if (secdef->label == NULL)
        return 0;

    if (fstat(fd, &buf) < 0) {
        virReportSystemError(errno, _("cannot stat tap fd %d"), fd);
        goto cleanup;
    }

    if ((buf.st_mode & S_IFMT) != S_IFCHR) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("tap fd %d is not character device"), fd);
        goto cleanup;
    }

2320
    if (getContext(mgr, "/dev/tap.*", buf.st_mode, &fcon) < 0) {
2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot lookup default selinux label for tap fd %d"), fd);
        goto cleanup;
    }

    if (!(str = virSecuritySELinuxContextAddRange(secdef->label, fcon))) {
        goto cleanup;
    } else {
        rc = virSecuritySELinuxFSetFilecon(fd, str);
    }

cleanup:
    freecon(fcon);
    VIR_FREE(str);
    return rc;
}

2338 2339 2340 2341
static char *
virSecuritySELinuxGenImageLabel(virSecurityManagerPtr mgr,
                                virDomainDefPtr def)
{
2342
    virSecurityLabelDefPtr secdef;
2343 2344 2345 2346 2347 2348
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
    const char *range;
    context_t ctx = NULL;
    char *label = NULL;
    const char *mcs = NULL;

2349 2350 2351 2352
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        goto cleanup;

2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365
    if (secdef->label) {
        ctx = context_new(secdef->label);
        if (!ctx) {
            virReportOOMError();
            goto cleanup;
        }
        range = context_range_get(ctx);
        if (range) {
            mcs = strdup(range);
            if (!mcs) {
                virReportOOMError();
                goto cleanup;
            }
2366 2367
            if (!(label = virSecuritySELinuxGenNewContext(data->file_context,
                                                          mcs, true)))
2368 2369 2370 2371 2372 2373 2374 2375 2376 2377
                goto cleanup;
        }
    }

cleanup:
        context_free(ctx);
        VIR_FREE(mcs);
        return label;
}

2378 2379 2380 2381
static char *
virSecuritySELinuxGetSecurityMountOptions(virSecurityManagerPtr mgr,
                                          virDomainDefPtr def)
{
2382
    char *opts = NULL;
2383 2384
    virSecurityLabelDefPtr secdef;

2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396
    if ((secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME))) {
        if (!secdef->imagelabel)
            secdef->imagelabel = virSecuritySELinuxGenImageLabel(mgr, def);

        if (secdef->imagelabel &&
            virAsprintf(&opts,
                        ",context=\"%s\"",
                        (const char*) secdef->imagelabel) < 0) {
            virReportOOMError();
            return NULL;
        }
    }
2397

2398 2399 2400 2401
    if (!opts &&
        !(opts = strdup(""))) {
        virReportOOMError();
        return NULL;
2402 2403
    }

2404 2405
    VIR_DEBUG("imageLabel=%s opts=%s",
              secdef ? secdef->imagelabel : "(null)", opts);
2406 2407 2408
    return opts;
}

2409
virSecurityDriver virSecurityDriverSELinux = {
2410 2411
    .privateDataLen                     = sizeof(virSecuritySELinuxData),
    .name                               = SECURITY_SELINUX_NAME,
2412 2413 2414
    .probe                              = virSecuritySELinuxSecurityDriverProbe,
    .open                               = virSecuritySELinuxSecurityDriverOpen,
    .close                              = virSecuritySELinuxSecurityDriverClose,
2415

2416 2417
    .getModel                           = virSecuritySELinuxSecurityGetModel,
    .getDOI                             = virSecuritySELinuxSecurityGetDOI,
2418

2419
    .domainSecurityVerify               = virSecuritySELinuxSecurityVerify,
2420

2421 2422
    .domainSetSecurityImageLabel        = virSecuritySELinuxSetSecurityImageLabel,
    .domainRestoreSecurityImageLabel    = virSecuritySELinuxRestoreSecurityImageLabel,
2423

2424 2425 2426
    .domainSetSecurityDaemonSocketLabel = virSecuritySELinuxSetSecurityDaemonSocketLabel,
    .domainSetSecuritySocketLabel       = virSecuritySELinuxSetSecuritySocketLabel,
    .domainClearSecuritySocketLabel     = virSecuritySELinuxClearSecuritySocketLabel,
2427

2428 2429 2430
    .domainGenSecurityLabel             = virSecuritySELinuxGenSecurityLabel,
    .domainReserveSecurityLabel         = virSecuritySELinuxReserveSecurityLabel,
    .domainReleaseSecurityLabel         = virSecuritySELinuxReleaseSecurityLabel,
2431

2432 2433
    .domainGetSecurityProcessLabel      = virSecuritySELinuxGetSecurityProcessLabel,
    .domainSetSecurityProcessLabel      = virSecuritySELinuxSetSecurityProcessLabel,
2434
    .domainSetSecurityChildProcessLabel = virSecuritySELinuxSetSecurityChildProcessLabel,
2435

2436 2437
    .domainSetSecurityAllLabel          = virSecuritySELinuxSetSecurityAllLabel,
    .domainRestoreSecurityAllLabel      = virSecuritySELinuxRestoreSecurityAllLabel,
2438

2439 2440
    .domainSetSecurityHostdevLabel      = virSecuritySELinuxSetSecurityHostdevLabel,
    .domainRestoreSecurityHostdevLabel  = virSecuritySELinuxRestoreSecurityHostdevLabel,
2441

2442 2443
    .domainSetSavedStateLabel           = virSecuritySELinuxSetSavedStateLabel,
    .domainRestoreSavedStateLabel       = virSecuritySELinuxRestoreSavedStateLabel,
2444

2445
    .domainSetSecurityImageFDLabel      = virSecuritySELinuxSetImageFDLabel,
2446
    .domainSetSecurityTapFDLabel        = virSecuritySELinuxSetTapFDLabel,
2447

2448
    .domainGetSecurityMountOptions      = virSecuritySELinuxGetSecurityMountOptions,
2449
};