security_dac.c 55.8 KB
Newer Older
1
/*
2
 * Copyright (C) 2010-2014 Red Hat, Inc.
3 4 5 6 7 8 9 10 11 12 13 14
 *
 * 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.
 *
 * 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
 * <http://www.gnu.org/licenses/>.
17 18 19 20 21 22 23 24 25
 *
 * POSIX DAC security driver
 */

#include <config.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

26 27 28 29 30
#ifdef  __FreeBSD__
# include <sys/sysctl.h>
# include <sys/user.h>
#endif

31
#include "security_dac.h"
32
#include "virerror.h"
33
#include "virfile.h"
34
#include "viralloc.h"
35
#include "virlog.h"
36
#include "virpci.h"
37
#include "virusb.h"
38
#include "virscsi.h"
39
#include "virscsivhost.h"
40
#include "virstoragefile.h"
41
#include "virstring.h"
M
Martin Kletzander 已提交
42
#include "virutil.h"
43 44

#define VIR_FROM_THIS VIR_FROM_SECURITY
45 46 47

VIR_LOG_INIT("security.security_dac");

48
#define SECURITY_DAC_NAME "dac"
49 50 51 52 53 54 55

typedef struct _virSecurityDACData virSecurityDACData;
typedef virSecurityDACData *virSecurityDACDataPtr;

struct _virSecurityDACData {
    uid_t user;
    gid_t group;
56 57
    gid_t *groups;
    int ngroups;
58
    bool dynamicOwnership;
59
    char *baselabel;
60
    virSecurityManagerDACChownCallback chownCallback;
61 62
};

63 64 65 66 67 68 69 70
typedef struct _virSecurityDACCallbackData virSecurityDACCallbackData;
typedef virSecurityDACCallbackData *virSecurityDACCallbackDataPtr;

struct _virSecurityDACCallbackData {
    virSecurityManagerPtr manager;
    virSecurityLabelDefPtr secdef;
};

71 72 73
typedef struct _virSecurityDACChownItem virSecurityDACChownItem;
typedef virSecurityDACChownItem *virSecurityDACChownItemPtr;
struct _virSecurityDACChownItem {
74
    char *path;
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
    const virStorageSource *src;
    uid_t uid;
    gid_t gid;
};

typedef struct _virSecurityDACChownList virSecurityDACChownList;
typedef virSecurityDACChownList *virSecurityDACChownListPtr;
struct _virSecurityDACChownList {
    virSecurityDACDataPtr priv;
    virSecurityDACChownItemPtr *items;
    size_t nItems;
};


virThreadLocal chownList;

static int
virSecurityDACChownListAppend(virSecurityDACChownListPtr list,
                              const char *path,
                              const virStorageSource *src,
                              uid_t uid,
                              gid_t gid)
{
98 99 100
    int ret = -1;
    char *tmp = NULL;
    virSecurityDACChownItemPtr item = NULL;
101 102 103 104

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

105 106 107 108
    if (VIR_STRDUP(tmp, path) < 0)
        goto cleanup;

    item->path = tmp;
109 110 111 112
    item->src = src;
    item->uid = uid;
    item->gid = gid;

113 114
    if (VIR_APPEND_ELEMENT(list->items, list->nItems, item) < 0)
        goto cleanup;
115

116 117 118 119 120 121 122
    tmp = NULL;

    ret = 0;
 cleanup:
    VIR_FREE(tmp);
    VIR_FREE(item);
    return ret;
123 124 125 126 127 128 129 130 131 132 133
}

static void
virSecurityDACChownListFree(void *opaque)
{
    virSecurityDACChownListPtr list = opaque;
    size_t i;

    if (!list)
        return;

134 135
    for (i = 0; i < list->nItems; i++) {
        VIR_FREE(list->items[i]->path);
136
        VIR_FREE(list->items[i]);
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 208 209 210 211 212
    VIR_FREE(list);
}


/**
 * virSecurityDACTransactionAppend:
 * @path: Path to chown
 * @src: disk source to chown
 * @uid: user ID
 * @gid: group ID
 *
 * Appends an entry onto transaction list.
 *
 * Returns: 1 in case of successful append
 *          0 if there is no transaction enabled
 *         -1 otherwise.
 */
static int
virSecurityDACTransactionAppend(const char *path,
                                const virStorageSource *src,
                                uid_t uid,
                                gid_t gid)
{
    virSecurityDACChownListPtr list = virThreadLocalGet(&chownList);
    if (!list)
        return 0;

    if (virSecurityDACChownListAppend(list, path, src, uid, gid) < 0)
        return -1;

    return 1;
}


static int virSecurityDACSetOwnershipInternal(const virSecurityDACData *priv,
                                              const virStorageSource *src,
                                              const char *path,
                                              uid_t uid,
                                              gid_t gid);

/**
 * virSecurityDACTransactionRun:
 * @pid: process pid
 * @opaque: opaque data
 *
 * This is the callback that runs in the same namespace as the domain we are
 * relabelling. For given transaction (@opaque) it relabels all the paths on
 * the list.
 *
 * Returns: 0 on success
 *         -1 otherwise.
 */
static int
virSecurityDACTransactionRun(pid_t pid ATTRIBUTE_UNUSED,
                             void *opaque)
{
    virSecurityDACChownListPtr list = opaque;
    size_t i;

    for (i = 0; i < list->nItems; i++) {
        virSecurityDACChownItemPtr item = list->items[i];

        /* TODO Implement rollback */
        if (virSecurityDACSetOwnershipInternal(list->priv,
                                               item->src,
                                               item->path,
                                               item->uid,
                                               item->gid) < 0)
            return -1;
    }

    return 0;
}


213 214 215 216 217
/* returns -1 on error, 0 on success */
int
virSecurityDACSetUserAndGroup(virSecurityManagerPtr mgr,
                              uid_t user,
                              gid_t group)
218 219 220 221
{
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
    priv->user = user;
    priv->group = group;
222

223
    if (virAsprintf(&priv->baselabel, "+%u:+%u",
224 225 226 227 228
                    (unsigned int) user,
                    (unsigned int) group) < 0)
        return -1;

    return 0;
229 230
}

O
Osier Yang 已提交
231 232 233
void
virSecurityDACSetDynamicOwnership(virSecurityManagerPtr mgr,
                                  bool dynamicOwnership)
234 235 236 237 238
{
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
    priv->dynamicOwnership = dynamicOwnership;
}

239 240 241 242 243 244 245 246
void
virSecurityDACSetChownCallback(virSecurityManagerPtr mgr,
                               virSecurityManagerDACChownCallback chownCallback)
{
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
    priv->chownCallback = chownCallback;
}

247
/* returns 1 if label isn't found, 0 on success, -1 on error */
O
Osier Yang 已提交
248
static int
249
ATTRIBUTE_NONNULL(2) ATTRIBUTE_NONNULL(3)
250 251
virSecurityDACParseIds(virSecurityLabelDefPtr seclabel,
                       uid_t *uidPtr, gid_t *gidPtr)
252
{
253
    if (!seclabel || !seclabel->label)
254
        return 1;
255

256
    if (virParseOwnershipIds(seclabel->label, uidPtr, gidPtr) < 0)
257 258 259 260 261
        return -1;

    return 0;
}

O
Osier Yang 已提交
262
static int
263
ATTRIBUTE_NONNULL(3) ATTRIBUTE_NONNULL(4)
264 265
virSecurityDACGetIds(virSecurityLabelDefPtr seclabel,
                     virSecurityDACDataPtr priv,
266 267
                     uid_t *uidPtr, gid_t *gidPtr,
                     gid_t **groups, int *ngroups)
268
{
269 270
    int ret;

271 272 273 274 275
    if (groups)
        *groups = priv ? priv->groups : NULL;
    if (ngroups)
        *ngroups = priv ? priv->ngroups : 0;

276
    if ((ret = virSecurityDACParseIds(seclabel, uidPtr, gidPtr)) <= 0)
277 278 279
        return ret;

    if (!priv) {
280 281
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("DAC seclabel couldn't be determined"));
282 283 284
        return -1;
    }

285 286
    *uidPtr = priv->user;
    *gidPtr = priv->group;
287 288

    return 0;
289 290
}

