security_selinux.c 82.9 KB
Newer Older
1
/*
2
 * Copyright (C) 2008-2014 Red Hat, Inc.
3 4 5 6 7 8
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
O
Osier Yang 已提交
9 10 11 12 13 14
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
15
 * License along with this library.  If not, see
O
Osier Yang 已提交
16 17
 * <http://www.gnu.org/licenses/>.
 *
18 19
 * Authors:
 *     James Morris <jmorris@namei.org>
20
 *     Dan Walsh <dwalsh@redhat.com>
21 22 23 24 25 26 27 28 29
 *
 * SELinux security driver.
 */
#include <config.h>
#include <selinux/selinux.h>
#include <selinux/context.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
E
Eric Blake 已提交
30 31 32
#if HAVE_SELINUX_LABEL_H
# include <selinux/label.h>
#endif
33

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

#define VIR_FROM_THIS VIR_FROM_SECURITY

52 53
VIR_LOG_INIT("security.security_selinux");

54 55 56 57 58 59 60
#define MAX_CONTEXT 1024

typedef struct _virSecuritySELinuxData virSecuritySELinuxData;
typedef virSecuritySELinuxData *virSecuritySELinuxDataPtr;

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

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

75
struct _virSecuritySELinuxCallbackData {
76 77 78 79
    virSecurityManagerPtr mgr;
    virDomainDefPtr def;
};

80 81 82
#define SECURITY_SELINUX_VOID_DOI       "0"
#define SECURITY_SELINUX_NAME "selinux"

83 84 85 86 87 88
static int
virSecuritySELinuxRestoreSecurityTPMFileLabelInt(virSecurityManagerPtr mgr,
                                                 virDomainDefPtr def,
                                                 virDomainTPMDefPtr tpm);


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

98 99 100 101
    if (virHashLookup(data->mcs, mcs))
        return 1;

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

104 105 106
    return 0;
}

107 108 109
static void
virSecuritySELinuxMCSRemove(virSecurityManagerPtr mgr,
                            const char *mcs)
110
{
111 112 113
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);

    virHashRemoveEntry(data->mcs, mcs);
114 115
}

116 117

static char *
118 119 120 121
virSecuritySELinuxMCSFind(virSecurityManagerPtr mgr,
                          const char *sens,
                          int catMin,
                          int catMax)
122 123
{
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
124
    int catRange;
125
    char *mcs = NULL;
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146

    /* +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) {
147
            if (virAsprintf(&mcs, "%s:c%d", sens, catMin + c1) < 0)
148 149 150 151 152 153 154
                return NULL;
        } else {
            if (c1 > c2) {
                int t = c1;
                c1 = c2;
                c2 = t;
            }
155
            if (virAsprintf(&mcs, "%s:c%d,c%d", sens, catMin + c1, catMin + c2) < 0)
156 157 158 159 160 161 162 163 164 165 166 167
                return NULL;
        }

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

        VIR_FREE(mcs);
    }

    return mcs;
}

168 169 170 171

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

M
Martin Kletzander 已提交
196
    if (getcon_raw(&ourSecContext) < 0) {
197 198 199 200 201 202 203 204 205 206
        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;
    }
207 208
    if (!(contextRange = context_range_get(ourContext)))
        contextRange = "s0";
209

210
    if (VIR_STRDUP(*sens, contextRange) < 0)
211 212
        goto cleanup;

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

224
    /* If there was no category part, just assume c0.c1023 */
225 226
    if (!cat) {
        *catMin = 0;
227
        *catMax = 1023;
228 229 230 231
        ret = 0;
        goto cleanup;
    }

232 233 234 235 236 237 238 239 240
    /* Find & extract category min */
    tmp = cat;
    if (tmp[0] != 'c') {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot parse category in %s"),
                       cat);
        goto cleanup;
    }
    tmp++;
241
    if (virStrToLong_i(tmp, &tmp, 10, catMin) < 0) {
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
        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++;
271
    if (virStrToLong_i(tmp, &tmp, 10, catMax) < 0) {
272 273 274 275 276 277
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot parse category in %s"),
                       cat);
        goto cleanup;
    }

278
    ret = 0;
279

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

288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
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;
    }

318
    ignore_value(VIR_STRDUP(ret, str));
319

320
 cleanup:
321 322 323 324
    if (srccon) context_free(srccon);
    if (dstcon) context_free(dstcon);
    return ret;
}
325

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

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

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

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

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

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

377 378 379 380 381 382 383 384 385 386 387
    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;
    }
388
    if (VIR_STRDUP(ret, str) < 0)
389
        goto cleanup;
390
    VIR_DEBUG("Generated context '%s'",  ret);
391
 cleanup:
392 393
    freecon(ourSecContext);
    context_free(ourContext);
394 395
    context_free(context);
    return ret;
396 397
}

398

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

409 410
    data->skipAllLabel = true;

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

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

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

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

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

447 448 449
    if (VIR_STRDUP(data->domain_context, scon->str) < 0 ||
        VIR_STRDUP(data->file_context, tcon->str) < 0 ||
        VIR_STRDUP(data->content_context, dcon->str) < 0)
450
        goto error;
451 452 453 454

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

455 456 457
    virConfFree(selinux_conf);
    return 0;

458
 error:
459
# if HAVE_SELINUX_LABEL_H
460
    selabel_close(data->label_handle);
461
    data->label_handle = NULL;
462
# endif
463 464 465 466
    virConfFree(selinux_conf);
    VIR_FREE(data->domain_context);
    VIR_FREE(data->file_context);
    VIR_FREE(data->content_context);
467
    virHashFree(data->mcs);
468 469
    return -1;
}
470 471
#else
static int
472
virSecuritySELinuxLXCInitialize(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED)
473 474 475 476 477 478
{
    virReportSystemError(ENOSYS, "%s",
                         _("libselinux does not support LXC contexts path"));
    return -1;
}
#endif
479 480 481


static int
482
virSecuritySELinuxQEMUInitialize(virSecurityManagerPtr mgr)
483
{
484 485
    char *ptr;
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
486

487 488
    data->skipAllLabel = false;

489 490 491 492 493 494 495 496 497
#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

498
    if (virFileReadAll(selinux_virtual_domain_context_path(), MAX_CONTEXT, &(data->domain_context)) < 0) {
499
        virReportSystemError(errno,
500
                             _("cannot read SELinux virtual domain context file '%s'"),
501
                             selinux_virtual_domain_context_path());
502
        goto error;
503 504
    }

505
    ptr = strchrnul(data->domain_context, '\n');
506
    if (ptr && *ptr == '\n') {
507
        *ptr = '\0';
508 509
        ptr++;
        if (*ptr != '\0') {
510
            if (VIR_STRDUP(data->alt_domain_context, ptr) < 0)
511 512 513 514 515 516 517 518 519
                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));

520

521
    if (virFileReadAll(selinux_virtual_image_context_path(), 2*MAX_CONTEXT, &(data->file_context)) < 0) {
522
        virReportSystemError(errno,
523 524
                             _("cannot read SELinux virtual image context file %s"),
                             selinux_virtual_image_context_path());
525
        goto error;
526 527
    }

528 529
    ptr = strchrnul(data->file_context, '\n');
    if (ptr && *ptr == '\n') {
530
        *ptr = '\0';
531
        if (VIR_STRDUP(data->content_context, ptr + 1) < 0)
532 533 534
            goto error;
        ptr = strchrnul(data->content_context, '\n');
        if (ptr && *ptr == '\n')
535 536
            *ptr = '\0';
    }
537

538 539 540
    VIR_DEBUG("Loaded file context '%s', content context '%s'",
              data->file_context, data->content_context);

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

544
    return 0;
545

546
 error:
547 548
#if HAVE_SELINUX_LABEL_H
    selabel_close(data->label_handle);
549
    data->label_handle = NULL;
550
#endif
551
    VIR_FREE(data->domain_context);
552
    VIR_FREE(data->alt_domain_context);
553 554
    VIR_FREE(data->file_context);
    VIR_FREE(data->content_context);
555
    virHashFree(data->mcs);
556
    return -1;
557 558
}

559 560

static int
561
virSecuritySELinuxInitialize(virSecurityManagerPtr mgr)
562 563 564
{
    VIR_DEBUG("SELinuxInitialize %s", virSecurityManagerGetDriver(mgr));
    if (STREQ(virSecurityManagerGetDriver(mgr),  "LXC")) {
565
        return virSecuritySELinuxLXCInitialize(mgr);
566
    } else {
567
        return virSecuritySELinuxQEMUInitialize(mgr);
568 569 570 571
    }
}


572
static int
573 574
virSecuritySELinuxGenSecurityLabel(virSecurityManagerPtr mgr,
                                   virDomainDefPtr def)
575 576
{
    int rc = -1;
577
    char *mcs = NULL;
578
    char *scontext = NULL;
579
    context_t ctx = NULL;
580
    const char *range;
581 582
    virSecurityLabelDefPtr seclabel;
    virSecuritySELinuxDataPtr data;
583
    const char *baselabel;
584 585
    char *sens = NULL;
    int catMin, catMax;
586

587
    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
P
Peter Krempa 已提交
588
    if (seclabel == NULL)
589
        return 0;
590 591 592 593 594 595

    data = virSecurityManagerGetPrivateData(mgr);

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

601
    if (seclabel->imagelabel) {
P
Peter Krempa 已提交
602 603
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("security image label already defined for VM"));
604 605 606
        return rc;
    }

