security_selinux.c 100.2 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 "virmdev.h"
40
#include "virpci.h"
41
#include "virusb.h"
42
#include "virscsi.h"
43
#include "virscsivhost.h"
44
#include "virstoragefile.h"
E
Eric Blake 已提交
45
#include "virfile.h"
46
#include "virhash.h"
47
#include "virrandom.h"
48
#include "virconf.h"
49
#include "virtpm.h"
50
#include "virstring.h"
D
Daniel P. Berrange 已提交
51 52 53

#define VIR_FROM_THIS VIR_FROM_SECURITY

54 55
VIR_LOG_INIT("security.security_selinux");

56 57 58 59 60 61 62
#define MAX_CONTEXT 1024

typedef struct _virSecuritySELinuxData virSecuritySELinuxData;
typedef virSecuritySELinuxData *virSecuritySELinuxDataPtr;

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

73 74 75
/* Data structure to pass to various callbacks so we have everything we need */
typedef struct _virSecuritySELinuxCallbackData virSecuritySELinuxCallbackData;
typedef virSecuritySELinuxCallbackData *virSecuritySELinuxCallbackDataPtr;
76

77
struct _virSecuritySELinuxCallbackData {
78 79 80 81
    virSecurityManagerPtr mgr;
    virDomainDefPtr def;
};

82 83 84
typedef struct _virSecuritySELinuxContextItem virSecuritySELinuxContextItem;
typedef virSecuritySELinuxContextItem *virSecuritySELinuxContextItemPtr;
struct _virSecuritySELinuxContextItem {
85 86
    char *path;
    char *tcon;
87 88 89 90 91 92
    bool optional;
};

typedef struct _virSecuritySELinuxContextList virSecuritySELinuxContextList;
typedef virSecuritySELinuxContextList *virSecuritySELinuxContextListPtr;
struct _virSecuritySELinuxContextList {
93
    virSecurityManagerPtr manager;
94 95
    virSecuritySELinuxContextItemPtr *items;
    size_t nItems;
96
    bool lock;
97 98
};

99 100 101
#define SECURITY_SELINUX_VOID_DOI       "0"
#define SECURITY_SELINUX_NAME "selinux"

102
static int
103 104 105
virSecuritySELinuxRestoreTPMFileLabelInt(virSecurityManagerPtr mgr,
                                         virDomainDefPtr def,
                                         virDomainTPMDefPtr tpm);
106 107


108 109
virThreadLocal contextList;

110 111 112 113 114 115 116 117 118 119 120 121

static void
virSecuritySELinuxContextItemFree(virSecuritySELinuxContextItemPtr item)
{
    if (!item)
        return;

    VIR_FREE(item->path);
    VIR_FREE(item->tcon);
    VIR_FREE(item);
}

122 123 124 125 126 127
static int
virSecuritySELinuxContextListAppend(virSecuritySELinuxContextListPtr list,
                                    const char *path,
                                    const char *tcon,
                                    bool optional)
{
128 129
    int ret = -1;
    virSecuritySELinuxContextItemPtr item = NULL;
130 131 132 133

    if (VIR_ALLOC(item) < 0)
        return -1;

134 135 136
    if (VIR_STRDUP(item->path, path) < 0 || VIR_STRDUP(item->tcon, tcon) < 0)
        goto cleanup;

137 138
    item->optional = optional;

139 140
    if (VIR_APPEND_ELEMENT(list->items, list->nItems, item) < 0)
        goto cleanup;
141

142 143 144 145
    ret = 0;
 cleanup:
    virSecuritySELinuxContextItemFree(item);
    return ret;
146 147 148 149 150 151 152 153 154 155 156 157
}

static void
virSecuritySELinuxContextListFree(void *opaque)
{
    virSecuritySELinuxContextListPtr list = opaque;
    size_t i;

    if (!list)
        return;

    for (i = 0; i < list->nItems; i++)
158 159
        virSecuritySELinuxContextItemFree(list->items[i]);

160
    VIR_FREE(list->items);
161
    virObjectUnref(list->manager);
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    VIR_FREE(list);
}


/**
 * virSecuritySELinuxTransactionAppend:
 * @path: Path to chown
 * @tcon: target context
 * @optional: true if setting @tcon is optional
 *
 * Appends an entry onto transaction list.
 *
 * Returns: 1 in case of successful append
 *          0 if there is no transaction enabled
 *         -1 otherwise.
 */
static int
virSecuritySELinuxTransactionAppend(const char *path,
                                    const char *tcon,
                                    bool optional)
{
    virSecuritySELinuxContextListPtr list;

    list = virThreadLocalGet(&contextList);
    if (!list)
        return 0;

    if (virSecuritySELinuxContextListAppend(list, path, tcon, optional) < 0)
        return -1;

    return 1;
}


static int virSecuritySELinuxSetFileconHelper(const char *path,
                                              const char *tcon,
                                              bool optional,
                                              bool privileged);

/**
 * virSecuritySELinuxTransactionRun:
 * @pid: process pid
 * @opaque: opaque data
 *
 * This is the callback that runs in the same namespace as the domain we are
 * relabelling. For given transaction (@opaque) it relabels all the paths on
 * the list.
 *
 * Returns: 0 on success
 *         -1 otherwise.
 */
static int
virSecuritySELinuxTransactionRun(pid_t pid ATTRIBUTE_UNUSED,
                                 void *opaque)
{
    virSecuritySELinuxContextListPtr list = opaque;
218
    virSecurityManagerMetadataLockStatePtr state;
219 220 221
    bool privileged = virSecurityManagerGetPrivileged(list->manager);
    const char **paths = NULL;
    size_t npaths = 0;
222
    size_t i;
223 224 225
    int rv;
    int ret = -1;

226 227 228
    if (list->lock) {
        if (VIR_ALLOC_N(paths, list->nItems) < 0)
            return -1;
229

230 231
        for (i = 0; i < list->nItems; i++) {
            const char *p = list->items[i]->path;
232

233 234
            VIR_APPEND_ELEMENT_COPY_INPLACE(paths, npaths, p);
        }
235

236
        if (!(state = virSecurityManagerMetadataLock(list->manager, paths, npaths)))
237 238
            goto cleanup;
    }
239

240
    rv = 0;
241 242 243 244 245 246 247
    for (i = 0; i < list->nItems; i++) {
        virSecuritySELinuxContextItemPtr item = list->items[i];

        /* TODO Implement rollback */
        if (virSecuritySELinuxSetFileconHelper(item->path,
                                               item->tcon,
                                               item->optional,
248 249 250 251
                                               privileged) < 0) {
            rv = -1;
            break;
        }
252 253
    }

254 255
    if (list->lock)
        virSecurityManagerMetadataUnlock(list->manager, &state);
256 257 258 259 260 261 262 263

    if (rv < 0)
        goto cleanup;

    ret = 0;
 cleanup:
    VIR_FREE(paths);
    return ret;
264 265 266
}


267 268 269
/*
 * Returns 0 on success, 1 if already reserved, or -1 on fatal error
 */
270
static int
271 272
virSecuritySELinuxMCSAdd(virSecurityManagerPtr mgr,
                         const char *mcs)
273
{
274
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
275

276 277 278 279
    if (virHashLookup(data->mcs, mcs))
        return 1;

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

282 283 284
    return 0;
}

285 286 287
static void
virSecuritySELinuxMCSRemove(virSecurityManagerPtr mgr,
                            const char *mcs)
288
{
289 290 291
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);

    virHashRemoveEntry(data->mcs, mcs);
292 293
}

294 295

static char *
296 297 298 299
virSecuritySELinuxMCSFind(virSecurityManagerPtr mgr,
                          const char *sens,
                          int catMin,
                          int catMax)
300 301
{
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
302
    int catRange;
303
    char *mcs = NULL;
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324

    /* +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) {
325
            if (virAsprintf(&mcs, "%s:c%d", sens, catMin + c1) < 0)
326 327 328 329 330 331 332
                return NULL;
        } else {
            if (c1 > c2) {
                int t = c1;
                c1 = c2;
                c2 = t;
            }
333
            if (virAsprintf(&mcs, "%s:c%d,c%d", sens, catMin + c1, catMin + c2) < 0)
334 335 336 337 338 339 340 341 342 343 344 345
                return NULL;
        }

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

        VIR_FREE(mcs);
    }

    return mcs;
}

346 347 348 349

/*
 * This needs to cope with several styles of range
 *
350
 * system_u:system_r:virtd_t
351 352 353 354
 * 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
 *
355 356
 * In the first case we'll assume s0:c0.c1023 and
 * in the next two cases, we'll assume c0.c1023 for
357 358 359
 * 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 已提交
360
 * mode when run with a weird process label.
361
 */
362 363 364 365 366
static int
virSecuritySELinuxMCSGetProcessRange(char **sens,
                                     int *catMin,
                                     int *catMax)
{
367 368
    security_context_t ourSecContext = NULL;
    context_t ourContext = NULL;
369 370
    char *cat = NULL;
    char *tmp;
371
    const char *contextRange;
372
    int ret = -1;
373

M
Martin Kletzander 已提交
374
    if (getcon_raw(&ourSecContext) < 0) {
375 376 377 378 379 380 381 382 383 384
        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;
    }
385 386
    if (!(contextRange = context_range_get(ourContext)))
        contextRange = "s0";
387

388
    if (VIR_STRDUP(*sens, contextRange) < 0)
389 390
        goto cleanup;

391 392 393 394 395
    /* Find and blank out the category part (if any) */
    tmp = strchr(*sens, ':');
    if (tmp) {
        *tmp = '\0';
        cat = tmp + 1;
396 397
    }
    /* Find and blank out the sensitivity upper bound */
398
    if ((tmp = strchr(*sens, '-')))
399 400 401
        *tmp = '\0';
    /* sens now just contains the sensitivity lower bound */

402
    /* If there was no category part, just assume c0.c1023 */
403 404
    if (!cat) {
        *catMin = 0;
405
        *catMax = 1023;
406 407 408 409
        ret = 0;
        goto cleanup;
    }

410 411 412 413 414 415 416 417 418
    /* Find & extract category min */
    tmp = cat;
    if (tmp[0] != 'c') {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot parse category in %s"),
                       cat);
        goto cleanup;
    }
    tmp++;
419
    if (virStrToLong_i(tmp, &tmp, 10, catMin) < 0) {
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
        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++;
449
    if (virStrToLong_i(tmp, &tmp, 10, catMax) < 0) {
450 451 452 453 454 455
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot parse category in %s"),
                       cat);
        goto cleanup;
    }

456
    ret = 0;
457

458
 cleanup:
459 460
    if (ret < 0)
        VIR_FREE(*sens);
461 462
    freecon(ourSecContext);
    context_free(ourContext);
463
    return ret;
464 465
}

466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
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;
    }

496
    ignore_value(VIR_STRDUP(ret, str));
497

498
 cleanup:
499 500 501 502
    if (srccon) context_free(srccon);
    if (dstcon) context_free(dstcon);
    return ret;
}
503

504
static char *
505 506 507
virSecuritySELinuxGenNewContext(const char *basecontext,
                                const char *mcs,
                                bool isObjectContext)
508
{
509
    context_t context = NULL;
510 511
    char *ret = NULL;
    char *str;
512 513 514
    security_context_t ourSecContext = NULL;
    context_t ourContext = NULL;

515 516 517
    VIR_DEBUG("basecontext=%s mcs=%s isObjectContext=%d",
              basecontext, mcs, isObjectContext);

M
Martin Kletzander 已提交
518
    if (getcon_raw(&ourSecContext) < 0) {
519 520 521 522 523 524 525 526 527 528
        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;
    }
529
    VIR_DEBUG("process=%s", ourSecContext);
530 531 532 533 534 535 536 537

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

538 539 540 541 542 543 544 545
    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;
    }

546 547
    if (!isObjectContext &&
        context_role_set(context,
548 549
                         context_role_get(ourContext)) != 0) {
        virReportSystemError(errno,
550
                             _("Unable to set SELinux context role '%s'"),
551 552 553 554
                             context_role_get(ourContext));
        goto cleanup;
    }

555 556 557 558 559 560 561 562 563 564 565
    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;
    }
566
    if (VIR_STRDUP(ret, str) < 0)
567
        goto cleanup;
568
    VIR_DEBUG("Generated context '%s'",  ret);
569
 cleanup:
570 571
    freecon(ourSecContext);
    context_free(ourContext);
572 573
    context_free(context);
    return ret;
574 575
}

576

577
#ifdef HAVE_SELINUX_LXC_CONTEXTS_PATH
578
static int
579
virSecuritySELinuxLXCInitialize(virSecurityManagerPtr mgr)
580 581 582 583
{
    virConfPtr selinux_conf;
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);

584 585
    data->skipAllLabel = true;

586
# if HAVE_SELINUX_LABEL_H
587 588 589 590 591 592
    data->label_handle = selabel_open(SELABEL_CTX_FILE, NULL, 0);
    if (!data->label_handle) {
        virReportSystemError(errno, "%s",
                             _("cannot open SELinux label_handle"));
        return -1;
    }
593
# endif
594

595
    if (!(selinux_conf = virConfReadFile(selinux_lxc_contexts_path(), 0)))