291 292

/* returns 1 if label isn't found, 0 on success, -1 on error */
O
Osier Yang 已提交
293
static int
294
ATTRIBUTE_NONNULL(2) ATTRIBUTE_NONNULL(3)
295
virSecurityDACParseImageIds(virSecurityLabelDefPtr seclabel,
O
Osier Yang 已提交
296
                            uid_t *uidPtr, gid_t *gidPtr)
297
{
298
    if (!seclabel || !seclabel->imagelabel)
299
        return 1;
300

301
    if (virParseOwnershipIds(seclabel->imagelabel, uidPtr, gidPtr) < 0)
302 303 304 305 306
        return -1;

    return 0;
}

O
Osier Yang 已提交
307
static int
308
ATTRIBUTE_NONNULL(3) ATTRIBUTE_NONNULL(4)
309 310
virSecurityDACGetImageIds(virSecurityLabelDefPtr seclabel,
                          virSecurityDACDataPtr priv,
O
Osier Yang 已提交
311
                          uid_t *uidPtr, gid_t *gidPtr)
312
{
313 314
    int ret;

315
    if ((ret = virSecurityDACParseImageIds(seclabel, uidPtr, gidPtr)) <= 0)
316 317 318
        return ret;

    if (!priv) {
319 320
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("DAC imagelabel couldn't be determined"));
321
        return -1;
322
    }
323

324 325
    *uidPtr = priv->user;
    *gidPtr = priv->group;
326 327

    return 0;
328 329
}

330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
/**
 * virSecurityDACRememberLabel:
 * @priv: driver's private data
 * @path: path to the file
 * @uid: user owning the @path
 * @gid: group owning the @path
 *
 * Remember the owner of @path (represented by @uid:@gid).
 *
 * Returns: 0 on success, -1 on failure
 */
static int
virSecurityDACRememberLabel(virSecurityDACDataPtr priv ATTRIBUTE_UNUSED,
                            const char *path ATTRIBUTE_UNUSED,
                            uid_t uid ATTRIBUTE_UNUSED,
                            gid_t gid ATTRIBUTE_UNUSED)
{
    return 0;
}

/**
 * virSecurityDACRecallLabel:
 * @priv: driver's private data
 * @path: path to the file
 * @uid: user owning the @path
 * @gid: group owning the @path
 *
 * Recall the previously recorded owner for the @path. However, it may happen
 * that @path is still in use (e.g. by another domain). In that case, 1 is
 * returned and caller should not relabel the @path.
 *
 * Returns: 1 if @path is still in use (@uid and @gid not touched)
 *          0 if @path should be restored (@uid and @gid set)
 *         -1 on failure (@uid and @gid not touched)
 */
static int
virSecurityDACRecallLabel(virSecurityDACDataPtr priv ATTRIBUTE_UNUSED,
                          const char *path ATTRIBUTE_UNUSED,
                          uid_t *uid ATTRIBUTE_UNUSED,
                          gid_t *gid ATTRIBUTE_UNUSED)
{
    return 0;
}
373

374
static virSecurityDriverStatus
375
virSecurityDACProbe(const char *virtDriver ATTRIBUTE_UNUSED)
376 377 378 379 380 381 382
{
    return SECURITY_DRIVER_ENABLE;
}

static int
virSecurityDACOpen(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED)
{
383 384 385 386 387 388 389
    if (virThreadLocalInit(&chownList,
                           virSecurityDACChownListFree) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to initialize thread local variable"));
        return -1;
    }

390 391 392 393
    return 0;
}

static int
394
virSecurityDACClose(virSecurityManagerPtr mgr)
395
{
396 397
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
    VIR_FREE(priv->groups);
398
    VIR_FREE(priv->baselabel);
399 400 401 402
    return 0;
}


O
Osier Yang 已提交
403 404
static const char *
virSecurityDACGetModel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED)
405
{
406
    return SECURITY_DAC_NAME;
407 408
}

O
Osier Yang 已提交
409 410
static const char *
virSecurityDACGetDOI(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED)
411 412 413 414
{
    return "0";
}

415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
static int
virSecurityDACPreFork(virSecurityManagerPtr mgr)
{
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
    int ngroups;

    VIR_FREE(priv->groups);
    priv->ngroups = 0;
    if ((ngroups = virGetGroupList(priv->user, priv->group,
                                   &priv->groups)) < 0)
        return -1;
    priv->ngroups = ngroups;
    return 0;
}

430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
/**
 * virSecurityDACTransactionStart:
 * @mgr: security manager
 *
 * Starts a new transaction. In transaction nothing is chown()-ed until
 * TransactionCommit() is called. This is implemented as a list that is
 * appended to whenever chown() would be called. Since secdriver APIs
 * can be called from multiple threads (to work over different domains)
 * the pointer to the list is stored in thread local variable.
 *
 * Returns 0 on success,
 *        -1 otherwise.
 */
static int
virSecurityDACTransactionStart(virSecurityManagerPtr mgr)
{
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
    virSecurityDACChownListPtr list;

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

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

    list->priv = priv;

    if (virThreadLocalSet(&chownList, list) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to set thread local variable"));
        VIR_FREE(list);
        return -1;
    }

    return 0;
}

/**
 * virSecurityDACTransactionCommit:
 * @mgr: security manager
 * @pid: domain's PID
 *
 * Enters the @pid namespace (usually @pid refers to a domain) and
 * performs all the chown()-s on the list. Note that the transaction is
 * also freed, therefore new one has to be started after successful
 * return from this function. Also it is considered as error if there's
 * no transaction set and this function is called.
 *
 * Returns: 0 on success,
 *         -1 otherwise.
 */
static int
virSecurityDACTransactionCommit(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                                pid_t pid)
{
    virSecurityDACChownListPtr list;
    int ret = -1;

    list = virThreadLocalGet(&chownList);
    if (!list) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("No transaction is set"));
        goto cleanup;
    }

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

    if (virProcessRunInMountNamespace(pid,
                                      virSecurityDACTransactionRun,
                                      list) < 0)
        goto cleanup;

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

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

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

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


537
static int
538 539
virSecurityDACSetOwnershipInternal(const virSecurityDACData *priv,
                                   const virStorageSource *src,
540 541 542
                                   const char *path,
                                   uid_t uid,
                                   gid_t gid)
543
{
544 545
    int rc;

546 547 548 549 550 551 552 553
    /* Be aware that this function might run in a separate process.
     * Therefore, any driver state changes would be thrown away. */

    if ((rc = virSecurityDACTransactionAppend(path, src, uid, gid)) < 0)
        return -1;
    else if (rc > 0)
        return 0;

554
    VIR_INFO("Setting DAC user and group on '%s' to '%ld:%ld'",
555 556 557 558 559 560 561 562 563 564 565
             NULLSTR(src ? src->path : path), (long) uid, (long) gid);

    if (priv && src && priv->chownCallback) {
        rc = priv->chownCallback(src, uid, gid);
        /* here path is used only for error messages */
        path = NULLSTR(src->path);

        /* on -2 returned an error was already reported */
        if (rc == -2)
            return -1;
    } else {
566 567
        struct stat sb;

568 569 570 571 572 573 574 575 576 577
        if (!path) {
            if (!src || !src->path)
                return 0;

            if (!virStorageSourceIsLocalStorage(src))
                return 0;

            path = src->path;
        }

578 579 580 581
        if (stat(path, &sb) < 0) {
            virReportSystemError(errno, _("unable to stat: %s"), path);
            return -1;
        }
582

583 584 585
        if (sb.st_uid == uid && sb.st_gid == gid) {
            /* nothing to chown */
            return 0;
586
        }
587 588

        rc = chown(path, uid, gid);
589
    }
590

591
    if (rc < 0) {
592
        if (errno == EOPNOTSUPP || errno == EINVAL) {
593 594 595
            VIR_INFO("Setting user and group to '%ld:%ld' on '%s' not "
                     "supported by filesystem",
                     (long) uid, (long) gid, path);
596
        } else if (errno == EPERM) {
597 598 599
            VIR_INFO("Setting user and group to '%ld:%ld' on '%s' not "
                     "permitted",
                     (long) uid, (long) gid, path);
600
        } else if (errno == EROFS) {
601 602 603
            VIR_INFO("Setting user and group to '%ld:%ld' on '%s' not "
                     "possible on readonly filesystem",
                     (long) uid, (long) gid, path);
604
        } else {
605
            virReportSystemError(errno,
606 607 608
                                 _("unable to set user and group to '%ld:%ld' "
                                   "on '%s'"),
                                 (long) uid, (long) gid, path);
609 610 611 612 613 614
            return -1;
        }
    }
    return 0;
}

