security_selinux.c 75.8 KB
Newer Older
1
/*
2
 * Copyright (C) 2008-2014 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 "viralloc.h"
38
#include "virlog.h"
39
#include "virpci.h"
40
#include "virusb.h"
41
#include "virscsi.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"
48
#include "virstring.h"
D
Daniel P. Berrange 已提交
49 50 51

#define VIR_FROM_THIS VIR_FROM_SECURITY

52 53
VIR_LOG_INIT("security.security_selinux");

54 55 56 57 58 59 60
#define MAX_CONTEXT 1024

typedef struct _virSecuritySELinuxData virSecuritySELinuxData;
typedef virSecuritySELinuxData *virSecuritySELinuxDataPtr;

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
#define SECURITY_SELINUX_VOID_DOI       "0"
#define SECURITY_SELINUX_NAME "selinux"

74 75 76 77 78 79
static int
virSecuritySELinuxRestoreSecurityTPMFileLabelInt(virSecurityManagerPtr mgr,
                                                 virDomainDefPtr def,
                                                 virDomainTPMDefPtr tpm);


80 81 82
/*
 * Returns 0 on success, 1 if already reserved, or -1 on fatal error
 */
83
static int
84 85
virSecuritySELinuxMCSAdd(virSecurityManagerPtr mgr,
                         const char *mcs)
86
{
87
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
88

89 90 91 92
    if (virHashLookup(data->mcs, mcs))
        return 1;

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

95 96 97
    return 0;
}

98 99 100
static void
virSecuritySELinuxMCSRemove(virSecurityManagerPtr mgr,
                            const char *mcs)
101
{
102 103 104
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);

    virHashRemoveEntry(data->mcs, mcs);
105 106
}

107 108

static char *
109 110 111 112
virSecuritySELinuxMCSFind(virSecurityManagerPtr mgr,
                          const char *sens,
                          int catMin,
                          int catMax)
113 114
{
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
115
    int catRange;
116
    char *mcs = NULL;
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137

    /* +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) {
138
            if (virAsprintf(&mcs, "%s:c%d", sens, catMin + c1) < 0)
139 140 141 142 143 144 145
                return NULL;
        } else {
            if (c1 > c2) {
                int t = c1;
                c1 = c2;
                c2 = t;
            }
146
            if (virAsprintf(&mcs, "%s:c%d,c%d", sens, catMin + c1, catMin + c2) < 0)
147 148 149 150 151 152 153 154 155 156 157 158
                return NULL;
        }

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

        VIR_FREE(mcs);
    }

    return mcs;
}

159 160 161 162

/*
 * This needs to cope with several styles of range
 *
163
 * system_u:system_r:virtd_t
164 165 166 167
 * 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
 *
168 169
 * In the first case we'll assume s0:c0.c1023 and
 * in the next two cases, we'll assume c0.c1023 for
170 171 172
 * 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
N
Nehal J Wani 已提交
173
 * mode when run with a weird process label.
174
 */
175 176 177 178 179
static int
virSecuritySELinuxMCSGetProcessRange(char **sens,
                                     int *catMin,
                                     int *catMax)
{
180 181
    security_context_t ourSecContext = NULL;
    context_t ourContext = NULL;
182 183
    char *cat = NULL;
    char *tmp;
184
    const char *contextRange;
185
    int ret = -1;
186

M
Martin Kletzander 已提交
187
    if (getcon_raw(&ourSecContext) < 0) {
188 189 190 191 192 193 194 195 196 197
        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;
    }
198 199
    if (!(contextRange = context_range_get(ourContext)))
        contextRange = "s0";
200

201
    if (VIR_STRDUP(*sens, contextRange) < 0)
202 203
        goto cleanup;

204 205 206 207 208
    /* Find and blank out the category part (if any) */
    tmp = strchr(*sens, ':');
    if (tmp) {
        *tmp = '\0';
        cat = tmp + 1;
209 210
    }
    /* Find and blank out the sensitivity upper bound */
211
    if ((tmp = strchr(*sens, '-')))
212 213 214
        *tmp = '\0';
    /* sens now just contains the sensitivity lower bound */

215
    /* If there was no category part, just assume c0.c1023 */
216 217
    if (!cat) {
        *catMin = 0;
218
        *catMax = 1023;
219 220 221 222
        ret = 0;
        goto cleanup;
    }

223 224 225 226 227 228 229 230 231
    /* Find & extract category min */
    tmp = cat;
    if (tmp[0] != 'c') {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot parse category in %s"),
                       cat);
        goto cleanup;
    }
    tmp++;
232
    if (virStrToLong_i(tmp, &tmp, 10, catMin) < 0) {
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 258 259 260 261
        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++;
262
    if (virStrToLong_i(tmp, &tmp, 10, catMax) < 0) {
263 264 265 266 267 268
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot parse category in %s"),
                       cat);
        goto cleanup;
    }

269
    ret = 0;
270

271
 cleanup:
272 273
    if (ret < 0)
        VIR_FREE(*sens);
274 275
    freecon(ourSecContext);
    context_free(ourContext);
276
    return ret;
277 278
}

279 280 281 282 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
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;
    }

309
    ignore_value(VIR_STRDUP(ret, str));
310

311
 cleanup:
312 313 314 315
    if (srccon) context_free(srccon);
    if (dstcon) context_free(dstcon);
    return ret;
}
316

317
static char *
318 319 320
virSecuritySELinuxGenNewContext(const char *basecontext,
                                const char *mcs,
                                bool isObjectContext)
321
{
322
    context_t context = NULL;
323 324
    char *ret = NULL;
    char *str;
325 326 327
    security_context_t ourSecContext = NULL;
    context_t ourContext = NULL;

328 329 330
    VIR_DEBUG("basecontext=%s mcs=%s isObjectContext=%d",
              basecontext, mcs, isObjectContext);

M
Martin Kletzander 已提交
331
    if (getcon_raw(&ourSecContext) < 0) {
332 333 334 335 336 337 338 339 340 341
        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;
    }
342
    VIR_DEBUG("process=%s", ourSecContext);
343 344 345 346 347 348 349 350

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

351 352 353 354 355 356 357 358
    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;
    }

359 360
    if (!isObjectContext &&
        context_role_set(context,
361 362
                         context_role_get(ourContext)) != 0) {
        virReportSystemError(errno,
363
                             _("Unable to set SELinux context role '%s'"),
364 365 366 367
                             context_role_get(ourContext));
        goto cleanup;
    }

368 369 370 371 372 373 374 375 376 377 378
    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;
    }
379
    if (VIR_STRDUP(ret, str) < 0)
380
        goto cleanup;
381
    VIR_DEBUG("Generated context '%s'",  ret);
382
 cleanup:
383 384
    freecon(ourSecContext);
    context_free(ourContext);
385 386
    context_free(context);
    return ret;
387 388
}

389

390
#ifdef HAVE_SELINUX_LXC_CONTEXTS_PATH
391
static int
392
virSecuritySELinuxLXCInitialize(virSecurityManagerPtr mgr)
393 394 395 396 397 398 399
{
    virConfValuePtr scon = NULL;
    virConfValuePtr tcon = NULL;
    virConfValuePtr dcon = NULL;
    virConfPtr selinux_conf;
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);

400 401
    data->skipAllLabel = true;

402
# if HAVE_SELINUX_LABEL_H
403 404 405 406 407 408
    data->label_handle = selabel_open(SELABEL_CTX_FILE, NULL, 0);
    if (!data->label_handle) {
        virReportSystemError(errno, "%s",
                             _("cannot open SELinux label_handle"));
        return -1;
    }
409
# endif
410

411
    if (!(selinux_conf = virConfReadFile(selinux_lxc_contexts_path(), 0)))
412
        goto error;
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

    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;
    }

438 439 440
    if (VIR_STRDUP(data->domain_context, scon->str) < 0 ||
        VIR_STRDUP(data->file_context, tcon->str) < 0 ||
        VIR_STRDUP(data->content_context, dcon->str) < 0)
441
        goto error;
442 443 444 445

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

446 447 448
    virConfFree(selinux_conf);
    return 0;

449
 error:
450
# if HAVE_SELINUX_LABEL_H
451
    selabel_close(data->label_handle);
452
    data->label_handle = NULL;
453
# endif
454 455 456 457
    virConfFree(selinux_conf);
    VIR_FREE(data->domain_context);
    VIR_FREE(data->file_context);
    VIR_FREE(data->content_context);
458
    virHashFree(data->mcs);
459 460
    return -1;
}
461 462
#else
static int
463
virSecuritySELinuxLXCInitialize(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED)
464 465 466 467 468 469
{
    virReportSystemError(ENOSYS, "%s",
                         _("libselinux does not support LXC contexts path"));
    return -1;
}
#endif
470 471 472