596
        goto error;
597

598
    if (virConfGetValueString(selinux_conf, "process", &data->domain_context) < 0)
599 600
        goto error;

601 602 603 604
    if (!data->domain_context) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("missing 'process' value in selinux lxc contexts file '%s'"),
                       selinux_lxc_contexts_path());
605 606 607
        goto error;
    }

608 609 610 611 612 613 614
    if (virConfGetValueString(selinux_conf, "file", &data->file_context) < 0)
        goto error;

    if (!data->file_context) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("missing 'file' value in selinux lxc contexts file '%s'"),
                       selinux_lxc_contexts_path());
615 616 617
        goto error;
    }

618 619 620 621 622 623 624
    if (virConfGetValueString(selinux_conf, "content", &data->content_context) < 0)
        goto error;

    if (!data->content_context) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("missing 'content' value in selinux lxc contexts file '%s'"),
                       selinux_lxc_contexts_path());
625
        goto error;
626
    }
627 628 629 630

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

631 632 633
    virConfFree(selinux_conf);
    return 0;

634
 error:
635
# if HAVE_SELINUX_LABEL_H
636
    selabel_close(data->label_handle);
637
    data->label_handle = NULL;
638
# endif
639 640 641 642
    virConfFree(selinux_conf);
    VIR_FREE(data->domain_context);
    VIR_FREE(data->file_context);
    VIR_FREE(data->content_context);
643
    virHashFree(data->mcs);
644 645
    return -1;
}
646 647
#else
static int
648
virSecuritySELinuxLXCInitialize(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED)
649 650 651 652 653 654
{
    virReportSystemError(ENOSYS, "%s",
                         _("libselinux does not support LXC contexts path"));
    return -1;
}
#endif
655 656 657


static int
658
virSecuritySELinuxQEMUInitialize(virSecurityManagerPtr mgr)
659
{
660 661
    char *ptr;
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
662

663 664
    data->skipAllLabel = false;

665 666 667 668 669 670 671 672 673
#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

674
    if (virFileReadAll(selinux_virtual_domain_context_path(), MAX_CONTEXT, &(data->domain_context)) < 0) {
675
        virReportSystemError(errno,
676
                             _("cannot read SELinux virtual domain context file '%s'"),
677
                             selinux_virtual_domain_context_path());
678
        goto error;
679 680
    }

681
    ptr = strchrnul(data->domain_context, '\n');
682
    if (ptr && *ptr == '\n') {
683
        *ptr = '\0';
684 685
        ptr++;
        if (*ptr != '\0') {
686
            if (VIR_STRDUP(data->alt_domain_context, ptr) < 0)
687 688 689 690 691 692 693 694 695
                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));

696

697
    if (virFileReadAll(selinux_virtual_image_context_path(), 2*MAX_CONTEXT, &(data->file_context)) < 0) {
698
        virReportSystemError(errno,
699 700
                             _("cannot read SELinux virtual image context file %s"),
                             selinux_virtual_image_context_path());
701
        goto error;
702 703
    }

704 705
    ptr = strchrnul(data->file_context, '\n');
    if (ptr && *ptr == '\n') {
706
        *ptr = '\0';
707
        if (VIR_STRDUP(data->content_context, ptr + 1) < 0)
708 709 710
            goto error;
        ptr = strchrnul(data->content_context, '\n');
        if (ptr && *ptr == '\n')
711 712
            *ptr = '\0';
    }
713

714 715 716
    VIR_DEBUG("Loaded file context '%s', content context '%s'",
              data->file_context, data->content_context);

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

720
    return 0;
721

722
 error:
723 724
#if HAVE_SELINUX_LABEL_H
    selabel_close(data->label_handle);
725
    data->label_handle = NULL;
726
#endif
727
    VIR_FREE(data->domain_context);
728
    VIR_FREE(data->alt_domain_context);
729 730
    VIR_FREE(data->file_context);
    VIR_FREE(data->content_context);
731
    virHashFree(data->mcs);
732
    return -1;
733 734
}

735 736

static int
737
virSecuritySELinuxInitialize(virSecurityManagerPtr mgr)
738 739
{
    VIR_DEBUG("SELinuxInitialize %s", virSecurityManagerGetDriver(mgr));
740 741 742 743 744 745 746 747

    if (virThreadLocalInit(&contextList,
                           virSecuritySELinuxContextListFree) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to initialize thread local variable"));
        return -1;
    }

748
    if (STREQ(virSecurityManagerGetDriver(mgr),  "LXC")) {
749
        return virSecuritySELinuxLXCInitialize(mgr);
750
    } else {
751
        return virSecuritySELinuxQEMUInitialize(mgr);
752 753 754 755
    }
}


756
static int
757 758
virSecuritySELinuxGenLabel(virSecurityManagerPtr mgr,
                           virDomainDefPtr def)
759 760
{
    int rc = -1;
761
    char *mcs = NULL;
762
    char *scontext = NULL;
763
    context_t ctx = NULL;
764
    const char *range;
765 766
    virSecurityLabelDefPtr seclabel;
    virSecuritySELinuxDataPtr data;
767
    const char *baselabel;
768 769
    char *sens = NULL;
    int catMin, catMax;
770

771
    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
P
Peter Krempa 已提交
772
    if (seclabel == NULL)
773
        return 0;
774 775 776 777 778 779

    data = virSecurityManagerGetPrivateData(mgr);

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

785
    if (seclabel->imagelabel) {
P
Peter Krempa 已提交
786 787
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("security image label already defined for VM"));
788 789 790
        return rc;
    }

791 792
    if (seclabel->model &&
        STRNEQ(seclabel->model, SECURITY_SELINUX_NAME)) {
793 794
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label model %s is not supported with selinux"),
795
                       seclabel->model);
796 797 798
        return rc;
    }

799
    VIR_DEBUG("type=%d", seclabel->type);
800

801
    switch (seclabel->type) {
802
    case VIR_DOMAIN_SECLABEL_STATIC:
803
        if (!(ctx = context_new(seclabel->label))) {
804 805
            virReportSystemError(errno,
                                 _("unable to allocate socket security context '%s'"),
806
                                 seclabel->label);
807
            return rc;
808 809
        }

P
Peter Krempa 已提交
810
        if (!(range = context_range_get(ctx))) {
811
            virReportSystemError(errno, "%s", _("unable to get selinux context range"));
812 813
            goto cleanup;
        }
814 815
        if (VIR_STRDUP(mcs, range) < 0)
            goto cleanup;
816 817 818
        break;

    case VIR_DOMAIN_SECLABEL_DYNAMIC:
819 820 821 822 823 824 825 826 827
        if (virSecuritySELinuxMCSGetProcessRange(&sens,
                                                 &catMin,
                                                 &catMax) < 0)
            goto cleanup;

        if (!(mcs = virSecuritySELinuxMCSFind(mgr,
                                              sens,
                                              catMin,
                                              catMax)))
828 829 830 831
            goto cleanup;

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

833 834 835 836
        baselabel = seclabel->baselabel;
        if (!baselabel) {
            if (def->virtType == VIR_DOMAIN_VIRT_QEMU) {
                if (data->alt_domain_context == NULL) {
837
                    static bool warned;
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
                    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;
            }
        }

853 854
        seclabel->label = virSecuritySELinuxGenNewContext(baselabel, mcs, false);
        if (!seclabel->label)
855
            goto cleanup;
856

857 858 859
        break;

    case VIR_DOMAIN_SECLABEL_NONE:
860 861 862 863 864 865 866 867
        if (virSecuritySELinuxMCSGetProcessRange(&sens,
                                                 &catMin,
                                                 &catMax) < 0)
            goto cleanup;

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

868 869 870
        break;

    default:
871 872
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected security label type '%s'"),
873
                       virDomainSeclabelTypeToString(seclabel->type));
874
        goto cleanup;
D
Daniel P. Berrange 已提交
875
    }
876

877 878 879 880 881 882
    /* always generate a image label, needed to label new objects */
    seclabel->imagelabel = virSecuritySELinuxGenNewContext(data->file_context,
                                                           mcs,
                                                           true);
    if (!seclabel->imagelabel)
        goto cleanup;
883

884
    if (!seclabel->model &&
885
        VIR_STRDUP(seclabel->model, SECURITY_SELINUX_NAME) < 0)
886
        goto cleanup;
D
Daniel P. Berrange 已提交
887

888
    rc = 0;
889

890
 cleanup:
891
    if (rc != 0) {
892 893 894 895 896 897
        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);
898 899 900 901
    }

    if (ctx)
        context_free(ctx);
D
Daniel P. Berrange 已提交
902
    VIR_FREE(scontext);
903
    VIR_FREE(mcs);
904
    VIR_FREE(sens);
905 906

    VIR_DEBUG("model=%s label=%s imagelabel=%s baselabel=%s",
907 908 909 910
              NULLSTR(seclabel->model),
              NULLSTR(seclabel->label),
              NULLSTR(seclabel->imagelabel),
              NULLSTR(seclabel->baselabel));
911

912 913 914
    return rc;
}

915
static int
916 917 918
virSecuritySELinuxReserveLabel(virSecurityManagerPtr mgr,
                               virDomainDefPtr def,
                               pid_t pid)
919 920 921 922
{
    security_context_t pctx;
    context_t ctx = NULL;
    const char *mcs;
923
    int rv;
924
    virSecurityLabelDefPtr seclabel;
925

926
    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
927 928 929
    if (!seclabel ||
        seclabel->type == VIR_DOMAIN_SECLABEL_NONE ||
        seclabel->type == VIR_DOMAIN_SECLABEL_STATIC)
930 931
        return 0;

M
Martin Kletzander 已提交
932
    if (getpidcon_raw(pid, &pctx) == -1) {
933
        virReportSystemError(errno,
934
                             _("unable to get PID %d security context"), pid);
935 936 937 938
        return -1;
    }

    ctx = context_new(pctx);
939
    freecon(pctx);
940
    if (!ctx)
941
        goto error;
942 943 944

    mcs = context_range_get(ctx);
    if (!mcs)
945 946
        goto error;

947
    if ((rv = virSecuritySELinuxMCSAdd(mgr, mcs)) < 0)
948
        goto error;
949

950 951 952 953 954 955
    if (rv == 1) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("MCS level for existing domain label %s already reserved"),
                       (char*)pctx);
        goto error;
    }
956 957 958 959 960

    context_free(ctx);

    return 0;

961
 error:
962 963 964 965 966
    context_free(ctx);
    return -1;
}


967
static int
968
virSecuritySELinuxDriverProbe(const char *virtDriver)
969
{
970
    if (is_selinux_enabled() <= 0)
971 972
        return SECURITY_DRIVER_DISABLE;

973 974 975 976 977 978
    if (virtDriver && STREQ(virtDriver, "LXC")) {
#if HAVE_SELINUX_LXC_CONTEXTS_PATH
        if (!virFileExists(selinux_lxc_contexts_path()))
#endif
            return SECURITY_DRIVER_DISABLE;
    }
979 980

    return SECURITY_DRIVER_ENABLE;
981 982
}

983

984
static int
985
virSecuritySELinuxDriverOpen(virSecurityManagerPtr mgr)
986
{
987
    return virSecuritySELinuxInitialize(mgr);
988 989
}

990

991
static int
992
virSecuritySELinuxDriverClose(virSecurityManagerPtr mgr)
993
{
994 995 996 997 998
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);

    if (!data)
        return 0;

999
#if HAVE_SELINUX_LABEL_H
1000 1001
    if (data->label_handle)
        selabel_close(data->label_handle);
1002 1003
#endif

1004 1005
    virHashFree(data->mcs);

1006
    VIR_FREE(data->domain_context);
1007
    VIR_FREE(data->alt_domain_context);
1008 1009 1010
    VIR_FREE(data->file_context);
    VIR_FREE(data->content_context);

1011 1012 1013 1014
    return 0;
}


1015
static const char *
1016
virSecuritySELinuxGetModel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED)
1017 1018 1019 1020
{
    return SECURITY_SELINUX_NAME;
}

1021
static const char *
1022
virSecuritySELinuxGetDOI(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED)
1023 1024 1025 1026 1027
{
    /*
     * Where will the DOI come from?  SELinux configuration, or qemu
     * configuration? For the moment, we'll just set it to "0".
     */
1028
    return SECURITY_SELINUX_VOID_DOI;
1029 1030
}

1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
/**
 * virSecuritySELinuxTransactionStart:
 * @mgr: security manager
 *
 * Starts a new transaction. In transaction nothing is changed context
 * until TransactionCommit() is called. This is implemented as a list
 * that is appended to whenever setfilecon() would be called. Since
 * secdriver APIs can be called from multiple threads (to work over
 * different domains) the pointer to the list is stored in thread local
 * variable.
 *
 * Returns 0 on success,
 *        -1 otherwise.
 */
static int
virSecuritySELinuxTransactionStart(virSecurityManagerPtr mgr)
{
    virSecuritySELinuxContextListPtr list;

    list = virThreadLocalGet(&contextList);
    if (list) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Another relabel transaction is already started"));
        return -1;
    }

    if (VIR_ALLOC(list) < 0)
        return -1;