615

616
static int
617
virSecurityDACSetOwnership(virSecurityDACDataPtr priv,
618
                           virStorageSourcePtr src,
619 620 621
                           const char *path,
                           uid_t uid,
                           gid_t gid)
622
{
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
    struct stat sb;

    if (!path && src && src->path &&
        virStorageSourceIsLocalStorage(src))
        path = src->path;

    if (path) {
        if (stat(path, &sb) < 0) {
            virReportSystemError(errno, _("unable to stat: %s"), path);
            return -1;
        }

        if (virSecurityDACRememberLabel(priv, path, sb.st_uid, sb.st_gid) < 0)
            return -1;
    }

639
    return virSecurityDACSetOwnershipInternal(priv, src, path, uid, gid);
640 641 642 643
}


static int
644 645 646
virSecurityDACRestoreFileLabelInternal(virSecurityDACDataPtr priv,
                                       virStorageSourcePtr src,
                                       const char *path)
647
{
648 649 650 651
    int rv;
    uid_t uid = 0;  /* By default return to root:root */
    gid_t gid = 0;

652 653
    VIR_INFO("Restoring DAC user and group on '%s'",
             NULLSTR(src ? src->path : path));
654

655 656 657 658 659 660 661 662 663 664 665 666 667
    if (!path && src && src->path &&
        virStorageSourceIsLocalStorage(src))
        path = src->path;

    if (path) {
        rv = virSecurityDACRecallLabel(priv, path, &uid, &gid);
        if (rv < 0)
            return -1;
        if (rv > 0)
            return 0;
    }

    return virSecurityDACSetOwnershipInternal(priv, src, path, uid, gid);
668 669 670 671
}


static int
672 673
virSecurityDACRestoreFileLabel(virSecurityDACDataPtr priv,
                               const char *path)
674
{
675
    return virSecurityDACRestoreFileLabelInternal(priv, NULL, path);
676 677 678 679
}


static int
680 681 682
virSecurityDACSetImageLabel(virSecurityManagerPtr mgr,
                            virDomainDefPtr def,
                            virStorageSourcePtr src)
683
{
684
    virSecurityLabelDefPtr secdef;
685
    virSecurityDeviceLabelDefPtr disk_seclabel;
686
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
687 688 689
    uid_t user;
    gid_t group;

690 691 692 693
    if (!priv->dynamicOwnership)
        return 0;

    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_DAC_NAME);
694
    if (secdef && !secdef->relabel)
695
        return 0;
696

697 698
    disk_seclabel = virStorageSourceGetSecurityLabelDef(src,
                                                        SECURITY_DAC_NAME);
699
    if (disk_seclabel && !disk_seclabel->relabel)
700 701 702 703 704 705 706 707 708
        return 0;

    if (disk_seclabel && disk_seclabel->label) {
        if (virParseOwnershipIds(disk_seclabel->label, &user, &group) < 0)
            return -1;
    } else {
        if (virSecurityDACGetImageIds(secdef, priv, &user, &group))
            return -1;
    }
709

710
    return virSecurityDACSetOwnership(priv, src, NULL, user, group);
711 712 713 714
}


static int
715 716 717
virSecurityDACSetDiskLabel(virSecurityManagerPtr mgr,
                           virDomainDefPtr def,
                           virDomainDiskDefPtr disk)
718 719

{
720
    virStorageSourcePtr next;
721

722
    for (next = disk->src; next; next = next->backingStore) {
723
        if (virSecurityDACSetImageLabel(mgr, def, next) < 0)
724 725
            return -1;
    }
726

727
    return 0;
728 729 730 731
}


static int
732 733 734 735
virSecurityDACRestoreImageLabelInt(virSecurityManagerPtr mgr,
                                   virDomainDefPtr def,
                                   virStorageSourcePtr src,
                                   bool migrated)
736 737
{
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
738 739
    virSecurityLabelDefPtr secdef;
    virSecurityDeviceLabelDefPtr disk_seclabel;
740 741 742 743

    if (!priv->dynamicOwnership)
        return 0;

744 745 746 747 748 749 750
    /* Don't restore labels on readoly/shared disks, because other VMs may
     * still be accessing these. Alternatively we could iterate over all
     * running domains and try to figure out if it is in use, but this would
     * not work for clustered filesystems, since we can't see running VMs using
     * the file on other nodes. Safest bet is thus to skip the restore step. */
    if (src->readonly || src->shared)
        return 0;
751

752
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_DAC_NAME);
753
    if (secdef && !secdef->relabel)
754 755
        return 0;

756
    disk_seclabel = virStorageSourceGetSecurityLabelDef(src,
757
                                                        SECURITY_DAC_NAME);
758
    if (disk_seclabel && !disk_seclabel->relabel)
759 760
        return 0;

761 762 763
    /* 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 :-) */
764
    if (migrated) {
765 766 767 768 769 770 771 772 773 774
        int rc = 1;

        if (virStorageSourceIsLocalStorage(src)) {
            if (!src->path)
                return 0;

            if ((rc = virFileIsSharedFS(src->path)) < 0)
                return -1;
        }

775 776
        if (rc == 1) {
            VIR_DEBUG("Skipping image label restore on %s because FS is shared",
777
                      src->path);
778 779 780 781
            return 0;
        }
    }

782
    return virSecurityDACRestoreFileLabelInternal(priv, src, NULL);
783 784 785 786
}


static int
787 788 789
virSecurityDACRestoreImageLabel(virSecurityManagerPtr mgr,
                                virDomainDefPtr def,
                                virStorageSourcePtr src)
790
{
791
    return virSecurityDACRestoreImageLabelInt(mgr, def, src, false);
792 793 794 795
}


static int
796 797 798
virSecurityDACRestoreDiskLabel(virSecurityManagerPtr mgr,
                               virDomainDefPtr def,
                               virDomainDiskDefPtr disk)
799
{
800
    return virSecurityDACRestoreImageLabelInt(mgr, def, disk->src, false);
801 802 803 804
}


static int
805 806
virSecurityDACSetHostdevLabelHelper(const char *file,
                                    void *opaque)
807
{
808 809 810
    virSecurityDACCallbackDataPtr cbdata = opaque;
    virSecurityManagerPtr mgr = cbdata->manager;
    virSecurityLabelDefPtr secdef = cbdata->secdef;
811
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
812 813
    uid_t user;
    gid_t group;
814

815
    if (virSecurityDACGetIds(secdef, priv, &user, &group, NULL, NULL) < 0)
816 817
        return -1;

818
    return virSecurityDACSetOwnership(priv, NULL, file, user, group);
819 820 821
}


822
static int
823 824 825
virSecurityDACSetPCILabel(virPCIDevicePtr dev ATTRIBUTE_UNUSED,
                          const char *file,
                          void *opaque)
