security_manager.c 36.4 KB
Newer Older
1 2 3
/*
 * security_manager.c: Internal security manager API
 *
4
 * Copyright (C) 2010-2014 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16
 *
 * 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
17
 * License along with this library.  If not, see
O
Osier Yang 已提交
18
 * <http://www.gnu.org/licenses/>.
19 20 21
 */
#include <config.h>

22 23 24 25
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

26 27 28
#include "security_driver.h"
#include "security_stack.h"
#include "security_dac.h"
29
#include "virerror.h"
30
#include "viralloc.h"
31
#include "virobject.h"
32
#include "virlog.h"
33
#include "virfile.h"
34 35 36

#define VIR_FROM_THIS VIR_FROM_SECURITY

37
VIR_LOG_INIT("security.security_manager");
38 39

struct _virSecurityManager {
40 41
    virObjectLockable parent;

42
    virSecurityDriverPtr drv;
43
    unsigned int flags;
44
    const char *virtDriver;
45
    void *privateData;
46 47
};

48 49
static virClassPtr virSecurityManagerClass;

50 51 52 53 54 55

static
void virSecurityManagerDispose(void *obj)
{
    virSecurityManagerPtr mgr = obj;

56
    if (mgr->drv->close)
57 58 59 60
        mgr->drv->close(mgr);
    VIR_FREE(mgr->privateData);
}

61

62 63
static int
virSecurityManagerOnceInit(void)
64
{
65
    if (!VIR_CLASS_NEW(virSecurityManager, virClassForObjectLockable()))
66 67 68 69 70 71 72
        return -1;

    return 0;
}

VIR_ONCE_GLOBAL_INIT(virSecurityManager);

73 74 75 76

static virSecurityManagerPtr
virSecurityManagerNewDriver(virSecurityDriverPtr drv,
                            const char *virtDriver,
77
                            unsigned int flags)
78
{
79 80
    virSecurityManagerPtr mgr = NULL;
    char *privateData = NULL;
81 82 83

    if (virSecurityManagerInitialize() < 0)
        return NULL;
84

85
    VIR_DEBUG("drv=%p (%s) virtDriver=%s flags=0x%x",
86 87 88
              drv, drv->name, virtDriver, flags);

    virCheckFlags(VIR_SECURITY_MANAGER_NEW_MASK, NULL);
89

90
    if (VIR_ALLOC_N(privateData, drv->privateDataLen) < 0)
91 92
        return NULL;

93 94
    if (!(mgr = virObjectLockableNew(virSecurityManagerClass)))
        goto error;
95

96
    mgr->drv = drv;
97
    mgr->flags = flags;
98
    mgr->virtDriver = virtDriver;
99
    mgr->privateData = g_steal_pointer(&privateData);
100

101 102
    if (drv->open(mgr) < 0)
        goto error;
103 104

    return mgr;
105 106 107 108
 error:
    VIR_FREE(privateData);
    virObjectUnref(mgr);
    return NULL;
109 110
}

111 112 113

virSecurityManagerPtr
virSecurityManagerNewStack(virSecurityManagerPtr primary)
114 115 116
{
    virSecurityManagerPtr mgr =
        virSecurityManagerNewDriver(&virSecurityDriverStack,
117
                                    virSecurityManagerGetVirtDriver(primary),
118
                                    primary->flags);
119 120 121 122

    if (!mgr)
        return NULL;

123 124
    if (virSecurityStackAddNested(mgr, primary) < 0)
        goto error;
125 126

    return mgr;
127 128 129
 error:
    virObjectUnref(mgr);
    return NULL;
130 131
}

132 133 134 135

int
virSecurityManagerStackAddNested(virSecurityManagerPtr stack,
                                 virSecurityManagerPtr nested)
136
{
137
    if (STRNEQ("stack", stack->drv->name))
138 139 140 141
        return -1;
    return virSecurityStackAddNested(stack, nested);
}

142 143 144 145 146

virSecurityManagerPtr
virSecurityManagerNewDAC(const char *virtDriver,
                         uid_t user,
                         gid_t group,
147
                         unsigned int flags,
148
                         virSecurityManagerDACChownCallback chownCallback)
149
{
150 151 152
    virSecurityManagerPtr mgr;

    virCheckFlags(VIR_SECURITY_MANAGER_NEW_MASK |
153 154
                  VIR_SECURITY_MANAGER_DYNAMIC_OWNERSHIP |
                  VIR_SECURITY_MANAGER_MOUNT_NAMESPACE, NULL);
155 156 157 158

    mgr = virSecurityManagerNewDriver(&virSecurityDriverDAC,
                                      virtDriver,
                                      flags & VIR_SECURITY_MANAGER_NEW_MASK);
159 160 161 162

    if (!mgr)
        return NULL;

163 164 165 166
    if (virSecurityDACSetUserAndGroup(mgr, user, group) < 0) {
        virSecurityManagerDispose(mgr);
        return NULL;
    }
167

168
    virSecurityDACSetDynamicOwnership(mgr, flags & VIR_SECURITY_MANAGER_DYNAMIC_OWNERSHIP);
169
    virSecurityDACSetMountNamespace(mgr, flags & VIR_SECURITY_MANAGER_MOUNT_NAMESPACE);
170
    virSecurityDACSetChownCallback(mgr, chownCallback);
171 172 173 174

    return mgr;
}

175 176 177 178

virSecurityManagerPtr
virSecurityManagerNew(const char *name,
                      const char *virtDriver,
179
                      unsigned int flags)