1060
    list->manager = virObjectRef(mgr);
1061 1062 1063 1064

    if (virThreadLocalSet(&contextList, list) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to set thread local variable"));
1065
        virSecuritySELinuxContextListFree(list);
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
        return -1;
    }

    return 0;
}

/**
 * virSecuritySELinuxTransactionCommit:
 * @mgr: security manager
 * @pid: domain's PID
1076
 * @lock: lock and unlock paths that are relabeled
1077
 *
1078 1079 1080 1081 1082
 * If @pis is not -1 then enter the @pid namespace (usually @pid refers
 * to a domain) and perform all the sefilecon()-s on the list. If @pid
 * is -1 then the transaction is performed in the namespace of the
 * caller.
 *
1083 1084 1085
 * If @lock is true then all the paths that transaction would
 * touch are locked before and unlocked after it is done so.
 *
1086 1087 1088 1089
 * Note that the transaction is also freed, therefore new one has to be
 * started after successful return from this function. Also it is
 * considered as error if there's no transaction set and this function
 * is called.
1090 1091 1092 1093 1094 1095
 *
 * Returns: 0 on success,
 *         -1 otherwise.
 */
static int
virSecuritySELinuxTransactionCommit(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
1096 1097
                                    pid_t pid,
                                    bool lock)
1098 1099
{
    virSecuritySELinuxContextListPtr list;
1100
    int rc;
1101
    int ret = -1;
1102 1103

    list = virThreadLocalGet(&contextList);
1104 1105 1106 1107 1108
    if (!list) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("No transaction is set"));
        return -1;
    }
1109 1110 1111 1112 1113 1114 1115

    if (virThreadLocalSet(&contextList, NULL) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to clear thread local variable"));
        goto cleanup;
    }

1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
    list->lock = lock;

    if (pid == -1) {
        if (lock)
            rc = virProcessRunInFork(virSecuritySELinuxTransactionRun, list);
        else
            rc = virSecuritySELinuxTransactionRun(pid, list);
    } else {
        rc = virProcessRunInMountNamespace(pid,
                                           virSecuritySELinuxTransactionRun,
                                           list);
    }

    if (rc < 0)
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
        goto cleanup;

    ret = 0;
 cleanup:
    virSecuritySELinuxContextListFree(list);
    return ret;
}

/**
 * virSecuritySELinuxTransactionAbort:
 * @mgr: security manager
 *
 * Cancels and frees any out standing transaction.
 */
static void
virSecuritySELinuxTransactionAbort(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED)
{
    virSecuritySELinuxContextListPtr list;

    list = virThreadLocalGet(&contextList);
    if (!list)
        return;

    if (virThreadLocalSet(&contextList, NULL) < 0)
        VIR_DEBUG("Unable to clear thread local variable");
    virSecuritySELinuxContextListFree(list);
}

1158
static int
1159 1160 1161 1162
virSecuritySELinuxGetProcessLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                  virDomainDefPtr def ATTRIBUTE_UNUSED,
                                  pid_t pid,
                                  virSecurityLabelPtr sec)
1163 1164 1165
{
    security_context_t ctx;

M
Martin Kletzander 已提交
1166
    if (getpidcon_raw(pid, &ctx) == -1) {
1167
        virReportSystemError(errno,
1168
                             _("unable to get PID %d security context"),
1169
                             pid);
1170 1171 1172
        return -1;
    }

1173
    if (strlen((char *)ctx) >= VIR_SECURITY_LABEL_BUFLEN) {
1174 1175 1176 1177
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label exceeds "
                         "maximum length: %d"),
                       VIR_SECURITY_LABEL_BUFLEN - 1);
1178
        freecon(ctx);
1179 1180 1181
        return -1;
    }

1182
    strcpy(sec->label, (char *)ctx);
1183
    freecon(ctx);
1184

1185
    VIR_DEBUG("label=%s", sec->label);
1186 1187
    sec->enforcing = security_getenforce();
    if (sec->enforcing == -1) {
1188
        virReportSystemError(errno, "%s",
1189
                             _("error calling security_getenforce()"));
1190 1191 1192 1193 1194 1195
        return -1;
    }

    return 0;
}

1196 1197 1198
/* 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.  */
1199
static int
1200 1201
virSecuritySELinuxSetFileconImpl(const char *path, const char *tcon,
                                 bool optional, bool privileged)
1202
{
1203
    security_context_t econ;
1204 1205 1206 1207

    /* Be aware that this function might run in a separate process.
     * Therefore, any driver state changes would be thrown away. */

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

1210
    if (setfilecon_raw(path, (VIR_SELINUX_CTX_CONST char *)tcon) < 0) {
1211 1212
        int setfilecon_errno = errno;

M
Martin Kletzander 已提交
1213
        if (getfilecon_raw(path, &econ) >= 0) {
1214 1215 1216
            if (STREQ(tcon, econ)) {
                freecon(econ);
                /* It's alright, there's nothing to change anyway. */
1217
                return optional ? 1 : 0;
1218 1219 1220
            }
            freecon(econ);
        }
1221

1222 1223 1224 1225 1226
        /* 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 ...
1227
         */
1228
        VIR_WARNINGS_NO_WLOGICALOP_EQUAL_EXPR
1229 1230
        if (setfilecon_errno != EOPNOTSUPP && setfilecon_errno != ENOTSUP &&
            setfilecon_errno != EROFS) {
1231
        VIR_WARNINGS_RESET
1232
            virReportSystemError(setfilecon_errno,
1233
                                 _("unable to set security context '%s' on '%s'"),
1234
                                 tcon, path);
1235 1236 1237 1238
            /* However, don't claim error if SELinux is in Enforcing mode and
             * we are running as unprivileged user and we really did see EPERM.
             * Otherwise we want to return error if SELinux is Enforcing. */
            if (security_getenforce() == 1 && (setfilecon_errno != EPERM || privileged))
1239
                return -1;
1240
        } else {
1241
            const char *msg;
1242
            if (virFileIsSharedFSType(path, VIR_FILE_SHFS_NFS) == 1 &&
1243 1244 1245
                security_get_boolean_active("virt_use_nfs") != 1) {
                msg = _("Setting security context '%s' on '%s' not supported. "
                        "Consider setting virt_use_nfs");
1246 1247 1248 1249
                if (security_getenforce() == 1)
                    VIR_WARN(msg, tcon, path);
                else
                    VIR_INFO(msg, tcon, path);
1250 1251 1252 1253
            } else {
                VIR_INFO("Setting security context '%s' on '%s' not supported",
                         tcon, path);
            }
1254 1255
            if (optional)
                return 1;
1256
        }
1257 1258 1259 1260
    }
    return 0;
}

1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276

static int
virSecuritySELinuxSetFileconHelper(const char *path, const char *tcon,
                                   bool optional, bool privileged)
{
    int rc;

    if ((rc = virSecuritySELinuxTransactionAppend(path, tcon, optional)) < 0)
        return -1;
    else if (rc > 0)
        return 0;

    return virSecuritySELinuxSetFileconImpl(path, tcon, optional, privileged);
}


1277
static int
1278
virSecuritySELinuxSetFileconOptional(virSecurityManagerPtr mgr,
1279
                                     const char *path, const char *tcon)
1280
{
1281 1282
    bool privileged = virSecurityManagerGetPrivileged(mgr);
    return virSecuritySELinuxSetFileconHelper(path, tcon, true, privileged);
1283 1284 1285
}

static int
1286
virSecuritySELinuxSetFilecon(virSecurityManagerPtr mgr,
1287
                             const char *path, const char *tcon)
1288
{
1289 1290
    bool privileged = virSecurityManagerGetPrivileged(mgr);
    return virSecuritySELinuxSetFileconHelper(path, tcon, false, privileged);
1291 1292
}