826
{
827
    return virSecurityDACSetHostdevLabelHelper(file, opaque);
828 829 830
}


831
static int
832 833 834
virSecurityDACSetUSBLabel(virUSBDevicePtr dev ATTRIBUTE_UNUSED,
                          const char *file,
                          void *opaque)
835
{
836
    return virSecurityDACSetHostdevLabelHelper(file, opaque);
837
}
838

839

840
static int
841 842 843
virSecurityDACSetSCSILabel(virSCSIDevicePtr dev ATTRIBUTE_UNUSED,
                           const char *file,
                           void *opaque)
844
{
845
    return virSecurityDACSetHostdevLabelHelper(file, opaque);
846 847 848
}


849 850 851 852 853 854 855 856 857
static int
virSecurityDACSetHostLabel(virSCSIVHostDevicePtr dev ATTRIBUTE_UNUSED,
                           const char *file,
                           void *opaque)
{
    return virSecurityDACSetHostdevLabelHelper(file, opaque);
}


858
static int
859 860 861 862
virSecurityDACSetHostdevLabel(virSecurityManagerPtr mgr,
                              virDomainDefPtr def,
                              virDomainHostdevDefPtr dev,
                              const char *vroot)
863 864
{
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
865
    virSecurityDACCallbackData cbdata;
866
    virDomainHostdevSubsysUSBPtr usbsrc = &dev->source.subsys.u.usb;
867
    virDomainHostdevSubsysPCIPtr pcisrc = &dev->source.subsys.u.pci;
868
    virDomainHostdevSubsysSCSIPtr scsisrc = &dev->source.subsys.u.scsi;
869
    virDomainHostdevSubsysSCSIVHostPtr hostsrc = &dev->source.subsys.u.scsi_host;
870 871 872 873 874 875 876 877
    int ret = -1;

    if (!priv->dynamicOwnership)
        return 0;

    if (dev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS)
        return 0;

878
    /* Like virSecurityDACSetImageLabel() for a networked disk,
879 880
     * do nothing for an iSCSI hostdev
     */
881 882
    if (dev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI &&
        scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI)
883 884
        return 0;

885 886 887
    cbdata.manager = mgr;
    cbdata.secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_DAC_NAME);

888
    if (cbdata.secdef && !cbdata.secdef->relabel)
889 890
        return 0;

891
    switch ((virDomainHostdevSubsysType) dev->source.subsys.type) {
892
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB: {
893
        virUSBDevicePtr usb;
894

895 896 897
        if (dev->missing)
            return 0;

898
        if (!(usb = virUSBDeviceNew(usbsrc->bus, usbsrc->device, vroot)))
899 900
            goto done;

901
        ret = virUSBDeviceFileIterate(usb,
902
                                      virSecurityDACSetUSBLabel,
903
                                      &cbdata);
904
        virUSBDeviceFree(usb);
905 906 907 908
        break;
    }

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI: {
909
        virPCIDevicePtr pci =
910 911
            virPCIDeviceNew(pcisrc->addr.domain, pcisrc->addr.bus,
                            pcisrc->addr.slot, pcisrc->addr.function);
912 913 914 915

        if (!pci)
            goto done;

916
        if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
917
            char *vfioGroupDev = virPCIDeviceGetIOMMUGroupDev(pci);
918

919 920
            if (!vfioGroupDev) {
                virPCIDeviceFree(pci);
921
                goto done;
922
            }
923
            ret = virSecurityDACSetPCILabel(pci, vfioGroupDev, &cbdata);
924 925
            VIR_FREE(vfioGroupDev);
        } else {
926
            ret = virPCIDeviceFileIterate(pci,
927
                                          virSecurityDACSetPCILabel,
928
                                          &cbdata);
929 930
        }

931
        virPCIDeviceFree(pci);
932 933 934
        break;
    }

935
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI: {
936
        virDomainHostdevSubsysSCSIHostPtr scsihostsrc = &scsisrc->u.host;
937
        virSCSIDevicePtr scsi =
938
            virSCSIDeviceNew(NULL,
939 940
                             scsihostsrc->adapter, scsihostsrc->bus,
                             scsihostsrc->target, scsihostsrc->unit,
941
                             dev->readonly, dev->shareable);
942 943 944 945

        if (!scsi)
            goto done;

946
        ret = virSCSIDeviceFileIterate(scsi,
947
                                       virSecurityDACSetSCSILabel,
948
                                       &cbdata);
949 950 951 952 953
        virSCSIDeviceFree(scsi);

        break;
    }

954
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI_HOST: {
955 956 957 958 959 960 961 962 963 964
        virSCSIVHostDevicePtr host = virSCSIVHostDeviceNew(hostsrc->wwpn);

        if (!host)
            goto done;

        ret = virSCSIVHostDeviceFileIterate(host,
                                            virSecurityDACSetHostLabel,
                                            &cbdata);
        virSCSIVHostDeviceFree(host);
        break;
965 966
    }

967
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_LAST:
968 969 970 971
        ret = 0;
        break;
    }

972
 done:
973 974 975 976 977
    return ret;
}


static int
978 979 980
virSecurityDACRestorePCILabel(virPCIDevicePtr dev ATTRIBUTE_UNUSED,
                              const char *file,
                              void *opaque)
981
{
982 983
    virSecurityManagerPtr mgr = opaque;
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
984
    return virSecurityDACRestoreFileLabel(priv, file);
985 986 987 988
}


static int
989 990 991
virSecurityDACRestoreUSBLabel(virUSBDevicePtr dev ATTRIBUTE_UNUSED,
                              const char *file,
                              void *opaque)
992
{
993 994
    virSecurityManagerPtr mgr = opaque;
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
995
    return virSecurityDACRestoreFileLabel(priv, file);
996 997 998
}


999
static int
1000 1001 1002
virSecurityDACRestoreSCSILabel(virSCSIDevicePtr dev ATTRIBUTE_UNUSED,
                               const char *file,
                               void *opaque)
1003
{
1004 1005
    virSecurityManagerPtr mgr = opaque;
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
1006
    return virSecurityDACRestoreFileLabel(priv, file);
1007 1008 1009
}


1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
static int
virSecurityDACRestoreHostLabel(virSCSIVHostDevicePtr dev ATTRIBUTE_UNUSED,
                               const char *file,
                               void *opaque)
{
    virSecurityManagerPtr mgr = opaque;
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
    return virSecurityDACRestoreFileLabel(priv, file);
}


1021
static int
1022 1023 1024 1025
virSecurityDACRestoreHostdevLabel(virSecurityManagerPtr mgr,
                                  virDomainDefPtr def,
                                  virDomainHostdevDefPtr dev,
                                  const char *vroot)
1026 1027 1028

{
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
1029
    virSecurityLabelDefPtr secdef;
1030
    virDomainHostdevSubsysUSBPtr usbsrc = &dev->source.subsys.u.usb;
1031
    virDomainHostdevSubsysPCIPtr pcisrc = &dev->source.subsys.u.pci;
1032
    virDomainHostdevSubsysSCSIPtr scsisrc = &dev->source.subsys.u.scsi;
1033
    virDomainHostdevSubsysSCSIVHostPtr hostsrc = &dev->source.subsys.u.scsi_host;
1034 1035
    int ret = -1;

1036 1037
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_DAC_NAME);

1038
    if (!priv->dynamicOwnership || (secdef && !secdef->relabel))
1039 1040 1041 1042 1043
        return 0;

    if (dev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS)
        return 0;

1044
    /* Like virSecurityDACRestoreImageLabelInt() for a networked disk,
1045 1046
     * do nothing for an iSCSI hostdev
     */
1047 1048
    if (dev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI &&
        scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI)
1049 1050
        return 0;