180
{
181
    virSecurityDriverPtr drv = virSecurityDriverLookup(name, virtDriver);
182 183 184
    if (!drv)
        return NULL;

185 186
    /* driver "none" needs some special handling of *Confined bools */
    if (STREQ(drv->name, "none")) {
187
        if (flags & VIR_SECURITY_MANAGER_REQUIRE_CONFINED) {
188 189
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Security driver \"none\" cannot create confined guests"));
190 191 192
            return NULL;
        }

193
        if (flags & VIR_SECURITY_MANAGER_DEFAULT_CONFINED) {
194 195 196 197 198 199 200
            if (name != NULL) {
                VIR_WARN("Configured security driver \"none\" disables default"
                         " policy to create confined guests");
            } else {
                VIR_DEBUG("Auto-probed security driver is \"none\";"
                          " confined guests will not be created");
            }
201
            flags &= ~VIR_SECURITY_MANAGER_DEFAULT_CONFINED;
202 203 204
        }
    }

205
    return virSecurityManagerNewDriver(drv,
206
                                       virtDriver,
207
                                       flags);
208 209
}

210 211 212

/*
 * Must be called before fork()'ing to ensure mutex state
213 214 215 216
 * is sane for the child to use. A negative return means the
 * child must not be forked; a successful return must be
 * followed by a call to virSecurityManagerPostFork() in both
 * parent and child.
217
 */
218 219
int
virSecurityManagerPreFork(virSecurityManagerPtr mgr)
220
{
221 222
    int ret = 0;

223
    virObjectLock(mgr);
224 225 226 227 228 229 230
    if (mgr->drv->preFork) {
        ret = mgr->drv->preFork(mgr);
        if (ret < 0)
            virObjectUnlock(mgr);
    }

    return ret;
231 232 233 234 235 236 237
}


/*
 * Must be called after fork()'ing in both parent and child
 * to ensure mutex state is sane for the child to use
 */
238 239
void
virSecurityManagerPostFork(virSecurityManagerPtr mgr)
240 241 242 243
{
    virObjectUnlock(mgr);
}

244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271

/**
 * virSecurityManagerTransactionStart:
 * @mgr: security manager
 *
 * Starts a new transaction. In transaction nothing is changed security
 * label until virSecurityManagerTransactionCommit() is called.
 *
 * Returns 0 on success,
 *        -1 otherwise.
 */
int
virSecurityManagerTransactionStart(virSecurityManagerPtr mgr)
{
    int ret = 0;

    virObjectLock(mgr);
    if (mgr->drv->transactionStart)
        ret = mgr->drv->transactionStart(mgr);
    virObjectUnlock(mgr);
    return ret;
}


/**
 * virSecurityManagerTransactionCommit:
 * @mgr: security manager
 * @pid: domain's PID
272
 * @lock: lock and unlock paths that are relabeled
273
 *
274 275 276 277 278
 * If @pid is not -1 then enter the @pid namespace (usually @pid refers
 * to a domain) and perform all the operations on the transaction list.
 * If @pid is -1 then the transaction is performed in the namespace of
 * the caller.
 *
279 280 281
 * If @lock is true then all the paths that transaction would
 * touch are locked before and unlocked after it is done so.
 *
282 283 284 285
 * 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.
286 287 288 289 290 291
 *
 * Returns: 0 on success,
 *         -1 otherwise.
 */
int
virSecurityManagerTransactionCommit(virSecurityManagerPtr mgr,
292 293
                                    pid_t pid,
                                    bool lock)
294 295 296 297 298
{
    int ret = 0;

    virObjectLock(mgr);
    if (mgr->drv->transactionCommit)
299
        ret = mgr->drv->transactionCommit(mgr, pid, lock);
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
    virObjectUnlock(mgr);
    return ret;
}


/**
 * virSecurityManagerTransactionAbort:
 * @mgr: security manager
 *
 * Cancels and frees any out standing transaction.
 */
void
virSecurityManagerTransactionAbort(virSecurityManagerPtr mgr)
{
    virObjectLock(mgr);
    if (mgr->drv->transactionAbort)
        mgr->drv->transactionAbort(mgr);
    virObjectUnlock(mgr);
}


321 322
void *
virSecurityManagerGetPrivateData(virSecurityManagerPtr mgr)
323
{
324
    return mgr->privateData;
325 326 327
}


328
const char *
329
virSecurityManagerGetVirtDriver(virSecurityManagerPtr mgr)
330 331 332 333
{
    return mgr->virtDriver;
}

334

335 336 337 338 339 340 341
const char *
virSecurityManagerGetDriver(virSecurityManagerPtr mgr)
{
    return mgr->drv->name;
}


342 343 344
const char *
virSecurityManagerGetDOI(virSecurityManagerPtr mgr)
{
345 346 347 348 349 350 351
    if (mgr->drv->getDOI) {
        const char *ret;
        virObjectLock(mgr);
        ret = mgr->drv->getDOI(mgr);
        virObjectUnlock(mgr);
        return ret;
    }
352

353
    virReportUnsupportedError();
354 355 356
    return NULL;
}

357

358 359 360
const char *
virSecurityManagerGetModel(virSecurityManagerPtr mgr)
{
361 362 363 364 365 366 367
    if (mgr->drv->getModel) {
        const char *ret;
        virObjectLock(mgr);
        ret = mgr->drv->getModel(mgr);
        virObjectUnlock(mgr);
        return ret;
    }
368

369
    virReportUnsupportedError();
370 371 372
    return NULL;
}

373

374 375
/* return NULL if a base label is not present */
const char *
376 377
virSecurityManagerGetBaseLabel(virSecurityManagerPtr mgr,
                               int virtType)