static int
473
virSecuritySELinuxQEMUInitialize(virSecurityManagerPtr mgr)
474
{
475 476
    char *ptr;
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
477

478 479
    data->skipAllLabel = false;

480 481 482 483 484 485 486 487 488
#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

489
    if (virFileReadAll(selinux_virtual_domain_context_path(), MAX_CONTEXT, &(data->domain_context)) < 0) {
490
        virReportSystemError(errno,
491
                             _("cannot read SELinux virtual domain context file '%s'"),
492
                             selinux_virtual_domain_context_path());
493
        goto error;
494 495
    }

496
    ptr = strchrnul(data->domain_context, '\n');
497
    if (ptr && *ptr == '\n') {
498
        *ptr = '\0';
499 500
        ptr++;
        if (*ptr != '\0') {
501
            if (VIR_STRDUP(data->alt_domain_context, ptr) < 0)
502 503 504 505 506 507 508 509 510
                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));

511

512
    if (virFileReadAll(selinux_virtual_image_context_path(), 2*MAX_CONTEXT, &(data->file_context)) < 0) {
513
        virReportSystemError(errno,
514 515
                             _("cannot read SELinux virtual image context file %s"),
                             selinux_virtual_image_context_path());
516
        goto error;
517 518
    }

519 520
    ptr = strchrnul(data->file_context, '\n');
    if (ptr && *ptr == '\n') {
521
        *ptr = '\0';
522
        if (VIR_STRDUP(data->content_context, ptr + 1) < 0)
523 524 525
            goto error;
        ptr = strchrnul(data->content_context, '\n');
        if (ptr && *ptr == '\n')
526 527
            *ptr = '\0';
    }
528

529 530 531
    VIR_DEBUG("Loaded file context '%s', content context '%s'",
              data->file_context, data->content_context);

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

535
    return 0;
536

537
 error:
538 539
#if HAVE_SELINUX_LABEL_H
    selabel_close(data->label_handle);
540
    data->label_handle = NULL;
541
#endif
542
    VIR_FREE(data->domain_context);
543
    VIR_FREE(data->alt_domain_context);
544 545
    VIR_FREE(data->file_context);
    VIR_FREE(data->content_context);
546
    virHashFree(data->mcs);
547
    return -1;
548 549
}

550 551

static int
552
virSecuritySELinuxInitialize(virSecurityManagerPtr mgr)
553 554 555
{
    VIR_DEBUG("SELinuxInitialize %s", virSecurityManagerGetDriver(mgr));
    if (STREQ(virSecurityManagerGetDriver(mgr),  "LXC")) {
556
        return virSecuritySELinuxLXCInitialize(mgr);
557
    } else {
558
        return virSecuritySELinuxQEMUInitialize(mgr);
559 560 561 562
    }
}


563
static int
564 565
virSecuritySELinuxGenSecurityLabel(virSecurityManagerPtr mgr,
                                   virDomainDefPtr def)
566 567
{
    int rc = -1;
568
    char *mcs = NULL;
569
    char *scontext = NULL;
570
    context_t ctx = NULL;
571
    const char *range;
572 573
    virSecurityLabelDefPtr seclabel;
    virSecuritySELinuxDataPtr data;
574
    const char *baselabel;
575 576
    char *sens = NULL;
    int catMin, catMax;
577

578
    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
P
Peter Krempa 已提交
579
    if (seclabel == NULL)
580
        return 0;
581 582 583 584 585 586

    data = virSecurityManagerGetPrivateData(mgr);

    VIR_DEBUG("label=%s", virSecurityManagerGetDriver(mgr));
    if (seclabel->type == VIR_DOMAIN_SECLABEL_DYNAMIC &&
        seclabel->label) {
P
Peter Krempa 已提交
587 588
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("security label already defined for VM"));
589
        return rc;
D
Daniel P. Berrange 已提交
590
    }
591

592
    if (seclabel->imagelabel) {
P
Peter Krempa 已提交
593 594
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("security image label already defined for VM"));
595 596 597
        return rc;
    }

598 599
    if (seclabel->model &&
        STRNEQ(seclabel->model, SECURITY_SELINUX_NAME)) {
600 601
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label model %s is not supported with selinux"),
602
                       seclabel->model);
603 604 605
        return rc;
    }

606
    VIR_DEBUG("type=%d", seclabel->type);
607

608
    switch (seclabel->type) {
609
    case VIR_DOMAIN_SECLABEL_STATIC:
610
        if (!(ctx = context_new(seclabel->label))) {
611 612
            virReportSystemError(errno,
                                 _("unable to allocate socket security context '%s'"),
613
                                 seclabel->label);
614
            return rc;
615 616
        }

P
Peter Krempa 已提交
617
        if (!(range = context_range_get(ctx))) {
618
            virReportSystemError(errno, "%s", _("unable to get selinux context range"));
619 620
            goto cleanup;
        }
621 622
        if (VIR_STRDUP(mcs, range) < 0)
            goto cleanup;
623 624 625
        break;

    case VIR_DOMAIN_SECLABEL_DYNAMIC:
626 627 628 629 630 631 632 633 634
        if (virSecuritySELinuxMCSGetProcessRange(&sens,
                                                 &catMin,
                                                 &catMax) < 0)
            goto cleanup;

        if (!(mcs = virSecuritySELinuxMCSFind(mgr,
                                              sens,
                                              catMin,
                                              catMax)))
635 636 637 638
            goto cleanup;

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

640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
        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;
            }
        }

660 661
        seclabel->label = virSecuritySELinuxGenNewContext(baselabel, mcs, false);
        if (!seclabel->label)
662
            goto cleanup;
663

664 665 666
        break;

    case VIR_DOMAIN_SECLABEL_NONE:
667 668 669 670 671 672 673 674
        if (virSecuritySELinuxMCSGetProcessRange(&sens,
                                                 &catMin,
                                                 &catMax) < 0)
            goto cleanup;

        if (VIR_STRDUP(mcs, sens) < 0)
            goto cleanup;

675 676 677
        break;

    default:
678 679
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected security label type '%s'"),
680
                       virDomainSeclabelTypeToString(seclabel->type));
681
        goto cleanup;
D
Daniel P. Berrange 已提交
682
    }
683

684 685 686 687 688 689
    /* always generate a image label, needed to label new objects */
    seclabel->imagelabel = virSecuritySELinuxGenNewContext(data->file_context,
                                                           mcs,
                                                           true);
    if (!seclabel->imagelabel)
        goto cleanup;
690

691
    if (!seclabel->model &&
692
        VIR_STRDUP(seclabel->model, SECURITY_SELINUX_NAME) < 0)
693
        goto cleanup;
D
Daniel P. Berrange 已提交
694

695
    rc = 0;
696

697
 cleanup:
698
    if (rc != 0) {
699 700 701 702 703 704
        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);
705 706 707 708
    }

    if (ctx)
        context_free(ctx);
D
Daniel P. Berrange 已提交
709
    VIR_FREE(scontext);
710
    VIR_FREE(mcs);
711
    VIR_FREE(sens);
712 713

    VIR_DEBUG("model=%s label=%s imagelabel=%s baselabel=%s",
714 715 716 717
              NULLSTR(seclabel->model),
              NULLSTR(seclabel->label),
              NULLSTR(seclabel->imagelabel),
              NULLSTR(seclabel->baselabel));
718

719 720 721
    return rc;
}

722
static int
723
virSecuritySELinuxReserveSecurityLabel(virSecurityManagerPtr mgr,
724 725
                                       virDomainDefPtr def,
                                       pid_t pid)
726 727 728 729
{
    security_context_t pctx;
    context_t ctx = NULL;
    const char *mcs;
730
    int rv;
731
    virSecurityLabelDefPtr seclabel;
732

733
    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
734
    if (!seclabel || seclabel->type == VIR_DOMAIN_SECLABEL_STATIC)
735 736
        return 0;

M
Martin Kletzander 已提交
737
    if (getpidcon_raw(pid, &pctx) == -1) {
738
        virReportSystemError(errno,
739
                             _("unable to get PID %d security context"), pid);
740 741 742 743
        return -1;
    }

    ctx = context_new(pctx);
744
    freecon(pctx);
745
    if (!ctx)
746
        goto error;
747 748 749

    mcs = context_range_get(ctx);
    if (!mcs)
750 751
        goto error;

752
    if ((rv = virSecuritySELinuxMCSAdd(mgr, mcs)) < 0)
753
        goto error;
754

755 756 757 758 759 760
    if (rv == 1) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("MCS level for existing domain label %s already reserved"),
                       (char*)pctx);
        goto error;
    }
761 762 763 764 765

    context_free(ctx);

    return 0;

766
 error:
767 768 769 770 771
    context_free(ctx);
    return -1;
}


772
static int
773
virSecuritySELinuxSecurityDriverProbe(const char *virtDriver)
774
{
775
    if (is_selinux_enabled() <= 0)
776 777
        return SECURITY_DRIVER_DISABLE;

778 779 780 781 782 783
    if (virtDriver && STREQ(virtDriver, "LXC")) {
#if HAVE_SELINUX_LXC_CONTEXTS_PATH
        if (!virFileExists(selinux_lxc_contexts_path()))
#endif
            return SECURITY_DRIVER_DISABLE;
    }
784 785

    return SECURITY_DRIVER_ENABLE;
786 787
}