1051
    switch ((virDomainHostdevSubsysType) dev->source.subsys.type) {
1052
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB: {
1053
        virUSBDevicePtr usb;
1054 1055 1056

        if (dev->missing)
            return 0;
1057

1058
        if (!(usb = virUSBDeviceNew(usbsrc->bus, usbsrc->device, vroot)))
1059 1060
            goto done;

1061
        ret = virUSBDeviceFileIterate(usb, virSecurityDACRestoreUSBLabel, mgr);
1062
        virUSBDeviceFree(usb);
1063 1064 1065 1066 1067

        break;
    }

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI: {
1068
        virPCIDevicePtr pci =
1069 1070
            virPCIDeviceNew(pcisrc->addr.domain, pcisrc->addr.bus,
                            pcisrc->addr.slot, pcisrc->addr.function);
1071 1072 1073 1074

        if (!pci)
            goto done;

1075
        if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
1076
            char *vfioGroupDev = virPCIDeviceGetIOMMUGroupDev(pci);
1077

1078 1079
            if (!vfioGroupDev) {
                virPCIDeviceFree(pci);
1080
                goto done;
1081
            }
1082
            ret = virSecurityDACRestorePCILabel(pci, vfioGroupDev, mgr);
1083 1084
            VIR_FREE(vfioGroupDev);
        } else {
1085
            ret = virPCIDeviceFileIterate(pci, virSecurityDACRestorePCILabel, mgr);
1086
        }
1087
        virPCIDeviceFree(pci);
1088 1089 1090
        break;
    }

1091
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI: {
1092
        virDomainHostdevSubsysSCSIHostPtr scsihostsrc = &scsisrc->u.host;
1093
        virSCSIDevicePtr scsi =
1094
            virSCSIDeviceNew(NULL,
1095 1096
                             scsihostsrc->adapter, scsihostsrc->bus,
                             scsihostsrc->target, scsihostsrc->unit,
1097
                             dev->readonly, dev->shareable);
1098 1099 1100 1101

        if (!scsi)
            goto done;

1102
        ret = virSCSIDeviceFileIterate(scsi, virSecurityDACRestoreSCSILabel, mgr);
1103 1104 1105 1106 1107
        virSCSIDeviceFree(scsi);

        break;
    }

1108
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI_HOST: {
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
        virSCSIVHostDevicePtr host = virSCSIVHostDeviceNew(hostsrc->wwpn);

        if (!host)
            goto done;

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

        break;
1120 1121
    }

1122
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_LAST:
1123 1124 1125 1126
        ret = 0;
        break;
    }

1127
 done:
1128 1129 1130 1131 1132 1133
    return ret;
}


static int
virSecurityDACSetChardevLabel(virSecurityManagerPtr mgr,
1134
                              virDomainDefPtr def,
1135 1136
                              virDomainChrDefPtr dev,
                              virDomainChrSourceDefPtr dev_source)
1137 1138 1139

{
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
1140
    virSecurityLabelDefPtr seclabel;
1141
    virSecurityDeviceLabelDefPtr chr_seclabel = NULL;
1142 1143
    char *in = NULL, *out = NULL;
    int ret = -1;
1144 1145 1146
    uid_t user;
    gid_t group;

1147 1148
    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_DAC_NAME);

1149 1150 1151 1152
    if (dev)
        chr_seclabel = virDomainChrDefGetSecurityLabelDef(dev,
                                                          SECURITY_DAC_NAME);

1153
    if (chr_seclabel && !chr_seclabel->relabel)
1154 1155 1156 1157 1158 1159 1160 1161 1162
        return 0;

    if (chr_seclabel && chr_seclabel->label) {
        if (virParseOwnershipIds(chr_seclabel->label, &user, &group) < 0)
            return -1;
    } else {
        if (virSecurityDACGetIds(seclabel, priv, &user, &group, NULL, NULL) < 0)
            return -1;
    }
1163

1164
    switch ((virDomainChrType) dev_source->type) {
1165 1166
    case VIR_DOMAIN_CHR_TYPE_DEV:
    case VIR_DOMAIN_CHR_TYPE_FILE:
1167 1168
        ret = virSecurityDACSetOwnership(priv, NULL,
                                         dev_source->data.file.path,
1169
                                         user, group);
1170 1171 1172
        break;

    case VIR_DOMAIN_CHR_TYPE_PIPE:
J
Jiri Denemark 已提交
1173 1174
        if (virAsprintf(&in, "%s.in", dev_source->data.file.path) < 0 ||
            virAsprintf(&out, "%s.out", dev_source->data.file.path) < 0)
1175 1176
            goto done;
        if (virFileExists(in) && virFileExists(out)) {
J
Jiri Denemark 已提交
1177 1178
            if (virSecurityDACSetOwnership(priv, NULL, in, user, group) < 0 ||
                virSecurityDACSetOwnership(priv, NULL, out, user, group) < 0)
1179
                goto done;
1180 1181
        } else if (virSecurityDACSetOwnership(priv, NULL,
                                              dev_source->data.file.path,
1182
                                              user, group) < 0) {
1183
            goto done;
1184 1185 1186 1187
        }
        ret = 0;
        break;

1188 1189
    case VIR_DOMAIN_CHR_TYPE_UNIX:
        if (!dev_source->data.nix.listen) {
1190 1191
            if (virSecurityDACSetOwnership(priv, NULL,
                                           dev_source->data.nix.path,
1192 1193 1194 1195 1196 1197
                                           user, group) < 0)
                goto done;
        }
        ret = 0;
        break;

1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
    case VIR_DOMAIN_CHR_TYPE_SPICEPORT:
    case VIR_DOMAIN_CHR_TYPE_NULL:
    case VIR_DOMAIN_CHR_TYPE_VC:
    case VIR_DOMAIN_CHR_TYPE_PTY:
    case VIR_DOMAIN_CHR_TYPE_STDIO:
    case VIR_DOMAIN_CHR_TYPE_UDP:
    case VIR_DOMAIN_CHR_TYPE_TCP:
    case VIR_DOMAIN_CHR_TYPE_SPICEVMC:
    case VIR_DOMAIN_CHR_TYPE_NMDM:
    case VIR_DOMAIN_CHR_TYPE_LAST:
1208 1209 1210 1211
        ret = 0;
        break;
    }

1212
 done:
1213 1214 1215 1216 1217 1218
    VIR_FREE(in);
    VIR_FREE(out);
    return ret;
}

static int
1219
virSecurityDACRestoreChardevLabel(virSecurityManagerPtr mgr,
1220
                                  virDomainDefPtr def ATTRIBUTE_UNUSED,
1221 1222
                                  virDomainChrDefPtr dev,
                                  virDomainChrSourceDefPtr dev_source)
1223
{
1224
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
1225
    virSecurityDeviceLabelDefPtr chr_seclabel = NULL;
1226 1227 1228
    char *in = NULL, *out = NULL;
    int ret = -1;

1229 1230 1231 1232
    if (dev)
        chr_seclabel = virDomainChrDefGetSecurityLabelDef(dev,
                                                          SECURITY_DAC_NAME);

1233
    if (chr_seclabel && !chr_seclabel->relabel)
1234 1235
        return 0;

1236
    switch ((virDomainChrType) dev_source->type) {
1237 1238
    case VIR_DOMAIN_CHR_TYPE_DEV:
    case VIR_DOMAIN_CHR_TYPE_FILE:
1239
        ret = virSecurityDACRestoreFileLabel(priv, dev_source->data.file.path);
1240 1241 1242
        break;

    case VIR_DOMAIN_CHR_TYPE_PIPE:
J
Jiri Denemark 已提交
1243 1244
        if (virAsprintf(&out, "%s.out", dev_source->data.file.path) < 0 ||
            virAsprintf(&in, "%s.in", dev_source->data.file.path) < 0)
1245
            goto done;
1246
        if (virFileExists(in) && virFileExists(out)) {
1247 1248
            if (virSecurityDACRestoreFileLabel(priv, out) < 0 ||
                virSecurityDACRestoreFileLabel(priv, in) < 0)
J
Jim Fehlig 已提交
1249
                goto done;
1250
        } else if (virSecurityDACRestoreFileLabel(priv, dev_source->data.file.path) < 0) {
1251 1252
            goto done;
        }
1253 1254 1255
        ret = 0;
        break;

1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
    case VIR_DOMAIN_CHR_TYPE_NULL:
    case VIR_DOMAIN_CHR_TYPE_VC:
    case VIR_DOMAIN_CHR_TYPE_PTY:
    case VIR_DOMAIN_CHR_TYPE_STDIO:
    case VIR_DOMAIN_CHR_TYPE_UDP:
    case VIR_DOMAIN_CHR_TYPE_TCP:
    case VIR_DOMAIN_CHR_TYPE_UNIX:
    case VIR_DOMAIN_CHR_TYPE_SPICEVMC:
    case VIR_DOMAIN_CHR_TYPE_SPICEPORT:
    case VIR_DOMAIN_CHR_TYPE_NMDM:
    case VIR_DOMAIN_CHR_TYPE_LAST:
1267 1268 1269 1270
        ret = 0;
        break;
    }

1271
 done:
1272 1273 1274 1275 1276 1277 1278
    VIR_FREE(in);
    VIR_FREE(out);
    return ret;
}