378 379 380 381 382 383 384 385 386 387 388 389
{
    if (mgr->drv->getBaseLabel) {
        const char *ret;
        virObjectLock(mgr);
        ret = mgr->drv->getBaseLabel(mgr, virtType);
        virObjectUnlock(mgr);
        return ret;
    }

    return NULL;
}

390 391 392

bool
virSecurityManagerGetDefaultConfined(virSecurityManagerPtr mgr)
393
{
394
    return mgr->flags & VIR_SECURITY_MANAGER_DEFAULT_CONFINED;
395 396
}

397 398 399

bool
virSecurityManagerGetRequireConfined(virSecurityManagerPtr mgr)
400
{
401
    return mgr->flags & VIR_SECURITY_MANAGER_REQUIRE_CONFINED;
402 403
}

404

405 406 407
bool
virSecurityManagerGetPrivileged(virSecurityManagerPtr mgr)
{
408
    return mgr->flags & VIR_SECURITY_MANAGER_PRIVILEGED;
409 410 411
}


412 413 414 415 416
/**
 * virSecurityManagerRestoreImageLabel:
 * @mgr: security manager object
 * @vm: domain definition object
 * @src: disk source definition to operate on
417
 * @flags: bitwise or of 'virSecurityDomainImageLabelFlags'
418
 *
419
 * Removes security label from @src according to @flags.
420 421 422 423 424 425
 *
 * Returns: 0 on success, -1 on error.
 */
int
virSecurityManagerRestoreImageLabel(virSecurityManagerPtr mgr,
                                   virDomainDefPtr vm,
426 427
                                   virStorageSourcePtr src,
                                   virSecurityDomainImageLabelFlags flags)
428 429 430 431
{
    if (mgr->drv->domainRestoreSecurityImageLabel) {
        int ret;
        virObjectLock(mgr);
432
        ret = mgr->drv->domainRestoreSecurityImageLabel(mgr, vm, src, flags);
433 434 435 436 437 438 439 440 441
        virObjectUnlock(mgr);
        return ret;
    }

    virReportUnsupportedError();
    return -1;
}


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
/**
 * virSecurityManagerMoveImageMetadata:
 * @mgr: security manager
 * @pid: domain's PID
 * @src: source of metadata
 * @dst: destination to move metadata to
 *
 * For given source @src, metadata is moved to destination @dst.
 *
 * If @dst is NULL then metadata is removed from @src and not
 * stored anywhere.
 *
 * If @pid is not -1 enther the @pid mount namespace (usually
 * @pid refers to a domain) and perform the move from there. If
 * @pid is -1 then the move is performed from the caller's
 * namespace.
 *
 * Returns: 0 on success,
 *         -1 otherwise.
 */
int
virSecurityManagerMoveImageMetadata(virSecurityManagerPtr mgr,
                                    pid_t pid,
                                    virStorageSourcePtr src,
                                    virStorageSourcePtr dst)
{
    if (mgr->drv->domainMoveImageMetadata) {
        int ret;
        virObjectLock(mgr);
        ret = mgr->drv->domainMoveImageMetadata(mgr, pid, src, dst);
        virObjectUnlock(mgr);
        return ret;
    }

    virReportUnsupportedError();
    return -1;
}


481 482 483
int
virSecurityManagerSetDaemonSocketLabel(virSecurityManagerPtr mgr,
                                       virDomainDefPtr vm)
484
{
485 486 487 488 489 490 491
    if (mgr->drv->domainSetSecurityDaemonSocketLabel) {
        int ret;
        virObjectLock(mgr);
        ret = mgr->drv->domainSetSecurityDaemonSocketLabel(mgr, vm);
        virObjectUnlock(mgr);
        return ret;
    }
492

493
    virReportUnsupportedError();
494 495 496
    return -1;
}

497 498 499 500

int
virSecurityManagerSetSocketLabel(virSecurityManagerPtr mgr,
                                 virDomainDefPtr vm)
501
{
502 503 504 505 506 507 508
    if (mgr->drv->domainSetSecuritySocketLabel) {
        int ret;
        virObjectLock(mgr);
        ret = mgr->drv->domainSetSecuritySocketLabel(mgr, vm);
        virObjectUnlock(mgr);
        return ret;
    }
509

510
    virReportUnsupportedError();
511 512 513
    return -1;
}

514 515 516 517

int
virSecurityManagerClearSocketLabel(virSecurityManagerPtr mgr,
                                   virDomainDefPtr vm)
518
{
519 520 521 522 523 524 525
    if (mgr->drv->domainClearSecuritySocketLabel) {
        int ret;
        virObjectLock(mgr);
        ret = mgr->drv->domainClearSecuritySocketLabel(mgr, vm);
        virObjectUnlock(mgr);
        return ret;
    }
526

527
    virReportUnsupportedError();
528 529 530
    return -1;
}

531

532 533 534 535 536
/**
 * virSecurityManagerSetImageLabel:
 * @mgr: security manager object
 * @vm: domain definition object
 * @src: disk source definition to operate on
537
 * @flags: bitwise or of 'virSecurityDomainImageLabelFlags'
538
 *
539
 * Labels a storage image with the configured security label according to @flags.
540 541 542 543 544 545
 *
 * Returns: 0 on success, -1 on error.
 */
int
virSecurityManagerSetImageLabel(virSecurityManagerPtr mgr,
                                virDomainDefPtr vm,
546 547
                                virStorageSourcePtr src,
                                virSecurityDomainImageLabelFlags flags)