607 608
    if (seclabel->model &&
        STRNEQ(seclabel->model, SECURITY_SELINUX_NAME)) {
609 610
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label model %s is not supported with selinux"),
611
                       seclabel->model);
612 613 614
        return rc;
    }

615
    VIR_DEBUG("type=%d", seclabel->type);
616

617
    switch (seclabel->type) {
618
    case VIR_DOMAIN_SECLABEL_STATIC:
619
        if (!(ctx = context_new(seclabel->label))) {
620 621
            virReportSystemError(errno,
                                 _("unable to allocate socket security context '%s'"),
622
                                 seclabel->label);
623
            return rc;
624 625
        }

P
Peter Krempa 已提交
626
        if (!(range = context_range_get(ctx))) {
627
            virReportSystemError(errno, "%s", _("unable to get selinux context range"));
628 629
            goto cleanup;
        }
630 631
        if (VIR_STRDUP(mcs, range) < 0)
            goto cleanup;
632 633 634
        break;

    case VIR_DOMAIN_SECLABEL_DYNAMIC:
635 636 637 638 639 640 641 642 643
        if (virSecuritySELinuxMCSGetProcessRange(&sens,
                                                 &catMin,
                                                 &catMax) < 0)
            goto cleanup;

        if (!(mcs = virSecuritySELinuxMCSFind(mgr,
                                              sens,
                                              catMin,
                                              catMax)))
644 645 646 647
            goto cleanup;

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

649 650 651 652
        baselabel = seclabel->baselabel;
        if (!baselabel) {
            if (def->virtType == VIR_DOMAIN_VIRT_QEMU) {
                if (data->alt_domain_context == NULL) {
653
                    static bool warned;
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
                    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;
            }
        }

669 670
        seclabel->label = virSecuritySELinuxGenNewContext(baselabel, mcs, false);
        if (!seclabel->label)
671
            goto cleanup;
672

673 674 675
        break;

    case VIR_DOMAIN_SECLABEL_NONE:
676 677 678 679 680 681 682 683
        if (virSecuritySELinuxMCSGetProcessRange(&sens,
                                                 &catMin,
                                                 &catMax) < 0)
            goto cleanup;

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

684 685 686
        break;

    default:
687 688
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected security label type '%s'"),
689
                       virDomainSeclabelTypeToString(seclabel->type));
690
        goto cleanup;
D
Daniel P. Berrange 已提交
691
    }
692

693 694 695 696 697 698
    /* always generate a image label, needed to label new objects */
    seclabel->imagelabel = virSecuritySELinuxGenNewContext(data->file_context,
                                                           mcs,
                                                           true);
    if (!seclabel->imagelabel)
        goto cleanup;
699

700
    if (!seclabel->model &&
701
        VIR_STRDUP(seclabel->model, SECURITY_SELINUX_NAME) < 0)
702
        goto cleanup;
D
Daniel P. Berrange 已提交
703

704
    rc = 0;
705

706
 cleanup:
707
    if (rc != 0) {
708 709 710 711 712 713
        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);
714 715 716 717
    }

    if (ctx)
        context_free(ctx);
D
Daniel P. Berrange 已提交
718
    VIR_FREE(scontext);
719
    VIR_FREE(mcs);
720
    VIR_FREE(sens);
721 722

    VIR_DEBUG("model=%s label=%s imagelabel=%s baselabel=%s",
723 724 725 726
              NULLSTR(seclabel->model),
              NULLSTR(seclabel->label),
              NULLSTR(seclabel->imagelabel),
              NULLSTR(seclabel->baselabel));
727

728 729 730
    return rc;
}

731
static int
732
virSecuritySELinuxReserveSecurityLabel(virSecurityManagerPtr mgr,
733 734
                                       virDomainDefPtr def,
                                       pid_t pid)
735 736 737 738
{
    security_context_t pctx;
    context_t ctx = NULL;
    const char *mcs;
739
    int rv;
740
    virSecurityLabelDefPtr seclabel;
741

742
    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
743 744 745
    if (!seclabel ||
        seclabel->type == VIR_DOMAIN_SECLABEL_NONE ||
        seclabel->type == VIR_DOMAIN_SECLABEL_STATIC)
746 747
        return 0;

M
Martin Kletzander 已提交
748
    if (getpidcon_raw(pid, &pctx) == -1) {
749
        virReportSystemError(errno,
750
                             _("unable to get PID %d security context"), pid);
751 752 753 754
        return -1;
    }

    ctx = context_new(pctx);
755
    freecon(pctx);
756
    if (!ctx)
757
        goto error;
758 759 760

    mcs = context_range_get(ctx);
    if (!mcs)
761 762
        goto error;

763
    if ((rv = virSecuritySELinuxMCSAdd(mgr, mcs)) < 0)
764
        goto error;
765

766 767 768 769 770 771
    if (rv == 1) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("MCS level for existing domain label %s already reserved"),
                       (char*)pctx);
        goto error;
    }
772 773 774 775 776

    context_free(ctx);

    return 0;

777
 error:
778 779 780 781 782
    context_free(ctx);
    return -1;
}


783
static int
784
virSecuritySELinuxSecurityDriverProbe(const char *virtDriver)
785
{
786
    if (is_selinux_enabled() <= 0)
787 788
        return SECURITY_DRIVER_DISABLE;

789 790 791 792 793 794
    if (virtDriver && STREQ(virtDriver, "LXC")) {
#if HAVE_SELINUX_LXC_CONTEXTS_PATH
        if (!virFileExists(selinux_lxc_contexts_path()))
#endif
            return SECURITY_DRIVER_DISABLE;
    }
795 796

    return SECURITY_DRIVER_ENABLE;
797 798
}

799

800
static int
801
virSecuritySELinuxSecurityDriverOpen(virSecurityManagerPtr mgr)
802
{
803
    return virSecuritySELinuxInitialize(mgr);
804 805
}

806

807
static int
808
virSecuritySELinuxSecurityDriverClose(virSecurityManagerPtr mgr)
809
{
810 811 812 813 814
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);

    if (!data)
        return 0;

815
#if HAVE_SELINUX_LABEL_H
816 817
    if (data->label_handle)
        selabel_close(data->label_handle);
818 819
#endif

820 821
    virHashFree(data->mcs);

822
    VIR_FREE(data->domain_context);
823
    VIR_FREE(data->alt_domain_context);
824 825 826
    VIR_FREE(data->file_context);
    VIR_FREE(data->content_context);

827 828 829 830
    return 0;
}


831 832
static const char *
virSecuritySELinuxSecurityGetModel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED)
833 834 835 836
{
    return SECURITY_SELINUX_NAME;
}

837 838
static const char *
virSecuritySELinuxSecurityGetDOI(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED)
839 840 841 842 843
{
    /*
     * Where will the DOI come from?  SELinux configuration, or qemu
     * configuration? For the moment, we'll just set it to "0".
     */
844
    return SECURITY_SELINUX_VOID_DOI;
845 846 847
}

static int
848 849 850 851
virSecuritySELinuxGetSecurityProcessLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                          virDomainDefPtr def ATTRIBUTE_UNUSED,
                                          pid_t pid,
                                          virSecurityLabelPtr sec)
852 853 854
{
    security_context_t ctx;

M
Martin Kletzander 已提交
855
    if (getpidcon_raw(pid, &ctx) == -1) {
856
        virReportSystemError(errno,
857
                             _("unable to get PID %d security context"),
858
                             pid);
859 860 861 862
        return -1;
    }

    if (strlen((char *) ctx) >= VIR_SECURITY_LABEL_BUFLEN) {
863 864 865 866
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label exceeds "
                         "maximum length: %d"),
                       VIR_SECURITY_LABEL_BUFLEN - 1);
867
        freecon(ctx);
868 869 870 871
        return -1;
    }

    strcpy(sec->label, (char *) ctx);
872
    freecon(ctx);
873

874
    VIR_DEBUG("label=%s", sec->label);
875 876
    sec->enforcing = security_getenforce();
    if (sec->enforcing == -1) {
877
        virReportSystemError(errno, "%s",
878
                             _("error calling security_getenforce()"));
879 880 881 882 883 884
        return -1;
    }

    return 0;
}

885 886 887
/* 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.  */
888
static int
889 890
virSecuritySELinuxSetFileconHelper(const char *path, char *tcon,
                                   bool optional, bool privileged)