788

789
static int
790
virSecuritySELinuxSecurityDriverOpen(virSecurityManagerPtr mgr)
791
{
792
    return virSecuritySELinuxInitialize(mgr);
793 794
}

795

796
static int
797
virSecuritySELinuxSecurityDriverClose(virSecurityManagerPtr mgr)
798
{
799 800 801 802 803
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);

    if (!data)
        return 0;

804
#if HAVE_SELINUX_LABEL_H
805 806
    if (data->label_handle)
        selabel_close(data->label_handle);
807 808
#endif

809 810
    virHashFree(data->mcs);

811
    VIR_FREE(data->domain_context);
812
    VIR_FREE(data->alt_domain_context);
813 814 815
    VIR_FREE(data->file_context);
    VIR_FREE(data->content_context);

816 817 818 819
    return 0;
}


820 821
static const char *
virSecuritySELinuxSecurityGetModel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED)
822 823 824 825
{
    return SECURITY_SELINUX_NAME;
}

826 827
static const char *
virSecuritySELinuxSecurityGetDOI(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED)
828 829 830 831 832
{
    /*
     * Where will the DOI come from?  SELinux configuration, or qemu
     * configuration? For the moment, we'll just set it to "0".
     */
833
    return SECURITY_SELINUX_VOID_DOI;
834 835 836
}

static int
837 838 839 840
virSecuritySELinuxGetSecurityProcessLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                          virDomainDefPtr def ATTRIBUTE_UNUSED,
                                          pid_t pid,
                                          virSecurityLabelPtr sec)
841 842 843
{
    security_context_t ctx;

M
Martin Kletzander 已提交
844
    if (getpidcon_raw(pid, &ctx) == -1) {
845
        virReportSystemError(errno,
846
                             _("unable to get PID %d security context"),
847
                             pid);
848 849 850 851
        return -1;
    }

    if (strlen((char *) ctx) >= VIR_SECURITY_LABEL_BUFLEN) {
852 853 854 855
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label exceeds "
                         "maximum length: %d"),
                       VIR_SECURITY_LABEL_BUFLEN - 1);
856
        freecon(ctx);
857 858 859 860
        return -1;
    }

    strcpy(sec->label, (char *) ctx);
861
    freecon(ctx);
862

863
    VIR_DEBUG("label=%s", sec->label);
864 865
    sec->enforcing = security_getenforce();
    if (sec->enforcing == -1) {
866
        virReportSystemError(errno, "%s",
867
                             _("error calling security_getenforce()"));
868 869 870 871 872 873
        return -1;
    }

    return 0;
}

874 875 876
/* 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.  */
877
static int
878
virSecuritySELinuxSetFileconHelper(const char *path, char *tcon, bool optional)
879
{
880
    security_context_t econ;
881

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

M
Martin Kletzander 已提交
884
    if (setfilecon_raw(path, tcon) < 0) {
885 886
        int setfilecon_errno = errno;

M
Martin Kletzander 已提交
887
        if (getfilecon_raw(path, &econ) >= 0) {
888 889 890
            if (STREQ(tcon, econ)) {
                freecon(econ);
                /* It's alright, there's nothing to change anyway. */
891
                return optional ? 1 : 0;
892 893 894
            }
            freecon(econ);
        }
895

896 897 898 899 900
        /* If the error complaint is related to an image hosted on a (possibly
         * read-only) NFS mount, or a usbfs/sysfs filesystem not supporting
         * labelling, then just ignore it & hope for the best.  The user
         * hopefully sets one of the necessary SELinux virt_use_{nfs,usb,pci}
         * boolean tunables to allow it ...
901
         */
902 903
        if (setfilecon_errno != EOPNOTSUPP && setfilecon_errno != ENOTSUP &&
            setfilecon_errno != EROFS) {
904
            virReportSystemError(setfilecon_errno,
905
                                 _("unable to set security context '%s' on '%s'"),
906
                                 tcon, path);
907 908
            if (security_getenforce() == 1)
                return -1;
909
        } else {
910
            const char *msg;
911
            if (virFileIsSharedFSType(path, VIR_FILE_SHFS_NFS) == 1 &&
912 913 914
                security_get_boolean_active("virt_use_nfs") != 1) {
                msg = _("Setting security context '%s' on '%s' not supported. "
                        "Consider setting virt_use_nfs");
915 916 917 918
                if (security_getenforce() == 1)
                    VIR_WARN(msg, tcon, path);
                else
                    VIR_INFO(msg, tcon, path);
919 920 921 922
            } else {
                VIR_INFO("Setting security context '%s' on '%s' not supported",
                         tcon, path);
            }
923 924
            if (optional)
                return 1;
925
        }
926 927 928 929
    }
    return 0;
}

930
static int
931
virSecuritySELinuxSetFileconOptional(const char *path, char *tcon)
932
{
933
    return virSecuritySELinuxSetFileconHelper(path, tcon, true);
934 935 936
}

static int
937
virSecuritySELinuxSetFilecon(const char *path, char *tcon)
938
{
939
    return virSecuritySELinuxSetFileconHelper(path, tcon, false);
940 941
}

942
static int
943
virSecuritySELinuxFSetFilecon(int fd, char *tcon)
944 945 946 947 948
{
    security_context_t econ;

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

M
Martin Kletzander 已提交
949
    if (fsetfilecon_raw(fd, tcon) < 0) {
950 951
        int fsetfilecon_errno = errno;

M
Martin Kletzander 已提交
952
        if (fgetfilecon_raw(fd, &econ) >= 0) {
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
            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 已提交
981 982
/* Set fcon to the appropriate label for path and mode, or return -1.  */
static int
983
getContext(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
984
           const char *newpath, mode_t mode, security_context_t *fcon)
E
Eric Blake 已提交
985 986
{
#if HAVE_SELINUX_LABEL_H
987
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
E
Eric Blake 已提交
988

989
    return selabel_lookup_raw(data->label_handle, fcon, newpath, mode);
E
Eric Blake 已提交
990 991 992 993 994
#else
    return matchpathcon(newpath, mode, fcon);
#endif
}

995 996 997

/* This method shouldn't raise errors, since they'll overwrite
 * errors that the caller(s) are already dealing with */
998
static int
999 1000
virSecuritySELinuxRestoreSecurityFileLabel(virSecurityManagerPtr mgr,
                                           const char *path)
1001
{
1002 1003 1004 1005
    struct stat buf;
    security_context_t fcon = NULL;
    int rc = -1;
    char *newpath = NULL;
1006
    char ebuf[1024];
1007

1008 1009
    VIR_INFO("Restoring SELinux context on '%s'", path);

1010
    if (virFileResolveLink(path, &newpath) < 0) {
1011 1012
        VIR_WARN("cannot resolve symlink %s: %s", path,
                 virStrerror(errno, ebuf, sizeof(ebuf)));
D
Daniel P. Berrange 已提交
1013
        goto err;
1014
    }
1015

1016
    if (stat(newpath, &buf) != 0) {
1017 1018
        VIR_WARN("cannot stat %s: %s", newpath,
                 virStrerror(errno, ebuf, sizeof(ebuf)));
D
Daniel P. Berrange 已提交
1019
        goto err;
1020
    }
D
Daniel P. Berrange 已提交
1021

1022
    if (getContext(mgr, newpath, buf.st_mode, &fcon) < 0) {
1023 1024 1025
        /* Any user created path likely does not have a default label,
         * which makes this an expected non error
         */
1026
        VIR_WARN("cannot lookup default selinux label for %s", newpath);
1027
        rc = 0;
1028
    } else {
1029
        rc = virSecuritySELinuxSetFilecon(newpath, fcon);
1030
    }
1031

1032
 err:
1033
    freecon(fcon);
1034 1035
    VIR_FREE(newpath);
    return rc;
1036 1037
}

1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050

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)
1051
        return 0;
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 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

    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)
1093
        return 0;
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114

    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;
}


1115
static int
1116
virSecuritySELinuxRestoreSecurityImageLabelInt(virSecurityManagerPtr mgr,
1117
                                               virDomainDefPtr def,
1118
                                               virStorageSourcePtr src,
1119
                                               bool migrated)
