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

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

#define VIR_FROM_THIS VIR_FROM_SECURITY

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

typedef struct _virSecuritySELinuxData virSecuritySELinuxData;
typedef virSecuritySELinuxData *virSecuritySELinuxDataPtr;

typedef struct _virSecuritySELinuxCallbackData virSecuritySELinuxCallbackData;
typedef virSecuritySELinuxCallbackData *virSecuritySELinuxCallbackDataPtr;

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

struct _virSecuritySELinuxCallbackData {
    virSecurityManagerPtr manager;
    virSecurityLabelDefPtr secdef;
};

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

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

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

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

94 95 96
    return 0;
}

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

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

106 107 108 109 110 111 112 113

static char *
virSecuritySELinuxMCSFind(virSecurityManagerPtr mgr)
{
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
    int c1 = 0;
    int c2 = 0;
    char *mcs = NULL;
114 115
    security_context_t ourSecContext = NULL;
    context_t ourContext = NULL;
116
    char *sens = NULL, *cat, *tmp;
117 118
    int catMin, catMax, catRange;

M
Martin Kletzander 已提交
119
    if (getcon_raw(&ourSecContext) < 0) {
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
        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;
    }

    if (!(sens = strdup(context_range_get(ourContext)))) {
        virReportOOMError();
        goto cleanup;
    }

    /* Find and blank out the category part */
    if (!(tmp = strchr(sens, ':'))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot parse sensitivity level in %s"),
                       sens);
        goto cleanup;
    }
    *tmp = '\0';
    cat = tmp + 1;
    /* Find and blank out the sensitivity upper bound */
    if ((tmp = strchr(sens, '-')))
        *tmp = '\0';
    /* sens now just contains the sensitivity lower bound */

    /* Find & extract category min */
    tmp = cat;
    if (tmp[0] != 'c') {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot parse category in %s"),
                       cat);
        goto cleanup;
    }
    tmp++;
    if (virStrToLong_i(tmp, &tmp, 10, &catMin) < 0) {
        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++;
    if (virStrToLong_i(tmp, &tmp, 10, &catMax) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot parse category in %s"),
                       cat);
        goto cleanup;
    }

    /* +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);
        goto cleanup;
    }

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

    for (;;) {
210 211 212
        c1 = virRandomInt(catRange);
        c2 = virRandomInt(catRange);
        VIR_DEBUG("Try cat %s:c%d,c%d", sens, c1+catMin, c2+catMin);
213 214

        if (c1 == c2) {
215
            if (virAsprintf(&mcs, "%s:c%d", sens, catMin + c1) < 0) {
216 217 218 219 220 221 222 223 224
                virReportOOMError();
                return NULL;
            }
        } else {
            if (c1 > c2) {
                int t = c1;
                c1 = c2;
                c2 = t;
            }
225
            if (virAsprintf(&mcs, "%s:c%d,c%d", sens, catMin + c1, catMin + c2) < 0) {
226 227 228 229 230 231 232 233 234 235 236 237 238
                virReportOOMError();
                return NULL;
            }
        }

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

        VIR_FREE(mcs);
    }

cleanup:
    VIR_DEBUG("Found context '%s'", NULLSTR(mcs));
239 240 241
    VIR_FREE(sens);
    freecon(ourSecContext);
    context_free(ourContext);
242 243 244
    return mcs;
}

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 271 272 273 274 275 276 277 278 279 280 281 282 283 284
static char *
virSecuritySELinuxContextAddRange(security_context_t src,
                                  security_context_t dst)
{
    char *str = NULL;
    char *ret = NULL;
    context_t srccon = NULL;
    context_t dstcon = NULL;

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

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

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

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

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

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

286
static char *
287 288 289
virSecuritySELinuxGenNewContext(const char *basecontext,
                                const char *mcs,
                                bool isObjectContext)
290
{
291
    context_t context = NULL;
292 293
    char *ret = NULL;
    char *str;
294 295 296
    security_context_t ourSecContext = NULL;
    context_t ourContext = NULL;

297 298 299
    VIR_DEBUG("basecontext=%s mcs=%s isObjectContext=%d",
              basecontext, mcs, isObjectContext);

M
Martin Kletzander 已提交
300
    if (getcon_raw(&ourSecContext) < 0) {
301 302 303 304 305 306 307 308 309 310
        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;
    }
311
    VIR_DEBUG("process=%s", ourSecContext);
312 313 314 315 316 317 318 319

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

320 321 322 323 324 325 326 327
    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;
    }

328 329
    if (!isObjectContext &&
        context_role_set(context,
330 331
                         context_role_get(ourContext)) != 0) {
        virReportSystemError(errno,
332
                             _("Unable to set SELinux context role '%s'"),
333 334 335 336
                             context_role_get(ourContext));
        goto cleanup;
    }

337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
    if (context_range_set(context, mcs) != 0) {
        virReportSystemError(errno,
                             _("Unable to set SELinux context MCS '%s'"),
                             mcs);
        goto cleanup;
    }
    if (!(str = context_str(context))) {
        virReportSystemError(errno, "%s",
                             _("Unable to format SELinux context"));
        goto cleanup;
    }
    if (!(ret = strdup(str))) {
        virReportOOMError();
        goto cleanup;
    }
352
    VIR_DEBUG("Generated context '%s'",  ret);
353
cleanup:
354 355
    freecon(ourSecContext);
    context_free(ourContext);
356 357
    context_free(context);
    return ret;
358 359
}

360

361
#ifdef HAVE_SELINUX_LXC_CONTEXTS_PATH
362
static int
363
virSecuritySELinuxLXCInitialize(virSecurityManagerPtr mgr)
364 365 366 367 368 369 370
{
    virConfValuePtr scon = NULL;
    virConfValuePtr tcon = NULL;
    virConfValuePtr dcon = NULL;
    virConfPtr selinux_conf;
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);

371 372
    data->skipAllLabel = true;

373
# if HAVE_SELINUX_LABEL_H
374 375 376 377 378 379
    data->label_handle = selabel_open(SELABEL_CTX_FILE, NULL, 0);
    if (!data->label_handle) {
        virReportSystemError(errno, "%s",
                             _("cannot open SELinux label_handle"));
        return -1;
    }
380
# endif
381

382 383 384 385 386
    selinux_conf = virConfReadFile(selinux_lxc_contexts_path(), 0);
    if (!selinux_conf) {
        virReportSystemError(errno,
                             _("cannot open SELinux lxc contexts file '%s'"),
                             selinux_lxc_contexts_path());
387
        goto error;
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
    }

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

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

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

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

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

429 430 431 432
    virConfFree(selinux_conf);
    return 0;

error:
433
# if HAVE_SELINUX_LABEL_H
434
    selabel_close(data->label_handle);
435
# endif
436 437 438 439
    virConfFree(selinux_conf);
    VIR_FREE(data->domain_context);
    VIR_FREE(data->file_context);
    VIR_FREE(data->content_context);
440
    virHashFree(data->mcs);
441 442
    return -1;
}
443 444
#else
static int
445
virSecuritySELinuxLXCInitialize(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED)
446 447 448 449 450 451
{
    virReportSystemError(ENOSYS, "%s",
                         _("libselinux does not support LXC contexts path"));
    return -1;
}
#endif
452 453 454


static int
455
virSecuritySELinuxQEMUInitialize(virSecurityManagerPtr mgr)
456
{
457 458
    char *ptr;
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
459

460 461
    data->skipAllLabel = false;

462 463 464 465 466 467 468 469 470
#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

471
    if (virFileReadAll(selinux_virtual_domain_context_path(), MAX_CONTEXT, &(data->domain_context)) < 0) {
472
        virReportSystemError(errno,
473
                             _("cannot read SELinux virtual domain context file '%s'"),
474
                             selinux_virtual_domain_context_path());
475
        goto error;
476 477
    }

478
    ptr = strchrnul(data->domain_context, '\n');
479
    if (ptr && *ptr == '\n') {
480
        *ptr = '\0';
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
        ptr++;
        if (*ptr != '\0') {
            data->alt_domain_context = strdup(ptr);
            if (!data->alt_domain_context) {
                virReportOOMError();
                goto error;
            }
            ptr = strchrnul(data->alt_domain_context, '\n');
            if (ptr && *ptr == '\n')
                *ptr = '\0';
        }
    }
    VIR_DEBUG("Loaded domain context '%s', alt domain context '%s'",
              data->domain_context, NULLSTR(data->alt_domain_context));

496

497
    if (virFileReadAll(selinux_virtual_image_context_path(), 2*MAX_CONTEXT, &(data->file_context)) < 0) {
498
        virReportSystemError(errno,
499 500
                             _("cannot read SELinux virtual image context file %s"),
                             selinux_virtual_image_context_path());
501
        goto error;
502 503
    }

504 505
    ptr = strchrnul(data->file_context, '\n');
    if (ptr && *ptr == '\n') {
506
        *ptr = '\0';
507 508 509 510 511 512 513
        data->content_context = strdup(ptr+1);
        if (!data->content_context) {
            virReportOOMError();
            goto error;
        }
        ptr = strchrnul(data->content_context, '\n');
        if (ptr && *ptr == '\n')
514 515
            *ptr = '\0';
    }
516

517 518 519
    VIR_DEBUG("Loaded file context '%s', content context '%s'",
              data->file_context, data->content_context);

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

523
    return 0;
524 525

error:
526 527 528
#if HAVE_SELINUX_LABEL_H
    selabel_close(data->label_handle);
#endif
529
    VIR_FREE(data->domain_context);
530
    VIR_FREE(data->alt_domain_context);
531 532
    VIR_FREE(data->file_context);
    VIR_FREE(data->content_context);
533
    virHashFree(data->mcs);
534
    return -1;
535 536
}

537 538

static int
539
virSecuritySELinuxInitialize(virSecurityManagerPtr mgr)
540 541 542
{
    VIR_DEBUG("SELinuxInitialize %s", virSecurityManagerGetDriver(mgr));
    if (STREQ(virSecurityManagerGetDriver(mgr),  "LXC")) {
543
        return virSecuritySELinuxLXCInitialize(mgr);
544
    } else {
545
        return virSecuritySELinuxQEMUInitialize(mgr);
546 547 548 549
    }
}


550
static int
551 552
virSecuritySELinuxGenSecurityLabel(virSecurityManagerPtr mgr,
                                   virDomainDefPtr def)
553 554
{
    int rc = -1;
555
    char *mcs = NULL;
556
    char *scontext = NULL;
557
    context_t ctx = NULL;
558
    const char *range;
559 560
    virSecurityLabelDefPtr seclabel;
    virSecuritySELinuxDataPtr data;
561
    const char *baselabel;
562

563
    if (mgr == NULL) {
564
        virReportError(VIR_ERR_INTERNAL_ERROR,
565
                       "%s", _("invalid security driver"));
566 567 568
        return rc;
    }

569 570 571 572 573 574 575 576 577 578
    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (seclabel == NULL) {
        return rc;
    }

    data = virSecurityManagerGetPrivateData(mgr);

    VIR_DEBUG("label=%s", virSecurityManagerGetDriver(mgr));
    if (seclabel->type == VIR_DOMAIN_SECLABEL_DYNAMIC &&
        seclabel->label) {
579 580
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("security label already defined for VM"));
581
        return rc;
D
Daniel P. Berrange 已提交
582
    }
583

584
    if (seclabel->imagelabel) {
585 586
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("security image label already defined for VM"));
587 588 589
        return rc;
    }

590 591
    if (seclabel->model &&
        STRNEQ(seclabel->model, SECURITY_SELINUX_NAME)) {
592 593
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label model %s is not supported with selinux"),
594
                       seclabel->model);
595 596 597
        return rc;
    }

598
    VIR_DEBUG("type=%d", seclabel->type);
599

600
    switch (seclabel->type) {
601
    case VIR_DOMAIN_SECLABEL_STATIC:
602
        if (!(ctx = context_new(seclabel->label))) {
603 604
            virReportSystemError(errno,
                                 _("unable to allocate socket security context '%s'"),
605
                                 seclabel->label);
606
            return rc;
607 608
        }

609
        range = context_range_get(ctx);
610 611 612 613 614
        if (!range ||
            !(mcs = strdup(range))) {
            virReportOOMError();
            goto cleanup;
        }
615 616 617
        break;

    case VIR_DOMAIN_SECLABEL_DYNAMIC:
618 619 620 621 622
        if (!(mcs = virSecuritySELinuxMCSFind(mgr)))
            goto cleanup;

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

624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
        baselabel = seclabel->baselabel;
        if (!baselabel) {
            if (def->virtType == VIR_DOMAIN_VIRT_QEMU) {
                if (data->alt_domain_context == NULL) {
                    static bool warned = false;
                    if (!warned) {
                        VIR_WARN("SELinux policy does not define a domain type for QEMU TCG. "
                                 "Guest startup may be denied due to missing 'execmem' privilege "
                                 "unless the 'virt_use_execmem' policy boolean is enabled");
                        warned = true;
                    }
                    baselabel = data->domain_context;
                } else {
                    baselabel = data->alt_domain_context;
                }
            } else {
                baselabel = data->domain_context;
            }
        }

644
        seclabel->label =
645
            virSecuritySELinuxGenNewContext(baselabel, mcs, false);
646
        if (!seclabel->label)  {
647 648
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot generate selinux context for %s"), mcs);
649
            goto cleanup;
650
        }
651 652 653 654 655 656 657
        break;

    case VIR_DOMAIN_SECLABEL_NONE:
        /* no op */
        break;

    default:
658 659
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected security label type '%s'"),
660
                       virDomainSeclabelTypeToString(seclabel->type));
661
        goto cleanup;
D
Daniel P. Berrange 已提交
662
    }
663

664
    if (!seclabel->norelabel) {
665
        seclabel->imagelabel = virSecuritySELinuxGenNewContext(data->file_context,
666 667 668
                                                               mcs,
                                                               true);
        if (!seclabel->imagelabel)  {
669 670
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot generate selinux context for %s"), mcs);
671
            goto cleanup;
672
        }
673 674
    }

675 676
    if (!seclabel->model &&
        !(seclabel->model = strdup(SECURITY_SELINUX_NAME))) {
677
        virReportOOMError();
678
        goto cleanup;
D
Daniel P. Berrange 已提交
679 680
    }

681
    rc = 0;
682 683 684

cleanup:
    if (rc != 0) {
685 686 687 688 689 690
        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);
691 692 693 694
    }

    if (ctx)
        context_free(ctx);
D
Daniel P. Berrange 已提交
695
    VIR_FREE(scontext);
696 697 698
    VIR_FREE(mcs);

    VIR_DEBUG("model=%s label=%s imagelabel=%s baselabel=%s",
699 700 701 702
              NULLSTR(seclabel->model),
              NULLSTR(seclabel->label),
              NULLSTR(seclabel->imagelabel),
              NULLSTR(seclabel->baselabel));
703

704 705 706
    return rc;
}

707
static int
708
virSecuritySELinuxReserveSecurityLabel(virSecurityManagerPtr mgr,
709 710
                                       virDomainDefPtr def,
                                       pid_t pid)