548 549 550 551
{
    if (mgr->drv->domainSetSecurityImageLabel) {
        int ret;
        virObjectLock(mgr);
552
        ret = mgr->drv->domainSetSecurityImageLabel(mgr, vm, src, flags);
553 554 555 556 557 558 559 560 561
        virObjectUnlock(mgr);
        return ret;
    }

    virReportUnsupportedError();
    return -1;
}


562 563 564 565 566
int
virSecurityManagerRestoreHostdevLabel(virSecurityManagerPtr mgr,
                                      virDomainDefPtr vm,
                                      virDomainHostdevDefPtr dev,
                                      const char *vroot)
567
{
568 569 570 571 572 573 574
    if (mgr->drv->domainRestoreSecurityHostdevLabel) {
        int ret;
        virObjectLock(mgr);
        ret = mgr->drv->domainRestoreSecurityHostdevLabel(mgr, vm, dev, vroot);
        virObjectUnlock(mgr);
        return ret;
    }
575

576
    virReportUnsupportedError();
577 578 579
    return -1;
}

580 581 582 583 584 585

int
virSecurityManagerSetHostdevLabel(virSecurityManagerPtr mgr,
                                  virDomainDefPtr vm,
                                  virDomainHostdevDefPtr dev,
                                  const char *vroot)
586
{
587 588 589 590 591 592 593
    if (mgr->drv->domainSetSecurityHostdevLabel) {
        int ret;
        virObjectLock(mgr);
        ret = mgr->drv->domainSetSecurityHostdevLabel(mgr, vm, dev, vroot);
        virObjectUnlock(mgr);
        return ret;
    }
594

595
    virReportUnsupportedError();
596 597 598
    return -1;
}

599 600 601 602 603

int
virSecurityManagerSetSavedStateLabel(virSecurityManagerPtr mgr,
                                     virDomainDefPtr vm,
                                     const char *savefile)
604
{
605 606 607 608 609 610 611
    if (mgr->drv->domainSetSavedStateLabel) {
        int ret;
        virObjectLock(mgr);
        ret = mgr->drv->domainSetSavedStateLabel(mgr, vm, savefile);
        virObjectUnlock(mgr);
        return ret;
    }
612

613
    virReportUnsupportedError();
614 615 616
    return -1;
}

617 618 619 620
int
virSecurityManagerRestoreSavedStateLabel(virSecurityManagerPtr mgr,
                                         virDomainDefPtr vm,
                                         const char *savefile)
621
{
622 623 624 625 626 627 628
    if (mgr->drv->domainRestoreSavedStateLabel) {
        int ret;
        virObjectLock(mgr);
        ret = mgr->drv->domainRestoreSavedStateLabel(mgr, vm, savefile);
        virObjectUnlock(mgr);
        return ret;
    }
629

630
    virReportUnsupportedError();
631 632 633
    return -1;
}

634 635 636 637

int
virSecurityManagerGenLabel(virSecurityManagerPtr mgr,
                           virDomainDefPtr vm)
638
{
639
    int ret = -1;
640
    size_t i;
641 642
    virSecurityManagerPtr* sec_managers = NULL;
    virSecurityLabelDefPtr seclabel;
643
    bool generated = false;
644

645
    if ((sec_managers = virSecurityManagerGetNested(mgr)) == NULL)
646
        return ret;
647

648
    virObjectLock(mgr);
649

650
    for (i = 0; sec_managers[i]; i++) {
651 652
        generated = false;
        seclabel = virDomainDefGetSecurityLabelDef(vm, sec_managers[i]->drv->name);
653 654 655 656 657
        if (seclabel == NULL) {
            /* Only generate seclabel if confinement is enabled */
            if (!virSecurityManagerGetDefaultConfined(sec_managers[i])) {
                VIR_DEBUG("Skipping auto generated seclabel");
                continue;
658
            } else {
659 660 661 662 663 664 665 666 667 668 669 670 671
                if (!(seclabel = virSecurityLabelDefNew(sec_managers[i]->drv->name)))
                    goto cleanup;
                generated = seclabel->implicit = true;
                seclabel->type = VIR_DOMAIN_SECLABEL_DYNAMIC;
            }
        } else {
            if (seclabel->type == VIR_DOMAIN_SECLABEL_DEFAULT) {
                if (virSecurityManagerGetDefaultConfined(sec_managers[i])) {
                    seclabel->type = VIR_DOMAIN_SECLABEL_DYNAMIC;
                } else {
                    seclabel->type = VIR_DOMAIN_SECLABEL_NONE;
                    seclabel->relabel = false;
                }
672
            }
673

674 675 676 677 678 679
            if (seclabel->type == VIR_DOMAIN_SECLABEL_NONE) {
                if (virSecurityManagerGetRequireConfined(sec_managers[i])) {
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                                   _("Unconfined guests are not allowed on this host"));
                    goto cleanup;
                }
680
            }
681 682 683
        }

        if (!sec_managers[i]->drv->domainGenSecurityLabel) {
684
            virReportUnsupportedError();
685 686
            virSecurityLabelDefFree(seclabel);
            seclabel = NULL;
687
        } else {
688 689
            /* The seclabel must be added to @vm prior calling domainGenSecurityLabel
             * which may require seclabel to be presented already */
690
            if (generated &&
691
                VIR_APPEND_ELEMENT(vm->seclabels, vm->nseclabels, seclabel) < 0)
692 693 694 695 696 697
                goto cleanup;

            if (sec_managers[i]->drv->domainGenSecurityLabel(sec_managers[i], vm) < 0) {
                if (VIR_DELETE_ELEMENT(vm->seclabels,
                                       vm->nseclabels -1, vm->nseclabels) < 0)
                    vm->nseclabels--;
698
                goto cleanup;
699
            }
700 701

            seclabel = NULL;
702 703 704
        }
    }