891
{
892
    security_context_t econ;
893

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

M
Martin Kletzander 已提交
896
    if (setfilecon_raw(path, tcon) < 0) {
897 898
        int setfilecon_errno = errno;

M
Martin Kletzander 已提交
899
        if (getfilecon_raw(path, &econ) >= 0) {
900 901 902
            if (STREQ(tcon, econ)) {
                freecon(econ);
                /* It's alright, there's nothing to change anyway. */
903
                return optional ? 1 : 0;
904 905 906
            }
            freecon(econ);
        }
907

908 909 910 911 912
        /* 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 ...
913
         */
914 915
        if (setfilecon_errno != EOPNOTSUPP && setfilecon_errno != ENOTSUP &&
            setfilecon_errno != EROFS) {
916
            virReportSystemError(setfilecon_errno,
917
                                 _("unable to set security context '%s' on '%s'"),
918
                                 tcon, path);
919 920 921 922
            /* 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))
923
                return -1;
924
        } else {
925
            const char *msg;
926
            if (virFileIsSharedFSType(path, VIR_FILE_SHFS_NFS) == 1 &&
927 928 929
                security_get_boolean_active("virt_use_nfs") != 1) {
                msg = _("Setting security context '%s' on '%s' not supported. "
                        "Consider setting virt_use_nfs");
930 931 932 933
                if (security_getenforce() == 1)
                    VIR_WARN(msg, tcon, path);
                else
                    VIR_INFO(msg, tcon, path);
934 935 936 937
            } else {
                VIR_INFO("Setting security context '%s' on '%s' not supported",
                         tcon, path);
            }
938 939
            if (optional)
                return 1;
940
        }
941 942 943 944
    }
    return 0;
}

945
static int
946 947
virSecuritySELinuxSetFileconOptional(virSecurityManagerPtr mgr,
                                     const char *path, char *tcon)
948
{
949 950
    bool privileged = virSecurityManagerGetPrivileged(mgr);
    return virSecuritySELinuxSetFileconHelper(path, tcon, true, privileged);
951 952 953
}

static int
954 955
virSecuritySELinuxSetFilecon(virSecurityManagerPtr mgr,
                             const char *path, char *tcon)
956
{
957 958
    bool privileged = virSecurityManagerGetPrivileged(mgr);
    return virSecuritySELinuxSetFileconHelper(path, tcon, false, privileged);
959 960
}

961
static int
962
virSecuritySELinuxFSetFilecon(int fd, char *tcon)
963 964 965 966 967
{
    security_context_t econ;

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

M
Martin Kletzander 已提交
968
    if (fsetfilecon_raw(fd, tcon) < 0) {
969 970
        int fsetfilecon_errno = errno;

M
Martin Kletzander 已提交
971
        if (fgetfilecon_raw(fd, &econ) >= 0) {
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
            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 已提交
1000 1001
/* Set fcon to the appropriate label for path and mode, or return -1.  */
static int
1002
getContext(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
1003
           const char *newpath, mode_t mode, security_context_t *fcon)
E
Eric Blake 已提交
1004 1005
{
#if HAVE_SELINUX_LABEL_H
1006
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
E
Eric Blake 已提交
1007

1008
    return selabel_lookup_raw(data->label_handle, fcon, newpath, mode);
E
Eric Blake 已提交
1009 1010 1011 1012 1013
#else
    return matchpathcon(newpath, mode, fcon);
#endif
}

1014 1015 1016

/* This method shouldn't raise errors, since they'll overwrite
 * errors that the caller(s) are already dealing with */
1017
static int
1018 1019
virSecuritySELinuxRestoreSecurityFileLabel(virSecurityManagerPtr mgr,
                                           const char *path)
1020
{
1021 1022 1023 1024
    struct stat buf;
    security_context_t fcon = NULL;
    int rc = -1;
    char *newpath = NULL;
1025
    char ebuf[1024];
1026

1027 1028
    VIR_INFO("Restoring SELinux context on '%s'", path);

1029
    if (virFileResolveLink(path, &newpath) < 0) {
1030 1031
        VIR_WARN("cannot resolve symlink %s: %s", path,
                 virStrerror(errno, ebuf, sizeof(ebuf)));
D
Daniel P. Berrange 已提交
1032
        goto err;
1033
    }
1034

1035
    if (stat(newpath, &buf) != 0) {
1036 1037
        VIR_WARN("cannot stat %s: %s", newpath,
                 virStrerror(errno, ebuf, sizeof(ebuf)));
D
Daniel P. Berrange 已提交
1038
        goto err;
1039
    }
D
Daniel P. Berrange 已提交
1040

1041
    if (getContext(mgr, newpath, buf.st_mode, &fcon) < 0) {
1042 1043 1044
        /* Any user created path likely does not have a default label,
         * which makes this an expected non error
         */
1045
        VIR_WARN("cannot lookup default selinux label for %s", newpath);
1046
        rc = 0;
1047
    } else {
1048
        rc = virSecuritySELinuxSetFilecon(mgr, newpath, fcon);
1049
    }
1050

1051
 err:
1052
    freecon(fcon);
1053 1054
    VIR_FREE(newpath);
    return rc;
1055 1056
}

1057

1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
static int
virSecuritySELinuxSetInputLabel(virSecurityManagerPtr mgr,
                                virDomainDefPtr def,
                                virDomainInputDefPtr input)
{
    virSecurityLabelDefPtr seclabel;

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

    switch ((virDomainInputType) input->type) {
    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;

    switch ((virDomainInputType) input->type) {
    case VIR_DOMAIN_INPUT_TYPE_PASSTHROUGH:
        rc = virSecuritySELinuxRestoreSecurityFileLabel(mgr,
                                                        input->source.evdev);
        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;
}


1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
static int
virSecuritySELinuxSetSecurityTPMFileLabel(virSecurityManagerPtr mgr,
                                          virDomainDefPtr def,
                                          virDomainTPMDefPtr tpm)
{
    int rc;
    virSecurityLabelDefPtr seclabel;
    char *cancel_path;
    const char *tpmdev;

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

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

        if ((cancel_path = virTPMCreateCancelPath(tpmdev)) != NULL) {
1138 1139
            rc = virSecuritySELinuxSetFilecon(mgr,
                                              cancel_path,
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
                                              seclabel->imagelabel);
            VIR_FREE(cancel_path);
            if (rc < 0) {
                virSecuritySELinuxRestoreSecurityTPMFileLabelInt(mgr, def,
                                                                 tpm);
                return -1;
            }
        } else {
            return -1;
        }
        break;
    case VIR_DOMAIN_TPM_TYPE_LAST:
        break;
    }

    return 0;
}


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

    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (seclabel == NULL)
1171
        return 0;
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192

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

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

    return rc;
}


1193
static int
1194
virSecuritySELinuxRestoreSecurityImageLabelInt(virSecurityManagerPtr mgr,
1195
                                               virDomainDefPtr def,
1196
                                               virStorageSourcePtr src,
1197
                                               bool migrated)
1198
{
1199 1200
    virSecurityLabelDefPtr seclabel;
    virSecurityDeviceLabelDefPtr disk_seclabel;
1201 1202 1203

    if (!src->path || !virStorageSourceIsLocalStorage(src))
        return 0;
1204 1205 1206

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

1209
    disk_seclabel = virStorageSourceGetSecurityLabelDef(src,
1210
                                                        SECURITY_SELINUX_NAME);
1211
    if (!seclabel->relabel || (disk_seclabel && !disk_seclabel->relabel))
1212 1213
        return 0;

1214 1215 1216
    /* 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
1217
     * per-file attribute instead of a disk attribute. */
1218
    if (disk_seclabel && disk_seclabel->labelskip &&
1219
        !src->backingStore)
1220 1221
        return 0;

1222
    /* Don't restore labels on readonly/shared disks, because other VMs may
1223 1224 1225 1226 1227
     * 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)
1228 1229 1230
        return 0;


1231 1232 1233
    /* 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 :-) */
1234
    if (migrated) {
1235
        int rc = virFileIsSharedFS(src->path);
1236 1237 1238 1239
        if (rc < 0)
            return -1;
        if (rc == 1) {
            VIR_DEBUG("Skipping image label restore on %s because FS is shared",
1240
                      src->path);
1241 1242 1243 1244
            return 0;
        }
    }

1245
    return virSecuritySELinuxRestoreSecurityFileLabel(mgr, src->path);
1246 1247
}

1248 1249

static int
1250 1251 1252
virSecuritySELinuxRestoreSecurityDiskLabel(virSecurityManagerPtr mgr,
                                           virDomainDefPtr def,
                                           virDomainDiskDefPtr disk)
1253
{
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
    return virSecuritySELinuxRestoreSecurityImageLabelInt(mgr, def, disk->src,
                                                          false);
}


static int
virSecuritySELinuxRestoreSecurityImageLabel(virSecurityManagerPtr mgr,
                                            virDomainDefPtr def,
                                            virStorageSourcePtr src)
{
    return virSecuritySELinuxRestoreSecurityImageLabelInt(mgr, def, src, false);
1265 1266 1267
}


1268
static int
1269 1270 1271 1272
virSecuritySELinuxSetSecurityImageLabelInternal(virSecurityManagerPtr mgr,
                                                virDomainDefPtr def,
                                                virStorageSourcePtr src,
                                                bool first)
1273
{
1274 1275
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
    virSecurityLabelDefPtr secdef;
1276
    virSecurityDeviceLabelDefPtr disk_seclabel;
1277
    int ret;
1278

1279 1280 1281 1282
    if (!src->path || !virStorageSourceIsLocalStorage(src))
        return 0;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
1283
    if (!secdef || !secdef->relabel)
1284 1285 1286
        return 0;

    disk_seclabel = virStorageSourceGetSecurityLabelDef(src,
1287 1288
                                                        SECURITY_SELINUX_NAME);

1289
    if (disk_seclabel && !disk_seclabel->relabel)
1290 1291
        return 0;

1292
    if (disk_seclabel && disk_seclabel->relabel && disk_seclabel->label) {
1293
        ret = virSecuritySELinuxSetFilecon(mgr, src->path, disk_seclabel->label);
1294 1295
    } else if (first) {
        if (src->shared) {
1296 1297
            ret = virSecuritySELinuxSetFileconOptional(mgr,
                                                       src->path,
1298 1299
                                                       data->file_context);
        } else if (src->readonly) {
1300 1301
            ret = virSecuritySELinuxSetFileconOptional(mgr,
                                                       src->path,
1302
                                                       data->content_context);
1303
        } else if (secdef->imagelabel) {
1304 1305
            ret = virSecuritySELinuxSetFileconOptional(mgr,
                                                       src->path,
1306
                                                       secdef->imagelabel);
1307
        } else {
1308
            ret = 0;
1309 1310
        }
    } else {
1311 1312
        ret = virSecuritySELinuxSetFileconOptional(mgr,
                                                   src->path,
1313
                                                   data->content_context);
1314
    }
1315

1316
    if (ret == 1 && !disk_seclabel) {
1317 1318
        /* If we failed to set a label, but virt_use_nfs let us
         * proceed anyway, then we don't need to relabel later.  */
1319
        disk_seclabel = virSecurityDeviceLabelDefNew(SECURITY_SELINUX_NAME);
1320
        if (!disk_seclabel)
1321
            return -1;
1322
        disk_seclabel->labelskip = true;
1323
        if (VIR_APPEND_ELEMENT(src->seclabels, src->nseclabels,
1324
                               disk_seclabel) < 0) {
1325 1326 1327
            virSecurityDeviceLabelDefFree(disk_seclabel);
            return -1;
        }
1328
        ret = 0;
1329
    }
1330

1331
    return ret;
1332 1333
}

1334 1335 1336 1337 1338 1339 1340 1341 1342 1343

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


1344
static int
1345 1346 1347
virSecuritySELinuxSetSecurityDiskLabel(virSecurityManagerPtr mgr,
                                       virDomainDefPtr def,
                                       virDomainDiskDefPtr disk)
1348 1349

{
1350 1351
    bool first = true;
    virStorageSourcePtr next;
1352

1353 1354 1355 1356
    for (next = disk->src; next; next = next->backingStore) {
        if (virSecuritySELinuxSetSecurityImageLabelInternal(mgr, def, next,
                                                            first) < 0)
            return -1;
1357

1358 1359 1360 1361
        first = false;
    }

    return 0;
1362 1363
}

1364
static int
1365
virSecuritySELinuxSetSecurityHostdevLabelHelper(const char *file, void *opaque)
1366
{
1367
    virSecurityLabelDefPtr secdef;
1368 1369 1370
    virSecuritySELinuxCallbackDataPtr data = opaque;
    virSecurityManagerPtr mgr = data->mgr;
    virDomainDefPtr def = data->def;
1371

1372 1373
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
1374
        return 0;
1375
    return virSecuritySELinuxSetFilecon(mgr, file, secdef->imagelabel);
1376 1377 1378
}

static int
1379
virSecuritySELinuxSetSecurityPCILabel(virPCIDevicePtr dev ATTRIBUTE_UNUSED,
1380
                                      const char *file, void *opaque)
1381
{
1382 1383
    return virSecuritySELinuxSetSecurityHostdevLabelHelper(file, opaque);
}
1384

1385 1386 1387 1388 1389
static int
virSecuritySELinuxSetSecurityUSBLabel(virUSBDevicePtr dev ATTRIBUTE_UNUSED,
                                      const char *file, void *opaque)
{
    return virSecuritySELinuxSetSecurityHostdevLabelHelper(file, opaque);
1390 1391
}

1392
static int
1393
virSecuritySELinuxSetSecuritySCSILabel(virSCSIDevicePtr dev,
1394 1395
                                       const char *file, void *opaque)
{
1396
    virSecurityLabelDefPtr secdef;
1397
    virSecuritySELinuxCallbackDataPtr ptr = opaque;
1398 1399 1400 1401 1402 1403 1404 1405
    virSecurityManagerPtr mgr = ptr->mgr;
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);

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

    if (virSCSIDeviceGetShareable(dev))
1406
        return virSecuritySELinuxSetFileconOptional(mgr, file,
1407 1408
                                                    data->file_context);
    else if (virSCSIDeviceGetReadonly(dev))
1409
        return virSecuritySELinuxSetFileconOptional(mgr, file,
1410 1411
                                                    data->content_context);
    else
1412 1413
        return virSecuritySELinuxSetFileconOptional(mgr, file,
                                                    secdef->imagelabel);
1414
}
1415

1416
static int
1417 1418
virSecuritySELinuxSetSecurityHostdevSubsysLabel(virSecurityManagerPtr mgr,
                                                virDomainDefPtr def,
1419 1420
                                                virDomainHostdevDefPtr dev,
                                                const char *vroot)
1421 1422

{
1423
    virDomainHostdevSubsysUSBPtr usbsrc = &dev->source.subsys.u.usb;
1424
    virDomainHostdevSubsysPCIPtr pcisrc = &dev->source.subsys.u.pci;
1425
    virDomainHostdevSubsysSCSIPtr scsisrc = &dev->source.subsys.u.scsi;
1426 1427
    virSecuritySELinuxCallbackData data = {.mgr = mgr, .def = def};

1428 1429
    int ret = -1;

1430 1431 1432
    /* Like virSecuritySELinuxSetSecurityImageLabelInternal() for a networked
     * disk, do nothing for an iSCSI hostdev
     */
1433 1434
    if (dev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI &&
        scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI)
1435 1436
        return 0;

1437 1438
    switch (dev->source.subsys.type) {
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB: {
1439
        virUSBDevicePtr usb;
1440

1441 1442 1443
        if (dev->missing)
            return 0;

1444 1445
        usb = virUSBDeviceNew(usbsrc->bus,
                              usbsrc->device,
1446
                              vroot);
1447 1448
        if (!usb)
            goto done;
1449

1450
        ret = virUSBDeviceFileIterate(usb, virSecuritySELinuxSetSecurityUSBLabel, &data);
1451
        virUSBDeviceFree(usb);
M
Mark McLoughlin 已提交
1452
        break;
1453 1454 1455
    }

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI: {
1456
        virPCIDevicePtr pci =
1457 1458
            virPCIDeviceNew(pcisrc->addr.domain, pcisrc->addr.bus,
                            pcisrc->addr.slot, pcisrc->addr.function);
1459 1460 1461 1462

        if (!pci)
            goto done;

1463
        if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
1464
            char *vfioGroupDev = virPCIDeviceGetIOMMUGroupDev(pci);
1465

1466 1467
            if (!vfioGroupDev) {
                virPCIDeviceFree(pci);
1468
                goto done;
1469
            }
1470
            ret = virSecuritySELinuxSetSecurityPCILabel(pci, vfioGroupDev, &data);
1471 1472
            VIR_FREE(vfioGroupDev);
        } else {
1473
            ret = virPCIDeviceFileIterate(pci, virSecuritySELinuxSetSecurityPCILabel, &data);
1474
        }
1475
        virPCIDeviceFree(pci);
1476 1477 1478
        break;
    }

1479
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI: {
1480
        virDomainHostdevSubsysSCSIHostPtr scsihostsrc = &scsisrc->u.host;
1481

1482
        virSCSIDevicePtr scsi =
1483
            virSCSIDeviceNew(NULL,
1484 1485
                             scsihostsrc->adapter, scsihostsrc->bus,
                             scsihostsrc->target, scsihostsrc->unit,
1486
                             dev->readonly, dev->shareable);
1487 1488 1489 1490

        if (!scsi)
            goto done;

1491 1492 1493
        ret = virSCSIDeviceFileIterate(scsi,
                                       virSecuritySELinuxSetSecuritySCSILabel,
                                       &data);
1494 1495 1496 1497 1498
        virSCSIDeviceFree(scsi);

        break;
    }

1499 1500 1501 1502 1503
    default:
        ret = 0;
        break;
    }

1504
 done:
1505 1506 1507
    return ret;
}

1508

1509
static int
1510 1511
virSecuritySELinuxSetSecurityHostdevCapsLabel(virSecurityManagerPtr mgr,
                                              virDomainDefPtr def,
1512 1513 1514 1515 1516 1517 1518 1519 1520
                                              virDomainHostdevDefPtr dev,
                                              const char *vroot)
{
    int ret = -1;
    virSecurityLabelDefPtr secdef;
    char *path;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
1521
        return 0;
1522 1523 1524 1525 1526

    switch (dev->source.caps.type) {
    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_STORAGE: {
        if (vroot) {
            if (virAsprintf(&path, "%s/%s", vroot,
1527
                            dev->source.caps.u.storage.block) < 0)
1528 1529
                return -1;
        } else {
1530
            if (VIR_STRDUP(path, dev->source.caps.u.storage.block) < 0)
1531 1532
                return -1;
        }
1533
        ret = virSecuritySELinuxSetFilecon(mgr, path, secdef->imagelabel);
1534 1535 1536 1537 1538 1539 1540
        VIR_FREE(path);
        break;
    }

    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_MISC: {
        if (vroot) {
            if (virAsprintf(&path, "%s/%s", vroot,
1541
                            dev->source.caps.u.misc.chardev) < 0)
1542 1543
                return -1;
        } else {
1544
            if (VIR_STRDUP(path, dev->source.caps.u.misc.chardev) < 0)
1545 1546
                return -1;
        }
1547
        ret = virSecuritySELinuxSetFilecon(mgr, path, secdef->imagelabel);
1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
        VIR_FREE(path);
        break;
    }

    default:
        ret = 0;
        break;
    }

    return ret;
}


1561
static int
1562
virSecuritySELinuxSetSecurityHostdevLabel(virSecurityManagerPtr mgr,
1563 1564 1565 1566 1567 1568 1569 1570
                                          virDomainDefPtr def,
                                          virDomainHostdevDefPtr dev,
                                          const char *vroot)

{
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
1571
    if (!secdef || !secdef->relabel)
1572 1573 1574 1575
        return 0;

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

1579
    case VIR_DOMAIN_HOSTDEV_MODE_CAPABILITIES:
1580 1581
        return virSecuritySELinuxSetSecurityHostdevCapsLabel(mgr, def,
                                                             dev, vroot);
1582

1583 1584 1585 1586 1587
    default:
        return 0;
    }
}