711 712 713 714
{
    security_context_t pctx;
    context_t ctx = NULL;
    const char *mcs;
715
    int rv;
716
    virSecurityLabelDefPtr seclabel;
717

718 719 720 721 722 723
    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (seclabel == NULL) {
        return -1;
    }

    if (seclabel->type == VIR_DOMAIN_SECLABEL_STATIC)
724 725
        return 0;

M
Martin Kletzander 已提交
726
    if (getpidcon_raw(pid, &pctx) == -1) {
727
        virReportSystemError(errno,
728
                             _("unable to get PID %d security context"), pid);
729 730 731 732
        return -1;
    }

    ctx = context_new(pctx);
733
    freecon(pctx);
734
    if (!ctx)
735
        goto error;
736 737 738

    mcs = context_range_get(ctx);
    if (!mcs)
739 740
        goto error;

741
    if ((rv = virSecuritySELinuxMCSAdd(mgr, mcs)) < 0)
742
        goto error;
743

744 745 746 747 748 749
    if (rv == 1) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("MCS level for existing domain label %s already reserved"),
                       (char*)pctx);
        goto error;
    }
750 751 752 753 754

    context_free(ctx);

    return 0;

755
error:
756 757 758 759 760
    context_free(ctx);
    return -1;
}


761
static int
762
virSecuritySELinuxSecurityDriverProbe(const char *virtDriver)
763
{
764 765 766
    if (!is_selinux_enabled())
        return SECURITY_DRIVER_DISABLE;

767 768 769 770 771 772
    if (virtDriver && STREQ(virtDriver, "LXC")) {
#if HAVE_SELINUX_LXC_CONTEXTS_PATH
        if (!virFileExists(selinux_lxc_contexts_path()))
#endif
            return SECURITY_DRIVER_DISABLE;
    }
773 774

    return SECURITY_DRIVER_ENABLE;
775 776
}

777

778
static int
779
virSecuritySELinuxSecurityDriverOpen(virSecurityManagerPtr mgr)
780
{
781
    return virSecuritySELinuxInitialize(mgr);
782 783
}

784

785
static int
786
virSecuritySELinuxSecurityDriverClose(virSecurityManagerPtr mgr)
787
{
788 789 790 791 792
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);

    if (!data)
        return 0;

793 794 795 796
#if HAVE_SELINUX_LABEL_H
    selabel_close(data->label_handle);
#endif

797 798
    virHashFree(data->mcs);

799
    VIR_FREE(data->domain_context);
800
    VIR_FREE(data->alt_domain_context);
801 802 803
    VIR_FREE(data->file_context);
    VIR_FREE(data->content_context);

804 805 806 807
    return 0;
}


808 809
static const char *
virSecuritySELinuxSecurityGetModel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED)
810 811 812 813
{
    return SECURITY_SELINUX_NAME;
}

814 815
static const char *
virSecuritySELinuxSecurityGetDOI(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED)
816 817 818 819 820
{
    /*
     * Where will the DOI come from?  SELinux configuration, or qemu
     * configuration? For the moment, we'll just set it to "0".
     */
821
    return SECURITY_SELINUX_VOID_DOI;
822 823 824
}

static int
825 826 827 828
virSecuritySELinuxGetSecurityProcessLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                          virDomainDefPtr def ATTRIBUTE_UNUSED,
                                          pid_t pid,
                                          virSecurityLabelPtr sec)
829 830 831
{
    security_context_t ctx;

M
Martin Kletzander 已提交
832
    if (getpidcon_raw(pid, &ctx) == -1) {
833
        virReportSystemError(errno,
834
                             _("unable to get PID %d security context"),
835
                             pid);
836 837 838 839
        return -1;
    }

    if (strlen((char *) ctx) >= VIR_SECURITY_LABEL_BUFLEN) {
840 841 842 843
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label exceeds "
                         "maximum length: %d"),
                       VIR_SECURITY_LABEL_BUFLEN - 1);
844
        freecon(ctx);
845 846 847 848
        return -1;
    }

    strcpy(sec->label, (char *) ctx);
849
    freecon(ctx);
850

851
    VIR_DEBUG("label=%s", sec->label);
852 853
    sec->enforcing = security_getenforce();
    if (sec->enforcing == -1) {
854
        virReportSystemError(errno, "%s",
855
                             _("error calling security_getenforce()"));
856 857 858 859 860 861
        return -1;
    }

    return 0;
}

862 863 864
/* 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.  */
865
static int
866
virSecuritySELinuxSetFileconHelper(const char *path, char *tcon, bool optional)
867
{
868
    security_context_t econ;
869

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

M
Martin Kletzander 已提交
872
    if (setfilecon_raw(path, tcon) < 0) {
873 874
        int setfilecon_errno = errno;

M
Martin Kletzander 已提交
875
        if (getfilecon_raw(path, &econ) >= 0) {
876 877 878
            if (STREQ(tcon, econ)) {
                freecon(econ);
                /* It's alright, there's nothing to change anyway. */
879
                return optional ? 1 : 0;
880 881 882
            }
            freecon(econ);
        }
883 884

        /* if the error complaint is related to an image hosted on
885 886
         * an nfs mount, or a usbfs/sysfs filesystem not supporting
         * labelling, then just ignore it & hope for the best.
887
         * The user hopefully set one of the necessary SELinux
888
         * virt_use_{nfs,usb,pci}  boolean tunables to allow it...
889
         */
890
        if (setfilecon_errno != EOPNOTSUPP && setfilecon_errno != ENOTSUP) {
891
            virReportSystemError(setfilecon_errno,
892
                                 _("unable to set security context '%s' on '%s'"),
893
                                 tcon, path);
894 895
            if (security_getenforce() == 1)
                return -1;
896
        } else {
897 898 899 900 901 902 903 904 905 906 907 908 909 910
            const char *msg;
            if ((virStorageFileIsSharedFSType(path,
                                              VIR_STORAGE_FILE_SHFS_NFS) == 1) &&
                security_get_boolean_active("virt_use_nfs") != 1) {
                msg = _("Setting security context '%s' on '%s' not supported. "
                        "Consider setting virt_use_nfs");
               if (security_getenforce() == 1)
                   VIR_WARN(msg, tcon, path);
               else
                   VIR_INFO(msg, tcon, path);
            } else {
                VIR_INFO("Setting security context '%s' on '%s' not supported",
                         tcon, path);
            }
911 912
            if (optional)
                return 1;
913
        }
914 915 916 917
    }
    return 0;
}

918
static int
919
virSecuritySELinuxSetFileconOptional(const char *path, char *tcon)
920
{
921
    return virSecuritySELinuxSetFileconHelper(path, tcon, true);
922 923 924
}

static int
925
virSecuritySELinuxSetFilecon(const char *path, char *tcon)
926
{
927
    return virSecuritySELinuxSetFileconHelper(path, tcon, false);
928 929
}