1293
static int
1294
virSecuritySELinuxFSetFilecon(int fd, char *tcon)
1295 1296 1297 1298 1299
{
    security_context_t econ;

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

M
Martin Kletzander 已提交
1300
    if (fsetfilecon_raw(fd, tcon) < 0) {
1301 1302
        int fsetfilecon_errno = errno;

M
Martin Kletzander 已提交
1303
        if (fgetfilecon_raw(fd, &econ) >= 0) {
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
            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 已提交
1332 1333
/* Set fcon to the appropriate label for path and mode, or return -1.  */
static int
1334
getContext(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
1335
           const char *newpath, mode_t mode, security_context_t *fcon)
E
Eric Blake 已提交
1336 1337
{
#if HAVE_SELINUX_LABEL_H
1338
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
E
Eric Blake 已提交
1339

1340
    return selabel_lookup_raw(data->label_handle, fcon, newpath, mode);
E
Eric Blake 已提交
1341 1342 1343 1344 1345
#else
    return matchpathcon(newpath, mode, fcon);
#endif
}

1346 1347 1348

/* This method shouldn't raise errors, since they'll overwrite
 * errors that the caller(s) are already dealing with */
1349
static int
1350 1351
virSecuritySELinuxRestoreFileLabel(virSecurityManagerPtr mgr,
                                   const char *path)
1352
{
1353
    bool privileged = virSecurityManagerGetPrivileged(mgr);
1354 1355 1356
    struct stat buf;
    security_context_t fcon = NULL;
    char *newpath = NULL;
1357
    char ebuf[1024];
1358
    int rc;
1359
    int ret = -1;
1360

1361 1362 1363 1364 1365 1366
    /* Some paths are auto-generated, so let's be safe here and do
     * nothing if nothing is needed.
     */
    if (!path)
        return 0;

1367 1368
    VIR_INFO("Restoring SELinux context on '%s'", path);

1369
    if (virFileResolveLink(path, &newpath) < 0) {
1370 1371
        VIR_WARN("cannot resolve symlink %s: %s", path,
                 virStrerror(errno, ebuf, sizeof(ebuf)));
1372
        goto cleanup;
1373
    }
1374

1375
    if (stat(newpath, &buf) != 0) {
1376 1377
        VIR_WARN("cannot stat %s: %s", newpath,
                 virStrerror(errno, ebuf, sizeof(ebuf)));
1378
        goto cleanup;
1379
    }
D
Daniel P. Berrange 已提交
1380

1381
    if (getContext(mgr, newpath, buf.st_mode, &fcon) < 0) {
1382 1383 1384
        /* Any user created path likely does not have a default label,
         * which makes this an expected non error
         */
1385
        VIR_WARN("cannot lookup default selinux label for %s", newpath);
1386 1387
        ret = 0;
        goto cleanup;
1388
    }
1389

1390 1391 1392 1393 1394 1395
    if ((rc = virSecuritySELinuxTransactionAppend(path, fcon, false)) < 0)
        return -1;
    else if (rc > 0)
        return 0;

    if (virSecuritySELinuxSetFileconImpl(newpath, fcon, false, privileged) < 0)
1396 1397 1398
        goto cleanup;

    ret = 0;
1399
 cleanup:
1400
    freecon(fcon);
1401
    VIR_FREE(newpath);
1402
    return ret;
1403 1404
}

1405

1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
static int
virSecuritySELinuxSetInputLabel(virSecurityManagerPtr mgr,
                                virDomainDefPtr def,
                                virDomainInputDefPtr input)
{
    virSecurityLabelDefPtr seclabel;

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

1417
    switch ((virDomainInputType)input->type) {
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
    case VIR_DOMAIN_INPUT_TYPE_PASSTHROUGH:
        if (virSecuritySELinuxSetFilecon(mgr, input->source.evdev,
                                         seclabel->imagelabel) < 0)
            return -1;
        break;

    case VIR_DOMAIN_INPUT_TYPE_MOUSE:
    case VIR_DOMAIN_INPUT_TYPE_TABLET:
    case VIR_DOMAIN_INPUT_TYPE_KBD:
    case VIR_DOMAIN_INPUT_TYPE_LAST:
        break;
    }

    return 0;
}


static int
virSecuritySELinuxRestoreInputLabel(virSecurityManagerPtr mgr,
                                    virDomainDefPtr def,
                                    virDomainInputDefPtr input)
{
    int rc = 0;
    virSecurityLabelDefPtr seclabel;

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

1447
    switch ((virDomainInputType)input->type) {
1448
    case VIR_DOMAIN_INPUT_TYPE_PASSTHROUGH:
1449
        rc = virSecuritySELinuxRestoreFileLabel(mgr, input->source.evdev);
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
        break;

    case VIR_DOMAIN_INPUT_TYPE_MOUSE:
    case VIR_DOMAIN_INPUT_TYPE_TABLET:
    case VIR_DOMAIN_INPUT_TYPE_KBD:
    case VIR_DOMAIN_INPUT_TYPE_LAST:
        break;
    }

    return rc;
}


1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
static int
virSecuritySELinuxSetMemoryLabel(virSecurityManagerPtr mgr,
                                 virDomainDefPtr def,
                                 virDomainMemoryDefPtr mem)
{
    virSecurityLabelDefPtr seclabel;

    switch ((virDomainMemoryModel) mem->model) {
    case VIR_DOMAIN_MEMORY_MODEL_NVDIMM:
        seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
        if (!seclabel || !seclabel->relabel)
            return 0;

        if (virSecuritySELinuxSetFilecon(mgr, mem->nvdimmPath,
                                         seclabel->imagelabel) < 0)
            return -1;
        break;

    case VIR_DOMAIN_MEMORY_MODEL_NONE:
    case VIR_DOMAIN_MEMORY_MODEL_DIMM:
    case VIR_DOMAIN_MEMORY_MODEL_LAST:
        break;
    }

    return 0;
}


static int
virSecuritySELinuxRestoreMemoryLabel(virSecurityManagerPtr mgr,
                                     virDomainDefPtr def,
                                     virDomainMemoryDefPtr mem)
{
    int ret = -1;
    virSecurityLabelDefPtr seclabel;

    switch ((virDomainMemoryModel) mem->model) {
    case VIR_DOMAIN_MEMORY_MODEL_NVDIMM:
        seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
        if (!seclabel || !seclabel->relabel)
            return 0;

        ret = virSecuritySELinuxRestoreFileLabel(mgr, mem->nvdimmPath);
        break;

    case VIR_DOMAIN_MEMORY_MODEL_DIMM:
    case VIR_DOMAIN_MEMORY_MODEL_NONE:
    case VIR_DOMAIN_MEMORY_MODEL_LAST:
        ret = 0;
        break;
    }

    return ret;
}


1519
static int
1520 1521 1522
virSecuritySELinuxSetTPMFileLabel(virSecurityManagerPtr mgr,
                                  virDomainDefPtr def,
                                  virDomainTPMDefPtr tpm)
1523 1524 1525 1526 1527 1528 1529 1530
{
    int rc;
    virSecurityLabelDefPtr seclabel;
    char *cancel_path;
    const char *tpmdev;

    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (seclabel == NULL)
1531
        return 0;
1532 1533 1534 1535

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

        if ((cancel_path = virTPMCreateCancelPath(tpmdev)) != NULL) {
1541 1542
            rc = virSecuritySELinuxSetFilecon(mgr,
                                              cancel_path,
1543 1544 1545
                                              seclabel->imagelabel);
            VIR_FREE(cancel_path);
            if (rc < 0) {
1546
                virSecuritySELinuxRestoreTPMFileLabelInt(mgr, def, tpm);
1547 1548 1549 1550 1551 1552
                return -1;
            }
        } else {
            return -1;
        }
        break;
1553
    case VIR_DOMAIN_TPM_TYPE_EMULATOR:
1554 1555 1556 1557 1558
        tpmdev = tpm->data.emulator.source.data.nix.path;
        rc = virSecuritySELinuxSetFilecon(mgr, tpmdev, seclabel->imagelabel);
        if (rc < 0)
            return -1;
        break;
1559 1560 1561 1562 1563 1564 1565 1566 1567
    case VIR_DOMAIN_TPM_TYPE_LAST:
        break;
    }

    return 0;
}


static int
1568 1569 1570
virSecuritySELinuxRestoreTPMFileLabelInt(virSecurityManagerPtr mgr,
                                         virDomainDefPtr def,
                                         virDomainTPMDefPtr tpm)
1571 1572 1573 1574 1575 1576 1577 1578
{
    int rc = 0;
    virSecurityLabelDefPtr seclabel;
    char *cancel_path;
    const char *tpmdev;

    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (seclabel == NULL)
1579
        return 0;
1580 1581 1582 1583

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

        if ((cancel_path = virTPMCreateCancelPath(tpmdev)) != NULL) {
1587
            if (virSecuritySELinuxRestoreFileLabel(mgr, cancel_path) < 0)
1588 1589 1590 1591
                rc = -1;
            VIR_FREE(cancel_path);
        }
        break;
1592
    case VIR_DOMAIN_TPM_TYPE_EMULATOR:
1593
        /* swtpm will have removed the Unix socket upon termination */
1594 1595 1596 1597 1598 1599 1600 1601
    case VIR_DOMAIN_TPM_TYPE_LAST:
        break;
    }

    return rc;
}


1602
static int
1603 1604 1605 1606
virSecuritySELinuxRestoreImageLabelInt(virSecurityManagerPtr mgr,
                                       virDomainDefPtr def,
                                       virStorageSourcePtr src,
                                       bool migrated)
1607
{
1608 1609
    virSecurityLabelDefPtr seclabel;
    virSecurityDeviceLabelDefPtr disk_seclabel;
1610 1611 1612

    if (!src->path || !virStorageSourceIsLocalStorage(src))
        return 0;
1613 1614 1615

    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (seclabel == NULL)
1616
        return 0;
1617

1618
    disk_seclabel = virStorageSourceGetSecurityLabelDef(src,
1619
                                                        SECURITY_SELINUX_NAME);
1620
    if (!seclabel->relabel || (disk_seclabel && !disk_seclabel->relabel))
1621 1622
        return 0;

1623 1624 1625
    /* 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
1626
     * per-file attribute instead of a disk attribute. */
1627
    if (disk_seclabel && disk_seclabel->labelskip &&
1628
        !virStorageSourceHasBacking(src))
1629 1630
        return 0;

1631
    /* Don't restore labels on readonly/shared disks, because other VMs may
1632 1633 1634 1635 1636
     * 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)
1637 1638 1639
        return 0;


1640 1641 1642
    /* 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 :-) */
1643
    if (migrated) {
1644
        int rc = virFileIsSharedFS(src->path);
1645 1646 1647 1648
        if (rc < 0)
            return -1;
        if (rc == 1) {
            VIR_DEBUG("Skipping image label restore on %s because FS is shared",
1649
                      src->path);
1650 1651 1652 1653
            return 0;
        }
    }

1654
    return virSecuritySELinuxRestoreFileLabel(mgr, src->path);
1655 1656
}

1657 1658

static int
1659 1660 1661
virSecuritySELinuxRestoreDiskLabel(virSecurityManagerPtr mgr,
                                   virDomainDefPtr def,
                                   virDomainDiskDefPtr disk)
1662
{
1663 1664
    return virSecuritySELinuxRestoreImageLabelInt(mgr, def, disk->src,
                                                  false);
1665 1666 1667 1668
}


static int
1669 1670 1671
virSecuritySELinuxRestoreImageLabel(virSecurityManagerPtr mgr,
                                    virDomainDefPtr def,
                                    virStorageSourcePtr src)
1672
{
1673
    return virSecuritySELinuxRestoreImageLabelInt(mgr, def, src, false);
1674 1675 1676
}


1677
static int
1678 1679 1680
virSecuritySELinuxSetImageLabelInternal(virSecurityManagerPtr mgr,
                                        virDomainDefPtr def,
                                        virStorageSourcePtr src,
1681
                                        virStorageSourcePtr parent)
1682
{
1683 1684
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
    virSecurityLabelDefPtr secdef;
1685
    virSecurityDeviceLabelDefPtr disk_seclabel;
1686
    virSecurityDeviceLabelDefPtr parent_seclabel = NULL;
1687
    int ret;
1688

1689 1690 1691 1692
    if (!src->path || !virStorageSourceIsLocalStorage(src))
        return 0;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
1693
    if (!secdef || !secdef->relabel)
1694 1695 1696
        return 0;

    disk_seclabel = virStorageSourceGetSecurityLabelDef(src,
1697
                                                        SECURITY_SELINUX_NAME);
1698 1699 1700
    if (parent)
        parent_seclabel = virStorageSourceGetSecurityLabelDef(parent,
                                                              SECURITY_SELINUX_NAME);
1701

1702 1703 1704
    if (disk_seclabel && (!disk_seclabel->relabel || disk_seclabel->label)) {
        if (!disk_seclabel->relabel)
            return 0;
1705

1706
        ret = virSecuritySELinuxSetFilecon(mgr, src->path, disk_seclabel->label);
1707 1708 1709 1710 1711
    } else if (parent_seclabel && (!parent_seclabel->relabel || parent_seclabel->label)) {
        if (!parent_seclabel->relabel)
            return 0;

        ret = virSecuritySELinuxSetFilecon(mgr, src->path, parent_seclabel->label);
1712
    } else if (!parent || parent == src) {
1713
        if (src->shared) {
1714 1715
            ret = virSecuritySELinuxSetFileconOptional(mgr,
                                                       src->path,
1716 1717
                                                       data->file_context);
        } else if (src->readonly) {
1718 1719
            ret = virSecuritySELinuxSetFileconOptional(mgr,
                                                       src->path,
1720
                                                       data->content_context);
1721
        } else if (secdef->imagelabel) {
1722 1723
            ret = virSecuritySELinuxSetFileconOptional(mgr,
                                                       src->path,
1724
                                                       secdef->imagelabel);
1725
        } else {
1726
            ret = 0;
1727 1728
        }
    } else {
1729 1730
        ret = virSecuritySELinuxSetFileconOptional(mgr,
                                                   src->path,
1731
                                                   data->content_context);
1732
    }
1733

1734
    if (ret == 1 && !disk_seclabel) {
1735 1736
        /* If we failed to set a label, but virt_use_nfs let us
         * proceed anyway, then we don't need to relabel later.  */
1737
        disk_seclabel = virSecurityDeviceLabelDefNew(SECURITY_SELINUX_NAME);
1738
        if (!disk_seclabel)
1739
            return -1;
1740
        disk_seclabel->labelskip = true;
1741
        if (VIR_APPEND_ELEMENT(src->seclabels, src->nseclabels,
1742
                               disk_seclabel) < 0) {
1743 1744 1745
            virSecurityDeviceLabelDefFree(disk_seclabel);
            return -1;
        }
1746
        ret = 0;
1747
    }
1748

1749
    return ret;
1750 1751
}

1752 1753

static int
1754 1755 1756
virSecuritySELinuxSetImageLabel(virSecurityManagerPtr mgr,
                                virDomainDefPtr def,
                                virStorageSourcePtr src)
1757
{
1758
    return virSecuritySELinuxSetImageLabelInternal(mgr, def, src, NULL);
1759 1760 1761
}


1762
static int
1763 1764 1765
virSecuritySELinuxSetDiskLabel(virSecurityManagerPtr mgr,
                               virDomainDefPtr def,
                               virDomainDiskDefPtr disk)
1766 1767

{
1768
    virStorageSourcePtr next;
1769

1770
    for (next = disk->src; virStorageSourceIsBacking(next); next = next->backingStore) {
1771
        if (virSecuritySELinuxSetImageLabelInternal(mgr, def, next, disk->src) < 0)
1772 1773 1774 1775
            return -1;
    }

    return 0;
1776 1777
}

1778
static int
1779
virSecuritySELinuxSetHostdevLabelHelper(const char *file, void *opaque)
1780
{
1781
    virSecurityLabelDefPtr secdef;
1782 1783 1784
    virSecuritySELinuxCallbackDataPtr data = opaque;
    virSecurityManagerPtr mgr = data->mgr;
    virDomainDefPtr def = data->def;
1785

1786 1787
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
1788
        return 0;
1789
    return virSecuritySELinuxSetFilecon(mgr, file, secdef->imagelabel);
1790 1791 1792
}

static int
1793 1794
virSecuritySELinuxSetPCILabel(virPCIDevicePtr dev ATTRIBUTE_UNUSED,
                              const char *file, void *opaque)
1795
{
1796
    return virSecuritySELinuxSetHostdevLabelHelper(file, opaque);
1797
}
1798

1799
static int
1800 1801
virSecuritySELinuxSetUSBLabel(virUSBDevicePtr dev ATTRIBUTE_UNUSED,
                              const char *file, void *opaque)
1802
{
1803
    return virSecuritySELinuxSetHostdevLabelHelper(file, opaque);
1804 1805
}

1806
static int
1807 1808
virSecuritySELinuxSetSCSILabel(virSCSIDevicePtr dev,
                               const char *file, void *opaque)
1809
{
1810
    virSecurityLabelDefPtr secdef;
1811
    virSecuritySELinuxCallbackDataPtr ptr = opaque;
1812 1813 1814 1815 1816 1817 1818 1819
    virSecurityManagerPtr mgr = ptr->mgr;
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);

    secdef = virDomainDefGetSecurityLabelDef(ptr->def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        return 0;

    if (virSCSIDeviceGetShareable(dev))
1820
        return virSecuritySELinuxSetFileconOptional(mgr, file,
1821 1822
                                                    data->file_context);
    else if (virSCSIDeviceGetReadonly(dev))
1823
        return virSecuritySELinuxSetFileconOptional(mgr, file,
1824 1825
                                                    data->content_context);
    else
1826 1827
        return virSecuritySELinuxSetFileconOptional(mgr, file,
                                                    secdef->imagelabel);
1828
}
1829

1830 1831 1832 1833 1834 1835 1836
static int
virSecuritySELinuxSetHostLabel(virSCSIVHostDevicePtr dev ATTRIBUTE_UNUSED,
                               const char *file, void *opaque)
{
    return virSecuritySELinuxSetHostdevLabelHelper(file, opaque);
}

1837

1838
static int
1839 1840 1841 1842
virSecuritySELinuxSetHostdevSubsysLabel(virSecurityManagerPtr mgr,
                                        virDomainDefPtr def,
                                        virDomainHostdevDefPtr dev,
                                        const char *vroot)
1843 1844

{
1845
    virDomainHostdevSubsysUSBPtr usbsrc = &dev->source.subsys.u.usb;
1846
    virDomainHostdevSubsysPCIPtr pcisrc = &dev->source.subsys.u.pci;
1847
    virDomainHostdevSubsysSCSIPtr scsisrc = &dev->source.subsys.u.scsi;
1848
    virDomainHostdevSubsysSCSIVHostPtr hostsrc = &dev->source.subsys.u.scsi_host;
1849
    virDomainHostdevSubsysMediatedDevPtr mdevsrc = &dev->source.subsys.u.mdev;
1850 1851
    virSecuritySELinuxCallbackData data = {.mgr = mgr, .def = def};

1852 1853
    int ret = -1;

1854
    /* Like virSecuritySELinuxSetImageLabelInternal() for a networked
1855 1856
     * disk, do nothing for an iSCSI hostdev
     */
1857 1858
    if (dev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI &&
        scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI)
1859 1860
        return 0;

1861
    switch ((virDomainHostdevSubsysType)dev->source.subsys.type) {
1862
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB: {
1863
        virUSBDevicePtr usb;
1864

1865 1866 1867
        if (dev->missing)
            return 0;

1868 1869
        usb = virUSBDeviceNew(usbsrc->bus,
                              usbsrc->device,
1870
                              vroot);
1871 1872
        if (!usb)
            goto done;
1873

1874
        ret = virUSBDeviceFileIterate(usb, virSecuritySELinuxSetUSBLabel, &data);
1875
        virUSBDeviceFree(usb);
M
Mark McLoughlin 已提交
1876
        break;
1877 1878 1879
    }

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI: {
1880
        virPCIDevicePtr pci =
1881 1882
            virPCIDeviceNew(pcisrc->addr.domain, pcisrc->addr.bus,
                            pcisrc->addr.slot, pcisrc->addr.function);
1883 1884 1885 1886

        if (!pci)
            goto done;

1887
        if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
1888
            char *vfioGroupDev = virPCIDeviceGetIOMMUGroupDev(pci);
1889

1890 1891
            if (!vfioGroupDev) {
                virPCIDeviceFree(pci);
1892
                goto done;
1893
            }
1894
            ret = virSecuritySELinuxSetPCILabel(pci, vfioGroupDev, &data);
1895 1896
            VIR_FREE(vfioGroupDev);
        } else {
1897
            ret = virPCIDeviceFileIterate(pci, virSecuritySELinuxSetPCILabel, &data);
1898
        }
1899
        virPCIDeviceFree(pci);
1900 1901 1902
        break;
    }

1903
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI: {
1904
        virDomainHostdevSubsysSCSIHostPtr scsihostsrc = &scsisrc->u.host;
1905

1906
        virSCSIDevicePtr scsi =
1907
            virSCSIDeviceNew(NULL,
1908 1909
                             scsihostsrc->adapter, scsihostsrc->bus,
                             scsihostsrc->target, scsihostsrc->unit,
1910
                             dev->readonly, dev->shareable);
1911 1912 1913 1914

        if (!scsi)
            goto done;

1915
        ret = virSCSIDeviceFileIterate(scsi,
1916
                                       virSecuritySELinuxSetSCSILabel,
1917
                                       &data);
1918 1919 1920 1921 1922
        virSCSIDeviceFree(scsi);

        break;
    }

1923
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI_HOST: {
1924 1925 1926 1927 1928 1929 1930 1931 1932 1933
        virSCSIVHostDevicePtr host = virSCSIVHostDeviceNew(hostsrc->wwpn);

        if (!host)
            goto done;

        ret = virSCSIVHostDeviceFileIterate(host,
                                            virSecuritySELinuxSetHostLabel,
                                            &data);
        virSCSIVHostDeviceFree(host);
        break;
1934 1935
    }

1936 1937 1938
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_MDEV: {
        char *vfiodev = NULL;

1939
        if (!(vfiodev = virMediatedDeviceGetIOMMUGroupDev(mdevsrc->uuidstr)))
1940 1941 1942 1943 1944 1945 1946 1947
            goto done;

        ret = virSecuritySELinuxSetHostdevLabelHelper(vfiodev, &data);

        VIR_FREE(vfiodev);
        break;
    }

1948
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_LAST:
1949 1950 1951 1952
        ret = 0;
        break;
    }

1953
 done:
1954 1955 1956
    return ret;
}