1120
{
1121 1122
    virSecurityLabelDefPtr seclabel;
    virSecurityDeviceLabelDefPtr disk_seclabel;
1123 1124 1125

    if (!src->path || !virStorageSourceIsLocalStorage(src))
        return 0;
1126 1127 1128

    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (seclabel == NULL)
1129
        return 0;
1130

1131
    disk_seclabel = virStorageSourceGetSecurityLabelDef(src,
1132
                                                        SECURITY_SELINUX_NAME);
1133
    if (!seclabel->relabel || (disk_seclabel && !disk_seclabel->relabel))
1134 1135
        return 0;

1136 1137 1138
    /* If labelskip is true and there are no backing files, then we
     * know it is safe to skip the restore.  FIXME - backing files should
     * be tracked in domain XML, at which point labelskip should be a
1139
     * per-file attribute instead of a disk attribute. */
1140
    if (disk_seclabel && disk_seclabel->labelskip &&
1141
        !src->backingStore)
1142 1143
        return 0;

1144 1145 1146 1147 1148 1149
    /* 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 (src->readonly || src->shared)
1150 1151 1152
        return 0;


1153 1154 1155
    /* If we have a shared FS and are doing migration, 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 :-) */
1156
    if (migrated) {
1157
        int rc = virFileIsSharedFS(src->path);
1158 1159 1160 1161
        if (rc < 0)
            return -1;
        if (rc == 1) {
            VIR_DEBUG("Skipping image label restore on %s because FS is shared",
1162
                      src->path);
1163 1164 1165 1166
            return 0;
        }
    }

1167
    return virSecuritySELinuxRestoreSecurityFileLabel(mgr, src->path);
1168 1169
}

1170 1171

static int
1172 1173 1174
virSecuritySELinuxRestoreSecurityDiskLabel(virSecurityManagerPtr mgr,
                                           virDomainDefPtr def,
                                           virDomainDiskDefPtr disk)
1175
{
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
    return virSecuritySELinuxRestoreSecurityImageLabelInt(mgr, def, disk->src,
                                                          false);
}


static int
virSecuritySELinuxRestoreSecurityImageLabel(virSecurityManagerPtr mgr,
                                            virDomainDefPtr def,
                                            virStorageSourcePtr src)
{
    return virSecuritySELinuxRestoreSecurityImageLabelInt(mgr, def, src, false);
1187 1188 1189
}


1190
static int
1191 1192 1193 1194
virSecuritySELinuxSetSecurityImageLabelInternal(virSecurityManagerPtr mgr,
                                                virDomainDefPtr def,
                                                virStorageSourcePtr src,
                                                bool first)
1195
{
1196 1197
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
    virSecurityLabelDefPtr secdef;
1198
    virSecurityDeviceLabelDefPtr disk_seclabel;
1199
    int ret;
1200

1201 1202 1203 1204
    if (!src->path || !virStorageSourceIsLocalStorage(src))
        return 0;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
1205
    if (!secdef || !secdef->relabel)
1206 1207 1208
        return 0;

    disk_seclabel = virStorageSourceGetSecurityLabelDef(src,
1209 1210
                                                        SECURITY_SELINUX_NAME);

1211
    if (disk_seclabel && !disk_seclabel->relabel)
1212 1213
        return 0;

1214
    if (disk_seclabel && disk_seclabel->relabel && disk_seclabel->label) {
1215 1216 1217 1218 1219 1220 1221 1222
        ret = virSecuritySELinuxSetFilecon(src->path, disk_seclabel->label);
    } else if (first) {
        if (src->shared) {
            ret = virSecuritySELinuxSetFileconOptional(src->path,
                                                       data->file_context);
        } else if (src->readonly) {
            ret = virSecuritySELinuxSetFileconOptional(src->path,
                                                       data->content_context);
1223
        } else if (secdef->imagelabel) {
1224 1225
            ret = virSecuritySELinuxSetFileconOptional(src->path,
                                                       secdef->imagelabel);
1226
        } else {
1227
            ret = 0;
1228 1229
        }
    } else {
1230 1231
        ret = virSecuritySELinuxSetFileconOptional(src->path,
                                                   data->content_context);
1232
    }
1233

1234
    if (ret == 1 && !disk_seclabel) {
1235 1236
        /* If we failed to set a label, but virt_use_nfs let us
         * proceed anyway, then we don't need to relabel later.  */
1237
        disk_seclabel = virSecurityDeviceLabelDefNew(SECURITY_SELINUX_NAME);
1238
        if (!disk_seclabel)
1239
            return -1;
1240
        disk_seclabel->labelskip = true;
1241
        if (VIR_APPEND_ELEMENT(src->seclabels, src->nseclabels,
1242
                               disk_seclabel) < 0) {
1243 1244 1245
            virSecurityDeviceLabelDefFree(disk_seclabel);
            return -1;
        }
1246
        ret = 0;
1247
    }
1248

1249
    return ret;
1250 1251
}

1252 1253 1254 1255 1256 1257 1258 1259 1260 1261

static int
virSecuritySELinuxSetSecurityImageLabel(virSecurityManagerPtr mgr,
                                        virDomainDefPtr def,
                                        virStorageSourcePtr src)
{
    return virSecuritySELinuxSetSecurityImageLabelInternal(mgr, def, src, true);
}


1262
static int
1263 1264 1265
virSecuritySELinuxSetSecurityDiskLabel(virSecurityManagerPtr mgr,
                                       virDomainDefPtr def,
                                       virDomainDiskDefPtr disk)
1266 1267

{
1268 1269
    bool first = true;
    virStorageSourcePtr next;
1270

1271 1272 1273 1274
    for (next = disk->src; next; next = next->backingStore) {
        if (virSecuritySELinuxSetSecurityImageLabelInternal(mgr, def, next,
                                                            first) < 0)
            return -1;
1275

1276 1277 1278 1279
        first = false;
    }

    return 0;
1280 1281
}

1282

1283
static int
1284
virSecuritySELinuxSetSecurityHostdevLabelHelper(const char *file, void *opaque)
1285
{
1286
    virSecurityLabelDefPtr secdef;
1287
    virDomainDefPtr def = opaque;
1288

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

static int
1296
virSecuritySELinuxSetSecurityPCILabel(virPCIDevicePtr dev ATTRIBUTE_UNUSED,
1297
                                      const char *file, void *opaque)
1298
{
1299 1300
    return virSecuritySELinuxSetSecurityHostdevLabelHelper(file, opaque);
}
1301

1302 1303 1304 1305 1306
static int
virSecuritySELinuxSetSecurityUSBLabel(virUSBDevicePtr dev ATTRIBUTE_UNUSED,
                                      const char *file, void *opaque)
{
    return virSecuritySELinuxSetSecurityHostdevLabelHelper(file, opaque);
1307 1308
}

1309 1310 1311 1312 1313 1314
static int
virSecuritySELinuxSetSecuritySCSILabel(virSCSIDevicePtr dev ATTRIBUTE_UNUSED,
                                       const char *file, void *opaque)
{
    return virSecuritySELinuxSetSecurityHostdevLabelHelper(file, opaque);
}
1315

1316
static int
1317 1318 1319
virSecuritySELinuxSetSecurityHostdevSubsysLabel(virDomainDefPtr def,
                                                virDomainHostdevDefPtr dev,
                                                const char *vroot)
1320 1321

{
1322
    virDomainHostdevSubsysUSBPtr usbsrc = &dev->source.subsys.u.usb;
1323
    virDomainHostdevSubsysPCIPtr pcisrc = &dev->source.subsys.u.pci;
1324
    virDomainHostdevSubsysSCSIPtr scsisrc = &dev->source.subsys.u.scsi;
1325 1326 1327 1328
    int ret = -1;

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

1331 1332 1333
        if (dev->missing)
            return 0;

1334 1335
        usb = virUSBDeviceNew(usbsrc->bus,
                              usbsrc->device,
1336
                              vroot);
1337 1338
        if (!usb)
            goto done;
1339

1340 1341
        ret = virUSBDeviceFileIterate(usb, virSecuritySELinuxSetSecurityUSBLabel, def);
        virUSBDeviceFree(usb);
M
Mark McLoughlin 已提交
1342
        break;
1343 1344 1345
    }

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI: {
1346
        virPCIDevicePtr pci =
1347 1348
            virPCIDeviceNew(pcisrc->addr.domain, pcisrc->addr.bus,
                            pcisrc->addr.slot, pcisrc->addr.function);
1349 1350 1351 1352

        if (!pci)
            goto done;

1353
        if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
1354
            char *vfioGroupDev = virPCIDeviceGetIOMMUGroupDev(pci);
1355

1356 1357
            if (!vfioGroupDev) {
                virPCIDeviceFree(pci);
1358
                goto done;
1359
            }
1360 1361 1362 1363 1364
            ret = virSecuritySELinuxSetSecurityPCILabel(pci, vfioGroupDev, def);
            VIR_FREE(vfioGroupDev);
        } else {
            ret = virPCIDeviceFileIterate(pci, virSecuritySELinuxSetSecurityPCILabel, def);
        }
1365
        virPCIDeviceFree(pci);
1366 1367 1368
        break;
    }

1369
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI: {
1370
        virDomainHostdevSubsysSCSIHostPtr scsihostsrc = &scsisrc->u.host;
1371
        virSCSIDevicePtr scsi =
1372
            virSCSIDeviceNew(NULL,
1373 1374
                             scsihostsrc->adapter, scsihostsrc->bus,
                             scsihostsrc->target, scsihostsrc->unit,
1375
                             dev->readonly, dev->shareable);
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385

        if (!scsi)
            goto done;

        ret = virSCSIDeviceFileIterate(scsi, virSecuritySELinuxSetSecuritySCSILabel, def);
        virSCSIDeviceFree(scsi);

        break;
    }