705 706
    ret = 0;

707
 cleanup:
708
    virObjectUnlock(mgr);
709 710
    if (generated)
        virSecurityLabelDefFree(seclabel);
711
    VIR_FREE(sec_managers);
712
    return ret;
713 714
}

715 716 717 718 719

int
virSecurityManagerReserveLabel(virSecurityManagerPtr mgr,
                               virDomainDefPtr vm,
                               pid_t pid)
720
{
721 722 723 724 725 726 727
    if (mgr->drv->domainReserveSecurityLabel) {
        int ret;
        virObjectLock(mgr);
        ret = mgr->drv->domainReserveSecurityLabel(mgr, vm, pid);
        virObjectUnlock(mgr);
        return ret;
    }
728

729
    virReportUnsupportedError();
730 731 732
    return -1;
}

733 734 735 736

int
virSecurityManagerReleaseLabel(virSecurityManagerPtr mgr,
                               virDomainDefPtr vm)
737
{
738 739 740 741 742 743 744
    if (mgr->drv->domainReleaseSecurityLabel) {
        int ret;
        virObjectLock(mgr);
        ret = mgr->drv->domainReleaseSecurityLabel(mgr, vm);
        virObjectUnlock(mgr);
        return ret;
    }
745

746
    virReportUnsupportedError();
747 748 749
    return -1;
}

750

751 752 753
static int virSecurityManagerCheckModel(virSecurityManagerPtr mgr,
                                        char *secmodel)
{
754
    int ret = -1;
755 756 757 758 759 760
    size_t i;
    virSecurityManagerPtr *sec_managers = NULL;

    if (STREQ_NULLABLE(secmodel, "none"))
        return 0;

761 762 763
    if ((sec_managers = virSecurityManagerGetNested(mgr)) == NULL)
        return -1;

764
    for (i = 0; sec_managers[i]; i++) {
765 766 767 768
        if (STREQ_NULLABLE(secmodel, sec_managers[i]->drv->name)) {
            ret = 0;
            goto cleanup;
        }
769 770 771
    }

    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
772
                   _("Security driver model '%s' is not available"),
773
                   secmodel);
774 775 776
 cleanup:
    VIR_FREE(sec_managers);
    return ret;
777 778 779
}


780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
static int
virSecurityManagerCheckDomainLabel(virSecurityManagerPtr mgr,
                                   virDomainDefPtr def)
{
    size_t i;

    for (i = 0; i < def->nseclabels; i++) {
        if (virSecurityManagerCheckModel(mgr, def->seclabels[i]->model) < 0)
            return -1;
    }

    return 0;
}


795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
static int
virSecurityManagerCheckDiskLabel(virSecurityManagerPtr mgr,
                                 virDomainDiskDefPtr disk)
{
    size_t i;

    for (i = 0; i < disk->src->nseclabels; i++) {
        if (virSecurityManagerCheckModel(mgr, disk->src->seclabels[i]->model) < 0)
            return -1;
    }

    return 0;
}


static int
virSecurityManagerCheckChardevLabel(virSecurityManagerPtr mgr,
                                    virDomainChrDefPtr dev)
{
    size_t i;

816 817
    for (i = 0; i < dev->source->nseclabels; i++) {
        if (virSecurityManagerCheckModel(mgr, dev->source->seclabels[i]->model) < 0)
818 819 820 821 822 823 824 825
            return -1;
    }

    return 0;
}


static int
J
Ján Tomko 已提交
826
virSecurityManagerCheckChardevCallback(virDomainDefPtr def G_GNUC_UNUSED,
827 828 829 830 831 832 833 834 835 836 837 838 839
                                       virDomainChrDefPtr dev,
                                       void *opaque)
{
    virSecurityManagerPtr mgr = opaque;
    return virSecurityManagerCheckChardevLabel(mgr, dev);
}


int virSecurityManagerCheckAllLabel(virSecurityManagerPtr mgr,
                                    virDomainDefPtr vm)
{
    size_t i;

840 841 842
    if (virSecurityManagerCheckDomainLabel(mgr, vm) < 0)
        return -1;

843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
    for (i = 0; i < vm->ndisks; i++) {
        if (virSecurityManagerCheckDiskLabel(mgr, vm->disks[i]) < 0)
            return -1;
    }

    if (virDomainChrDefForeach(vm,
                               true,
                               virSecurityManagerCheckChardevCallback,
                               mgr) < 0)
        return -1;

    return 0;
}


858 859 860
int
virSecurityManagerSetAllLabel(virSecurityManagerPtr mgr,
                              virDomainDefPtr vm,
861
                              const char *stdin_path,
862 863
                              bool chardevStdioLogd,
                              bool migrated)
864
{
865 866 867
    if (mgr->drv->domainSetSecurityAllLabel) {
        int ret;
        virObjectLock(mgr);
868
        ret = mgr->drv->domainSetSecurityAllLabel(mgr, vm, stdin_path,
869 870
                                                  chardevStdioLogd,
                                                  migrated);
871 872 873
        virObjectUnlock(mgr);
        return ret;
    }
874

875
    virReportUnsupportedError();
876 877 878
    return -1;
}

879 880 881 882

int
virSecurityManagerRestoreAllLabel(virSecurityManagerPtr mgr,
                                  virDomainDefPtr vm,
883 884
                                  bool migrated,
                                  bool chardevStdioLogd)