1957

1958
static int
1959 1960 1961 1962
virSecuritySELinuxSetHostdevCapsLabel(virSecurityManagerPtr mgr,
                                      virDomainDefPtr def,
                                      virDomainHostdevDefPtr dev,
                                      const char *vroot)
1963 1964 1965 1966 1967 1968 1969
{
    int ret = -1;
    virSecurityLabelDefPtr secdef;
    char *path;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
1970
        return 0;
1971 1972 1973 1974 1975

    switch (dev->source.caps.type) {
    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_STORAGE: {
        if (vroot) {
            if (virAsprintf(&path, "%s/%s", vroot,
1976
                            dev->source.caps.u.storage.block) < 0)
1977 1978
                return -1;
        } else {
1979
            if (VIR_STRDUP(path, dev->source.caps.u.storage.block) < 0)
1980 1981
                return -1;
        }
1982
        ret = virSecuritySELinuxSetFilecon(mgr, path, secdef->imagelabel);
1983 1984 1985 1986 1987 1988 1989
        VIR_FREE(path);
        break;
    }

    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_MISC: {
        if (vroot) {
            if (virAsprintf(&path, "%s/%s", vroot,
1990
                            dev->source.caps.u.misc.chardev) < 0)
1991 1992
                return -1;
        } else {
1993
            if (VIR_STRDUP(path, dev->source.caps.u.misc.chardev) < 0)
1994 1995
                return -1;
        }
1996
        ret = virSecuritySELinuxSetFilecon(mgr, path, secdef->imagelabel);
1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009
        VIR_FREE(path);
        break;
    }

    default:
        ret = 0;
        break;
    }

    return ret;
}


2010
static int
2011 2012 2013 2014
virSecuritySELinuxSetHostdevLabel(virSecurityManagerPtr mgr,
                                  virDomainDefPtr def,
                                  virDomainHostdevDefPtr dev,
                                  const char *vroot)
2015 2016 2017 2018 2019

{
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2020
    if (!secdef || !secdef->relabel)
2021 2022 2023 2024
        return 0;

    switch (dev->mode) {
    case VIR_DOMAIN_HOSTDEV_MODE_SUBSYS:
2025
        return virSecuritySELinuxSetHostdevSubsysLabel(mgr, def, dev, vroot);
2026

2027
    case VIR_DOMAIN_HOSTDEV_MODE_CAPABILITIES:
2028
        return virSecuritySELinuxSetHostdevCapsLabel(mgr, def, dev, vroot);
2029

2030 2031 2032 2033 2034
    default:
        return 0;
    }
}

2035
static int
2036 2037 2038
virSecuritySELinuxRestorePCILabel(virPCIDevicePtr dev ATTRIBUTE_UNUSED,
                                  const char *file,
                                  void *opaque)
2039
{
2040 2041
    virSecurityManagerPtr mgr = opaque;

2042
    return virSecuritySELinuxRestoreFileLabel(mgr, file);
2043 2044 2045
}

static int
2046 2047 2048
virSecuritySELinuxRestoreUSBLabel(virUSBDevicePtr dev ATTRIBUTE_UNUSED,
                                  const char *file,
                                  void *opaque)
2049
{
2050 2051
    virSecurityManagerPtr mgr = opaque;

2052
    return virSecuritySELinuxRestoreFileLabel(mgr, file);
2053 2054
}

2055

2056
static int
2057 2058 2059
virSecuritySELinuxRestoreSCSILabel(virSCSIDevicePtr dev,
                                   const char *file,
                                   void *opaque)
2060 2061 2062
{
    virSecurityManagerPtr mgr = opaque;

2063 2064 2065 2066 2067 2068
    /* Don't restore labels on a shareable or readonly hostdev, because
     * other VMs may still be accessing.
     */
    if (virSCSIDeviceGetShareable(dev) || virSCSIDeviceGetReadonly(dev))
        return 0;

2069
    return virSecuritySELinuxRestoreFileLabel(mgr, file);
2070 2071
}

2072 2073 2074 2075 2076 2077 2078 2079 2080 2081
static int
virSecuritySELinuxRestoreHostLabel(virSCSIVHostDevicePtr dev ATTRIBUTE_UNUSED,
                                   const char *file,
                                   void *opaque)
{
    virSecurityManagerPtr mgr = opaque;

    return virSecuritySELinuxRestoreFileLabel(mgr, file);
}

2082

2083
static int
2084 2085 2086
virSecuritySELinuxRestoreHostdevSubsysLabel(virSecurityManagerPtr mgr,
                                            virDomainHostdevDefPtr dev,
                                            const char *vroot)
2087 2088

{
2089
    virDomainHostdevSubsysUSBPtr usbsrc = &dev->source.subsys.u.usb;
2090
    virDomainHostdevSubsysPCIPtr pcisrc = &dev->source.subsys.u.pci;
2091
    virDomainHostdevSubsysSCSIPtr scsisrc = &dev->source.subsys.u.scsi;
2092
    virDomainHostdevSubsysSCSIVHostPtr hostsrc = &dev->source.subsys.u.scsi_host;
2093
    virDomainHostdevSubsysMediatedDevPtr mdevsrc = &dev->source.subsys.u.mdev;
2094 2095
    int ret = -1;

2096
    /* Like virSecuritySELinuxRestoreImageLabelInt() for a networked
2097 2098
     * disk, do nothing for an iSCSI hostdev
     */
2099 2100
    if (dev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI &&
        scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI)
2101 2102
        return 0;

2103
    switch ((virDomainHostdevSubsysType)dev->source.subsys.type) {
2104
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB: {
2105
        virUSBDevicePtr usb;
2106 2107 2108

        if (dev->missing)
            return 0;
2109

2110 2111
        usb = virUSBDeviceNew(usbsrc->bus,
                              usbsrc->device,
2112
                              vroot);
2113 2114 2115
        if (!usb)
            goto done;

2116
        ret = virUSBDeviceFileIterate(usb, virSecuritySELinuxRestoreUSBLabel, mgr);
2117
        virUSBDeviceFree(usb);
2118 2119 2120 2121 2122

        break;
    }

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI: {
2123
        virPCIDevicePtr pci =
2124 2125
            virPCIDeviceNew(pcisrc->addr.domain, pcisrc->addr.bus,
                            pcisrc->addr.slot, pcisrc->addr.function);
2126 2127 2128 2129

        if (!pci)
            goto done;

2130
        if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
2131
            char *vfioGroupDev = virPCIDeviceGetIOMMUGroupDev(pci);
2132

2133 2134
            if (!vfioGroupDev) {
                virPCIDeviceFree(pci);
2135
                goto done;
2136
            }
2137
            ret = virSecuritySELinuxRestorePCILabel(pci, vfioGroupDev, mgr);
2138 2139
            VIR_FREE(vfioGroupDev);
        } else {
2140
            ret = virPCIDeviceFileIterate(pci, virSecuritySELinuxRestorePCILabel, mgr);
2141
        }
2142
        virPCIDeviceFree(pci);
2143 2144 2145
        break;
    }

2146
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI: {
2147
        virDomainHostdevSubsysSCSIHostPtr scsihostsrc = &scsisrc->u.host;
2148
        virSCSIDevicePtr scsi =
2149
            virSCSIDeviceNew(NULL,
2150 2151
                             scsihostsrc->adapter, scsihostsrc->bus,
                             scsihostsrc->target, scsihostsrc->unit,
2152
                             dev->readonly, dev->shareable);
2153

J
Ján Tomko 已提交
2154 2155
        if (!scsi)
            goto done;
2156

2157
        ret = virSCSIDeviceFileIterate(scsi, virSecuritySELinuxRestoreSCSILabel, mgr);
J
Ján Tomko 已提交
2158
        virSCSIDeviceFree(scsi);
2159

J
Ján Tomko 已提交
2160 2161
        break;
    }
2162

2163
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI_HOST: {
2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
        virSCSIVHostDevicePtr host = virSCSIVHostDeviceNew(hostsrc->wwpn);

        if (!host)
            goto done;

        ret = virSCSIVHostDeviceFileIterate(host,
                                            virSecuritySELinuxRestoreHostLabel,
                                            mgr);
        virSCSIVHostDeviceFree(host);

        break;
2175 2176
    }

2177 2178 2179
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_MDEV: {
        char *vfiodev = NULL;

2180
        if (!(vfiodev = virMediatedDeviceGetIOMMUGroupDev(mdevsrc->uuidstr)))
2181 2182 2183 2184 2185 2186 2187 2188
            goto done;

        ret = virSecuritySELinuxRestoreFileLabel(mgr, vfiodev);

        VIR_FREE(vfiodev);
        break;
    }

2189
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_LAST:
2190 2191 2192 2193
        ret = 0;
        break;
    }

2194
 done:
2195 2196 2197
    return ret;
}

2198

2199
static int
2200 2201 2202
virSecuritySELinuxRestoreHostdevCapsLabel(virSecurityManagerPtr mgr,
                                          virDomainHostdevDefPtr dev,
                                          const char *vroot)