1588
static int
1589
virSecuritySELinuxRestoreSecurityPCILabel(virPCIDevicePtr dev ATTRIBUTE_UNUSED,
1590
                                          const char *file,
1591
                                          void *opaque)
1592
{
1593 1594 1595
    virSecurityManagerPtr mgr = opaque;

    return virSecuritySELinuxRestoreSecurityFileLabel(mgr, file);
1596 1597 1598
}

static int
1599
virSecuritySELinuxRestoreSecurityUSBLabel(virUSBDevicePtr dev ATTRIBUTE_UNUSED,
1600
                                          const char *file,
1601
                                          void *opaque)
1602
{
1603 1604 1605
    virSecurityManagerPtr mgr = opaque;

    return virSecuritySELinuxRestoreSecurityFileLabel(mgr, file);
1606 1607
}

1608

1609
static int
1610
virSecuritySELinuxRestoreSecuritySCSILabel(virSCSIDevicePtr dev,
1611 1612 1613 1614 1615
                                           const char *file,
                                           void *opaque)
{
    virSecurityManagerPtr mgr = opaque;

1616 1617 1618 1619 1620 1621
    /* Don't restore labels on a shareable or readonly hostdev, because
     * other VMs may still be accessing.
     */
    if (virSCSIDeviceGetShareable(dev) || virSCSIDeviceGetReadonly(dev))
        return 0;

1622 1623 1624
    return virSecuritySELinuxRestoreSecurityFileLabel(mgr, file);
}