1386 1387 1388 1389 1390
    default:
        ret = 0;
        break;
    }

1391
 done:
1392 1393 1394
    return ret;
}

1395

1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
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)
1407
        return 0;
1408 1409 1410 1411 1412

    switch (dev->source.caps.type) {
    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_STORAGE: {
        if (vroot) {
            if (virAsprintf(&path, "%s/%s", vroot,
1413
                            dev->source.caps.u.storage.block) < 0)
1414 1415
                return -1;
        } else {
1416
            if (VIR_STRDUP(path, dev->source.caps.u.storage.block) < 0)
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
                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,
1427
                            dev->source.caps.u.misc.chardev) < 0)
1428 1429
                return -1;
        } else {
1430
            if (VIR_STRDUP(path, dev->source.caps.u.misc.chardev) < 0)
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
                return -1;
        }
        ret = virSecuritySELinuxSetFilecon(path, secdef->imagelabel);
        VIR_FREE(path);
        break;
    }

    default:
        ret = 0;
        break;
    }

    return ret;
}


1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
static int
virSecuritySELinuxSetSecurityHostdevLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                          virDomainDefPtr def,
                                          virDomainHostdevDefPtr dev,
                                          const char *vroot)

{
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
1457
    if (!secdef || !secdef->relabel)
1458 1459 1460 1461 1462 1463
        return 0;

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

1464 1465 1466
    case VIR_DOMAIN_HOSTDEV_MODE_CAPABILITIES:
        return virSecuritySELinuxSetSecurityHostdevCapsLabel(def, dev, vroot);

1467 1468 1469 1470 1471
    default:
        return 0;
    }
}

1472
static int
1473
virSecuritySELinuxRestoreSecurityPCILabel(virPCIDevicePtr dev ATTRIBUTE_UNUSED,
1474
                                          const char *file,
1475
                                          void *opaque)
1476
{
1477 1478 1479
    virSecurityManagerPtr mgr = opaque;

    return virSecuritySELinuxRestoreSecurityFileLabel(mgr, file);
1480 1481 1482
}

static int
1483
virSecuritySELinuxRestoreSecurityUSBLabel(virUSBDevicePtr dev ATTRIBUTE_UNUSED,
1484
                                          const char *file,
1485
                                          void *opaque)
1486
{
1487 1488 1489
    virSecurityManagerPtr mgr = opaque;

    return virSecuritySELinuxRestoreSecurityFileLabel(mgr, file);
1490 1491
}

1492

1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
static int
virSecuritySELinuxRestoreSecuritySCSILabel(virSCSIDevicePtr dev ATTRIBUTE_UNUSED,
                                           const char *file,
                                           void *opaque)
{
    virSecurityManagerPtr mgr = opaque;

    return virSecuritySELinuxRestoreSecurityFileLabel(mgr, file);
}

1503
static int
1504 1505
virSecuritySELinuxRestoreSecurityHostdevSubsysLabel(virSecurityManagerPtr mgr,
                                                    virDomainHostdevDefPtr dev,
1506
                                                    const char *vroot)
1507 1508

{
1509
    virDomainHostdevSubsysUSBPtr usbsrc = &dev->source.subsys.u.usb;
1510
    virDomainHostdevSubsysPCIPtr pcisrc = &dev->source.subsys.u.pci;
1511
    virDomainHostdevSubsysSCSIPtr scsisrc = &dev->source.subsys.u.scsi;
1512 1513 1514 1515
    int ret = -1;

    switch (dev->source.subsys.type) {
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB: {
1516
        virUSBDevicePtr usb;
1517 1518 1519

        if (dev->missing)
            return 0;
1520

1521 1522
        usb = virUSBDeviceNew(usbsrc->bus,
                              usbsrc->device,
1523
                              vroot);
1524 1525 1526
        if (!usb)
            goto done;

1527 1528
        ret = virUSBDeviceFileIterate(usb, virSecuritySELinuxRestoreSecurityUSBLabel, mgr);
        virUSBDeviceFree(usb);
1529 1530 1531 1532 1533

        break;
    }

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI: {
1534
        virPCIDevicePtr pci =
1535 1536
            virPCIDeviceNew(pcisrc->addr.domain, pcisrc->addr.bus,
                            pcisrc->addr.slot, pcisrc->addr.function);
1537 1538 1539 1540

        if (!pci)
            goto done;

1541
        if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
1542
            char *vfioGroupDev = virPCIDeviceGetIOMMUGroupDev(pci);
1543

1544 1545
            if (!vfioGroupDev) {
                virPCIDeviceFree(pci);
1546
                goto done;
1547
            }
1548 1549 1550 1551 1552
            ret = virSecuritySELinuxRestoreSecurityPCILabel(pci, vfioGroupDev, mgr);
            VIR_FREE(vfioGroupDev);
        } else {
            ret = virPCIDeviceFileIterate(pci, virSecuritySELinuxRestoreSecurityPCILabel, mgr);
        }
1553
        virPCIDeviceFree(pci);
1554 1555 1556
        break;
    }

1557
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI: {
1558
        virDomainHostdevSubsysSCSIHostPtr scsihostsrc = &scsisrc->u.host;
1559
        virSCSIDevicePtr scsi =
1560
            virSCSIDeviceNew(NULL,
1561 1562
                             scsihostsrc->adapter, scsihostsrc->bus,
                             scsihostsrc->target, scsihostsrc->unit,
1563
                             dev->readonly, dev->shareable);
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573

            if (!scsi)
                goto done;

            ret = virSCSIDeviceFileIterate(scsi, virSecuritySELinuxRestoreSecuritySCSILabel, mgr);
            virSCSIDeviceFree(scsi);

            break;
       }

1574 1575 1576 1577 1578
    default:
        ret = 0;
        break;
    }

1579
 done:
1580 1581 1582
    return ret;
}

1583

1584
static int
1585 1586
virSecuritySELinuxRestoreSecurityHostdevCapsLabel(virSecurityManagerPtr mgr,
                                                  virDomainHostdevDefPtr dev,
1587 1588 1589 1590 1591 1592 1593 1594 1595
                                                  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,
1596
                            dev->source.caps.u.storage.block) < 0)
1597 1598
                return -1;
        } else {
1599
            if (VIR_STRDUP(path, dev->source.caps.u.storage.block) < 0)
1600 1601
                return -1;
        }
1602
        ret = virSecuritySELinuxRestoreSecurityFileLabel(mgr, path);
1603 1604 1605 1606 1607 1608 1609
        VIR_FREE(path);
        break;
    }

    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_MISC: {
        if (vroot) {
            if (virAsprintf(&path, "%s/%s", vroot,
1610
                            dev->source.caps.u.misc.chardev) < 0)
1611 1612
                return -1;
        } else {
1613
            if (VIR_STRDUP(path, dev->source.caps.u.misc.chardev) < 0)
1614 1615
                return -1;
        }
1616
        ret = virSecuritySELinuxRestoreSecurityFileLabel(mgr, path);
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
        VIR_FREE(path);
        break;
    }

    default:
        ret = 0;
        break;
    }

    return ret;
}


1630
static int
1631
virSecuritySELinuxRestoreSecurityHostdevLabel(virSecurityManagerPtr mgr,
1632 1633 1634 1635 1636 1637 1638 1639
                                              virDomainDefPtr def,
                                              virDomainHostdevDefPtr dev,
                                              const char *vroot)

{
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
1640
    if (!secdef || !secdef->relabel)
1641 1642 1643 1644
        return 0;

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

1647
    case VIR_DOMAIN_HOSTDEV_MODE_CAPABILITIES:
1648
        return virSecuritySELinuxRestoreSecurityHostdevCapsLabel(mgr, dev, vroot);
1649

1650 1651 1652 1653 1654 1655
    default:
        return 0;
    }
}


1656
static int
1657
virSecuritySELinuxSetSecurityChardevLabel(virDomainDefPtr def,
1658 1659
                                          virDomainChrDefPtr dev,
                                          virDomainChrSourceDefPtr dev_source)
1660 1661