2203 2204 2205 2206 2207 2208 2209 2210
{
    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,
2211
                            dev->source.caps.u.storage.block) < 0)
2212 2213
                return -1;
        } else {
2214
            if (VIR_STRDUP(path, dev->source.caps.u.storage.block) < 0)
2215 2216
                return -1;
        }
2217
        ret = virSecuritySELinuxRestoreFileLabel(mgr, path);
2218 2219 2220 2221 2222 2223 2224
        VIR_FREE(path);
        break;
    }

    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_MISC: {
        if (vroot) {
            if (virAsprintf(&path, "%s/%s", vroot,
2225
                            dev->source.caps.u.misc.chardev) < 0)
2226 2227
                return -1;
        } else {
2228
            if (VIR_STRDUP(path, dev->source.caps.u.misc.chardev) < 0)
2229 2230
                return -1;
        }
2231
        ret = virSecuritySELinuxRestoreFileLabel(mgr, path);
2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244
        VIR_FREE(path);
        break;
    }

    default:
        ret = 0;
        break;
    }

    return ret;
}


2245
static int
2246 2247 2248 2249
virSecuritySELinuxRestoreHostdevLabel(virSecurityManagerPtr mgr,
                                      virDomainDefPtr def,
                                      virDomainHostdevDefPtr dev,
                                      const char *vroot)
2250 2251 2252 2253 2254

{
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2255
    if (!secdef || !secdef->relabel)
2256 2257 2258 2259
        return 0;

    switch (dev->mode) {
    case VIR_DOMAIN_HOSTDEV_MODE_SUBSYS:
2260
        return virSecuritySELinuxRestoreHostdevSubsysLabel(mgr, dev, vroot);
2261

2262
    case VIR_DOMAIN_HOSTDEV_MODE_CAPABILITIES:
2263
        return virSecuritySELinuxRestoreHostdevCapsLabel(mgr, dev, vroot);
2264

2265 2266 2267 2268 2269 2270
    default:
        return 0;
    }
}


2271
static int
2272 2273
virSecuritySELinuxSetChardevLabel(virSecurityManagerPtr mgr,
                                  virDomainDefPtr def,
2274 2275
                                  virDomainChrSourceDefPtr dev_source,
                                  bool chardevStdioLogd)
2276 2277

{
2278 2279 2280
    virSecurityLabelDefPtr seclabel;
    virSecurityDeviceLabelDefPtr chr_seclabel = NULL;
    char *imagelabel = NULL;
2281 2282 2283
    char *in = NULL, *out = NULL;
    int ret = -1;

2284
    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2285
    if (!seclabel || !seclabel->relabel)
2286
        return 0;
2287

2288 2289
    chr_seclabel = virDomainChrSourceDefGetSecurityLabelDef(dev_source,
                                                            SECURITY_SELINUX_NAME);
2290

2291
    if (chr_seclabel && !chr_seclabel->relabel)
2292 2293
        return 0;

2294 2295 2296
    if (!chr_seclabel &&
        dev_source->type == VIR_DOMAIN_CHR_TYPE_FILE &&
        chardevStdioLogd)
2297 2298
        return 0;

2299 2300 2301 2302 2303 2304
    if (chr_seclabel)
        imagelabel = chr_seclabel->label;
    if (!imagelabel)
        imagelabel = seclabel->imagelabel;

    switch (dev_source->type) {
2305 2306
    case VIR_DOMAIN_CHR_TYPE_DEV:
    case VIR_DOMAIN_CHR_TYPE_FILE:
2307 2308
        ret = virSecuritySELinuxSetFilecon(mgr,
                                           dev_source->data.file.path,
2309 2310 2311 2312 2313
                                           imagelabel);
        break;

    case VIR_DOMAIN_CHR_TYPE_UNIX:
        if (!dev_source->data.nix.listen) {
2314 2315
            if (virSecuritySELinuxSetFilecon(mgr,
                                             dev_source->data.nix.path,
2316 2317 2318 2319
                                             imagelabel) < 0)
                goto done;
        }
        ret = 0;
2320 2321 2322
        break;

    case VIR_DOMAIN_CHR_TYPE_PIPE:
2323
        if ((virAsprintf(&in, "%s.in", dev_source->data.file.path) < 0) ||
2324
            (virAsprintf(&out, "%s.out", dev_source->data.file.path) < 0))
2325 2326
            goto done;
        if (virFileExists(in) && virFileExists(out)) {
2327 2328
            if ((virSecuritySELinuxSetFilecon(mgr, in, imagelabel) < 0) ||
                (virSecuritySELinuxSetFilecon(mgr, out, imagelabel) < 0)) {
2329
                goto done;
2330
            }
2331 2332
        } else if (virSecuritySELinuxSetFilecon(mgr,
                                                dev_source->data.file.path,
2333
                                                imagelabel) < 0) {
2334
            goto done;
2335 2336 2337 2338 2339 2340 2341 2342 2343
        }
        ret = 0;
        break;

    default:
        ret = 0;
        break;
    }

2344
 done:
2345 2346 2347 2348 2349 2350
    VIR_FREE(in);
    VIR_FREE(out);
    return ret;
}

static int
2351 2352
virSecuritySELinuxRestoreChardevLabel(virSecurityManagerPtr mgr,
                                      virDomainDefPtr def,
2353 2354
                                      virDomainChrSourceDefPtr dev_source,
                                      bool chardevStdioLogd)
2355 2356

{
2357 2358
    virSecurityLabelDefPtr seclabel;
    virSecurityDeviceLabelDefPtr chr_seclabel = NULL;
2359 2360 2361
    char *in = NULL, *out = NULL;
    int ret = -1;

2362
    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2363
    if (!seclabel || !seclabel->relabel)
2364
        return 0;
2365

2366 2367
    chr_seclabel = virDomainChrSourceDefGetSecurityLabelDef(dev_source,
                                                            SECURITY_SELINUX_NAME);
2368
    if (chr_seclabel && !chr_seclabel->relabel)
2369 2370
        return 0;

2371 2372 2373
    if (!chr_seclabel &&
        dev_source->type == VIR_DOMAIN_CHR_TYPE_FILE &&
        chardevStdioLogd)
2374 2375
        return 0;

2376
    switch (dev_source->type) {
2377 2378
    case VIR_DOMAIN_CHR_TYPE_DEV:
    case VIR_DOMAIN_CHR_TYPE_FILE:
2379
        if (virSecuritySELinuxRestoreFileLabel(mgr, dev_source->data.file.path) < 0)
2380 2381
            goto done;
        ret = 0;
2382
        break;
2383 2384 2385

    case VIR_DOMAIN_CHR_TYPE_UNIX:
        if (!dev_source->data.nix.listen) {
2386
            if (virSecuritySELinuxRestoreFileLabel(mgr, dev_source->data.file.path) < 0)
2387 2388 2389 2390 2391
                goto done;
        }
        ret = 0;
        break;

2392
    case VIR_DOMAIN_CHR_TYPE_PIPE:
2393
        if ((virAsprintf(&out, "%s.out", dev_source->data.file.path) < 0) ||
2394
            (virAsprintf(&in, "%s.in", dev_source->data.file.path) < 0))
2395
            goto done;
2396
        if (virFileExists(in) && virFileExists(out)) {
2397 2398
            if ((virSecuritySELinuxRestoreFileLabel(mgr, out) < 0) ||
                (virSecuritySELinuxRestoreFileLabel(mgr, in) < 0)) {
2399 2400
                goto done;
            }
2401
        } else if (virSecuritySELinuxRestoreFileLabel(mgr, dev_source->data.file.path) < 0) {
2402
            goto done;
2403
        }
2404 2405 2406 2407 2408 2409 2410 2411
        ret = 0;
        break;

    default:
        ret = 0;
        break;
    }

2412
 done:
2413 2414 2415 2416 2417 2418
    VIR_FREE(in);
    VIR_FREE(out);
    return ret;
}


2419 2420 2421 2422 2423 2424
struct _virSecuritySELinuxChardevCallbackData {
    virSecurityManagerPtr mgr;
    bool chardevStdioLogd;
};


2425
static int
2426
virSecuritySELinuxRestoreSecurityChardevCallback(virDomainDefPtr def,
2427
                                                 virDomainChrDefPtr dev ATTRIBUTE_UNUSED,
2428
                                                 void *opaque)
2429
{
2430
    struct _virSecuritySELinuxChardevCallbackData *data = opaque;
2431

2432 2433
    return virSecuritySELinuxRestoreChardevLabel(data->mgr, def, dev->source,
                                                 data->chardevStdioLogd);
2434 2435 2436
}


E
Eric Blake 已提交
2437
static int
2438 2439
virSecuritySELinuxRestoreSecuritySmartcardCallback(virDomainDefPtr def,
                                                   virDomainSmartcardDefPtr dev,
2440
                                                   void *opaque)
E
Eric Blake 已提交
2441
{
2442
    virSecurityManagerPtr mgr = opaque;
E
Eric Blake 已提交
2443 2444 2445 2446 2447 2448 2449 2450 2451 2452
    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;
2453
        return virSecuritySELinuxRestoreFileLabel(mgr, database);
E
Eric Blake 已提交
2454 2455

    case VIR_DOMAIN_SMARTCARD_TYPE_PASSTHROUGH:
2456 2457
        return virSecuritySELinuxRestoreChardevLabel(mgr, def,
                                                     dev->data.passthru, false);
E
Eric Blake 已提交
2458 2459

    default:
2460 2461 2462
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown smartcard type %d"),
                       dev->type);
E
Eric Blake 已提交
2463 2464 2465 2466 2467 2468 2469
        return -1;
    }

    return 0;
}


2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480
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;
}


2481
static int
2482 2483
virSecuritySELinuxRestoreAllLabel(virSecurityManagerPtr mgr,
                                  virDomainDefPtr def,
2484 2485
                                  bool migrated,
                                  bool chardevStdioLogd)
2486
{
2487
    virSecurityLabelDefPtr secdef;
2488
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
2489
    size_t i;
2490
    int rc = 0;
2491

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

2494 2495
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);

2496
    if (!secdef || !secdef->relabel || data->skipAllLabel)
2497 2498
        return 0;

2499
    if (def->tpm) {
2500
        if (virSecuritySELinuxRestoreTPMFileLabelInt(mgr, def, def->tpm) < 0)
2501 2502 2503
            rc = -1;
    }

2504
    for (i = 0; i < def->nhostdevs; i++) {
2505 2506 2507 2508
        if (virSecuritySELinuxRestoreHostdevLabel(mgr,
                                                  def,
                                                  def->hostdevs[i],
                                                  NULL) < 0)
2509
            rc = -1;
2510
    }
2511 2512 2513 2514 2515 2516

    for (i = 0; i < def->ninputs; i++) {
        if (virSecuritySELinuxRestoreInputLabel(mgr, def, def->inputs[i]) < 0)
            rc = -1;
    }

2517 2518 2519 2520 2521
    for (i = 0; i < def->nmems; i++) {
        if (virSecuritySELinuxRestoreMemoryLabel(mgr, def, def->mems[i]) < 0)
            return -1;
    }

2522
    for (i = 0; i < def->ndisks; i++) {
2523 2524
        virDomainDiskDefPtr disk = def->disks[i];

2525 2526
        if (virSecuritySELinuxRestoreImageLabelInt(mgr, def, disk->src,
                                                   migrated) < 0)
2527 2528
            rc = -1;
    }
2529

2530 2531 2532 2533 2534
    struct _virSecuritySELinuxChardevCallbackData chardevData = {
        .mgr = mgr,
        .chardevStdioLogd = chardevStdioLogd
    };

2535
    if (virDomainChrDefForeach(def,
2536
                               false,
2537
                               virSecuritySELinuxRestoreSecurityChardevCallback,
2538
                               &chardevData) < 0)
2539 2540
        rc = -1;

2541
    if (virDomainSmartcardDefForeach(def,
E
Eric Blake 已提交
2542
                                     false,
2543
                                     virSecuritySELinuxRestoreSecuritySmartcardCallback,
2544
                                     mgr) < 0)
E
Eric Blake 已提交
2545 2546
        rc = -1;

2547
    if (def->os.loader && def->os.loader->nvram &&
2548
        virSecuritySELinuxRestoreFileLabel(mgr, def->os.loader->nvram) < 0)
2549 2550
        rc = -1;

2551 2552 2553 2554
    return rc;
}

static int
2555 2556
virSecuritySELinuxReleaseLabel(virSecurityManagerPtr mgr,
                               virDomainDefPtr def)
2557
{
2558 2559 2560 2561
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
2562
        return 0;
2563

2564 2565 2566 2567
    if (secdef->type == VIR_DOMAIN_SECLABEL_DYNAMIC) {
        if (secdef->label != NULL) {
            context_t con = context_new(secdef->label);
            if (con) {
2568
                virSecuritySELinuxMCSRemove(mgr, context_range_get(con));
2569 2570 2571 2572 2573 2574
                context_free(con);
            }
        }
        VIR_FREE(secdef->label);
        if (!secdef->baselabel)
            VIR_FREE(secdef->model);
2575 2576 2577
    }
    VIR_FREE(secdef->imagelabel);

2578
    return 0;
2579 2580
}