930
static int
931
virSecuritySELinuxFSetFilecon(int fd, char *tcon)
932 933 934 935 936
{
    security_context_t econ;

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

M
Martin Kletzander 已提交
937
    if (fsetfilecon_raw(fd, tcon) < 0) {
938 939
        int fsetfilecon_errno = errno;

M
Martin Kletzander 已提交
940
        if (fgetfilecon_raw(fd, &econ) >= 0) {
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
            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 已提交
969 970
/* Set fcon to the appropriate label for path and mode, or return -1.  */
static int
971
getContext(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
972
           const char *newpath, mode_t mode, security_context_t *fcon)
E
Eric Blake 已提交
973 974
{
#if HAVE_SELINUX_LABEL_H
975
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
E
Eric Blake 已提交
976

977
    return selabel_lookup_raw(data->label_handle, fcon, newpath, mode);
E
Eric Blake 已提交
978 979 980 981 982
#else
    return matchpathcon(newpath, mode, fcon);
#endif
}

983 984 985

/* This method shouldn't raise errors, since they'll overwrite
 * errors that the caller(s) are already dealing with */
986
static int
987 988
virSecuritySELinuxRestoreSecurityFileLabel(virSecurityManagerPtr mgr,
                                           const char *path)
989
{
990 991 992 993
    struct stat buf;
    security_context_t fcon = NULL;
    int rc = -1;
    char *newpath = NULL;
994
    char ebuf[1024];
995

996 997
    VIR_INFO("Restoring SELinux context on '%s'", path);

998
    if (virFileResolveLink(path, &newpath) < 0) {
999 1000
        VIR_WARN("cannot resolve symlink %s: %s", path,
                 virStrerror(errno, ebuf, sizeof(ebuf)));
D
Daniel P. Berrange 已提交
1001
        goto err;
1002
    }
1003

1004
    if (stat(newpath, &buf) != 0) {
1005 1006
        VIR_WARN("cannot stat %s: %s", newpath,
                 virStrerror(errno, ebuf, sizeof(ebuf)));
D
Daniel P. Berrange 已提交
1007
        goto err;
1008
    }
D
Daniel P. Berrange 已提交
1009

1010
    if (getContext(mgr, newpath, buf.st_mode, &fcon) < 0) {
1011 1012 1013
        /* Any user created path likely does not have a default label,
         * which makes this an expected non error
         */
1014
        VIR_WARN("cannot lookup default selinux label for %s", newpath);
1015
        rc = 0;
1016
    } else {
1017
        rc = virSecuritySELinuxSetFilecon(newpath, fcon);
1018
    }
1019

1020
err:
1021
    freecon(fcon);
1022 1023
    VIR_FREE(newpath);
    return rc;
1024 1025
}

1026
static int
1027
virSecuritySELinuxRestoreSecurityImageLabelInt(virSecurityManagerPtr mgr,
1028 1029 1030
                                               virDomainDefPtr def,
                                               virDomainDiskDefPtr disk,
                                               int migrated)
1031
{
1032 1033 1034 1035 1036 1037
    virSecurityLabelDefPtr seclabel;
    virSecurityDeviceLabelDefPtr disk_seclabel;

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

1039 1040 1041
    disk_seclabel = virDomainDiskDefGetSecurityLabelDef(disk,
                                                        SECURITY_SELINUX_NAME);
    if (seclabel->norelabel || (disk_seclabel && disk_seclabel->norelabel))
1042 1043
        return 0;

1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
    /* Don't restore labels on readoly/shared disks, because
     * other VMs may still be accessing these
     * Alternatively we could iterate over all running
     * domains and try to figure out if it is in use, but
     * this would not work for clustered filesystems, since
     * we can't see running VMs using the file on other nodes
     * Safest bet is thus to skip the restore step.
     */
    if (disk->readonly || disk->shared)
        return 0;

1055
    if (!disk->src || disk->type == VIR_DOMAIN_DISK_TYPE_NETWORK)
1056 1057
        return 0;

1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
    /* If we have a shared FS & doing migrated, we must not
     * change ownership, because that kills access on the
     * destination host which is sub-optimal for the guest
     * VM's I/O attempts :-)
     */
    if (migrated) {
        int rc = virStorageFileIsSharedFS(disk->src);
        if (rc < 0)
            return -1;
        if (rc == 1) {
            VIR_DEBUG("Skipping image label restore on %s because FS is shared",
                      disk->src);
            return 0;
        }
    }

1074
    return virSecuritySELinuxRestoreSecurityFileLabel(mgr, disk->src);
1075 1076
}

1077 1078

static int
1079 1080 1081
virSecuritySELinuxRestoreSecurityImageLabel(virSecurityManagerPtr mgr,
                                            virDomainDefPtr def,
                                            virDomainDiskDefPtr disk)
1082
{
1083
    return virSecuritySELinuxRestoreSecurityImageLabelInt(mgr, def, disk, 0);
1084 1085 1086
}


1087
static int
1088 1089 1090 1091
virSecuritySELinuxSetSecurityFileLabel(virDomainDiskDefPtr disk,
                                       const char *path,
                                       size_t depth,
                                       void *opaque)
1092
{
1093 1094
    int ret;
    virSecurityDeviceLabelDefPtr disk_seclabel;
1095 1096 1097
    virSecuritySELinuxCallbackDataPtr cbdata = opaque;
    const virSecurityLabelDefPtr secdef = cbdata->secdef;
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(cbdata->manager);
1098

1099 1100 1101 1102
    disk_seclabel = virDomainDiskDefGetSecurityLabelDef(disk,
                                                        SECURITY_SELINUX_NAME);

    if (disk_seclabel && disk_seclabel->norelabel)
1103 1104
        return 0;

1105 1106 1107
    if (disk_seclabel && !disk_seclabel->norelabel &&
        disk_seclabel->label) {
        ret = virSecuritySELinuxSetFilecon(path, disk_seclabel->label);
1108
    } else if (depth == 0) {
1109

1110
        if (disk->shared) {
1111
            ret = virSecuritySELinuxSetFileconOptional(path, data->file_context);
1112
        } else if (disk->readonly) {
1113
            ret = virSecuritySELinuxSetFileconOptional(path, data->content_context);
1114
        } else if (secdef->imagelabel) {
1115
            ret = virSecuritySELinuxSetFileconOptional(path, secdef->imagelabel);
1116
        } else {
1117
            ret = 0;
1118 1119
        }
    } else {
1120
        ret = virSecuritySELinuxSetFileconOptional(path, data->content_context);
1121
    }
1122
    if (ret == 1 && !disk_seclabel) {
1123 1124
        /* If we failed to set a label, but virt_use_nfs let us
         * proceed anyway, then we don't need to relabel later.  */
1125 1126 1127
        disk_seclabel =
            virDomainDiskDefAddSecurityLabelDef(disk, SECURITY_SELINUX_NAME);
        if (!disk_seclabel)
1128
            return -1;
1129
        disk_seclabel->norelabel = true;
1130
        ret = 0;
1131
    }
1132
    return ret;
1133 1134
}

1135
static int
1136 1137 1138
virSecuritySELinuxSetSecurityImageLabel(virSecurityManagerPtr mgr,
                                        virDomainDefPtr def,
                                        virDomainDiskDefPtr disk)
1139 1140

{
1141 1142
    virSecuritySELinuxCallbackData cbdata;
    cbdata.manager = mgr;
1143
    cbdata.secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
1144

1145 1146
    if (cbdata.secdef == NULL)
        return -1;
1147

1148
    if (cbdata.secdef->norelabel)
1149 1150
        return 0;

1151 1152 1153
    if (disk->type == VIR_DOMAIN_DISK_TYPE_NETWORK)
        return 0;

1154
    return virDomainDiskDefForeachPath(disk,
1155
                                       true,
1156
                                       virSecuritySELinuxSetSecurityFileLabel,
1157
                                       &cbdata);
1158 1159
}

1160 1161

static int
1162
virSecuritySELinuxSetSecurityPCILabel(virPCIDevicePtr dev ATTRIBUTE_UNUSED,
1163
                                      const char *file, void *opaque)
1164
{
1165
    virSecurityLabelDefPtr secdef;
1166
    virDomainDefPtr def = opaque;
1167

1168 1169 1170
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        return -1;
1171
    return virSecuritySELinuxSetFilecon(file, secdef->imagelabel);
1172 1173 1174
}

static int
1175
virSecuritySELinuxSetSecurityUSBLabel(virUSBDevicePtr dev ATTRIBUTE_UNUSED,
1176
                                      const char *file, void *opaque)
1177
{
1178
    virSecurityLabelDefPtr secdef;
1179
    virDomainDefPtr def = opaque;
1180 1181 1182 1183

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

1185
    return virSecuritySELinuxSetFilecon(file, secdef->imagelabel);
1186 1187
}

1188

1189
static int
1190 1191 1192
virSecuritySELinuxSetSecurityHostdevSubsysLabel(virDomainDefPtr def,
                                                virDomainHostdevDefPtr dev,
                                                const char *vroot)
1193 1194 1195 1196 1197 1198

{
    int ret = -1;

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

1201 1202 1203
        if (dev->missing)
            return 0;

1204 1205 1206
        usb = virUSBDeviceNew(dev->source.subsys.u.usb.bus,
                              dev->source.subsys.u.usb.device,
                              vroot);
1207 1208
        if (!usb)
            goto done;
1209

1210 1211
        ret = virUSBDeviceFileIterate(usb, virSecuritySELinuxSetSecurityUSBLabel, def);
        virUSBDeviceFree(usb);
M
Mark McLoughlin 已提交
1212
        break;
1213 1214 1215
    }

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI: {
1216 1217 1218 1219 1220
        virPCIDevicePtr pci =
            virPCIDeviceNew(dev->source.subsys.u.pci.domain,
                            dev->source.subsys.u.pci.bus,
                            dev->source.subsys.u.pci.slot,
                            dev->source.subsys.u.pci.function);
1221 1222 1223 1224

        if (!pci)
            goto done;

1225 1226
        ret = virPCIDeviceFileIterate(pci, virSecuritySELinuxSetSecurityPCILabel, def);
        virPCIDeviceFree(pci);
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239

        break;
    }

    default:
        ret = 0;
        break;
    }

done:
    return ret;
}

1240

1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
static int
virSecuritySELinuxSetSecurityHostdevCapsLabel(virDomainDefPtr def,
                                              virDomainHostdevDefPtr dev,
                                              const char *vroot)
{
    int ret = -1;
    virSecurityLabelDefPtr secdef;
    char *path;

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

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

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

    default:
        ret = 0;
        break;
    }

    return ret;
}