{
1662 1663 1664
    virSecurityLabelDefPtr seclabel;
    virSecurityDeviceLabelDefPtr chr_seclabel = NULL;
    char *imagelabel = NULL;
1665 1666 1667
    char *in = NULL, *out = NULL;
    int ret = -1;

1668
    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
1669
    if (!seclabel || !seclabel->relabel)
1670
        return 0;
1671

1672 1673 1674 1675
    if (dev)
        chr_seclabel = virDomainChrDefGetSecurityLabelDef(dev,
                                                          SECURITY_SELINUX_NAME);

1676
    if (chr_seclabel && !chr_seclabel->relabel)
1677 1678
        return 0;

1679 1680 1681 1682 1683 1684
    if (chr_seclabel)
        imagelabel = chr_seclabel->label;
    if (!imagelabel)
        imagelabel = seclabel->imagelabel;

    switch (dev_source->type) {
1685 1686
    case VIR_DOMAIN_CHR_TYPE_DEV:
    case VIR_DOMAIN_CHR_TYPE_FILE:
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
        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;
1698 1699 1700
        break;

    case VIR_DOMAIN_CHR_TYPE_PIPE:
1701
        if ((virAsprintf(&in, "%s.in", dev_source->data.file.path) < 0) ||
1702
            (virAsprintf(&out, "%s.out", dev_source->data.file.path) < 0))
1703 1704
            goto done;
        if (virFileExists(in) && virFileExists(out)) {
1705 1706
            if ((virSecuritySELinuxSetFilecon(in, imagelabel) < 0) ||
                (virSecuritySELinuxSetFilecon(out, imagelabel) < 0)) {
1707
                goto done;
1708
            }
1709 1710
        } else if (virSecuritySELinuxSetFilecon(dev_source->data.file.path,
                                                imagelabel) < 0) {
1711
            goto done;
1712 1713 1714 1715 1716 1717 1718 1719 1720
        }
        ret = 0;
        break;

    default:
        ret = 0;
        break;
    }

1721
 done:
1722 1723 1724 1725 1726 1727
    VIR_FREE(in);
    VIR_FREE(out);
    return ret;
}

static int
1728 1729
virSecuritySELinuxRestoreSecurityChardevLabel(virSecurityManagerPtr mgr,
                                              virDomainDefPtr def,
1730 1731
                                              virDomainChrDefPtr dev,
                                              virDomainChrSourceDefPtr dev_source)
1732 1733

{
1734 1735
    virSecurityLabelDefPtr seclabel;
    virSecurityDeviceLabelDefPtr chr_seclabel = NULL;
1736 1737 1738
    char *in = NULL, *out = NULL;
    int ret = -1;

1739
    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
1740
    if (!seclabel || !seclabel->relabel)
1741
        return 0;
1742

1743 1744 1745
    if (dev)
        chr_seclabel = virDomainChrDefGetSecurityLabelDef(dev,
                                                          SECURITY_SELINUX_NAME);
1746
    if (chr_seclabel && !chr_seclabel->relabel)
1747 1748
        return 0;

1749
    switch (dev_source->type) {
1750 1751
    case VIR_DOMAIN_CHR_TYPE_DEV:
    case VIR_DOMAIN_CHR_TYPE_FILE:
1752
        if (virSecuritySELinuxRestoreSecurityFileLabel(mgr, dev_source->data.file.path) < 0)
1753 1754
            goto done;
        ret = 0;
1755
        break;
1756 1757 1758

    case VIR_DOMAIN_CHR_TYPE_UNIX:
        if (!dev_source->data.nix.listen) {
1759
            if (virSecuritySELinuxRestoreSecurityFileLabel(mgr, dev_source->data.file.path) < 0)
1760 1761 1762 1763 1764
                goto done;
        }
        ret = 0;
        break;

1765
    case VIR_DOMAIN_CHR_TYPE_PIPE:
1766
        if ((virAsprintf(&out, "%s.out", dev_source->data.file.path) < 0) ||
1767
            (virAsprintf(&in, "%s.in", dev_source->data.file.path) < 0))
1768
            goto done;
1769
        if (virFileExists(in) && virFileExists(out)) {
1770 1771
            if ((virSecuritySELinuxRestoreSecurityFileLabel(mgr, out) < 0) ||
                (virSecuritySELinuxRestoreSecurityFileLabel(mgr, in) < 0)) {
1772 1773
                goto done;
            }
1774
        } else if (virSecuritySELinuxRestoreSecurityFileLabel(mgr, dev_source->data.file.path) < 0) {
1775
            goto done;
1776
        }
1777 1778 1779 1780 1781 1782 1783 1784
        ret = 0;
        break;

    default:
        ret = 0;
        break;
    }

1785
 done:
1786 1787 1788 1789 1790 1791 1792
    VIR_FREE(in);
    VIR_FREE(out);
    return ret;
}


static int
1793 1794
virSecuritySELinuxRestoreSecurityChardevCallback(virDomainDefPtr def,
                                                 virDomainChrDefPtr dev,
1795
                                                 void *opaque)
1796
{
1797 1798
    virSecurityManagerPtr mgr = opaque;

1799 1800 1801 1802 1803
    /* 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;

1804
    return virSecuritySELinuxRestoreSecurityChardevLabel(mgr, def, dev,
1805
                                                         &dev->source);
1806 1807 1808
}


E
Eric Blake 已提交
1809
static int
1810 1811
virSecuritySELinuxRestoreSecuritySmartcardCallback(virDomainDefPtr def,
                                                   virDomainSmartcardDefPtr dev,
1812
                                                   void *opaque)
E
Eric Blake 已提交
1813
{
1814
    virSecurityManagerPtr mgr = opaque;
E
Eric Blake 已提交
1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
    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;
1825
        return virSecuritySELinuxRestoreSecurityFileLabel(mgr, database);
E
Eric Blake 已提交
1826 1827

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

    default:
1831 1832 1833
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown smartcard type %d"),
                       dev->type);
E
Eric Blake 已提交
1834 1835 1836 1837 1838 1839 1840
        return -1;
    }

    return 0;
}


1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
static const char *
virSecuritySELinuxGetBaseLabel(virSecurityManagerPtr mgr, int virtType)
{
    virSecuritySELinuxDataPtr priv = virSecurityManagerGetPrivateData(mgr);
    if (virtType == VIR_DOMAIN_VIRT_QEMU && priv->alt_domain_context)
        return priv->alt_domain_context;
    else
        return priv->domain_context;
}


1852
static int
1853
virSecuritySELinuxRestoreSecurityAllLabel(virSecurityManagerPtr mgr,
1854
                                          virDomainDefPtr def,
1855
                                          bool migrated)
1856
{
1857
    virSecurityLabelDefPtr secdef;
1858
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
1859
    size_t i;
1860
    int rc = 0;
1861

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

1864 1865
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);

1866
    if (!secdef || !secdef->relabel || data->skipAllLabel)
1867 1868
        return 0;

1869 1870 1871 1872 1873 1874
    if (def->tpm) {
        if (virSecuritySELinuxRestoreSecurityTPMFileLabelInt(mgr, def,
                                                             def->tpm) < 0)
            rc = -1;
    }

1875
    for (i = 0; i < def->nhostdevs; i++) {
1876 1877
        if (virSecuritySELinuxRestoreSecurityHostdevLabel(mgr,
                                                          def,
1878 1879
                                                          def->hostdevs[i],
                                                          NULL) < 0)
1880
            rc = -1;
1881
    }
1882
    for (i = 0; i < def->ndisks; i++) {
1883 1884 1885
        virDomainDiskDefPtr disk = def->disks[i];

        if (virSecuritySELinuxRestoreSecurityImageLabelInt(mgr, def, disk->src,
1886
                                                           migrated) < 0)
1887 1888
            rc = -1;
    }
1889

1890
    if (virDomainChrDefForeach(def,
1891
                               false,
1892
                               virSecuritySELinuxRestoreSecurityChardevCallback,
1893
                               mgr) < 0)
1894 1895
        rc = -1;

1896
    if (virDomainSmartcardDefForeach(def,
E
Eric Blake 已提交
1897
                                     false,
1898
                                     virSecuritySELinuxRestoreSecuritySmartcardCallback,
1899
                                     mgr) < 0)
E
Eric Blake 已提交
1900 1901
        rc = -1;

1902
    if (def->os.kernel &&
1903
        virSecuritySELinuxRestoreSecurityFileLabel(mgr, def->os.kernel) < 0)
1904 1905
        rc = -1;

1906
    if (def->os.initrd &&
1907
        virSecuritySELinuxRestoreSecurityFileLabel(mgr, def->os.initrd) < 0)
1908 1909
        rc = -1;

O
Olivia Yin 已提交
1910 1911 1912 1913
    if (def->os.dtb &&
        virSecuritySELinuxRestoreSecurityFileLabel(mgr, def->os.dtb) < 0)
        rc = -1;

1914 1915 1916 1917
    return rc;
}

static int
1918
virSecuritySELinuxReleaseSecurityLabel(virSecurityManagerPtr mgr,
1919
                                       virDomainDefPtr def)
1920
{
1921 1922 1923 1924
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
1925
        return 0;
1926

1927 1928 1929 1930
    if (secdef->type == VIR_DOMAIN_SECLABEL_DYNAMIC) {
        if (secdef->label != NULL) {
            context_t con = context_new(secdef->label);
            if (con) {
1931
                virSecuritySELinuxMCSRemove(mgr, context_range_get(con));
1932 1933 1934 1935 1936 1937
                context_free(con);
            }
        }
        VIR_FREE(secdef->label);
        if (!secdef->baselabel)
            VIR_FREE(secdef->model);
1938 1939 1940
    }
    VIR_FREE(secdef->imagelabel);

1941
    return 0;
1942 1943
}

1944 1945

static int
1946 1947 1948
virSecuritySELinuxSetSavedStateLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                     virDomainDefPtr def,
                                     const char *savefile)
1949
{
1950 1951 1952
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
1953
    if (!secdef || !secdef->relabel)
1954 1955
        return 0;

1956
    return virSecuritySELinuxSetFilecon(savefile, secdef->imagelabel);
1957 1958 1959 1960
}


static int
1961
virSecuritySELinuxRestoreSavedStateLabel(virSecurityManagerPtr mgr,
1962 1963
                                         virDomainDefPtr def,
                                         const char *savefile)
1964
{
1965 1966 1967
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
1968
    if (!secdef || !secdef->relabel)
1969 1970
        return 0;

1971
    return virSecuritySELinuxRestoreSecurityFileLabel(mgr, savefile);
1972 1973 1974
}


1975
static int
1976 1977
virSecuritySELinuxSecurityVerify(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                 virDomainDefPtr def)
1978
{
1979 1980 1981 1982
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
1983
        return 0;
1984

1985
    if (!STREQ(SECURITY_SELINUX_NAME, secdef->model)) {
1986 1987 1988 1989
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "'%s' model configured for domain, but "
                         "hypervisor driver is '%s'."),
1990
                       secdef->model, SECURITY_SELINUX_NAME);
1991 1992 1993
        return -1;
    }

1994 1995
    if (secdef->type == VIR_DOMAIN_SECLABEL_STATIC) {
        if (security_check_context(secdef->label) != 0) {
1996 1997
            virReportError(VIR_ERR_XML_ERROR,
                           _("Invalid security label %s"), secdef->label);
1998 1999 2000 2001 2002 2003
            return -1;
        }
    }
    return 0;
}

2004
static int
2005
virSecuritySELinuxSetSecurityProcessLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
2006
                                          virDomainDefPtr def)
2007 2008
{
    /* TODO: verify DOI */
2009 2010 2011
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2012
    if (!secdef || !secdef->label)
2013 2014
        return 0;

2015
    VIR_DEBUG("label=%s", secdef->label);
2016
    if (!STREQ(SECURITY_SELINUX_NAME, secdef->model)) {
2017 2018 2019 2020
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "'%s' model configured for domain, but "
                         "hypervisor driver is '%s'."),
2021
                       secdef->model, SECURITY_SELINUX_NAME);