2581 2582

static int
2583
virSecuritySELinuxSetSavedStateLabel(virSecurityManagerPtr mgr,
2584 2585
                                     virDomainDefPtr def,
                                     const char *savefile)
2586
{
2587 2588 2589
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2590
    if (!secdef || !secdef->relabel)
2591 2592
        return 0;

2593
    return virSecuritySELinuxSetFilecon(mgr, savefile, secdef->imagelabel);
2594 2595 2596 2597
}


static int
2598
virSecuritySELinuxRestoreSavedStateLabel(virSecurityManagerPtr mgr,
2599 2600
                                         virDomainDefPtr def,
                                         const char *savefile)
2601
{
2602 2603 2604
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2605
    if (!secdef || !secdef->relabel)
2606 2607
        return 0;

2608
    return virSecuritySELinuxRestoreFileLabel(mgr, savefile);
2609 2610 2611
}


2612
static int
2613 2614
virSecuritySELinuxVerify(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                         virDomainDefPtr def)
2615
{
2616 2617 2618 2619
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
2620
        return 0;
2621

2622
    if (STRNEQ(SECURITY_SELINUX_NAME, secdef->model)) {
2623 2624 2625 2626
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "'%s' model configured for domain, but "
                         "hypervisor driver is '%s'."),
2627
                       secdef->model, SECURITY_SELINUX_NAME);
2628 2629 2630
        return -1;
    }

2631 2632
    if (secdef->type == VIR_DOMAIN_SECLABEL_STATIC) {
        if (security_check_context(secdef->label) != 0) {
2633 2634
            virReportError(VIR_ERR_XML_ERROR,
                           _("Invalid security label %s"), secdef->label);
2635 2636 2637 2638 2639 2640
            return -1;
        }
    }
    return 0;
}

2641
static int
2642 2643
virSecuritySELinuxSetProcessLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                  virDomainDefPtr def)
2644 2645
{
    /* TODO: verify DOI */
2646 2647 2648
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2649
    if (!secdef || !secdef->label)
2650 2651
        return 0;

2652
    VIR_DEBUG("label=%s", secdef->label);
2653
    if (STRNEQ(SECURITY_SELINUX_NAME, secdef->model)) {
2654 2655 2656 2657
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "'%s' model configured for domain, but "
                         "hypervisor driver is '%s'."),
2658
                       secdef->model, SECURITY_SELINUX_NAME);
2659
        if (security_getenforce() == 1)
2660
            return -1;
2661 2662
    }

M
Martin Kletzander 已提交
2663
    if (setexeccon_raw(secdef->label) == -1) {
2664
        virReportSystemError(errno,
2665 2666
                             _("unable to set security context '%s'"),
                             secdef->label);
2667
        if (security_getenforce() == 1)
2668
            return -1;
2669 2670
    }

2671 2672 2673
    return 0;
}

2674
static int
2675 2676 2677
virSecuritySELinuxSetChildProcessLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                       virDomainDefPtr def,
                                       virCommandPtr cmd)
2678 2679 2680 2681 2682
{
    /* TODO: verify DOI */
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2683
    if (!secdef || !secdef->label)
2684 2685 2686
        return 0;

    VIR_DEBUG("label=%s", secdef->label);
2687
    if (STRNEQ(SECURITY_SELINUX_NAME, secdef->model)) {
2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701
        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;
}

2702
static int
2703 2704
virSecuritySELinuxSetDaemonSocketLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                       virDomainDefPtr def)
2705 2706
{
    /* TODO: verify DOI */
2707
    virSecurityLabelDefPtr secdef;
2708
    security_context_t scon = NULL;
2709
    char *str = NULL;
2710 2711
    int rc = -1;

2712
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2713
    if (!secdef || !secdef->label)
2714 2715
        return 0;

2716
    if (STRNEQ(SECURITY_SELINUX_NAME, secdef->model)) {
2717 2718 2719 2720
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "'%s' model configured for domain, but "
                         "hypervisor driver is '%s'."),
2721
                       secdef->model, SECURITY_SELINUX_NAME);
2722 2723 2724
        goto done;
    }

M
Martin Kletzander 已提交
2725
    if (getcon_raw(&scon) == -1) {
2726 2727 2728 2729 2730 2731
        virReportSystemError(errno,
                             _("unable to get current process context '%s'"),
                             secdef->label);
        goto done;
    }

2732
    if (!(str = virSecuritySELinuxContextAddRange(secdef->label, scon)))
2733 2734
        goto done;

2735 2736
    VIR_DEBUG("Setting VM %s socket context %s", def->name, str);
    if (setsockcreatecon_raw(str) == -1) {
2737
        virReportSystemError(errno,
2738
                             _("unable to set socket security context '%s'"), str);
2739 2740 2741 2742
        goto done;
    }

    rc = 0;
2743
 done:
2744 2745 2746 2747

    if (security_getenforce() != 1)
        rc = 0;
    freecon(scon);
2748
    VIR_FREE(str);
2749 2750 2751
    return rc;
}

2752
static int
2753 2754
virSecuritySELinuxSetSocketLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                 virDomainDefPtr vm)
2755
{
2756
    virSecurityLabelDefPtr secdef;
2757 2758
    int rc = -1;

2759
    secdef = virDomainDefGetSecurityLabelDef(vm, SECURITY_SELINUX_NAME);
2760
    if (!secdef || !secdef->label)
2761 2762
        return 0;

2763
    if (STRNEQ(SECURITY_SELINUX_NAME, secdef->model)) {
2764 2765 2766 2767
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "'%s' model configured for domain, but "
                         "hypervisor driver is '%s'."),
2768
                       secdef->model, SECURITY_SELINUX_NAME);
2769 2770 2771 2772
        goto done;
    }

    VIR_DEBUG("Setting VM %s socket context %s",
2773
              vm->name, secdef->label);
M
Martin Kletzander 已提交
2774
    if (setsockcreatecon_raw(secdef->label) == -1) {
2775 2776 2777 2778 2779 2780 2781 2782
        virReportSystemError(errno,
                             _("unable to set socket security context '%s'"),
                             secdef->label);
        goto done;
    }

    rc = 0;

2783
 done:
2784 2785 2786 2787 2788 2789
    if (security_getenforce() != 1)
        rc = 0;

    return rc;
}

2790
static int
2791 2792
virSecuritySELinuxClearSocketLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                   virDomainDefPtr def)
2793 2794
{
    /* TODO: verify DOI */
2795 2796 2797
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2798
    if (!secdef || !secdef->label)
2799 2800
        return 0;

2801
    if (STRNEQ(SECURITY_SELINUX_NAME, secdef->model)) {
2802 2803 2804 2805
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "'%s' model configured for domain, but "
                         "hypervisor driver is '%s'."),
2806
                       secdef->model, SECURITY_SELINUX_NAME);
2807 2808 2809 2810
        if (security_getenforce() == 1)
            return -1;
    }

M
Martin Kletzander 已提交
2811
    if (setsockcreatecon_raw(NULL) == -1) {
2812 2813 2814 2815 2816 2817 2818 2819 2820
        virReportSystemError(errno,
                             _("unable to clear socket security context '%s'"),
                             secdef->label);
        if (security_getenforce() == 1)
            return -1;
    }
    return 0;
}

2821 2822

static int
2823
virSecuritySELinuxSetSecurityChardevCallback(virDomainDefPtr def,
2824
                                             virDomainChrDefPtr dev ATTRIBUTE_UNUSED,
2825
                                             void *opaque)
2826
{
2827
    struct _virSecuritySELinuxChardevCallbackData *data = opaque;
2828

2829 2830
    return virSecuritySELinuxSetChardevLabel(data->mgr, def, dev->source,
                                             data->chardevStdioLogd);
2831 2832 2833
}


E
Eric Blake 已提交
2834
static int
2835 2836 2837
virSecuritySELinuxSetSecuritySmartcardCallback(virDomainDefPtr def,
                                               virDomainSmartcardDefPtr dev,
                                               void *opaque)
E
Eric Blake 已提交
2838 2839
{
    const char *database;
2840 2841
    virSecurityManagerPtr mgr = opaque;
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
E
Eric Blake 已提交
2842 2843 2844 2845 2846 2847 2848 2849 2850

    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;
2851
        return virSecuritySELinuxSetFilecon(mgr, database, data->content_context);
E
Eric Blake 已提交
2852 2853

    case VIR_DOMAIN_SMARTCARD_TYPE_PASSTHROUGH:
2854
        return virSecuritySELinuxSetChardevLabel(mgr, def,
2855
                                                 dev->data.passthru, false);
E
Eric Blake 已提交
2856 2857

    default:
2858 2859 2860
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown smartcard type %d"),
                       dev->type);
E
Eric Blake 已提交
2861 2862 2863 2864 2865 2866 2867
        return -1;
    }

    return 0;
}


2868
static int
2869 2870
virSecuritySELinuxSetAllLabel(virSecurityManagerPtr mgr,
                              virDomainDefPtr def,
2871 2872
                              const char *stdin_path,
                              bool chardevStdioLogd)
2873
{
2874
    size_t i;
2875 2876 2877 2878
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2879

2880
    if (!secdef || !secdef->relabel || data->skipAllLabel)
2881 2882
        return 0;

2883
    for (i = 0; i < def->ndisks; i++) {
2884
        /* XXX fixme - we need to recursively label the entire tree :-( */
E
Eric Blake 已提交
2885
        if (virDomainDiskGetType(def->disks[i]) == VIR_STORAGE_TYPE_DIR) {
2886
            VIR_WARN("Unable to relabel directory tree %s for disk %s",
2887 2888
                     virDomainDiskGetSource(def->disks[i]),
                     def->disks[i]->dst);
2889
            continue;
2890
        }
2891 2892
        if (virSecuritySELinuxSetDiskLabel(mgr,
                                           def, def->disks[i]) < 0)
2893 2894
            return -1;
    }
2895
    /* XXX fixme process  def->fss if relabel == true */
2896

2897
    for (i = 0; i < def->nhostdevs; i++) {
2898 2899 2900 2901
        if (virSecuritySELinuxSetHostdevLabel(mgr,
                                              def,
                                              def->hostdevs[i],
                                              NULL) < 0)
2902
            return -1;
2903
    }
2904 2905 2906 2907 2908 2909

    for (i = 0; i < def->ninputs; i++) {
        if (virSecuritySELinuxSetInputLabel(mgr, def, def->inputs[i]) < 0)
            return -1;
    }

2910 2911 2912 2913 2914
    for (i = 0; i < def->nmems; i++) {
        if (virSecuritySELinuxSetMemoryLabel(mgr, def, def->mems[i]) < 0)
            return -1;
    }

2915
    if (def->tpm) {
2916
        if (virSecuritySELinuxSetTPMFileLabel(mgr, def, def->tpm) < 0)
2917 2918
            return -1;
    }
2919

2920 2921 2922 2923 2924
    struct _virSecuritySELinuxChardevCallbackData chardevData = {
        .mgr = mgr,
        .chardevStdioLogd = chardevStdioLogd
    };

2925
    if (virDomainChrDefForeach(def,
2926
                               true,
2927
                               virSecuritySELinuxSetSecurityChardevCallback,
2928
                               &chardevData) < 0)
2929 2930
        return -1;

2931
    if (virDomainSmartcardDefForeach(def,
E
Eric Blake 已提交
2932
                                     true,
2933
                                     virSecuritySELinuxSetSecuritySmartcardCallback,
2934
                                     mgr) < 0)
E
Eric Blake 已提交
2935 2936
        return -1;

M
Michal Privoznik 已提交
2937 2938
    /* This is different than kernel or initrd. The nvram store
     * is really a disk, qemu can read and write to it. */
2939
    if (def->os.loader && def->os.loader->nvram &&
M
Michal Privoznik 已提交
2940
        secdef && secdef->imagelabel &&
2941 2942
        virSecuritySELinuxSetFilecon(mgr, def->os.loader->nvram,
                                     secdef->imagelabel) < 0)
2943 2944
        return -1;

2945
    if (def->os.kernel &&
2946 2947
        virSecuritySELinuxSetFilecon(mgr, def->os.kernel,
                                     data->content_context) < 0)
2948 2949
        return -1;

2950
    if (def->os.initrd &&
2951 2952
        virSecuritySELinuxSetFilecon(mgr, def->os.initrd,
                                     data->content_context) < 0)
2953 2954
        return -1;

O
Olivia Yin 已提交
2955
    if (def->os.dtb &&
2956 2957
        virSecuritySELinuxSetFilecon(mgr, def->os.dtb,
                                     data->content_context) < 0)
O
Olivia Yin 已提交
2958 2959
        return -1;

J
Ján Tomko 已提交
2960 2961 2962 2963 2964
    if (def->os.slic_table &&
        virSecuritySELinuxSetFilecon(mgr, def->os.slic_table,
                                     data->content_context) < 0)
        return -1;

2965
    if (stdin_path &&
2966 2967
        virSecuritySELinuxSetFilecon(mgr, stdin_path,
                                     data->content_context) < 0)
2968
        return -1;
2969

2970 2971 2972
    return 0;
}