static int
1279
virSecurityDACRestoreChardevCallback(virDomainDefPtr def,
1280 1281 1282 1283 1284
                                     virDomainChrDefPtr dev,
                                     void *opaque)
{
    virSecurityManagerPtr mgr = opaque;

1285
    return virSecurityDACRestoreChardevLabel(mgr, def, dev, dev->source);
1286 1287 1288
}


1289
static int
1290 1291 1292
virSecurityDACSetTPMFileLabel(virSecurityManagerPtr mgr,
                              virDomainDefPtr def,
                              virDomainTPMDefPtr tpm)
1293 1294 1295 1296 1297
{
    int ret = 0;

    switch (tpm->type) {
    case VIR_DOMAIN_TPM_TYPE_PASSTHROUGH:
1298
        ret = virSecurityDACSetChardevLabel(mgr, def, NULL,
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
                                            &tpm->data.passthrough.source);
        break;
    case VIR_DOMAIN_TPM_TYPE_LAST:
        break;
    }

    return ret;
}


static int
1310 1311 1312
virSecurityDACRestoreTPMFileLabel(virSecurityManagerPtr mgr,
                                  virDomainDefPtr def,
                                  virDomainTPMDefPtr tpm)
1313 1314 1315 1316 1317
{
    int ret = 0;

    switch (tpm->type) {
    case VIR_DOMAIN_TPM_TYPE_PASSTHROUGH:
1318
        ret = virSecurityDACRestoreChardevLabel(mgr, def, NULL,
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
                                          &tpm->data.passthrough.source);
        break;
    case VIR_DOMAIN_TPM_TYPE_LAST:
        break;
    }

    return ret;
}


1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
static int
virSecurityDACSetInputLabel(virSecurityManagerPtr mgr,
                            virDomainDefPtr def,
                            virDomainInputDefPtr input)

{
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
    virSecurityLabelDefPtr seclabel;
    int ret = -1;
    uid_t user;
    gid_t group;

    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_DAC_NAME);
    if (seclabel && !seclabel->relabel)
        return 0;

    switch ((virDomainInputType) input->type) {
    case VIR_DOMAIN_INPUT_TYPE_PASSTHROUGH:
        if (virSecurityDACGetIds(seclabel, priv, &user, &group, NULL, NULL) < 0)
            return -1;

        ret = virSecurityDACSetOwnership(priv, NULL, input->source.evdev, user, group);
        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:
        ret = 0;
        break;
    }

    return ret;
}

static int
virSecurityDACRestoreInputLabel(virSecurityManagerPtr mgr,
                                virDomainDefPtr def ATTRIBUTE_UNUSED,
                                virDomainInputDefPtr input)
{
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
    int ret = -1;

    switch ((virDomainInputType) input->type) {
    case VIR_DOMAIN_INPUT_TYPE_PASSTHROUGH:
1374
        ret = virSecurityDACRestoreFileLabel(priv, input->source.evdev);
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
        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:
        ret = 0;
        break;
    }

    return ret;
}


1389
static int
1390 1391 1392
virSecurityDACRestoreAllLabel(virSecurityManagerPtr mgr,
                              virDomainDefPtr def,
                              bool migrated)
1393 1394
{
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
1395
    virSecurityLabelDefPtr secdef;
1396
    size_t i;
1397 1398
    int rc = 0;

1399
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_DAC_NAME);
1400

1401
    if (!priv->dynamicOwnership || (secdef && !secdef->relabel))
1402
        return 0;
1403 1404

    VIR_DEBUG("Restoring security label on %s migrated=%d",
1405
              def->name, migrated);
1406

1407
    for (i = 0; i < def->nhostdevs; i++) {
1408 1409 1410 1411
        if (virSecurityDACRestoreHostdevLabel(mgr,
                                              def,
                                              def->hostdevs[i],
                                              NULL) < 0)
1412 1413
            rc = -1;
    }
1414 1415 1416 1417 1418 1419

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

1420
    for (i = 0; i < def->ndisks; i++) {
1421 1422 1423 1424
        if (virSecurityDACRestoreImageLabelInt(mgr,
                                               def,
                                               def->disks[i]->src,
                                               migrated) < 0)
1425 1426 1427
            rc = -1;
    }

1428
    if (virDomainChrDefForeach(def,
1429 1430
                               false,
                               virSecurityDACRestoreChardevCallback,
1431
                               mgr) < 0)
1432 1433
        rc = -1;

1434
    if (def->tpm) {
1435 1436 1437
        if (virSecurityDACRestoreTPMFileLabel(mgr,
                                              def,
                                              def->tpm) < 0)
1438 1439 1440
            rc = -1;
    }

1441
    if (def->os.loader && def->os.loader->nvram &&
1442
        virSecurityDACRestoreFileLabel(priv, def->os.loader->nvram) < 0)
1443 1444
        rc = -1;

1445 1446 1447 1448 1449
    return rc;
}


static int
1450
virSecurityDACSetChardevCallback(virDomainDefPtr def,
1451 1452 1453 1454 1455
                                 virDomainChrDefPtr dev,
                                 void *opaque)
{
    virSecurityManagerPtr mgr = opaque;

1456
    return virSecurityDACSetChardevLabel(mgr, def, dev, dev->source);
1457 1458 1459 1460
}


static int
1461 1462 1463
virSecurityDACSetAllLabel(virSecurityManagerPtr mgr,
                          virDomainDefPtr def,
                          const char *stdin_path ATTRIBUTE_UNUSED)
1464 1465
{
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
1466
    virSecurityLabelDefPtr secdef;
1467
    size_t i;
1468 1469
    uid_t user;
    gid_t group;
1470

1471 1472
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_DAC_NAME);

1473
    if (!priv->dynamicOwnership || (secdef && !secdef->relabel))
1474 1475
        return 0;

1476
    for (i = 0; i < def->ndisks; i++) {
1477
        /* XXX fixme - we need to recursively label the entire tree :-( */
E
Eric Blake 已提交
1478
        if (virDomainDiskGetType(def->disks[i]) == VIR_STORAGE_TYPE_DIR)
1479
            continue;
1480 1481 1482
        if (virSecurityDACSetDiskLabel(mgr,
                                       def,
                                       def->disks[i]) < 0)
1483 1484
            return -1;
    }
1485 1486 1487 1488 1489 1490

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

1491
    for (i = 0; i < def->nhostdevs; i++) {
1492 1493 1494 1495
        if (virSecurityDACSetHostdevLabel(mgr,
                                          def,
                                          def->hostdevs[i],
                                          NULL) < 0)
1496 1497 1498
            return -1;
    }

1499
    if (virDomainChrDefForeach(def,
1500 1501
                               true,
                               virSecurityDACSetChardevCallback,
1502
                               mgr) < 0)