1625
static int
1626 1627
virSecuritySELinuxRestoreSecurityHostdevSubsysLabel(virSecurityManagerPtr mgr,
                                                    virDomainHostdevDefPtr dev,
1628
                                                    const char *vroot)
1629 1630

{
1631
    virDomainHostdevSubsysUSBPtr usbsrc = &dev->source.subsys.u.usb;
1632
    virDomainHostdevSubsysPCIPtr pcisrc = &dev->source.subsys.u.pci;
1633
    virDomainHostdevSubsysSCSIPtr scsisrc = &dev->source.subsys.u.scsi;
1634 1635
    int ret = -1;

1636 1637 1638
    /* Like virSecuritySELinuxRestoreSecurityImageLabelInt() for a networked
     * disk, do nothing for an iSCSI hostdev
     */
1639 1640
    if (dev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI &&
        scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI)
1641 1642
        return 0;

1643 1644
    switch (dev->source.subsys.type) {
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB: {
1645
        virUSBDevicePtr usb;
1646 1647 1648

        if (dev->missing)
            return 0;
1649

1650 1651
        usb = virUSBDeviceNew(usbsrc->bus,
                              usbsrc->device,
1652
                              vroot);
1653 1654 1655
        if (!usb)
            goto done;

1656 1657
        ret = virUSBDeviceFileIterate(usb, virSecuritySELinuxRestoreSecurityUSBLabel, mgr);
        virUSBDeviceFree(usb);
1658 1659 1660 1661 1662

        break;
    }

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI: {
1663
        virPCIDevicePtr pci =
1664 1665
            virPCIDeviceNew(pcisrc->addr.domain, pcisrc->addr.bus,
                            pcisrc->addr.slot, pcisrc->addr.function);
1666 1667 1668 1669

        if (!pci)
            goto done;

1670
        if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
1671
            char *vfioGroupDev = virPCIDeviceGetIOMMUGroupDev(pci);
1672

1673 1674
            if (!vfioGroupDev) {
                virPCIDeviceFree(pci);
1675
                goto done;
1676
            }
1677 1678 1679 1680 1681
            ret = virSecuritySELinuxRestoreSecurityPCILabel(pci, vfioGroupDev, mgr);
            VIR_FREE(vfioGroupDev);
        } else {
            ret = virPCIDeviceFileIterate(pci, virSecuritySELinuxRestoreSecurityPCILabel, mgr);
        }
1682
        virPCIDeviceFree(pci);
1683 1684 1685
        break;
    }

1686
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI: {
1687
        virDomainHostdevSubsysSCSIHostPtr scsihostsrc = &scsisrc->u.host;
1688
        virSCSIDevicePtr scsi =
1689
            virSCSIDeviceNew(NULL,
1690 1691
                             scsihostsrc->adapter, scsihostsrc->bus,
                             scsihostsrc->target, scsihostsrc->unit,
1692
                             dev->readonly, dev->shareable);
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702

            if (!scsi)
                goto done;

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

            break;
       }

1703 1704 1705 1706 1707
    default:
        ret = 0;
        break;
    }

1708
 done:
1709 1710 1711
    return ret;
}

1712

1713
static int
1714 1715
virSecuritySELinuxRestoreSecurityHostdevCapsLabel(virSecurityManagerPtr mgr,
                                                  virDomainHostdevDefPtr dev,
1716 1717 1718 1719 1720 1721 1722 1723 1724
                                                  const char *vroot)
{
    int ret = -1;
    char *path;

    switch (dev->source.caps.type) {
    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_STORAGE: {
        if (vroot) {
            if (virAsprintf(&path, "%s/%s", vroot,
1725
                            dev->source.caps.u.storage.block) < 0)
1726 1727
                return -1;
        } else {
1728
            if (VIR_STRDUP(path, dev->source.caps.u.storage.block) < 0)
1729 1730
                return -1;
        }
1731
        ret = virSecuritySELinuxRestoreSecurityFileLabel(mgr, path);
1732 1733 1734 1735 1736 1737 1738
        VIR_FREE(path);
        break;
    }

    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_MISC: {
        if (vroot) {
            if (virAsprintf(&path, "%s/%s", vroot,
1739
                            dev->source.caps.u.misc.chardev) < 0)
1740 1741
                return -1;
        } else {
1742
            if (VIR_STRDUP(path, dev->source.caps.u.misc.chardev) < 0)
1743 1744
                return -1;
        }
1745
        ret = virSecuritySELinuxRestoreSecurityFileLabel(mgr, path);
1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
        VIR_FREE(path);
        break;
    }

    default:
        ret = 0;
        break;
    }

    return ret;
}


1759
static int
1760
virSecuritySELinuxRestoreSecurityHostdevLabel(virSecurityManagerPtr mgr,
1761 1762 1763 1764 1765 1766 1767 1768
                                              virDomainDefPtr def,
                                              virDomainHostdevDefPtr dev,
                                              const char *vroot)

{
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
1769
    if (!secdef || !secdef->relabel)
1770 1771 1772 1773
        return 0;

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

1776
    case VIR_DOMAIN_HOSTDEV_MODE_CAPABILITIES:
1777
        return virSecuritySELinuxRestoreSecurityHostdevCapsLabel(mgr, dev, vroot);
1778

1779 1780 1781 1782 1783 1784
    default:
        return 0;
    }
}


1785
static int
1786 1787
virSecuritySELinuxSetSecurityChardevLabel(virSecurityManagerPtr mgr,
                                          virDomainDefPtr def,
1788 1789
                                          virDomainChrDefPtr dev,
                                          virDomainChrSourceDefPtr dev_source)
1790 1791

{
1792 1793 1794
    virSecurityLabelDefPtr seclabel;
    virSecurityDeviceLabelDefPtr chr_seclabel = NULL;
    char *imagelabel = NULL;
1795 1796 1797
    char *in = NULL, *out = NULL;
    int ret = -1;

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

1802 1803 1804 1805
    if (dev)
        chr_seclabel = virDomainChrDefGetSecurityLabelDef(dev,
                                                          SECURITY_SELINUX_NAME);

1806
    if (chr_seclabel && !chr_seclabel->relabel)
1807 1808
        return 0;

1809 1810 1811 1812 1813 1814
    if (chr_seclabel)
        imagelabel = chr_seclabel->label;
    if (!imagelabel)
        imagelabel = seclabel->imagelabel;

    switch (dev_source->type) {
1815 1816
    case VIR_DOMAIN_CHR_TYPE_DEV:
    case VIR_DOMAIN_CHR_TYPE_FILE:
1817 1818
        ret = virSecuritySELinuxSetFilecon(mgr,
                                           dev_source->data.file.path,
1819 1820 1821 1822 1823
                                           imagelabel);
        break;

    case VIR_DOMAIN_CHR_TYPE_UNIX:
        if (!dev_source->data.nix.listen) {
1824 1825
            if (virSecuritySELinuxSetFilecon(mgr,
                                             dev_source->data.nix.path,
1826 1827 1828 1829
                                             imagelabel) < 0)
                goto done;
        }
        ret = 0;
1830 1831 1832
        break;

    case VIR_DOMAIN_CHR_TYPE_PIPE:
1833
        if ((virAsprintf(&in, "%s.in", dev_source->data.file.path) < 0) ||
1834
            (virAsprintf(&out, "%s.out", dev_source->data.file.path) < 0))
1835 1836
            goto done;
        if (virFileExists(in) && virFileExists(out)) {
1837 1838
            if ((virSecuritySELinuxSetFilecon(mgr, in, imagelabel) < 0) ||
                (virSecuritySELinuxSetFilecon(mgr, out, imagelabel) < 0)) {
1839
                goto done;
1840
            }
1841 1842
        } else if (virSecuritySELinuxSetFilecon(mgr,
                                                dev_source->data.file.path,
1843
                                                imagelabel) < 0) {
1844
            goto done;
1845 1846 1847 1848 1849 1850 1851 1852 1853
        }
        ret = 0;
        break;

    default:
        ret = 0;
        break;
    }

1854
 done:
1855 1856 1857 1858 1859 1860
    VIR_FREE(in);
    VIR_FREE(out);
    return ret;
}