1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
static int
virSecuritySELinuxSetSecurityHostdevLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                          virDomainDefPtr def,
                                          virDomainHostdevDefPtr dev,
                                          const char *vroot)

{
    virSecurityLabelDefPtr secdef;

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

    if (secdef->norelabel)
        return 0;

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

1320 1321 1322
    case VIR_DOMAIN_HOSTDEV_MODE_CAPABILITIES:
        return virSecuritySELinuxSetSecurityHostdevCapsLabel(def, dev, vroot);

1323 1324 1325 1326 1327 1328
    default:
        return 0;
    }
}


1329
static int
1330
virSecuritySELinuxRestoreSecurityPCILabel(virPCIDevicePtr dev ATTRIBUTE_UNUSED,
1331
                                          const char *file,
1332
                                          void *opaque)
1333
{
1334 1335 1336
    virSecurityManagerPtr mgr = opaque;

    return virSecuritySELinuxRestoreSecurityFileLabel(mgr, file);
1337 1338 1339
}

static int
1340
virSecuritySELinuxRestoreSecurityUSBLabel(virUSBDevicePtr dev ATTRIBUTE_UNUSED,
1341
                                          const char *file,
1342
                                          void *opaque)
1343
{
1344 1345 1346
    virSecurityManagerPtr mgr = opaque;

    return virSecuritySELinuxRestoreSecurityFileLabel(mgr, file);
1347 1348
}

1349

1350
static int
1351 1352
virSecuritySELinuxRestoreSecurityHostdevSubsysLabel(virSecurityManagerPtr mgr,
                                                    virDomainHostdevDefPtr dev,
1353
                                                    const char *vroot)
1354 1355 1356 1357 1358 1359

{
    int ret = -1;

    switch (dev->source.subsys.type) {
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB: {
1360
        virUSBDevicePtr usb;
1361 1362 1363

        if (dev->missing)
            return 0;
1364

1365 1366 1367
        usb = virUSBDeviceNew(dev->source.subsys.u.usb.bus,
                              dev->source.subsys.u.usb.device,
                              vroot);
1368 1369 1370
        if (!usb)
            goto done;

1371 1372
        ret = virUSBDeviceFileIterate(usb, virSecuritySELinuxRestoreSecurityUSBLabel, mgr);
        virUSBDeviceFree(usb);
1373 1374 1375 1376 1377

        break;
    }

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI: {
1378 1379 1380 1381 1382
        virPCIDevicePtr pci =
            virPCIDeviceNew(dev->source.subsys.u.pci.domain,
                            dev->source.subsys.u.pci.bus,
                            dev->source.subsys.u.pci.slot,
                            dev->source.subsys.u.pci.function);
1383 1384 1385 1386

        if (!pci)
            goto done;

1387 1388
        ret = virPCIDeviceFileIterate(pci, virSecuritySELinuxRestoreSecurityPCILabel, mgr);
        virPCIDeviceFree(pci);
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401

        break;
    }

    default:
        ret = 0;
        break;
    }

done:
    return ret;
}

1402

1403
static int
1404 1405
virSecuritySELinuxRestoreSecurityHostdevCapsLabel(virSecurityManagerPtr mgr,
                                                  virDomainHostdevDefPtr dev,
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
                                                  const char *vroot)
{
    int ret = -1;
    char *path;

    switch (dev->source.caps.type) {
    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_STORAGE: {
        if (vroot) {
            if (virAsprintf(&path, "%s/%s", vroot,
                            dev->source.caps.u.storage.block) < 0) {
                virReportOOMError();
                return -1;
            }
        } else {
            if (!(path = strdup(dev->source.caps.u.storage.block))) {
                virReportOOMError();
                return -1;
            }
        }
1425
        ret = virSecuritySELinuxRestoreSecurityFileLabel(mgr, path);
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
        VIR_FREE(path);
        break;
    }

    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_MISC: {
        if (vroot) {
            if (virAsprintf(&path, "%s/%s", vroot,
                            dev->source.caps.u.misc.chardev) < 0) {
                virReportOOMError();
                return -1;
            }
        } else {
            if (!(path = strdup(dev->source.caps.u.misc.chardev))) {
                virReportOOMError();
                return -1;
            }
        }
1443
        ret = virSecuritySELinuxRestoreSecurityFileLabel(mgr, path);
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
        VIR_FREE(path);
        break;
    }

    default:
        ret = 0;
        break;
    }

    return ret;
}


1457
static int
1458
virSecuritySELinuxRestoreSecurityHostdevLabel(virSecurityManagerPtr mgr,
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
                                              virDomainDefPtr def,
                                              virDomainHostdevDefPtr dev,
                                              const char *vroot)

{
    virSecurityLabelDefPtr secdef;

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

    if (secdef->norelabel)
        return 0;

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

1477
    case VIR_DOMAIN_HOSTDEV_MODE_CAPABILITIES:
1478
        return virSecuritySELinuxRestoreSecurityHostdevCapsLabel(mgr, dev, vroot);
1479

1480 1481 1482 1483 1484 1485
    default:
        return 0;
    }
}


1486
static int
1487
virSecuritySELinuxSetSecurityChardevLabel(virDomainDefPtr def,
1488 1489
                                          virDomainChrDefPtr dev,
                                          virDomainChrSourceDefPtr dev_source)
1490 1491