885
{
886 887 888
    if (mgr->drv->domainRestoreSecurityAllLabel) {
        int ret;
        virObjectLock(mgr);
889 890
        ret = mgr->drv->domainRestoreSecurityAllLabel(mgr, vm, migrated,
                                                      chardevStdioLogd);
891 892 893
        virObjectUnlock(mgr);
        return ret;
    }
894

895
    virReportUnsupportedError();
896 897 898
    return -1;
}

899 900 901 902 903
int
virSecurityManagerGetProcessLabel(virSecurityManagerPtr mgr,
                                  virDomainDefPtr vm,
                                  pid_t pid,
                                  virSecurityLabelPtr sec)
904
{
905 906 907 908 909 910 911
    if (mgr->drv->domainGetSecurityProcessLabel) {
        int ret;
        virObjectLock(mgr);
        ret = mgr->drv->domainGetSecurityProcessLabel(mgr, vm, pid, sec);
        virObjectUnlock(mgr);
        return ret;
    }
912

913
    virReportUnsupportedError();
914 915 916
    return -1;
}

917 918 919 920

int
virSecurityManagerSetProcessLabel(virSecurityManagerPtr mgr,
                                  virDomainDefPtr vm)
921
{
922 923 924 925 926 927 928
    if (mgr->drv->domainSetSecurityProcessLabel) {
        int ret;
        virObjectLock(mgr);
        ret = mgr->drv->domainSetSecurityProcessLabel(mgr, vm);
        virObjectUnlock(mgr);
        return ret;
    }
929

930
    virReportUnsupportedError();
931 932 933
    return -1;
}

934 935 936 937 938

int
virSecurityManagerSetChildProcessLabel(virSecurityManagerPtr mgr,
                                       virDomainDefPtr vm,
                                       virCommandPtr cmd)
939 940 941 942
{
    if (mgr->drv->domainSetSecurityChildProcessLabel)
       return mgr->drv->domainSetSecurityChildProcessLabel(mgr, vm, cmd);

943
    virReportUnsupportedError();
944 945 946
    return -1;
}

947 948 949 950

int
virSecurityManagerVerify(virSecurityManagerPtr mgr,
                         virDomainDefPtr def)
951
{
952 953 954 955 956
    virSecurityLabelDefPtr secdef;

    if (mgr == NULL || mgr->drv == NULL)
        return 0;

957 958 959 960
    /* NULL model == dynamic labelling, with whatever driver
     * is active, so we can short circuit verify check to
     * avoid drivers de-referencing NULLs by accident
     */
961 962
    secdef = virDomainDefGetSecurityLabelDef(def, mgr->drv->name);
    if (secdef == NULL || secdef->model == NULL)
963 964
        return 0;

965 966 967 968 969 970 971
    if (mgr->drv->domainSecurityVerify) {
        int ret;
        virObjectLock(mgr);
        ret = mgr->drv->domainSecurityVerify(mgr, def);
        virObjectUnlock(mgr);
        return ret;
    }
972

973
    virReportUnsupportedError();
974 975
    return -1;
}
976

977 978 979 980 981

int
virSecurityManagerSetImageFDLabel(virSecurityManagerPtr mgr,
                                  virDomainDefPtr vm,
                                  int fd)
982
{
983 984 985 986 987 988 989
    if (mgr->drv->domainSetSecurityImageFDLabel) {
        int ret;
        virObjectLock(mgr);
        ret = mgr->drv->domainSetSecurityImageFDLabel(mgr, vm, fd);
        virObjectUnlock(mgr);
        return ret;
    }
990

991
    virReportUnsupportedError();
992 993
    return -1;
}
994

995 996 997 998 999

int
virSecurityManagerSetTapFDLabel(virSecurityManagerPtr mgr,
                                virDomainDefPtr vm,
                                int fd)
1000
{
1001 1002 1003 1004 1005 1006 1007
    if (mgr->drv->domainSetSecurityTapFDLabel) {
        int ret;
        virObjectLock(mgr);
        ret = mgr->drv->domainSetSecurityTapFDLabel(mgr, vm, fd);
        virObjectUnlock(mgr);
        return ret;
    }
1008

1009
    virReportUnsupportedError();
1010 1011 1012
    return -1;
}

1013 1014 1015 1016

char *
virSecurityManagerGetMountOptions(virSecurityManagerPtr mgr,
                                  virDomainDefPtr vm)
1017
{
1018 1019 1020 1021 1022 1023 1024
    if (mgr->drv->domainGetSecurityMountOptions) {
        char *ret;
        virObjectLock(mgr);
        ret = mgr->drv->domainGetSecurityMountOptions(mgr, vm);
        virObjectUnlock(mgr);
        return ret;
    }
1025

1026
    virReportUnsupportedError();
1027 1028
    return NULL;
}
1029

1030

1031 1032 1033 1034 1035
virSecurityManagerPtr*
virSecurityManagerGetNested(virSecurityManagerPtr mgr)
{
    virSecurityManagerPtr* list = NULL;

1036
    if (STREQ("stack", mgr->drv->name))
1037 1038
        return virSecurityStackGetNested(mgr);

1039
    if (VIR_ALLOC_N(list, 2) < 0)
1040 1041 1042 1043 1044 1045
        return NULL;

    list[0] = mgr;
    list[1] = NULL;
    return list;
}
1046

1047

1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
/**
 * virSecurityManagerDomainSetPathLabel:
 * @mgr: security manager object
 * @vm: domain definition object
 * @path: path to label
 * @allowSubtree: whether to allow just @path or its subtree too
 *
 * This function relabels given @path so that @vm can access it.
 * If @allowSubtree is set to true the manager will grant access
 * to @path and its subdirectories at any level (currently
 * implemented only by AppArmor).
 *
 * Returns: 0 on success, -1 on error.
 */