static int
1861 1862
virSecuritySELinuxRestoreSecurityChardevLabel(virSecurityManagerPtr mgr,
                                              virDomainDefPtr def,
1863 1864
                                              virDomainChrDefPtr dev,
                                              virDomainChrSourceDefPtr dev_source)
1865 1866

{
1867 1868
    virSecurityLabelDefPtr seclabel;
    virSecurityDeviceLabelDefPtr chr_seclabel = NULL;
1869 1870 1871
    char *in = NULL, *out = NULL;
    int ret = -1;

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

1876 1877 1878
    if (dev)
        chr_seclabel = virDomainChrDefGetSecurityLabelDef(dev,
                                                          SECURITY_SELINUX_NAME);
1879
    if (chr_seclabel && !chr_seclabel->relabel)
1880 1881
        return 0;

1882
    switch (dev_source->type) {
1883 1884
    case VIR_DOMAIN_CHR_TYPE_DEV:
    case VIR_DOMAIN_CHR_TYPE_FILE:
1885
        if (virSecuritySELinuxRestoreSecurityFileLabel(mgr, dev_source->data.file.path) < 0)
1886 1887
            goto done;
        ret = 0;
1888
        break;
1889 1890 1891

    case VIR_DOMAIN_CHR_TYPE_UNIX:
        if (!dev_source->data.nix.listen) {
1892
            if (virSecuritySELinuxRestoreSecurityFileLabel(mgr, dev_source->data.file.path) < 0)
1893 1894 1895 1896 1897
                goto done;
        }
        ret = 0;
        break;

1898
    case VIR_DOMAIN_CHR_TYPE_PIPE:
1899
        if ((virAsprintf(&out, "%s.out", dev_source->data.file.path) < 0) ||
1900
            (virAsprintf(&in, "%s.in", dev_source->data.file.path) < 0))
1901
            goto done;
1902
        if (virFileExists(in) && virFileExists(out)) {
1903 1904
            if ((virSecuritySELinuxRestoreSecurityFileLabel(mgr, out) < 0) ||
                (virSecuritySELinuxRestoreSecurityFileLabel(mgr, in) < 0)) {
1905 1906
                goto done;
            }
1907
        } else if (virSecuritySELinuxRestoreSecurityFileLabel(mgr, dev_source->data.file.path) < 0) {
1908
            goto done;
1909
        }
1910 1911 1912 1913 1914 1915 1916 1917
        ret = 0;
        break;

    default:
        ret = 0;
        break;
    }

1918
 done:
1919 1920 1921 1922 1923 1924 1925
    VIR_FREE(in);
    VIR_FREE(out);
    return ret;
}


static int
1926 1927
virSecuritySELinuxRestoreSecurityChardevCallback(virDomainDefPtr def,
                                                 virDomainChrDefPtr dev,
1928
                                                 void *opaque)
1929
{
1930 1931
    virSecurityManagerPtr mgr = opaque;

1932 1933 1934 1935 1936
    /* This is taken care of by processing of def->serials */
    if (dev->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE &&
        dev->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL)
        return 0;

1937
    return virSecuritySELinuxRestoreSecurityChardevLabel(mgr, def, dev,
1938
                                                         &dev->source);
1939 1940 1941
}


E
Eric Blake 已提交
1942
static int
1943 1944
virSecuritySELinuxRestoreSecuritySmartcardCallback(virDomainDefPtr def,
                                                   virDomainSmartcardDefPtr dev,
1945
                                                   void *opaque)
E
Eric Blake 已提交
1946
{
1947
    virSecurityManagerPtr mgr = opaque;
E
Eric Blake 已提交
1948 1949 1950 1951 1952 1953 1954 1955 1956 1957
    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;
1958
        return virSecuritySELinuxRestoreSecurityFileLabel(mgr, database);
E
Eric Blake 已提交
1959 1960

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

    default:
1964 1965 1966
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown smartcard type %d"),
                       dev->type);
E
Eric Blake 已提交
1967 1968 1969 1970 1971 1972 1973
        return -1;
    }

    return 0;
}


1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984
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;
}


1985
static int
1986
virSecuritySELinuxRestoreSecurityAllLabel(virSecurityManagerPtr mgr,
1987
                                          virDomainDefPtr def,
1988
                                          bool migrated)
1989
{
1990
    virSecurityLabelDefPtr secdef;
1991
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
1992
    size_t i;
1993
    int rc = 0;
1994

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

1997 1998
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);

1999
    if (!secdef || !secdef->relabel || data->skipAllLabel)
2000 2001
        return 0;

2002 2003 2004 2005 2006 2007
    if (def->tpm) {
        if (virSecuritySELinuxRestoreSecurityTPMFileLabelInt(mgr, def,
                                                             def->tpm) < 0)
            rc = -1;
    }

2008
    for (i = 0; i < def->nhostdevs; i++) {
2009 2010
        if (virSecuritySELinuxRestoreSecurityHostdevLabel(mgr,
                                                          def,
2011 2012
                                                          def->hostdevs[i],
                                                          NULL) < 0)
2013
            rc = -1;
2014
    }
2015 2016 2017 2018 2019 2020

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

2021
    for (i = 0; i < def->ndisks; i++) {
2022 2023 2024
        virDomainDiskDefPtr disk = def->disks[i];

        if (virSecuritySELinuxRestoreSecurityImageLabelInt(mgr, def, disk->src,
2025
                                                           migrated) < 0)
2026 2027
            rc = -1;
    }
2028

2029
    if (virDomainChrDefForeach(def,
2030
                               false,
2031
                               virSecuritySELinuxRestoreSecurityChardevCallback,
2032
                               mgr) < 0)
2033 2034
        rc = -1;

2035
    if (virDomainSmartcardDefForeach(def,
E
Eric Blake 已提交
2036
                                     false,
2037
                                     virSecuritySELinuxRestoreSecuritySmartcardCallback,
2038
                                     mgr) < 0)
E
Eric Blake 已提交
2039 2040
        rc = -1;

2041 2042 2043 2044
    if (def->os.loader && def->os.loader->nvram &&
        virSecuritySELinuxRestoreSecurityFileLabel(mgr, def->os.loader->nvram) < 0)
        rc = -1;

2045
    if (def->os.kernel &&
2046
        virSecuritySELinuxRestoreSecurityFileLabel(mgr, def->os.kernel) < 0)
2047 2048
        rc = -1;

2049
    if (def->os.initrd &&
2050
        virSecuritySELinuxRestoreSecurityFileLabel(mgr, def->os.initrd) < 0)
2051 2052
        rc = -1;

O
Olivia Yin 已提交
2053 2054 2055 2056
    if (def->os.dtb &&
        virSecuritySELinuxRestoreSecurityFileLabel(mgr, def->os.dtb) < 0)
        rc = -1;

2057 2058 2059 2060
    return rc;
}

static int
2061
virSecuritySELinuxReleaseSecurityLabel(virSecurityManagerPtr mgr,
2062
                                       virDomainDefPtr def)
2063
{
2064 2065 2066 2067
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
2068
        return 0;
2069

2070 2071 2072 2073
    if (secdef->type == VIR_DOMAIN_SECLABEL_DYNAMIC) {
        if (secdef->label != NULL) {
            context_t con = context_new(secdef->label);
            if (con) {
2074
                virSecuritySELinuxMCSRemove(mgr, context_range_get(con));
2075 2076 2077 2078 2079 2080
                context_free(con);
            }
        }
        VIR_FREE(secdef->label);
        if (!secdef->baselabel)
            VIR_FREE(secdef->model);
2081 2082 2083
    }
    VIR_FREE(secdef->imagelabel);

2084
    return 0;
2085 2086
}

2087 2088

static int
2089
virSecuritySELinuxSetSavedStateLabel(virSecurityManagerPtr mgr,
2090 2091
                                     virDomainDefPtr def,
                                     const char *savefile)
2092
{
2093 2094 2095
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2096
    if (!secdef || !secdef->relabel)
2097 2098
        return 0;

2099
    return virSecuritySELinuxSetFilecon(mgr, savefile, secdef->imagelabel);
2100 2101 2102 2103
}


static int
2104
virSecuritySELinuxRestoreSavedStateLabel(virSecurityManagerPtr mgr,
2105 2106
                                         virDomainDefPtr def,
                                         const char *savefile)