{
1492 1493 1494
    virSecurityLabelDefPtr seclabel;
    virSecurityDeviceLabelDefPtr chr_seclabel = NULL;
    char *imagelabel = NULL;
1495 1496 1497
    char *in = NULL, *out = NULL;
    int ret = -1;

1498 1499
    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (seclabel == NULL)
1500 1501
        return -1;

1502 1503 1504 1505 1506
    if (dev)
        chr_seclabel = virDomainChrDefGetSecurityLabelDef(dev,
                                                          SECURITY_SELINUX_NAME);

    if (seclabel->norelabel || (chr_seclabel && chr_seclabel->norelabel))
1507 1508
        return 0;

1509 1510 1511 1512 1513 1514
    if (chr_seclabel)
        imagelabel = chr_seclabel->label;
    if (!imagelabel)
        imagelabel = seclabel->imagelabel;

    switch (dev_source->type) {
1515 1516
    case VIR_DOMAIN_CHR_TYPE_DEV:
    case VIR_DOMAIN_CHR_TYPE_FILE:
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
        ret = virSecuritySELinuxSetFilecon(dev_source->data.file.path,
                                           imagelabel);
        break;

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

    case VIR_DOMAIN_CHR_TYPE_PIPE:
1531 1532
        if ((virAsprintf(&in, "%s.in", dev_source->data.file.path) < 0) ||
            (virAsprintf(&out, "%s.out", dev_source->data.file.path) < 0)) {
1533 1534 1535 1536
            virReportOOMError();
            goto done;
        }
        if (virFileExists(in) && virFileExists(out)) {
1537 1538
            if ((virSecuritySELinuxSetFilecon(in, imagelabel) < 0) ||
                (virSecuritySELinuxSetFilecon(out, imagelabel) < 0)) {
1539
                goto done;
1540
            }
1541 1542
        } else if (virSecuritySELinuxSetFilecon(dev_source->data.file.path,
                                                imagelabel) < 0) {
1543
            goto done;
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
        }
        ret = 0;
        break;

    default:
        ret = 0;
        break;
    }

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

static int
1560 1561
virSecuritySELinuxRestoreSecurityChardevLabel(virSecurityManagerPtr mgr,
                                              virDomainDefPtr def,
1562 1563
                                              virDomainChrDefPtr dev,
                                              virDomainChrSourceDefPtr dev_source)
1564 1565

{
1566 1567
    virSecurityLabelDefPtr seclabel;
    virSecurityDeviceLabelDefPtr chr_seclabel = NULL;
1568 1569 1570
    char *in = NULL, *out = NULL;
    int ret = -1;

1571 1572
    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (seclabel == NULL)
1573 1574
        return -1;

1575 1576 1577 1578
    if (dev)
        chr_seclabel = virDomainChrDefGetSecurityLabelDef(dev,
                                                          SECURITY_SELINUX_NAME);
    if (seclabel->norelabel || (chr_seclabel && chr_seclabel->norelabel))
1579 1580
        return 0;

1581
    switch (dev_source->type) {
1582 1583
    case VIR_DOMAIN_CHR_TYPE_DEV:
    case VIR_DOMAIN_CHR_TYPE_FILE:
1584
        if (virSecuritySELinuxRestoreSecurityFileLabel(mgr, dev_source->data.file.path) < 0)
1585 1586
            goto done;
        ret = 0;
1587
        break;
1588 1589 1590

    case VIR_DOMAIN_CHR_TYPE_UNIX:
        if (!dev_source->data.nix.listen) {
1591
            if (virSecuritySELinuxRestoreSecurityFileLabel(mgr, dev_source->data.file.path) < 0)
1592 1593 1594 1595 1596
                goto done;
        }
        ret = 0;
        break;

1597
    case VIR_DOMAIN_CHR_TYPE_PIPE:
1598 1599
        if ((virAsprintf(&out, "%s.out", dev_source->data.file.path) < 0) ||
            (virAsprintf(&in, "%s.in", dev_source->data.file.path) < 0)) {
1600 1601 1602
            virReportOOMError();
            goto done;
        }
1603
        if (virFileExists(in) && virFileExists(out)) {
1604 1605
            if ((virSecuritySELinuxRestoreSecurityFileLabel(mgr, out) < 0) ||
                (virSecuritySELinuxRestoreSecurityFileLabel(mgr, in) < 0)) {
1606 1607
                goto done;
            }
1608
        } else if (virSecuritySELinuxRestoreSecurityFileLabel(mgr, dev_source->data.file.path) < 0) {
1609
            goto done;
1610
        }
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
        ret = 0;
        break;

    default:
        ret = 0;
        break;
    }

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


static int
1627 1628
virSecuritySELinuxRestoreSecurityChardevCallback(virDomainDefPtr def,
                                                 virDomainChrDefPtr dev,
1629
                                                 void *opaque)
1630
{
1631 1632
    virSecurityManagerPtr mgr = opaque;

1633 1634 1635 1636 1637
    /* 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;

1638
    return virSecuritySELinuxRestoreSecurityChardevLabel(mgr, def, dev,
1639
                                                         &dev->source);
1640 1641 1642
}


E
Eric Blake 已提交
1643
static int
1644 1645
virSecuritySELinuxRestoreSecuritySmartcardCallback(virDomainDefPtr def,
                                                   virDomainSmartcardDefPtr dev,
1646
                                                   void *opaque)
E
Eric Blake 已提交
1647
{
1648
    virSecurityManagerPtr mgr = opaque;
E
Eric Blake 已提交
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
    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;
1659
        return virSecuritySELinuxRestoreSecurityFileLabel(mgr, database);
E
Eric Blake 已提交
1660 1661

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

    default:
1665 1666 1667
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown smartcard type %d"),
                       dev->type);
E
Eric Blake 已提交
1668 1669 1670 1671 1672 1673 1674
        return -1;
    }

    return 0;
}


1675
static int
1676
virSecuritySELinuxRestoreSecurityAllLabel(virSecurityManagerPtr mgr,
1677 1678
                                          virDomainDefPtr def,
                                          int migrated ATTRIBUTE_UNUSED)
1679
{
1680
    virSecurityLabelDefPtr secdef;
1681
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
1682 1683
    int i;
    int rc = 0;
1684

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

1687 1688 1689 1690
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        return -1;

1691
    if (secdef->norelabel || data->skipAllLabel)
1692 1693
        return 0;

1694
    for (i = 0 ; i < def->nhostdevs ; i++) {
1695 1696
        if (virSecuritySELinuxRestoreSecurityHostdevLabel(mgr,
                                                          def,
1697 1698
                                                          def->hostdevs[i],
                                                          NULL) < 0)
1699
            rc = -1;
1700
    }
1701
    for (i = 0 ; i < def->ndisks ; i++) {
1702 1703 1704 1705
        if (virSecuritySELinuxRestoreSecurityImageLabelInt(mgr,
                                                           def,
                                                           def->disks[i],
                                                           migrated) < 0)
1706 1707
            rc = -1;
    }
1708

1709
    if (virDomainChrDefForeach(def,
1710
                               false,
1711
                               virSecuritySELinuxRestoreSecurityChardevCallback,
1712
                               mgr) < 0)
1713 1714
        rc = -1;

1715
    if (virDomainSmartcardDefForeach(def,
E
Eric Blake 已提交
1716
                                     false,
1717
                                     virSecuritySELinuxRestoreSecuritySmartcardCallback,
1718
                                     mgr) < 0)
E
Eric Blake 已提交
1719 1720
        rc = -1;

1721
    if (def->os.kernel &&
1722
        virSecuritySELinuxRestoreSecurityFileLabel(mgr, def->os.kernel) < 0)
1723 1724
        rc = -1;

1725
    if (def->os.initrd &&
1726
        virSecuritySELinuxRestoreSecurityFileLabel(mgr, def->os.initrd) < 0)
1727 1728
        rc = -1;

1729 1730 1731 1732
    return rc;
}

static int
1733
virSecuritySELinuxReleaseSecurityLabel(virSecurityManagerPtr mgr,
1734
                                       virDomainDefPtr def)
1735
{
1736 1737 1738 1739 1740
    virSecurityLabelDefPtr secdef;

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

1742 1743 1744 1745
    if (secdef->type == VIR_DOMAIN_SECLABEL_DYNAMIC) {
        if (secdef->label != NULL) {
            context_t con = context_new(secdef->label);
            if (con) {
1746
                virSecuritySELinuxMCSRemove(mgr, context_range_get(con));
1747 1748 1749 1750 1751 1752
                context_free(con);
            }
        }
        VIR_FREE(secdef->label);
        if (!secdef->baselabel)
            VIR_FREE(secdef->model);
1753 1754 1755
    }
    VIR_FREE(secdef->imagelabel);

1756
    return 0;
1757 1758
}

1759 1760

static int
1761 1762 1763
virSecuritySELinuxSetSavedStateLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                     virDomainDefPtr def,
                                     const char *savefile)
1764
{
1765 1766 1767 1768 1769
    virSecurityLabelDefPtr secdef;

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

1771
    if (secdef->norelabel)
1772 1773
        return 0;

1774
    return virSecuritySELinuxSetFilecon(savefile, secdef->imagelabel);
1775 1776 1777 1778
}


static int
1779
virSecuritySELinuxRestoreSavedStateLabel(virSecurityManagerPtr mgr,
1780 1781
                                         virDomainDefPtr def,
                                         const char *savefile)
1782
{
1783 1784 1785 1786 1787
    virSecurityLabelDefPtr secdef;

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

1789
    if (secdef->norelabel)
1790 1791
        return 0;

1792
    return virSecuritySELinuxRestoreSecurityFileLabel(mgr, savefile);
1793 1794 1795
}


1796
static int
1797 1798
virSecuritySELinuxSecurityVerify(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                 virDomainDefPtr def)
1799
{
1800 1801 1802 1803 1804 1805
    virSecurityLabelDefPtr secdef;

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

1806
    if (!STREQ(SECURITY_SELINUX_NAME, secdef->model)) {
1807 1808 1809 1810
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "'%s' model configured for domain, but "
                         "hypervisor driver is '%s'."),
1811
                       secdef->model, SECURITY_SELINUX_NAME);
1812 1813 1814
        return -1;
    }

1815 1816
    if (secdef->type == VIR_DOMAIN_SECLABEL_STATIC) {
        if (security_check_context(secdef->label) != 0) {
1817 1818
            virReportError(VIR_ERR_XML_ERROR,
                           _("Invalid security label %s"), secdef->label);
1819 1820 1821 1822 1823 1824
            return -1;
        }
    }
    return 0;
}

1825
static int
1826
virSecuritySELinuxSetSecurityProcessLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
1827
                                          virDomainDefPtr def)
1828 1829
{
    /* TODO: verify DOI */
1830 1831 1832 1833 1834
    virSecurityLabelDefPtr secdef;

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

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

1839
    VIR_DEBUG("label=%s", secdef->label);
1840
    if (!STREQ(SECURITY_SELINUX_NAME, secdef->model)) {
1841 1842 1843 1844
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "'%s' model configured for domain, but "
                         "hypervisor driver is '%s'."),
1845
                       secdef->model, SECURITY_SELINUX_NAME);
1846
        if (security_getenforce() == 1)
1847
            return -1;
1848 1849
    }

M
Martin Kletzander 已提交
1850
    if (setexeccon_raw(secdef->label) == -1) {
1851
        virReportSystemError(errno,
1852 1853
                             _("unable to set security context '%s'"),
                             secdef->label);
1854
        if (security_getenforce() == 1)
1855
            return -1;
1856 1857
    }

1858 1859 1860
    return 0;
}