1062
int
1063 1064
virSecurityManagerDomainSetPathLabel(virSecurityManagerPtr mgr,
                                     virDomainDefPtr vm,
1065 1066
                                     const char *path,
                                     bool allowSubtree)
1067
{
1068
    if (mgr->drv->domainSetPathLabel) {
1069 1070
        int ret;
        virObjectLock(mgr);
1071
        ret = mgr->drv->domainSetPathLabel(mgr, vm, path, allowSubtree);
1072 1073 1074 1075 1076 1077
        virObjectUnlock(mgr);
        return ret;
    }

    return 0;
}
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133


/**
 * virSecurityManagerSetMemoryLabel:
 * @mgr: security manager object
 * @vm: domain definition object
 * @mem: memory module to operate on
 *
 * Labels the host part of a memory module.
 *
 * Returns: 0 on success, -1 on error.
 */
int
virSecurityManagerSetMemoryLabel(virSecurityManagerPtr mgr,
                                     virDomainDefPtr vm,
                                     virDomainMemoryDefPtr mem)
{
    if (mgr->drv->domainSetSecurityMemoryLabel) {
        int ret;
        virObjectLock(mgr);
        ret = mgr->drv->domainSetSecurityMemoryLabel(mgr, vm, mem);
        virObjectUnlock(mgr);
        return ret;
    }

    virReportUnsupportedError();
    return -1;
}


/**
 * virSecurityManagerRestoreMemoryLabel:
 * @mgr: security manager object
 * @vm: domain definition object
 * @mem: memory module to operate on
 *
 * Removes security label from the host part of a memory module.
 *
 * Returns: 0 on success, -1 on error.
 */
int
virSecurityManagerRestoreMemoryLabel(virSecurityManagerPtr mgr,
                                        virDomainDefPtr vm,
                                        virDomainMemoryDefPtr mem)
{
    if (mgr->drv->domainRestoreSecurityMemoryLabel) {
        int ret;
        virObjectLock(mgr);
        ret = mgr->drv->domainRestoreSecurityMemoryLabel(mgr, vm, mem);
        virObjectUnlock(mgr);
        return ret;
    }

    virReportUnsupportedError();
    return -1;
}
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169


int
virSecurityManagerSetInputLabel(virSecurityManagerPtr mgr,
                                virDomainDefPtr vm,
                                virDomainInputDefPtr input)
{
    if (mgr->drv->domainSetSecurityInputLabel) {
        int ret;
        virObjectLock(mgr);
        ret = mgr->drv->domainSetSecurityInputLabel(mgr, vm, input);
        virObjectUnlock(mgr);
        return ret;
    }

    virReportUnsupportedError();
    return -1;
}


int
virSecurityManagerRestoreInputLabel(virSecurityManagerPtr mgr,
                                    virDomainDefPtr vm,
                                    virDomainInputDefPtr input)
{
    if (mgr->drv->domainRestoreSecurityInputLabel) {
        int ret;
        virObjectLock(mgr);
        ret = mgr->drv->domainRestoreSecurityInputLabel(mgr, vm, input);
        virObjectUnlock(mgr);
        return ret;
    }

    virReportUnsupportedError();
    return -1;
}
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209


int
virSecurityManagerSetChardevLabel(virSecurityManagerPtr mgr,
                                  virDomainDefPtr def,
                                  virDomainChrSourceDefPtr dev_source,
                                  bool chardevStdioLogd)
{
    if (mgr->drv->domainSetSecurityChardevLabel) {
        int ret;
        virObjectLock(mgr);
        ret = mgr->drv->domainSetSecurityChardevLabel(mgr, def, dev_source,
                                                      chardevStdioLogd);
        virObjectUnlock(mgr);
        return ret;
    }

    virReportUnsupportedError();
    return -1;
}


int
virSecurityManagerRestoreChardevLabel(virSecurityManagerPtr mgr,
                                      virDomainDefPtr def,
                                      virDomainChrSourceDefPtr dev_source,
                                      bool chardevStdioLogd)
{
    if (mgr->drv->domainRestoreSecurityChardevLabel) {
        int ret;
        virObjectLock(mgr);
        ret = mgr->drv->domainRestoreSecurityChardevLabel(mgr, def, dev_source,
                                                          chardevStdioLogd);
        virObjectUnlock(mgr);
        return ret;
    }

    virReportUnsupportedError();
    return -1;
}
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245


int
virSecurityManagerSetTPMLabels(virSecurityManagerPtr mgr,
                               virDomainDefPtr vm)
{
    int ret;

    if (mgr->drv->domainSetSecurityTPMLabels) {
        virObjectLock(mgr);
        ret = mgr->drv->domainSetSecurityTPMLabels(mgr, vm);
        virObjectUnlock(mgr);

        return ret;
    }

    return 0;
}


int
virSecurityManagerRestoreTPMLabels(virSecurityManagerPtr mgr,
                                   virDomainDefPtr vm)
{
    int ret;

    if (mgr->drv->domainRestoreSecurityTPMLabels) {
        virObjectLock(mgr);
        ret = mgr->drv->domainRestoreSecurityTPMLabels(mgr, vm);
        virObjectUnlock(mgr);

        return ret;
    }

    return 0;
}
1246 1247


1248 1249 1250 1251
struct _virSecurityManagerMetadataLockState {
    size_t nfds;
    int *fds;
};
1252 1253