1503 1504
        return -1;

1505
    if (def->tpm) {
1506 1507 1508
        if (virSecurityDACSetTPMFileLabel(mgr,
                                          def,
                                          def->tpm) < 0)
1509 1510 1511
            return -1;
    }

1512
    if (virSecurityDACGetImageIds(secdef, priv, &user, &group))
1513 1514
        return -1;

1515
    if (def->os.loader && def->os.loader->nvram &&
1516 1517
        virSecurityDACSetOwnership(priv, NULL,
                                   def->os.loader->nvram, user, group) < 0)
1518 1519
        return -1;

1520
    if (def->os.kernel &&
1521 1522
        virSecurityDACSetOwnership(priv, NULL,
                                   def->os.kernel, user, group) < 0)
1523 1524
        return -1;

1525
    if (def->os.initrd &&
1526 1527
        virSecurityDACSetOwnership(priv, NULL,
                                   def->os.initrd, user, group) < 0)
1528 1529
        return -1;

O
Olivia Yin 已提交
1530
    if (def->os.dtb &&
1531 1532
        virSecurityDACSetOwnership(priv, NULL,
                                   def->os.dtb, user, group) < 0)
O
Olivia Yin 已提交
1533 1534
        return -1;

J
Ján Tomko 已提交
1535 1536 1537 1538 1539
    if (def->os.slic_table &&
        virSecurityDACSetOwnership(priv, NULL,
                                   def->os.slic_table, user, group) < 0)
        return -1;

1540 1541 1542 1543 1544 1545
    return 0;
}


static int
virSecurityDACSetSavedStateLabel(virSecurityManagerPtr mgr,
1546
                                 virDomainDefPtr def,
1547 1548
                                 const char *savefile)
{
1549 1550
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
    virSecurityLabelDefPtr secdef;
1551 1552
    uid_t user;
    gid_t group;
1553

1554 1555 1556
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_DAC_NAME);

    if (virSecurityDACGetImageIds(secdef, priv, &user, &group) < 0)
1557 1558
        return -1;

1559
    return virSecurityDACSetOwnership(priv, NULL, savefile, user, group);
1560 1561 1562 1563 1564
}


static int
virSecurityDACRestoreSavedStateLabel(virSecurityManagerPtr mgr,
1565
                                     virDomainDefPtr def ATTRIBUTE_UNUSED,
1566 1567 1568 1569 1570 1571 1572
                                     const char *savefile)
{
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);

    if (!priv->dynamicOwnership)
        return 0;

1573
    return virSecurityDACRestoreFileLabel(priv, savefile);
1574 1575 1576 1577 1578
}


static int
virSecurityDACSetProcessLabel(virSecurityManagerPtr mgr,
1579
                              virDomainDefPtr def)
1580
{
1581 1582
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
    virSecurityLabelDefPtr secdef;
1583 1584
    uid_t user;
    gid_t group;
1585 1586
    gid_t *groups;
    int ngroups;
1587

1588 1589 1590
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_DAC_NAME);

    if (virSecurityDACGetIds(secdef, priv, &user, &group, &groups, &ngroups) < 0)
1591
        return -1;
1592

J
Jiri Denemark 已提交
1593
    VIR_DEBUG("Dropping privileges to %u:%u, %d supplemental groups",
1594
              (unsigned int) user, (unsigned int) group, ngroups);
1595

1596
    if (virSetUIDGID(user, group, groups, ngroups) < 0)
1597 1598 1599
        return -1;

    return 0;
1600 1601 1602
}


1603 1604
static int
virSecurityDACSetChildProcessLabel(virSecurityManagerPtr mgr,
1605
                                   virDomainDefPtr def,
1606 1607
                                   virCommandPtr cmd)
{
1608 1609
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
    virSecurityLabelDefPtr secdef;
1610 1611 1612
    uid_t user;
    gid_t group;

1613 1614
    secdef = virDomainDefGetSecurityLabelDef(def, SECURITY_DAC_NAME);

1615
    if (virSecurityDACGetIds(secdef, priv, &user, &group, NULL, NULL) < 0)
1616 1617
        return -1;

J
Jiri Denemark 已提交
1618
    VIR_DEBUG("Setting child to drop privileges to %u:%u",
1619 1620 1621 1622 1623 1624 1625 1626
              (unsigned int) user, (unsigned int) group);

    virCommandSetUID(cmd, user);
    virCommandSetGID(cmd, group);
    return 0;
}


1627 1628 1629 1630 1631 1632 1633 1634
static int
virSecurityDACVerify(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                     virDomainDefPtr def ATTRIBUTE_UNUSED)
{
    return 0;
}

static int
1635 1636
virSecurityDACGenLabel(virSecurityManagerPtr mgr,
                       virDomainDefPtr def)
1637
{
1638 1639 1640 1641 1642
    int rc = -1;
    virSecurityLabelDefPtr seclabel;
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);

    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_DAC_NAME);
1643
    if (seclabel == NULL)
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661
        return rc;

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

    if (seclabel->model
        && STRNEQ(seclabel->model, SECURITY_DAC_NAME)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security label model %s is not supported "
                         "with selinux"),
                       seclabel->model);
            return rc;
    }

1662
    switch ((virDomainSeclabelType) seclabel->type) {
1663 1664 1665 1666 1667 1668 1669 1670 1671
    case VIR_DOMAIN_SECLABEL_STATIC:
        if (seclabel->label == NULL) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("missing label for static security "
                             "driver in domain %s"), def->name);
            return rc;
        }
        break;
    case VIR_DOMAIN_SECLABEL_DYNAMIC:
1672
        if (virAsprintf(&seclabel->label, "+%u:+%u",
1673
                        (unsigned int) priv->user,
1674
                        (unsigned int) priv->group) < 0)
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
            return rc;
        if (seclabel->label == NULL) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot generate dac user and group id "
                             "for domain %s"), def->name);
            return rc;
        }
        break;
    case VIR_DOMAIN_SECLABEL_NONE:
        /* no op */
1685
        return 0;
1686 1687
    case VIR_DOMAIN_SECLABEL_DEFAULT:
    case VIR_DOMAIN_SECLABEL_LAST:
1688 1689 1690 1691 1692 1693
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected security label type '%s'"),
                       virDomainSeclabelTypeToString(seclabel->type));
        return rc;
    }

1694
    if (seclabel->relabel && !seclabel->imagelabel &&
1695 1696 1697
        VIR_STRDUP(seclabel->imagelabel, seclabel->label) < 0) {
        VIR_FREE(seclabel->label);
        return rc;
1698 1699
    }

1700 1701 1702 1703 1704
    return 0;
}

static int
virSecurityDACReleaseLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
1705
                           virDomainDefPtr def ATTRIBUTE_UNUSED)
1706 1707 1708 1709 1710 1711
{
    return 0;
}

static int
virSecurityDACReserveLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
1712 1713
                           virDomainDefPtr def ATTRIBUTE_UNUSED,
                           pid_t pid ATTRIBUTE_UNUSED)
1714 1715 1716 1717
{
    return 0;
}