1861
static int
1862
virSecuritySELinuxSetSecurityDaemonSocketLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
1863
                                               virDomainDefPtr def)
1864 1865
{
    /* TODO: verify DOI */
1866
    virSecurityLabelDefPtr secdef;
1867
    security_context_t scon = NULL;
1868
    char *str = NULL;
1869 1870
    int rc = -1;

1871 1872 1873 1874 1875
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        return -1;

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

1878
    if (!STREQ(SECURITY_SELINUX_NAME, secdef->model)) {
1879 1880 1881 1882
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "'%s' model configured for domain, but "
                         "hypervisor driver is '%s'."),
1883
                       secdef->model, SECURITY_SELINUX_NAME);
1884 1885 1886
        goto done;
    }

M
Martin Kletzander 已提交
1887
    if (getcon_raw(&scon) == -1) {
1888 1889 1890 1891 1892 1893
        virReportSystemError(errno,
                             _("unable to get current process context '%s'"),
                             secdef->label);
        goto done;
    }

1894
    if (!(str = virSecuritySELinuxContextAddRange(secdef->label, scon)))
1895 1896
        goto done;

1897 1898
    VIR_DEBUG("Setting VM %s socket context %s", def->name, str);
    if (setsockcreatecon_raw(str) == -1) {
1899
        virReportSystemError(errno,
1900
                             _("unable to set socket security context '%s'"), str);
1901 1902 1903 1904 1905 1906 1907 1908 1909
        goto done;
    }

    rc = 0;
done:

    if (security_getenforce() != 1)
        rc = 0;
    freecon(scon);
1910
    VIR_FREE(str);
1911 1912 1913
    return rc;
}

1914
static int
1915
virSecuritySELinuxSetSecuritySocketLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
1916
                                         virDomainDefPtr vm)
1917
{
1918
    virSecurityLabelDefPtr secdef;
1919 1920
    int rc = -1;

1921 1922 1923 1924
    secdef = virDomainDefGetSecurityLabelDef(vm, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        return -1;

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

1928
    if (!STREQ(SECURITY_SELINUX_NAME, secdef->model)) {
1929 1930 1931 1932
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label driver mismatch: "
                         "'%s' model configured for domain, but "
                         "hypervisor driver is '%s'."),
1933
                       secdef->model, SECURITY_SELINUX_NAME);
1934 1935 1936 1937
        goto done;
    }

    VIR_DEBUG("Setting VM %s socket context %s",
1938
              vm->name, secdef->label);
M
Martin Kletzander 已提交
1939
    if (setsockcreatecon_raw(secdef->label) == -1) {
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
        virReportSystemError(errno,
                             _("unable to set socket security context '%s'"),
                             secdef->label);
        goto done;
    }

    rc = 0;

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

    return rc;
}

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

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

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

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

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

1989 1990

static int
1991 1992 1993
virSecuritySELinuxSetSecurityChardevCallback(virDomainDefPtr def,
                                             virDomainChrDefPtr dev,
                                             void *opaque ATTRIBUTE_UNUSED)
1994
{
1995 1996 1997 1998 1999
    /* 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;

2000
    return virSecuritySELinuxSetSecurityChardevLabel(def, dev, &dev->source);
2001 2002 2003
}


E
Eric Blake 已提交
2004
static int
2005 2006 2007
virSecuritySELinuxSetSecuritySmartcardCallback(virDomainDefPtr def,
                                               virDomainSmartcardDefPtr dev,
                                               void *opaque)
E
Eric Blake 已提交
2008 2009
{
    const char *database;
2010 2011
    virSecurityManagerPtr mgr = opaque;
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
E
Eric Blake 已提交
2012 2013 2014 2015 2016 2017 2018 2019 2020

    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;
2021
        return virSecuritySELinuxSetFilecon(database, data->content_context);
E
Eric Blake 已提交
2022 2023

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

    default:
2027 2028 2029
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown smartcard type %d"),
                       dev->type);
E
Eric Blake 已提交
2030 2031 2032 2033 2034 2035 2036
        return -1;
    }

    return 0;
}


2037
static int
2038 2039 2040
virSecuritySELinuxSetSecurityAllLabel(virSecurityManagerPtr mgr,
                                      virDomainDefPtr def,
                                      const char *stdin_path)
2041 2042
{
    int i;
2043 2044 2045 2046 2047 2048
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
    virSecurityLabelDefPtr secdef;

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

2050
    if (secdef->norelabel || data->skipAllLabel)
2051 2052
        return 0;

2053
    for (i = 0 ; i < def->ndisks ; i++) {
2054
        /* XXX fixme - we need to recursively label the entire tree :-( */
2055
        if (def->disks[i]->type == VIR_DOMAIN_DISK_TYPE_DIR) {
2056
            VIR_WARN("Unable to relabel directory tree %s for disk %s",
2057
                     def->disks[i]->src, def->disks[i]->dst);
2058
            continue;
2059
        }
2060
        if (virSecuritySELinuxSetSecurityImageLabel(mgr,
2061
                                         def, def->disks[i]) < 0)
2062 2063
            return -1;
    }