2107
{
2108 2109 2110
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2111
    if (!secdef || !secdef->relabel)
2112 2113
        return 0;

2114
    return virSecuritySELinuxRestoreSecurityFileLabel(mgr, savefile);
2115 2116 2117
}


2118
static int
2119 2120
virSecuritySELinuxSecurityVerify(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                 virDomainDefPtr def)
2121
{
2122 2123 2124 2125
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
2126
        return 0;
2127

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

2137 2138
    if (secdef->type == VIR_DOMAIN_SECLABEL_STATIC) {
        if (security_check_context(secdef->label) != 0) {
2139 2140
            virReportError(VIR_ERR_XML_ERROR,
                           _("Invalid security label %s"), secdef->label);
2141 2142 2143 2144 2145 2146
            return -1;
        }
    }
    return 0;
}

2147
static int
2148
virSecuritySELinuxSetSecurityProcessLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
2149
                                          virDomainDefPtr def)
2150 2151
{
    /* TODO: verify DOI */
2152 2153 2154
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2155
    if (!secdef || !secdef->label)
2156 2157
        return 0;

2158
    VIR_DEBUG("label=%s", secdef->label);
2159
    if (STRNEQ(SECURITY_SELINUX_NAME, secdef->model)) {
2160 2161 2162 2163
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "'%s' model configured for domain, but "
                         "hypervisor driver is '%s'."),
2164
                       secdef->model, SECURITY_SELINUX_NAME);
2165
        if (security_getenforce() == 1)
2166
            return -1;
2167 2168
    }

M
Martin Kletzander 已提交
2169
    if (setexeccon_raw(secdef->label) == -1) {
2170
        virReportSystemError(errno,
2171 2172
                             _("unable to set security context '%s'"),
                             secdef->label);
2173
        if (security_getenforce() == 1)
2174
            return -1;
2175 2176
    }

2177 2178 2179
    return 0;
}

2180 2181 2182 2183 2184 2185 2186 2187 2188
static int
virSecuritySELinuxSetSecurityChildProcessLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                               virDomainDefPtr def,
                                               virCommandPtr cmd)
{
    /* TODO: verify DOI */
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2189
    if (!secdef || !secdef->label)
2190 2191 2192
        return 0;

    VIR_DEBUG("label=%s", secdef->label);
2193
    if (STRNEQ(SECURITY_SELINUX_NAME, secdef->model)) {
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
        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;
}

2208
static int
2209
virSecuritySELinuxSetSecurityDaemonSocketLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
2210
                                               virDomainDefPtr def)
2211 2212
{
    /* TODO: verify DOI */
2213
    virSecurityLabelDefPtr secdef;
2214
    security_context_t scon = NULL;
2215
    char *str = NULL;
2216 2217
    int rc = -1;

2218
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2219
    if (!secdef || !secdef->label)
2220 2221
        return 0;

2222
    if (STRNEQ(SECURITY_SELINUX_NAME, secdef->model)) {
2223 2224 2225 2226
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "'%s' model configured for domain, but "
                         "hypervisor driver is '%s'."),
2227
                       secdef->model, SECURITY_SELINUX_NAME);
2228 2229 2230
        goto done;
    }

M
Martin Kletzander 已提交
2231
    if (getcon_raw(&scon) == -1) {
2232 2233 2234 2235 2236 2237
        virReportSystemError(errno,
                             _("unable to get current process context '%s'"),
                             secdef->label);
        goto done;
    }

2238
    if (!(str = virSecuritySELinuxContextAddRange(secdef->label, scon)))
2239 2240
        goto done;

2241 2242
    VIR_DEBUG("Setting VM %s socket context %s", def->name, str);
    if (setsockcreatecon_raw(str) == -1) {
2243
        virReportSystemError(errno,
2244
                             _("unable to set socket security context '%s'"), str);
2245 2246 2247 2248
        goto done;
    }

    rc = 0;
2249
 done:
2250 2251 2252 2253

    if (security_getenforce() != 1)
        rc = 0;
    freecon(scon);
2254
    VIR_FREE(str);
2255 2256 2257
    return rc;
}

2258
static int
2259
virSecuritySELinuxSetSecuritySocketLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
2260
                                         virDomainDefPtr vm)
2261
{
2262
    virSecurityLabelDefPtr secdef;
2263 2264
    int rc = -1;

2265
    secdef = virDomainDefGetSecurityLabelDef(vm, SECURITY_SELINUX_NAME);
2266
    if (!secdef || !secdef->label)
2267 2268
        return 0;

2269
    if (STRNEQ(SECURITY_SELINUX_NAME, secdef->model)) {
2270 2271 2272 2273
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "'%s' model configured for domain, but "
                         "hypervisor driver is '%s'."),
2274
                       secdef->model, SECURITY_SELINUX_NAME);
2275 2276 2277 2278
        goto done;
    }

    VIR_DEBUG("Setting VM %s socket context %s",
2279
              vm->name, secdef->label);
M
Martin Kletzander 已提交
2280
    if (setsockcreatecon_raw(secdef->label) == -1) {
2281 2282 2283 2284 2285 2286 2287 2288
        virReportSystemError(errno,
                             _("unable to set socket security context '%s'"),
                             secdef->label);
        goto done;
    }

    rc = 0;

2289
 done:
2290 2291 2292 2293 2294 2295
    if (security_getenforce() != 1)
        rc = 0;

    return rc;
}

2296
static int
2297
virSecuritySELinuxClearSecuritySocketLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
2298
                                           virDomainDefPtr def)
2299 2300
{
    /* TODO: verify DOI */
2301 2302 2303
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2304
    if (!secdef || !secdef->label)
2305 2306
        return 0;

2307
    if (STRNEQ(SECURITY_SELINUX_NAME, secdef->model)) {
2308 2309 2310 2311
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "'%s' model configured for domain, but "
                         "hypervisor driver is '%s'."),
2312
                       secdef->model, SECURITY_SELINUX_NAME);
2313 2314 2315 2316
        if (security_getenforce() == 1)
            return -1;
    }

M
Martin Kletzander 已提交
2317
    if (setsockcreatecon_raw(NULL) == -1) {
2318 2319 2320 2321 2322 2323 2324 2325 2326
        virReportSystemError(errno,
                             _("unable to clear socket security context '%s'"),
                             secdef->label);
        if (security_getenforce() == 1)
            return -1;
    }
    return 0;
}

2327 2328

static int
2329 2330
virSecuritySELinuxSetSecurityChardevCallback(virDomainDefPtr def,
                                             virDomainChrDefPtr dev,
2331
                                             void *opaque)
2332
{
2333 2334
    virSecurityManagerPtr mgr = opaque;

2335 2336 2337 2338 2339
    /* This is taken care of by processing of def->serials */
    if (dev->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE &&
        dev->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL)
        return 0;

2340
    return virSecuritySELinuxSetSecurityChardevLabel(mgr, def, dev, &dev->source);
2341 2342 2343
}


E
Eric Blake 已提交
2344
static int
2345 2346 2347
virSecuritySELinuxSetSecuritySmartcardCallback(virDomainDefPtr def,
                                               virDomainSmartcardDefPtr dev,
                                               void *opaque)
E
Eric Blake 已提交
2348 2349
{
    const char *database;
2350 2351
    virSecurityManagerPtr mgr = opaque;
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
E
Eric Blake 已提交
2352 2353 2354 2355 2356 2357 2358 2359 2360

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

    case VIR_DOMAIN_SMARTCARD_TYPE_PASSTHROUGH:
2364 2365
        return virSecuritySELinuxSetSecurityChardevLabel(mgr, def, NULL,
                                                         &dev->data.passthru);
E
Eric Blake 已提交
2366 2367

    default:
2368 2369 2370
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown smartcard type %d"),
                       dev->type);
E
Eric Blake 已提交
2371 2372 2373 2374 2375 2376 2377
        return -1;
    }

    return 0;
}


2378
static int
2379 2380 2381
virSecuritySELinuxSetSecurityAllLabel(virSecurityManagerPtr mgr,
                                      virDomainDefPtr def,
                                      const char *stdin_path)