2973
static int
2974 2975 2976
virSecuritySELinuxSetImageFDLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                  virDomainDefPtr def,
                                  int fd)
2977
{
2978 2979 2980
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2981
    if (!secdef || !secdef->imagelabel)
2982 2983
        return 0;

2984
    return virSecuritySELinuxFSetFilecon(fd, secdef->imagelabel);
2985 2986
}

2987
static int
2988
virSecuritySELinuxSetTapFDLabel(virSecurityManagerPtr mgr,
2989 2990 2991
                                virDomainDefPtr def,
                                int fd)
{
2992 2993
    struct stat buf;
    security_context_t fcon = NULL;
2994
    virSecurityLabelDefPtr secdef;
2995
    char *str = NULL, *proc = NULL, *fd_path = NULL;
2996
    int rc = -1;
2997 2998

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2999
    if (!secdef || !secdef->label)
3000 3001
        return 0;

3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012
    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;
    }

3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030
    /* Label /dev/tap.* devices only. Leave /dev/net/tun alone! */
    if (virAsprintf(&proc, "/proc/self/fd/%d", fd) == -1)
        goto cleanup;

    if (virFileResolveLink(proc, &fd_path) < 0) {
        virReportSystemError(errno,
                             _("Unable to resolve link: %s"), proc);
        goto cleanup;
    }

    if (!STRPREFIX(fd_path, "/dev/tap")) {
        VIR_DEBUG("fd=%d points to %s not setting SELinux label",
                  fd, fd_path);
        rc = 0;
        goto cleanup;
    }

    if (getContext(mgr, "/dev/tap*", buf.st_mode, &fcon) < 0) {
3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043
        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);
3044 3045
    VIR_FREE(fd_path);
    VIR_FREE(proc);
3046 3047
    VIR_FREE(str);
    return rc;
3048 3049
}

3050 3051 3052 3053
static char *
virSecuritySELinuxGenImageLabel(virSecurityManagerPtr mgr,
                                virDomainDefPtr def)
{
3054
    virSecurityLabelDefPtr secdef;
3055 3056 3057 3058
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
    const char *range;
    context_t ctx = NULL;
    char *label = NULL;
3059
    char *mcs = NULL;
3060

3061 3062 3063 3064
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        goto cleanup;

3065 3066 3067
    if (secdef->label) {
        ctx = context_new(secdef->label);
        if (!ctx) {
3068 3069
            virReportSystemError(errno, _("unable to create selinux context for: %s"),
                                 secdef->label);
3070 3071 3072 3073
            goto cleanup;
        }
        range = context_range_get(ctx);
        if (range) {
3074
            if (VIR_STRDUP(mcs, range) < 0)
3075
                goto cleanup;
3076 3077
            if (!(label = virSecuritySELinuxGenNewContext(data->file_context,
                                                          mcs, true)))
3078 3079 3080 3081
                goto cleanup;
        }
    }

3082
 cleanup:
3083 3084 3085
    context_free(ctx);
    VIR_FREE(mcs);
    return label;
3086 3087
}

3088 3089 3090 3091
static char *
virSecuritySELinuxGetSecurityMountOptions(virSecurityManagerPtr mgr,
                                          virDomainDefPtr def)
{
3092
    char *opts = NULL;
3093 3094
    virSecurityLabelDefPtr secdef;

3095 3096 3097 3098 3099 3100 3101
    if ((secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME))) {
        if (!secdef->imagelabel)
            secdef->imagelabel = virSecuritySELinuxGenImageLabel(mgr, def);

        if (secdef->imagelabel &&
            virAsprintf(&opts,
                        ",context=\"%s\"",
3102
                        (const char*) secdef->imagelabel) < 0)
3103 3104
            return NULL;
    }
3105

3106
    if (!opts && VIR_STRDUP(opts, "") < 0)
3107
        return NULL;
3108

3109 3110
    VIR_DEBUG("imageLabel=%s opts=%s",
              secdef ? secdef->imagelabel : "(null)", opts);
3111 3112 3113
    return opts;
}

G
Guido Günther 已提交
3114
static int
3115 3116
virSecuritySELinuxDomainSetPathLabel(virSecurityManagerPtr mgr,
                                     virDomainDefPtr def,
3117 3118
                                     const char *path,
                                     bool allowSubtree ATTRIBUTE_UNUSED)
3119 3120 3121 3122 3123 3124 3125
{
    virSecurityLabelDefPtr seclabel;

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

3126
    return virSecuritySELinuxSetFilecon(mgr, path, seclabel->imagelabel);
3127 3128
}

3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289

/*
 * virSecuritySELinuxSetFileLabels:
 *
 * @mgr: the virSecurityManager
 * @path: path to a directory or a file
 * @seclabel: the security label
 *
 * Set the file labels on the given path; if the path is a directory
 * we label all files found there, including the directory itself,
 * otherwise we just label the file.
 */
static int
virSecuritySELinuxSetFileLabels(virSecurityManagerPtr mgr,
                                const char *path,
                                virSecurityLabelDefPtr seclabel)
{
    int ret = 0;
    struct dirent *ent;
    char *filename = NULL;
    DIR *dir;

    if ((ret = virSecuritySELinuxSetFilecon(mgr, path, seclabel->imagelabel)))
        return ret;

    if (!virFileIsDir(path))
        return 0;

    if (virDirOpen(&dir, path) < 0)
        return -1;

    while ((ret = virDirRead(dir, &ent, path)) > 0) {
        if (ent->d_type != DT_REG)
            continue;

        if (virAsprintf(&filename, "%s/%s", path, ent->d_name) < 0) {
            ret = -1;
            break;
        }
        ret = virSecuritySELinuxSetFilecon(mgr, filename,
                                           seclabel->imagelabel);
        VIR_FREE(filename);
        if (ret < 0)
            break;
    }
    if (ret < 0)
        virReportSystemError(errno, _("Unable to label files under %s"),
                             path);

    virDirClose(&dir);

    return ret;
}


/*
 * virSecuritySELinuxRestoreFileLabels:
 *
 * @mgr: the virSecurityManager
 * @path: path to a directory or a file
 *
 * Restore the file labels on the given path; if the path is a directory
 * we restore all file labels found there, including the label of the
 * directory itself, otherwise we just restore the label on the file.
 */
static int
virSecuritySELinuxRestoreFileLabels(virSecurityManagerPtr mgr,
                                    const char *path)
{
    int ret = 0;
    struct dirent *ent;
    char *filename = NULL;
    DIR *dir;

    if ((ret = virSecuritySELinuxRestoreFileLabel(mgr, path)))
        return ret;

    if (!virFileIsDir(path))
        return 0;

    if (virDirOpen(&dir, path) < 0)
        return -1;

    while ((ret = virDirRead(dir, &ent, path)) > 0) {
        if (ent->d_type != DT_REG)
            continue;

        if (virAsprintf(&filename, "%s/%s", path, ent->d_name) < 0) {
            ret = -1;
            break;
        }
        ret = virSecuritySELinuxRestoreFileLabel(mgr, filename);
        VIR_FREE(filename);
        if (ret < 0)
            break;
    }
    if (ret < 0)
        virReportSystemError(errno, _("Unable to restore file labels under %s"),
                             path);

    virDirClose(&dir);

    return ret;
}


static int
virSecuritySELinuxSetTPMLabels(virSecurityManagerPtr mgr,
                               virDomainDefPtr def)
{
    int ret = 0;
    virSecurityLabelDefPtr seclabel;

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

    switch (def->tpm->type) {
    case VIR_DOMAIN_TPM_TYPE_PASSTHROUGH:
        break;
    case VIR_DOMAIN_TPM_TYPE_EMULATOR:
        ret = virSecuritySELinuxSetFileLabels(
            mgr, def->tpm->data.emulator.storagepath,
            seclabel);
        if (ret == 0 && def->tpm->data.emulator.logfile)
            ret = virSecuritySELinuxSetFileLabels(
                mgr, def->tpm->data.emulator.logfile,
                seclabel);
        break;
    case VIR_DOMAIN_TPM_TYPE_LAST:
        break;
    }

    return ret;
}


static int
virSecuritySELinuxRestoreTPMLabels(virSecurityManagerPtr mgr,
                                   virDomainDefPtr def)
{
    int ret = 0;

    switch (def->tpm->type) {
    case VIR_DOMAIN_TPM_TYPE_PASSTHROUGH:
        break;
    case VIR_DOMAIN_TPM_TYPE_EMULATOR:
        ret = virSecuritySELinuxRestoreFileLabels(
            mgr, def->tpm->data.emulator.storagepath);
        if (ret == 0 && def->tpm->data.emulator.logfile)
            ret = virSecuritySELinuxRestoreFileLabels(
                mgr, def->tpm->data.emulator.logfile);
        break;
    case VIR_DOMAIN_TPM_TYPE_LAST:
        break;
    }

    return ret;
}


3290
virSecurityDriver virSecurityDriverSELinux = {
3291 3292
    .privateDataLen                     = sizeof(virSecuritySELinuxData),
    .name                               = SECURITY_SELINUX_NAME,
3293 3294 3295
    .probe                              = virSecuritySELinuxDriverProbe,
    .open                               = virSecuritySELinuxDriverOpen,
    .close                              = virSecuritySELinuxDriverClose,
3296

3297 3298
    .getModel                           = virSecuritySELinuxGetModel,
    .getDOI                             = virSecuritySELinuxGetDOI,
3299

3300 3301 3302 3303
    .transactionStart                   = virSecuritySELinuxTransactionStart,
    .transactionCommit                  = virSecuritySELinuxTransactionCommit,
    .transactionAbort                   = virSecuritySELinuxTransactionAbort,

3304
    .domainSecurityVerify               = virSecuritySELinuxVerify,
3305

3306 3307
    .domainSetSecurityDiskLabel         = virSecuritySELinuxSetDiskLabel,
    .domainRestoreSecurityDiskLabel     = virSecuritySELinuxRestoreDiskLabel,
3308

3309 3310
    .domainSetSecurityImageLabel        = virSecuritySELinuxSetImageLabel,
    .domainRestoreSecurityImageLabel    = virSecuritySELinuxRestoreImageLabel,
3311

3312 3313 3314
    .domainSetSecurityMemoryLabel       = virSecuritySELinuxSetMemoryLabel,
    .domainRestoreSecurityMemoryLabel   = virSecuritySELinuxRestoreMemoryLabel,

3315 3316 3317
    .domainSetSecurityInputLabel        = virSecuritySELinuxSetInputLabel,
    .domainRestoreSecurityInputLabel    = virSecuritySELinuxRestoreInputLabel,

3318 3319 3320
    .domainSetSecurityDaemonSocketLabel = virSecuritySELinuxSetDaemonSocketLabel,
    .domainSetSecuritySocketLabel       = virSecuritySELinuxSetSocketLabel,
    .domainClearSecuritySocketLabel     = virSecuritySELinuxClearSocketLabel,
3321

3322 3323 3324
    .domainGenSecurityLabel             = virSecuritySELinuxGenLabel,
    .domainReserveSecurityLabel         = virSecuritySELinuxReserveLabel,
    .domainReleaseSecurityLabel         = virSecuritySELinuxReleaseLabel,
3325

3326 3327 3328
    .domainGetSecurityProcessLabel      = virSecuritySELinuxGetProcessLabel,
    .domainSetSecurityProcessLabel      = virSecuritySELinuxSetProcessLabel,
    .domainSetSecurityChildProcessLabel = virSecuritySELinuxSetChildProcessLabel,
3329

3330 3331
    .domainSetSecurityAllLabel          = virSecuritySELinuxSetAllLabel,
    .domainRestoreSecurityAllLabel      = virSecuritySELinuxRestoreAllLabel,
3332

3333 3334
    .domainSetSecurityHostdevLabel      = virSecuritySELinuxSetHostdevLabel,
    .domainRestoreSecurityHostdevLabel  = virSecuritySELinuxRestoreHostdevLabel,
3335

3336 3337
    .domainSetSavedStateLabel           = virSecuritySELinuxSetSavedStateLabel,
    .domainRestoreSavedStateLabel       = virSecuritySELinuxRestoreSavedStateLabel,
3338

3339
    .domainSetSecurityImageFDLabel      = virSecuritySELinuxSetImageFDLabel,
3340
    .domainSetSecurityTapFDLabel        = virSecuritySELinuxSetTapFDLabel,
3341

3342
    .domainGetSecurityMountOptions      = virSecuritySELinuxGetSecurityMountOptions,
3343
    .getBaseLabel                       = virSecuritySELinuxGetBaseLabel,
3344

3345
    .domainSetPathLabel                 = virSecuritySELinuxDomainSetPathLabel,
3346 3347 3348

    .domainSetSecurityChardevLabel      = virSecuritySELinuxSetChardevLabel,
    .domainRestoreSecurityChardevLabel  = virSecuritySELinuxRestoreChardevLabel,
3349 3350 3351

    .domainSetSecurityTPMLabels         = virSecuritySELinuxSetTPMLabels,
    .domainRestoreSecurityTPMLabels     = virSecuritySELinuxRestoreTPMLabels,
3352
};