1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774
#ifdef __linux__
static int
virSecurityDACGetProcessLabelInternal(pid_t pid,
                                      virSecurityLabelPtr seclabel)
{
    struct stat sb;
    char *path = NULL;
    int ret = -1;

    VIR_DEBUG("Getting DAC user and group on process '%d'", pid);

    if (virAsprintf(&path, "/proc/%d", (int) pid) < 0)
        goto cleanup;

    if (lstat(path, &sb) < 0) {
        virReportSystemError(errno,
                             _("unable to get uid and gid for PID %d via procfs"),
                             pid);
        goto cleanup;
    }

    snprintf(seclabel->label, VIR_SECURITY_LABEL_BUFLEN,
             "+%u:+%u", (unsigned int) sb.st_uid, (unsigned int) sb.st_gid);
    ret = 0;

 cleanup:
    VIR_FREE(path);
    return ret;
}
#elif defined(__FreeBSD__)
static int
virSecurityDACGetProcessLabelInternal(pid_t pid,
                                      virSecurityLabelPtr seclabel)
{
    struct kinfo_proc p;
    int mib[4];
    size_t len = 4;

    sysctlnametomib("kern.proc.pid", mib, &len);

    len = sizeof(struct kinfo_proc);
    mib[3] = pid;

    if (sysctl(mib, 4, &p, &len, NULL, 0) < 0) {
        virReportSystemError(errno,
                             _("unable to get PID %d uid and gid via sysctl"),
                             pid);
        return -1;
    }

    snprintf(seclabel->label, VIR_SECURITY_LABEL_BUFLEN,
             "+%u:+%u", (unsigned int) p.ki_uid, (unsigned int) p.ki_groups[0]);

    return 0;
}
#else
static int
J
Ján Tomko 已提交
1775 1776
virSecurityDACGetProcessLabelInternal(pid_t pid ATTRIBUTE_UNUSED,
                                      virSecurityLabelPtr seclabel ATTRIBUTE_UNUSED)
1777 1778 1779 1780 1781 1782 1783
{
    virReportSystemError(ENOSYS, "%s",
                         _("Cannot get process uid and gid on this platform"));
    return -1;
}
#endif

1784 1785
static int
virSecurityDACGetProcessLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
1786
                              virDomainDefPtr def,
1787
                              pid_t pid,
1788
                              virSecurityLabelPtr seclabel)
1789
{
1790 1791 1792
    virSecurityLabelDefPtr secdef =
        virDomainDefGetSecurityLabelDef(def, SECURITY_DAC_NAME);

1793 1794 1795 1796 1797 1798 1799 1800
    if (secdef == NULL) {
        VIR_DEBUG("missing label for DAC security "
                  "driver in domain %s", def->name);

        if (virSecurityDACGetProcessLabelInternal(pid, seclabel) < 0)
            return -1;
        return 0;
    }
1801 1802

    if (secdef->label)
1803 1804
        ignore_value(virStrcpy(seclabel->label, secdef->label,
                               VIR_SECURITY_LABEL_BUFLEN));
1805

1806 1807 1808 1809
    return 0;
}

static int
1810
virSecurityDACSetDaemonSocketLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
1811
                                   virDomainDefPtr vm ATTRIBUTE_UNUSED)
1812 1813 1814 1815 1816
{
    return 0;
}


1817 1818
static int
virSecurityDACSetSocketLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
1819
                             virDomainDefPtr def ATTRIBUTE_UNUSED)
1820 1821 1822 1823 1824
{
    return 0;
}


1825 1826
static int
virSecurityDACClearSocketLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
1827
                               virDomainDefPtr def ATTRIBUTE_UNUSED)
1828 1829 1830 1831
{
    return 0;
}

1832
static int
1833
virSecurityDACSetImageFDLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
1834
                              virDomainDefPtr def ATTRIBUTE_UNUSED,
1835
                              int fd ATTRIBUTE_UNUSED)
1836 1837 1838 1839
{
    return 0;
}

1840 1841 1842 1843 1844 1845 1846 1847
static int
virSecurityDACSetTapFDLabel(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                            virDomainDefPtr def ATTRIBUTE_UNUSED,
                            int fd ATTRIBUTE_UNUSED)
{
    return 0;
}

O
Osier Yang 已提交
1848 1849 1850 1851
static char *
virSecurityDACGetMountOptions(virSecurityManagerPtr mgr ATTRIBUTE_UNUSED,
                              virDomainDefPtr vm ATTRIBUTE_UNUSED)
{
1852 1853 1854
    return NULL;
}

1855 1856 1857 1858 1859 1860 1861 1862
static const char *
virSecurityDACGetBaseLabel(virSecurityManagerPtr mgr,
                           int virt ATTRIBUTE_UNUSED)
{
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
    return priv->baselabel;
}

1863
static int
1864 1865 1866
virSecurityDACDomainSetPathLabel(virSecurityManagerPtr mgr,
                                 virDomainDefPtr def,
                                 const char *path)
1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
{
    virSecurityDACDataPtr priv = virSecurityManagerGetPrivateData(mgr);
    virSecurityLabelDefPtr seclabel;
    uid_t user;
    gid_t group;

    seclabel = virDomainDefGetSecurityLabelDef(def, SECURITY_DAC_NAME);

    if (virSecurityDACGetIds(seclabel, priv, &user, &group, NULL, NULL) < 0)
        return -1;

1878
    return virSecurityDACSetOwnership(priv, NULL, path, user, group);
1879 1880
}

1881
virSecurityDriver virSecurityDriverDAC = {
1882
    .privateDataLen                     = sizeof(virSecurityDACData),
1883
    .name                               = SECURITY_DAC_NAME,
1884 1885 1886
    .probe                              = virSecurityDACProbe,
    .open                               = virSecurityDACOpen,
    .close                              = virSecurityDACClose,
1887

1888 1889
    .getModel                           = virSecurityDACGetModel,
    .getDOI                             = virSecurityDACGetDOI,
1890

1891 1892
    .preFork                            = virSecurityDACPreFork,

1893 1894 1895 1896
    .transactionStart                   = virSecurityDACTransactionStart,
    .transactionCommit                  = virSecurityDACTransactionCommit,
    .transactionAbort                   = virSecurityDACTransactionAbort,

1897
    .domainSecurityVerify               = virSecurityDACVerify,
1898

1899 1900
    .domainSetSecurityDiskLabel         = virSecurityDACSetDiskLabel,
    .domainRestoreSecurityDiskLabel     = virSecurityDACRestoreDiskLabel,
1901

1902 1903
    .domainSetSecurityImageLabel        = virSecurityDACSetImageLabel,
    .domainRestoreSecurityImageLabel    = virSecurityDACRestoreImageLabel,
1904

1905 1906 1907
    .domainSetSecurityDaemonSocketLabel = virSecurityDACSetDaemonSocketLabel,
    .domainSetSecuritySocketLabel       = virSecurityDACSetSocketLabel,
    .domainClearSecuritySocketLabel     = virSecurityDACClearSocketLabel,
1908

1909 1910 1911
    .domainGenSecurityLabel             = virSecurityDACGenLabel,
    .domainReserveSecurityLabel         = virSecurityDACReserveLabel,
    .domainReleaseSecurityLabel         = virSecurityDACReleaseLabel,
1912

1913 1914
    .domainGetSecurityProcessLabel      = virSecurityDACGetProcessLabel,
    .domainSetSecurityProcessLabel      = virSecurityDACSetProcessLabel,
1915
    .domainSetSecurityChildProcessLabel = virSecurityDACSetChildProcessLabel,
1916

1917 1918
    .domainSetSecurityAllLabel          = virSecurityDACSetAllLabel,
    .domainRestoreSecurityAllLabel      = virSecurityDACRestoreAllLabel,
1919

1920 1921
    .domainSetSecurityHostdevLabel      = virSecurityDACSetHostdevLabel,
    .domainRestoreSecurityHostdevLabel  = virSecurityDACRestoreHostdevLabel,
1922

1923 1924
    .domainSetSavedStateLabel           = virSecurityDACSetSavedStateLabel,
    .domainRestoreSavedStateLabel       = virSecurityDACRestoreSavedStateLabel,
1925

1926
    .domainSetSecurityImageFDLabel      = virSecurityDACSetImageFDLabel,
1927
    .domainSetSecurityTapFDLabel        = virSecurityDACSetTapFDLabel,
1928

1929
    .domainGetSecurityMountOptions      = virSecurityDACGetMountOptions,
1930 1931

    .getBaseLabel                       = virSecurityDACGetBaseLabel,
1932

1933
    .domainSetPathLabel                 = virSecurityDACDomainSetPathLabel,
1934
};