2382
{
2383
    size_t i;
2384 2385 2386 2387
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2388

2389
    if (!secdef || !secdef->relabel || data->skipAllLabel)
2390 2391
        return 0;

2392
    for (i = 0; i < def->ndisks; i++) {
2393
        /* XXX fixme - we need to recursively label the entire tree :-( */
E
Eric Blake 已提交
2394
        if (virDomainDiskGetType(def->disks[i]) == VIR_STORAGE_TYPE_DIR) {
2395
            VIR_WARN("Unable to relabel directory tree %s for disk %s",
2396 2397
                     virDomainDiskGetSource(def->disks[i]),
                     def->disks[i]->dst);
2398
            continue;
2399
        }
2400
        if (virSecuritySELinuxSetSecurityDiskLabel(mgr,
2401
                                                   def, def->disks[i]) < 0)
2402 2403
            return -1;
    }
2404
    /* XXX fixme process  def->fss if relabel == true */
2405

2406
    for (i = 0; i < def->nhostdevs; i++) {
2407
        if (virSecuritySELinuxSetSecurityHostdevLabel(mgr,
2408 2409 2410
                                                      def,
                                                      def->hostdevs[i],
                                                      NULL) < 0)
2411
            return -1;
2412
    }
2413 2414 2415 2416 2417 2418

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

2419 2420 2421 2422 2423
    if (def->tpm) {
        if (virSecuritySELinuxSetSecurityTPMFileLabel(mgr, def,
                                                      def->tpm) < 0)
            return -1;
    }
2424

2425
    if (virDomainChrDefForeach(def,
2426
                               true,
2427
                               virSecuritySELinuxSetSecurityChardevCallback,
2428
                               mgr) < 0)
2429 2430
        return -1;

2431
    if (virDomainSmartcardDefForeach(def,
E
Eric Blake 已提交
2432
                                     true,
2433
                                     virSecuritySELinuxSetSecuritySmartcardCallback,
2434
                                     mgr) < 0)
E
Eric Blake 已提交
2435 2436
        return -1;

M
Michal Privoznik 已提交
2437 2438
    /* This is different than kernel or initrd. The nvram store
     * is really a disk, qemu can read and write to it. */
2439
    if (def->os.loader && def->os.loader->nvram &&
M
Michal Privoznik 已提交
2440
        secdef && secdef->imagelabel &&
2441 2442
        virSecuritySELinuxSetFilecon(mgr, def->os.loader->nvram,
                                     secdef->imagelabel) < 0)
2443 2444
        return -1;

2445
    if (def->os.kernel &&
2446 2447
        virSecuritySELinuxSetFilecon(mgr, def->os.kernel,
                                     data->content_context) < 0)
2448 2449
        return -1;

2450
    if (def->os.initrd &&
2451 2452
        virSecuritySELinuxSetFilecon(mgr, def->os.initrd,
                                     data->content_context) < 0)
2453 2454
        return -1;

O
Olivia Yin 已提交
2455
    if (def->os.dtb &&
2456 2457
        virSecuritySELinuxSetFilecon(mgr, def->os.dtb,
                                     data->content_context) < 0)
O
Olivia Yin 已提交
2458 2459
        return -1;

2460
    if (stdin_path &&
2461 2462
        virSecuritySELinuxSetFilecon(mgr, stdin_path,
                                     data->content_context) < 0)
2463
        return -1;
2464

2465 2466 2467
    return 0;
}

2468
static int
2469 2470 2471
virSecuritySELinuxSetImageFDLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                  virDomainDefPtr def,
                                  int fd)
2472
{
2473 2474 2475
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2476
    if (!secdef || !secdef->imagelabel)
2477 2478
        return 0;

2479
    return virSecuritySELinuxFSetFilecon(fd, secdef->imagelabel);
2480 2481
}

2482
static int
2483
virSecuritySELinuxSetTapFDLabel(virSecurityManagerPtr mgr,
2484 2485 2486
                                virDomainDefPtr def,
                                int fd)
{
2487 2488
    struct stat buf;
    security_context_t fcon = NULL;
2489
    virSecurityLabelDefPtr secdef;
2490
    char *str = NULL, *proc = NULL, *fd_path = NULL;
2491
    int rc = -1;
2492 2493

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
2494
    if (!secdef || !secdef->label)
2495 2496
        return 0;

2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507
    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;
    }

2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525
    /* 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) {
2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538
        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);
2539 2540
    VIR_FREE(fd_path);
    VIR_FREE(proc);
2541 2542
    VIR_FREE(str);
    return rc;
2543 2544
}

2545 2546 2547 2548
static char *
virSecuritySELinuxGenImageLabel(virSecurityManagerPtr mgr,
                                virDomainDefPtr def)
{
2549
    virSecurityLabelDefPtr secdef;
2550 2551 2552 2553
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
    const char *range;
    context_t ctx = NULL;
    char *label = NULL;
2554
    char *mcs = NULL;
2555

2556 2557 2558 2559
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        goto cleanup;

2560 2561 2562
    if (secdef->label) {
        ctx = context_new(secdef->label);
        if (!ctx) {
2563 2564
            virReportSystemError(errno, _("unable to create selinux context for: %s"),
                                 secdef->label);
2565 2566 2567 2568
            goto cleanup;
        }
        range = context_range_get(ctx);
        if (range) {
2569
            if (VIR_STRDUP(mcs, range) < 0)
2570
                goto cleanup;
2571 2572
            if (!(label = virSecuritySELinuxGenNewContext(data->file_context,
                                                          mcs, true)))
2573 2574 2575 2576
                goto cleanup;
        }
    }

2577
 cleanup:
2578 2579 2580
    context_free(ctx);
    VIR_FREE(mcs);
    return label;
2581 2582
}

2583 2584 2585 2586
static char *
virSecuritySELinuxGetSecurityMountOptions(virSecurityManagerPtr mgr,
                                          virDomainDefPtr def)
{
2587
    char *opts = NULL;
2588 2589
    virSecurityLabelDefPtr secdef;

2590 2591 2592 2593 2594 2595 2596
    if ((secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME))) {
        if (!secdef->imagelabel)
            secdef->imagelabel = virSecuritySELinuxGenImageLabel(mgr, def);

        if (secdef->imagelabel &&
            virAsprintf(&opts,
                        ",context=\"%s\"",
2597
                        (const char*) secdef->imagelabel) < 0)
2598 2599
            return NULL;
    }
2600

2601
    if (!opts && VIR_STRDUP(opts, "") < 0)
2602
        return NULL;
2603

2604 2605
    VIR_DEBUG("imageLabel=%s opts=%s",
              secdef ? secdef->imagelabel : "(null)", opts);
2606 2607 2608
    return opts;
}

G
Guido Günther 已提交
2609
static int
2610
virSecuritySELinuxDomainSetDirLabel(virSecurityManagerPtr mgr,
2611 2612 2613 2614 2615 2616 2617 2618 2619
                                    virDomainDefPtr def,
                                    const char *path)
{
    virSecurityLabelDefPtr seclabel;

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

2620
    return virSecuritySELinuxSetFilecon(mgr, path, seclabel->imagelabel);
2621 2622
}

2623
virSecurityDriver virSecurityDriverSELinux = {
2624 2625
    .privateDataLen                     = sizeof(virSecuritySELinuxData),
    .name                               = SECURITY_SELINUX_NAME,
2626 2627 2628
    .probe                              = virSecuritySELinuxSecurityDriverProbe,
    .open                               = virSecuritySELinuxSecurityDriverOpen,
    .close                              = virSecuritySELinuxSecurityDriverClose,
2629

2630 2631
    .getModel                           = virSecuritySELinuxSecurityGetModel,
    .getDOI                             = virSecuritySELinuxSecurityGetDOI,
2632

2633
    .domainSecurityVerify               = virSecuritySELinuxSecurityVerify,
2634

2635
    .domainSetSecurityDiskLabel         = virSecuritySELinuxSetSecurityDiskLabel,
2636
    .domainRestoreSecurityDiskLabel     = virSecuritySELinuxRestoreSecurityDiskLabel,
2637

2638
    .domainSetSecurityImageLabel        = virSecuritySELinuxSetSecurityImageLabel,
2639 2640
    .domainRestoreSecurityImageLabel    = virSecuritySELinuxRestoreSecurityImageLabel,

2641 2642 2643
    .domainSetSecurityDaemonSocketLabel = virSecuritySELinuxSetSecurityDaemonSocketLabel,
    .domainSetSecuritySocketLabel       = virSecuritySELinuxSetSecuritySocketLabel,
    .domainClearSecuritySocketLabel     = virSecuritySELinuxClearSecuritySocketLabel,
2644

2645 2646 2647
    .domainGenSecurityLabel             = virSecuritySELinuxGenSecurityLabel,
    .domainReserveSecurityLabel         = virSecuritySELinuxReserveSecurityLabel,
    .domainReleaseSecurityLabel         = virSecuritySELinuxReleaseSecurityLabel,
2648

2649 2650
    .domainGetSecurityProcessLabel      = virSecuritySELinuxGetSecurityProcessLabel,
    .domainSetSecurityProcessLabel      = virSecuritySELinuxSetSecurityProcessLabel,
2651
    .domainSetSecurityChildProcessLabel = virSecuritySELinuxSetSecurityChildProcessLabel,
2652

2653 2654
    .domainSetSecurityAllLabel          = virSecuritySELinuxSetSecurityAllLabel,
    .domainRestoreSecurityAllLabel      = virSecuritySELinuxRestoreSecurityAllLabel,
2655

2656 2657
    .domainSetSecurityHostdevLabel      = virSecuritySELinuxSetSecurityHostdevLabel,
    .domainRestoreSecurityHostdevLabel  = virSecuritySELinuxRestoreSecurityHostdevLabel,
2658

2659 2660
    .domainSetSavedStateLabel           = virSecuritySELinuxSetSavedStateLabel,
    .domainRestoreSavedStateLabel       = virSecuritySELinuxRestoreSavedStateLabel,
2661

2662
    .domainSetSecurityImageFDLabel      = virSecuritySELinuxSetImageFDLabel,
2663
    .domainSetSecurityTapFDLabel        = virSecuritySELinuxSetTapFDLabel,
2664

2665
    .domainGetSecurityMountOptions      = virSecuritySELinuxGetSecurityMountOptions,
2666
    .getBaseLabel                       = virSecuritySELinuxGetBaseLabel,
2667 2668

    .domainSetDirLabel                  = virSecuritySELinuxDomainSetDirLabel,
2669
};