2022
        if (security_getenforce() == 1)
2023
            return -1;
2024 2025
    }

M
Martin Kletzander 已提交
2026
    if (setexeccon_raw(secdef->label) == -1) {
2027
        virReportSystemError(errno,
2028 2029
                             _("unable to set security context '%s'"),
                             secdef->label);
2030
        if (security_getenforce() == 1)
2031
            return -1;
2032 2033
    }

2034 2035 2036
    return 0;
}

2037 2038 2039 2040 2041 2042 2043 2044 2045
static int
virSecuritySELinuxSetSecurityChildProcessLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                               virDomainDefPtr def,
                                               virCommandPtr cmd)
{
    /* TODO: verify DOI */
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2046
    if (!secdef || !secdef->label)
2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
        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;
}

2065
static int
2066
virSecuritySELinuxSetSecurityDaemonSocketLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
2067
                                               virDomainDefPtr def)
2068 2069
{
    /* TODO: verify DOI */
2070
    virSecurityLabelDefPtr secdef;
2071
    security_context_t scon = NULL;
2072
    char *str = NULL;
2073 2074
    int rc = -1;

2075
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2076
    if (!secdef || !secdef->label)
2077 2078
        return 0;

2079
    if (!STREQ(SECURITY_SELINUX_NAME, secdef->model)) {
2080 2081 2082 2083
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "'%s' model configured for domain, but "
                         "hypervisor driver is '%s'."),
2084
                       secdef->model, SECURITY_SELINUX_NAME);
2085 2086 2087
        goto done;
    }

M
Martin Kletzander 已提交
2088
    if (getcon_raw(&scon) == -1) {
2089 2090 2091 2092 2093 2094
        virReportSystemError(errno,
                             _("unable to get current process context '%s'"),
                             secdef->label);
        goto done;
    }

2095
    if (!(str = virSecuritySELinuxContextAddRange(secdef->label, scon)))
2096 2097
        goto done;

2098 2099
    VIR_DEBUG("Setting VM %s socket context %s", def->name, str);
    if (setsockcreatecon_raw(str) == -1) {
2100
        virReportSystemError(errno,
2101
                             _("unable to set socket security context '%s'"), str);
2102 2103 2104 2105
        goto done;
    }

    rc = 0;
2106
 done:
2107 2108 2109 2110

    if (security_getenforce() != 1)
        rc = 0;
    freecon(scon);
2111
    VIR_FREE(str);
2112 2113 2114
    return rc;
}

2115
static int
2116
virSecuritySELinuxSetSecuritySocketLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
2117
                                         virDomainDefPtr vm)
2118
{
2119
    virSecurityLabelDefPtr secdef;
2120 2121
    int rc = -1;

2122
    secdef = virDomainDefGetSecurityLabelDef(vm, SECURITY_SELINUX_NAME);
2123
    if (!secdef || !secdef->label)
2124 2125
        return 0;

2126
    if (!STREQ(SECURITY_SELINUX_NAME, secdef->model)) {
2127 2128 2129 2130
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "'%s' model configured for domain, but "
                         "hypervisor driver is '%s'."),
2131
                       secdef->model, SECURITY_SELINUX_NAME);
2132 2133 2134 2135
        goto done;
    }

    VIR_DEBUG("Setting VM %s socket context %s",
2136
              vm->name, secdef->label);
M
Martin Kletzander 已提交
2137
    if (setsockcreatecon_raw(secdef->label) == -1) {
2138 2139 2140 2141 2142 2143 2144 2145
        virReportSystemError(errno,
                             _("unable to set socket security context '%s'"),
                             secdef->label);
        goto done;
    }

    rc = 0;

2146
 done:
2147 2148 2149 2150 2151 2152
    if (security_getenforce() != 1)
        rc = 0;

    return rc;
}

2153
static int
2154
virSecuritySELinuxClearSecuritySocketLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
2155
                                           virDomainDefPtr def)
2156 2157
{
    /* TODO: verify DOI */
2158 2159 2160
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2161
    if (!secdef || !secdef->label)
2162 2163
        return 0;

2164
    if (!STREQ(SECURITY_SELINUX_NAME, secdef->model)) {
2165 2166 2167 2168
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "'%s' model configured for domain, but "
                         "hypervisor driver is '%s'."),
2169
                       secdef->model, SECURITY_SELINUX_NAME);
2170 2171 2172 2173
        if (security_getenforce() == 1)
            return -1;
    }

M
Martin Kletzander 已提交
2174
    if (setsockcreatecon_raw(NULL) == -1) {
2175 2176 2177 2178 2179 2180 2181 2182 2183
        virReportSystemError(errno,
                             _("unable to clear socket security context '%s'"),
                             secdef->label);
        if (security_getenforce() == 1)
            return -1;
    }
    return 0;
}

2184 2185

static int
2186 2187 2188
virSecuritySELinuxSetSecurityChardevCallback(virDomainDefPtr def,
                                             virDomainChrDefPtr dev,
                                             void *opaque ATTRIBUTE_UNUSED)
2189
{
2190 2191 2192 2193 2194
    /* 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;

2195
    return virSecuritySELinuxSetSecurityChardevLabel(def, dev, &dev->source);
2196 2197 2198
}


E
Eric Blake 已提交
2199
static int
2200 2201 2202
virSecuritySELinuxSetSecuritySmartcardCallback(virDomainDefPtr def,
                                               virDomainSmartcardDefPtr dev,
                                               void *opaque)
E
Eric Blake 已提交
2203 2204
{
    const char *database;
2205 2206
    virSecurityManagerPtr mgr = opaque;
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
E
Eric Blake 已提交
2207 2208 2209 2210 2211 2212 2213 2214 2215

    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;
2216
        return virSecuritySELinuxSetFilecon(database, data->content_context);
E
Eric Blake 已提交
2217 2218

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

    default:
2222 2223 2224
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown smartcard type %d"),
                       dev->type);
E
Eric Blake 已提交
2225 2226 2227 2228 2229 2230 2231
        return -1;
    }

    return 0;
}


2232
static int
2233 2234 2235
virSecuritySELinuxSetSecurityAllLabel(virSecurityManagerPtr mgr,
                                      virDomainDefPtr def,
                                      const char *stdin_path)
2236
{
2237
    size_t i;
2238 2239 2240 2241
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2242

2243
    if (!secdef || !secdef->relabel || data->skipAllLabel)
2244 2245
        return 0;

2246
    for (i = 0; i < def->ndisks; i++) {
2247
        /* XXX fixme - we need to recursively label the entire tree :-( */
E
Eric Blake 已提交
2248
        if (virDomainDiskGetType(def->disks[i]) == VIR_STORAGE_TYPE_DIR) {
2249
            VIR_WARN("Unable to relabel directory tree %s for disk %s",
2250 2251
                     virDomainDiskGetSource(def->disks[i]),
                     def->disks[i]->dst);
2252
            continue;
2253
        }
2254
        if (virSecuritySELinuxSetSecurityDiskLabel(mgr,
2255
                                         def, def->disks[i]) < 0)
2256 2257
            return -1;
    }