2064
    /* XXX fixme process  def->fss if relabel == true */
2065

2066
    for (i = 0 ; i < def->nhostdevs ; i++) {
2067
        if (virSecuritySELinuxSetSecurityHostdevLabel(mgr,
2068 2069 2070
                                                      def,
                                                      def->hostdevs[i],
                                                      NULL) < 0)
2071
            return -1;
2072 2073
    }

2074
    if (virDomainChrDefForeach(def,
2075
                               true,
2076
                               virSecuritySELinuxSetSecurityChardevCallback,
2077
                               NULL) < 0)
2078 2079
        return -1;

2080
    if (virDomainSmartcardDefForeach(def,
E
Eric Blake 已提交
2081
                                     true,
2082
                                     virSecuritySELinuxSetSecuritySmartcardCallback,
2083
                                     mgr) < 0)
E
Eric Blake 已提交
2084 2085
        return -1;

2086
    if (def->os.kernel &&
2087
        virSecuritySELinuxSetFilecon(def->os.kernel, data->content_context) < 0)
2088 2089
        return -1;

2090
    if (def->os.initrd &&
2091
        virSecuritySELinuxSetFilecon(def->os.initrd, data->content_context) < 0)
2092 2093
        return -1;

2094
    if (stdin_path) {
2095
        if (virSecuritySELinuxSetFilecon(stdin_path, data->content_context) < 0 &&
2096 2097 2098 2099
            virStorageFileIsSharedFSType(stdin_path,
                                         VIR_STORAGE_FILE_SHFS_NFS) != 1)
            return -1;
    }
2100

2101 2102 2103
    return 0;
}

2104
static int
2105 2106 2107
virSecuritySELinuxSetImageFDLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                  virDomainDefPtr def,
                                  int fd)
2108
{
2109 2110 2111 2112 2113
    virSecurityLabelDefPtr secdef;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        return -1;
2114 2115 2116 2117

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

2118
    return virSecuritySELinuxFSetFilecon(fd, secdef->imagelabel);
2119 2120
}

2121
static int
2122
virSecuritySELinuxSetTapFDLabel(virSecurityManagerPtr mgr,
2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149
                                virDomainDefPtr def,
                                int fd)
{
    struct stat buf;
    security_context_t fcon = NULL;
    virSecurityLabelDefPtr secdef;
    char *str = NULL;
    int rc = -1;

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

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

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

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

2150
    if (getContext(mgr, "/dev/tap.*", buf.st_mode, &fcon) < 0) {
2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot lookup default selinux label for tap fd %d"), fd);
        goto cleanup;
    }

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

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

2168 2169 2170 2171
static char *
virSecuritySELinuxGenImageLabel(virSecurityManagerPtr mgr,
                                virDomainDefPtr def)
{
2172
    virSecurityLabelDefPtr secdef;
2173 2174 2175 2176 2177 2178
    virSecuritySELinuxDataPtr data = virSecurityManagerGetPrivateData(mgr);
    const char *range;
    context_t ctx = NULL;
    char *label = NULL;
    const char *mcs = NULL;

2179 2180 2181 2182
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME);
    if (secdef == NULL)
        goto cleanup;

2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195
    if (secdef->label) {
        ctx = context_new(secdef->label);
        if (!ctx) {
            virReportOOMError();
            goto cleanup;
        }
        range = context_range_get(ctx);
        if (range) {
            mcs = strdup(range);
            if (!mcs) {
                virReportOOMError();
                goto cleanup;
            }
2196 2197
            if (!(label = virSecuritySELinuxGenNewContext(data->file_context,
                                                          mcs, true)))
2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
                goto cleanup;
        }
    }

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

2208 2209 2210 2211
static char *
virSecuritySELinuxGetSecurityMountOptions(virSecurityManagerPtr mgr,
                                          virDomainDefPtr def)
{
2212
    char *opts = NULL;
2213 2214
    virSecurityLabelDefPtr secdef;

2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226
    if ((secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_SELINUX_NAME))) {
        if (!secdef->imagelabel)
            secdef->imagelabel = virSecuritySELinuxGenImageLabel(mgr, def);

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

2228 2229 2230 2231
    if (!opts &&
        !(opts = strdup(""))) {
        virReportOOMError();
        return NULL;
2232 2233
    }

2234 2235
    VIR_DEBUG("imageLabel=%s opts=%s",
              secdef ? secdef->imagelabel : "(null)", opts);
2236 2237 2238
    return opts;
}

2239
virSecurityDriver virSecurityDriverSELinux = {
2240 2241
    .privateDataLen                     = sizeof(virSecuritySELinuxData),
    .name                               = SECURITY_SELINUX_NAME,
2242 2243 2244
    .probe                              = virSecuritySELinuxSecurityDriverProbe,
    .open                               = virSecuritySELinuxSecurityDriverOpen,
    .close                              = virSecuritySELinuxSecurityDriverClose,
2245

2246 2247
    .getModel                           = virSecuritySELinuxSecurityGetModel,
    .getDOI                             = virSecuritySELinuxSecurityGetDOI,
2248

2249
    .domainSecurityVerify               = virSecuritySELinuxSecurityVerify,
2250

2251 2252
    .domainSetSecurityImageLabel        = virSecuritySELinuxSetSecurityImageLabel,
    .domainRestoreSecurityImageLabel    = virSecuritySELinuxRestoreSecurityImageLabel,
2253

2254 2255 2256
    .domainSetSecurityDaemonSocketLabel = virSecuritySELinuxSetSecurityDaemonSocketLabel,
    .domainSetSecuritySocketLabel       = virSecuritySELinuxSetSecuritySocketLabel,
    .domainClearSecuritySocketLabel     = virSecuritySELinuxClearSecuritySocketLabel,
2257

2258 2259 2260
    .domainGenSecurityLabel             = virSecuritySELinuxGenSecurityLabel,
    .domainReserveSecurityLabel         = virSecuritySELinuxReserveSecurityLabel,
    .domainReleaseSecurityLabel         = virSecuritySELinuxReleaseSecurityLabel,
2261

2262 2263
    .domainGetSecurityProcessLabel      = virSecuritySELinuxGetSecurityProcessLabel,
    .domainSetSecurityProcessLabel      = virSecuritySELinuxSetSecurityProcessLabel,
2264

2265 2266
    .domainSetSecurityAllLabel          = virSecuritySELinuxSetSecurityAllLabel,
    .domainRestoreSecurityAllLabel      = virSecuritySELinuxRestoreSecurityAllLabel,
2267

2268 2269
    .domainSetSecurityHostdevLabel      = virSecuritySELinuxSetSecurityHostdevLabel,
    .domainRestoreSecurityHostdevLabel  = virSecuritySELinuxRestoreSecurityHostdevLabel,
2270

2271 2272
    .domainSetSavedStateLabel           = virSecuritySELinuxSetSavedStateLabel,
    .domainRestoreSavedStateLabel       = virSecuritySELinuxRestoreSavedStateLabel,
2273

2274
    .domainSetSecurityImageFDLabel      = virSecuritySELinuxSetImageFDLabel,
2275
    .domainSetSecurityTapFDLabel        = virSecuritySELinuxSetTapFDLabel,
2276

2277
    .domainGetSecurityMountOptions      = virSecuritySELinuxGetSecurityMountOptions,
2278
};