1254 1255 1256 1257 1258
static int
cmpstringp(const void *p1, const void *p2)
{
    const char *s1 = *(char * const *) p1;
    const char *s2 = *(char * const *) p2;
1259

1260 1261
    if (!s1 && !s2)
        return 0;
1262

1263 1264
    if (!s1 || !s2)
        return s2 ? -1 : 1;
1265

1266 1267 1268
    /* from man 3 qsort */
    return strcmp(s1, s2);
}
1269

1270 1271
#define METADATA_OFFSET 1
#define METADATA_LEN 1
1272

1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
/**
 * virSecurityManagerMetadataLock:
 * @mgr: security manager object
 * @paths: paths to lock
 * @npaths: number of items in @paths array
 *
 * Lock passed @paths for metadata change. The returned state
 * should be passed to virSecurityManagerMetadataUnlock.
 *
 * NOTE: this function is not thread safe (because of usage of
 * POSIX locks).
 *
 * Returns: state on success,
 *          NULL on failure.
 */
virSecurityManagerMetadataLockStatePtr
J
Ján Tomko 已提交
1289
virSecurityManagerMetadataLock(virSecurityManagerPtr mgr G_GNUC_UNUSED,
1290
                               const char **paths,
1291 1292
                               size_t npaths)
{
1293 1294 1295 1296
    size_t i = 0;
    size_t nfds = 0;
    int *fds = NULL;
    virSecurityManagerMetadataLockStatePtr ret = NULL;
1297

1298 1299
    if (VIR_ALLOC_N(fds, npaths) < 0)
        return NULL;
1300

1301 1302 1303 1304 1305
    /* Sort paths to lock in order to avoid deadlocks with other
     * processes. For instance, if one process wants to lock
     * paths A B and there's another that is trying to lock them
     * in reversed order a deadlock might occur.  But if we sort
     * the paths alphabetically then both processes will try lock
1306 1307 1308
     * paths in the same order and thus no deadlock can occur.
     * Lastly, it makes searching for duplicate paths below
     * simpler. */
1309
    qsort(paths, npaths, sizeof(*paths), cmpstringp);
1310

1311 1312 1313
    for (i = 0; i < npaths; i++) {
        const char *p = paths[i];
        struct stat sb;
1314
        size_t j;
1315 1316
        int retries = 10 * 1000;
        int fd;
1317

1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
        if (!p)
            continue;

        /* If there's a duplicate path on the list, skip it over.
         * Not only we would fail open()-ing it the second time,
         * we would deadlock with ourselves trying to lock it the
         * second time. After all, we've locked it when iterating
         * over it the first time. */
        for (j = 0; j < i; j++) {
            if (STREQ_NULLABLE(p, paths[j]))
                break;
        }

        if (i != j)
            continue;

        if (stat(p, &sb) < 0)
1335
            continue;
1336

1337 1338
        if (S_ISDIR(sb.st_mode)) {
            /* Directories can't be locked */
1339
            continue;
1340
        }
1341

1342
        if ((fd = open(p, O_RDWR)) < 0) {
1343
#ifndef WIN32
1344 1345 1346 1347 1348
            if (S_ISSOCK(sb.st_mode)) {
                /* Sockets can be opened only if there exists the
                 * other side that listens. */
                continue;
            }
1349
#endif /* !WIN32 */
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362

            virReportSystemError(errno,
                                 _("unable to open %s"),
                                 p);
            goto cleanup;
        }

        do {
            if (virFileLock(fd, false,
                            METADATA_OFFSET, METADATA_LEN, false) < 0) {
                if (retries && (errno == EACCES || errno == EAGAIN)) {
                    /* File is locked. Try again. */
                    retries--;
1363
                    g_usleep(1000);
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
                    continue;
                } else {
                    virReportSystemError(errno,
                                         _("unable to lock %s for metadata change"),
                                         p);
                    VIR_FORCE_CLOSE(fd);
                    goto cleanup;
                }
            }

            break;
        } while (1);

        VIR_APPEND_ELEMENT_COPY_INPLACE(fds, nfds, fd);
1378 1379
    }

1380
    if (VIR_ALLOC(ret) < 0)
1381 1382
        goto cleanup;

1383
    ret->fds = g_steal_pointer(&fds);
1384 1385
    ret->nfds = nfds;
    nfds = 0;
1386 1387

 cleanup:
1388 1389 1390
    for (i = nfds; i > 0; i--)
        VIR_FORCE_CLOSE(fds[i - 1]);
    VIR_FREE(fds);
1391 1392 1393 1394
    return ret;
}


1395
void
J
Ján Tomko 已提交
1396
virSecurityManagerMetadataUnlock(virSecurityManagerPtr mgr G_GNUC_UNUSED,
1397
                                 virSecurityManagerMetadataLockStatePtr *state)
1398
{
1399
    size_t i;
1400

1401 1402
    if (!state)
        return;
1403

1404 1405 1406
    for (i = 0; i < (*state)->nfds; i++) {
        char ebuf[1024];
        int fd = (*state)->fds[i];
1407

1408 1409 1410 1411 1412 1413
        /* Technically, unlock is not needed because it will
         * happen on VIR_CLOSE() anyway. But let's play it nice. */
        if (virFileUnlock(fd, METADATA_OFFSET, METADATA_LEN) < 0) {
            VIR_WARN("Unable to unlock fd %d: %s",
                     fd, virStrerror(errno, ebuf, sizeof(ebuf)));
        }
1414

1415 1416 1417 1418 1419
        if (VIR_CLOSE(fd) < 0) {
            VIR_WARN("Unable to close fd %d: %s",
                     fd, virStrerror(errno, ebuf, sizeof(ebuf)));
        }
    }
1420

1421 1422
    VIR_FREE((*state)->fds);
    VIR_FREE(*state);
1423
}