2258
    /* XXX fixme process  def->fss if relabel == true */
2259

2260
    for (i = 0; i < def->nhostdevs; i++) {
2261
        if (virSecuritySELinuxSetSecurityHostdevLabel(mgr,
2262 2263 2264
                                                      def,
                                                      def->hostdevs[i],
                                                      NULL) < 0)
2265
            return -1;
2266
    }
2267 2268 2269 2270 2271
    if (def->tpm) {
        if (virSecuritySELinuxSetSecurityTPMFileLabel(mgr, def,
                                                      def->tpm) < 0)
            return -1;
    }
2272

2273
    if (virDomainChrDefForeach(def,
2274
                               true,
2275
                               virSecuritySELinuxSetSecurityChardevCallback,
2276
                               NULL) < 0)
2277 2278
        return -1;

2279
    if (virDomainSmartcardDefForeach(def,
E
Eric Blake 已提交
2280
                                     true,
2281
                                     virSecuritySELinuxSetSecuritySmartcardCallback,
2282
                                     mgr) < 0)
E
Eric Blake 已提交
2283 2284
        return -1;

2285
    if (def->os.kernel &&
2286
        virSecuritySELinuxSetFilecon(def->os.kernel, data->content_context) < 0)
2287 2288
        return -1;

2289
    if (def->os.initrd &&
2290
        virSecuritySELinuxSetFilecon(def->os.initrd, data->content_context) < 0)
2291 2292
        return -1;

O
Olivia Yin 已提交
2293 2294 2295 2296
    if (def->os.dtb &&
        virSecuritySELinuxSetFilecon(def->os.dtb, data->content_context) < 0)
        return -1;

2297
    if (stdin_path) {
2298
        if (virSecuritySELinuxSetFilecon(stdin_path, data->content_context) < 0 &&
2299
            virFileIsSharedFSType(stdin_path, VIR_FILE_SHFS_NFS) != 1)
2300 2301
            return -1;
    }
2302

2303 2304 2305
    return 0;
}

2306
static int
2307 2308 2309
virSecuritySELinuxSetImageFDLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                  virDomainDefPtr def,
                                  int fd)
2310
{
2311 2312 2313
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2314
    if (!secdef || !secdef->imagelabel)
2315 2316
        return 0;

2317
    return virSecuritySELinuxFSetFilecon(fd, secdef->imagelabel);
2318 2319
}

2320
static int
2321
virSecuritySELinuxSetTapFDLabel(virSecurityManagerPtr mgr,
2322 2323 2324 2325 2326 2327 2328 2329 2330 2331
                                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);
2332
    if (!secdef || !secdef->label)
2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345
        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;
    }

2346
    if (getContext(mgr, "/dev/tap.*", buf.st_mode, &fcon) < 0) {
2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357
        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);
    }

2358
 cleanup:
2359 2360 2361 2362 2363
    freecon(fcon);
    VIR_FREE(str);
    return rc;
}

2364 2365 2366 2367
static char *
virSecuritySELinuxGenImageLabel(virSecurityManagerPtr mgr,
                                virDomainDefPtr def)
{
2368
    virSecurityLabelDefPtr secdef;
2369 2370 2371 2372
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
    const char *range;
    context_t ctx = NULL;
    char *label = NULL;
2373
    char *mcs = NULL;
2374

2375 2376 2377 2378
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        goto cleanup;

2379 2380 2381
    if (secdef->label) {
        ctx = context_new(secdef->label);
        if (!ctx) {
2382 2383
            virReportSystemError(errno, _("unable to create selinux context for: %s"),
                                 secdef->label);
2384 2385 2386 2387
            goto cleanup;
        }
        range = context_range_get(ctx);
        if (range) {
2388
            if (VIR_STRDUP(mcs, range) < 0)
2389
                goto cleanup;
2390 2391
            if (!(label = virSecuritySELinuxGenNewContext(data->file_context,
                                                          mcs, true)))
2392 2393 2394 2395
                goto cleanup;
        }
    }

2396
 cleanup:
2397 2398 2399
    context_free(ctx);
    VIR_FREE(mcs);
    return label;
2400 2401
}

2402 2403 2404 2405
static char *
virSecuritySELinuxGetSecurityMountOptions(virSecurityManagerPtr mgr,
                                          virDomainDefPtr def)
{
2406
    char *opts = NULL;
2407 2408
    virSecurityLabelDefPtr secdef;

2409 2410 2411 2412 2413 2414 2415
    if ((secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME))) {
        if (!secdef->imagelabel)
            secdef->imagelabel = virSecuritySELinuxGenImageLabel(mgr, def);

        if (secdef->imagelabel &&
            virAsprintf(&opts,
                        ",context=\"%s\"",
2416
                        (const char*) secdef->imagelabel) < 0)
2417 2418
            return NULL;
    }
2419

2420
    if (!opts && VIR_STRDUP(opts, "") < 0)
2421
        return NULL;
2422

2423 2424
    VIR_DEBUG("imageLabel=%s opts=%s",
              secdef ? secdef->imagelabel : "(null)", opts);
2425 2426 2427
    return opts;
}

2428
virSecurityDriver virSecurityDriverSELinux = {
2429 2430
    .privateDataLen                     = sizeof(virSecuritySELinuxData),
    .name                               = SECURITY_SELINUX_NAME,
2431 2432 2433
    .probe                              = virSecuritySELinuxSecurityDriverProbe,
    .open                               = virSecuritySELinuxSecurityDriverOpen,
    .close                              = virSecuritySELinuxSecurityDriverClose,
2434

2435 2436
    .getModel                           = virSecuritySELinuxSecurityGetModel,
    .getDOI                             = virSecuritySELinuxSecurityGetDOI,
2437

2438
    .domainSecurityVerify               = virSecuritySELinuxSecurityVerify,
2439

2440
    .domainSetSecurityDiskLabel         = virSecuritySELinuxSetSecurityDiskLabel,
2441
    .domainRestoreSecurityDiskLabel     = virSecuritySELinuxRestoreSecurityDiskLabel,
2442

2443
    .domainSetSecurityImageLabel        = virSecuritySELinuxSetSecurityImageLabel,
2444 2445
    .domainRestoreSecurityImageLabel    = virSecuritySELinuxRestoreSecurityImageLabel,

2446 2447 2448
    .domainSetSecurityDaemonSocketLabel = virSecuritySELinuxSetSecurityDaemonSocketLabel,
    .domainSetSecuritySocketLabel       = virSecuritySELinuxSetSecuritySocketLabel,
    .domainClearSecuritySocketLabel     = virSecuritySELinuxClearSecuritySocketLabel,
2449

2450 2451 2452
    .domainGenSecurityLabel             = virSecuritySELinuxGenSecurityLabel,
    .domainReserveSecurityLabel         = virSecuritySELinuxReserveSecurityLabel,
    .domainReleaseSecurityLabel         = virSecuritySELinuxReleaseSecurityLabel,
2453

2454 2455
    .domainGetSecurityProcessLabel      = virSecuritySELinuxGetSecurityProcessLabel,
    .domainSetSecurityProcessLabel      = virSecuritySELinuxSetSecurityProcessLabel,
2456
    .domainSetSecurityChildProcessLabel = virSecuritySELinuxSetSecurityChildProcessLabel,
2457

2458 2459
    .domainSetSecurityAllLabel          = virSecuritySELinuxSetSecurityAllLabel,
    .domainRestoreSecurityAllLabel      = virSecuritySELinuxRestoreSecurityAllLabel,
2460

2461 2462
    .domainSetSecurityHostdevLabel      = virSecuritySELinuxSetSecurityHostdevLabel,
    .domainRestoreSecurityHostdevLabel  = virSecuritySELinuxRestoreSecurityHostdevLabel,
2463

2464 2465
    .domainSetSavedStateLabel           = virSecuritySELinuxSetSavedStateLabel,
    .domainRestoreSavedStateLabel       = virSecuritySELinuxRestoreSavedStateLabel,
2466

2467
    .domainSetSecurityImageFDLabel      = virSecuritySELinuxSetImageFDLabel,
2468
    .domainSetSecurityTapFDLabel        = virSecuritySELinuxSetTapFDLabel,
2469

2470
    .domainGetSecurityMountOptions      = virSecuritySELinuxGetSecurityMountOptions,
2471
    .getBaseLabel                       = virSecuritySELinuxGetBaseLabel,
2472
};