Commit Graph

387 Commits

Author SHA1 Message Date
Jim Fehlig
bb917a90b1 security_dac: avoid relabeling hostdevs when relabel='no'
When relabel='no' at the domain level, there is no need to call
the hostdev relabeling functions.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
Signed-off-by: Jim Fehlig <jfehlig@suse.com>
2014-05-16 15:32:14 -06:00
Jim Fehlig
3c2487ab0a security_dac: honor relabel='no' in disk config
https://bugzilla.redhat.com/show_bug.cgi?id=999301

The DAC driver ignores the relabel='no' attribute in disk config

  <disk type='file' device='floppy'>
    <driver name='qemu' type='raw'/>
    <source file='/some/path/floppy.img'>
      <seclabel model='dac' relabel='no'/>
    </source>
    <target dev='fda' bus='fdc'/>
    <readonly/>
  </disk>

This patch avoid labeling disks when relabel='no' is specified.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
Signed-off-by: Jim Fehlig <jfehlig@suse.com>
2014-05-16 15:32:14 -06:00
Jim Fehlig
9369a56244 security_dac: avoid relabeling when relabel='no'
If relabel='no' at the domain level, no need to attempt relabeling
in virSecurityDAC{Set,Restore}SecurityAllLabel().

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
Signed-off-by: Jim Fehlig <jfehlig@suse.com>
2014-05-16 15:32:14 -06:00
Jim Fehlig
3de7e4ec5e security_dac: rework callback parameter passing
Currently, the DAC security driver passes callback data as

    void params[2];
    params[0] = mgr;
    params[1] = def;

Clean this up by defining a structure for passing the callback
data.  Moreover, there's no need to pass the whole virDomainDef
in the callback as the only thing needed in the callbacks is
virSecurityLabelDefPtr.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
Signed-off-by: Jim Fehlig <jfehlig@suse.com>
2014-05-16 15:32:14 -06:00
Jim Fehlig
1d98e713d5 security_dac: cleanup use of enum types
In switch statements, use enum types since it is safer when
adding new items to the enum.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
Signed-off-by: Jim Fehlig <jfehlig@suse.com>
2014-05-16 15:32:14 -06:00
Jim Fehlig
e1ce6d836e security_dac: annotate some functions with ATTRIBUTE_NONNULL
Annotate some static function parameters with ATTRIBUTE_NONNULL
and remove checks for NULL inputs.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
Signed-off-by: Jim Fehlig <jfehlig@suse.com>
2014-05-16 15:32:14 -06:00
Jim Fehlig
5099084eb3 security_dac: Fix indentation 2014-05-14 11:43:00 -06:00
Jim Fehlig
d77fa847c3 security_dac: Remove unnecessary curly braces 2014-05-14 11:43:00 -06:00
Jim Fehlig
fcf5ea7fc0 security_dac: Remove unnecessary ATTRIBUTE_UNUSED
Remove ATTRIBUTE_UNUSED on several function parameters that are
actually used.
2014-05-14 11:43:00 -06:00
Peter Krempa
8823272d41 util: storage: Invert the way recursive metadata retrieval works
To avoid having the root of a backing chain present twice in the list we
need to invert the working of virStorageFileGetMetadataRecurse.

Until now the recursive worker created a new backing chain element from
the name and other information passed as arguments. This required us to
pass the data of the parent in a deconstructed way and the worker
created a new entry for the parent.

This patch converts this function so that it just fills in metadata
about the parent and creates a backing chain element from those. This
removes the duplication of the first element.

To avoid breaking the test suite, virstoragetest now calls a wrapper
that creates the parent structure explicitly and pre-fills it with the
test data with same function signature as previously used.
2014-04-24 14:27:57 +02:00
Peter Krempa
44551275a9 storage: Move disk->backingChain to the recursive disk->src.backingStore
Switch over to storing of the backing chain as a recursive
virStorageSource structure.

This is a string based move. Currently the first element will be present
twice in the backing chain as currently the retrieval function stores
the parent in the newly detected chain. This will be fixed later.
2014-04-23 23:11:07 +02:00
Nehal J Wani
3d5c29a17c Fix typos in src/*
Fix minor typos in source comments

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-04-21 16:49:08 -06:00
Daniel P. Berrange
3cfa19da22 Replace Pci with PCI throughout
Since it is an abbreviation, PCI should always be fully
capitalized or full lower case, never Pci.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-04-08 11:15:55 +01:00
Eric Blake
8733303933 conf: avoid memleak on NULL path
I noticed that the apparmor code could request metadata even
for a cdrom with no media, which would cause a memory leak of
the hash table used to look for loops in the backing chain.
But even before that, we blindly dereferenced the path for
printing a debug statement, so it is just better to enforce
that this is only used on non-NULL names.

* src/util/virstoragefile.c (virStorageFileGetMetadata): Assume
non-NULL path.
* src/util/virstoragefile.h: Annotate this.
* src/security/virt-aa-helper.c (get_files): Fix caller.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-04-07 16:31:45 -06:00
Ján Tomko
66050f0f89 Fix coverity-reported leak in virSecurityManagerGenLabel
Coverity complains about a possible leak of seclabel if
!sec_managers[i]->drv->domainGenSecurityLabel is true
and the seclabel might be overwritten by the next iteration
of the loop.

This leak should never happen, because every security driver
has domainGenSecurityLabel defined.
2014-04-02 15:23:01 +02:00
Eric Blake
5160ab795a util: move detection of shared filesystems
The code in virstoragefile.c is getting more complex as I
consolidate backing chain handling code.  But for the setuid
virt-login-shell, we don't need to crawl backing chains.  It's
easier to audit things for setuid security if there are fewer
files involved, so this patch moves the one function that
virFileOpen() was actually relying on to also live in virfile.c.

* src/util/virstoragefile.c (virStorageFileIsSharedFS)
(virStorageFileIsSharedFSType): Move...
* src/util/virfile.c (virFileIsSharedFS, virFileIsSharedFSType):
...to here, and rename.
(virFileOpenAs): Update caller.
* src/security/security_selinux.c
(virSecuritySELinuxSetFileconHelper)
(virSecuritySELinuxSetSecurityAllLabel)
(virSecuritySELinuxRestoreSecurityImageLabelInt): Likewise.
* src/security/security_dac.c
(virSecurityDACRestoreSecurityImageLabelInt): Likewise.
* src/qemu/qemu_driver.c (qemuOpenFileAs): Likewise.
* src/qemu/qemu_migration.c (qemuMigrationIsSafe): Likewise.
* src/util/virstoragefile.h: Adjust declarations.
* src/util/virfile.h: Likewise.
* src/libvirt_private.syms (virfile.h, virstoragefile.h): Move
symbols as appropriate.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-04-01 10:38:14 -06:00
Eric Blake
16ac4c9d64 conf: move host disk type to util/
A continuation of the migration of disk details to virstoragefile.
This patch moves a single enum, but converting the name has quite
a bit of fallout.

* src/conf/domain_conf.h (virDomainDiskType): Move...
* src/util/virstoragefile.h (virStorageType): ...and rename.
* src/bhyve/bhyve_command.c (bhyveBuildDiskArgStr)
(virBhyveProcessBuildLoadCmd): Update clients.
* src/conf/domain_conf.c (virDomainDiskSourceDefParse)
(virDomainDiskDefParseXML, virDomainDiskSourceDefFormatInternal)
(virDomainDiskDefFormat, virDomainDiskGetActualType)
(virDomainDiskDefForeachPath, virDomainDiskSourceIsBlockType):
Likewise.
* src/conf/snapshot_conf.h (_virDomainSnapshotDiskDef): Likewise.
* src/conf/snapshot_conf.c (virDomainSnapshotDiskDefParseXML)
(virDomainSnapshotAlignDisks, virDomainSnapshotDiskDefFormat):
Likewise.
* src/esx/esx_driver.c (esxAutodetectSCSIControllerModel)
(esxDomainDefineXML): Likewise.
* src/locking/domain_lock.c (virDomainLockManagerAddDisk):
Likewise.
* src/lxc/lxc_controller.c
(virLXCControllerSetupLoopDeviceDisk)
(virLXCControllerSetupNBDDeviceDisk)
(virLXCControllerSetupLoopDevices, virLXCControllerSetupDisk):
Likewise.
* src/parallels/parallels_driver.c (parallelsGetHddInfo):
Likewise.
* src/phyp/phyp_driver.c (phypDiskType): Likewise.
* src/qemu/qemu_command.c (qemuGetDriveSourceString)
(qemuDomainDiskGetSourceString, qemuBuildDriveStr)
(qemuBuildCommandLine, qemuParseCommandLineDisk)
(qemuParseCommandLine): Likewise.
* src/qemu/qemu_conf.c (qemuCheckSharedDevice)
(qemuTranslateDiskSourcePool)
(qemuTranslateSnapshotDiskSourcePool): Likewise.
* src/qemu/qemu_domain.c (qemuDomainDeviceDefPostParse)
(qemuDomainDetermineDiskChain): Likewise.
* src/qemu/qemu_driver.c (qemuDomainGetBlockInfo)
(qemuDomainSnapshotPrepareDiskExternalBackingInactive)
(qemuDomainSnapshotPrepareDiskExternalBackingActive)
(qemuDomainSnapshotPrepareDiskExternalOverlayActive)
(qemuDomainSnapshotPrepareDiskExternalOverlayInactive)
(qemuDomainSnapshotPrepareDiskInternal)
(qemuDomainSnapshotPrepare)
(qemuDomainSnapshotCreateSingleDiskActive): Likewise.
* src/qemu/qemu_hotplug.c (qemuDomainChangeEjectableMedia):
Likewise.
* src/qemu/qemu_migration.c (qemuMigrationIsSafe): Likewise.
* src/security/security_apparmor.c
(AppArmorRestoreSecurityImageLabel)
(AppArmorSetSecurityImageLabel): Likewise.
* src/security/security_dac.c (virSecurityDACSetSecurityImageLabel)
(virSecurityDACRestoreSecurityImageLabelInt)
(virSecurityDACSetSecurityAllLabel): Likewise.
* src/security/security_selinux.c
(virSecuritySELinuxRestoreSecurityImageLabelInt)
(virSecuritySELinuxSetSecurityImageLabel)
(virSecuritySELinuxSetSecurityAllLabel): Likewise.
* src/storage/storage_backend.c (virStorageFileBackendForType):
Likewise.
* src/storage/storage_backend_fs.c (virStorageFileBackendFile)
(virStorageFileBackendBlock): Likewise.
* src/storage/storage_backend_gluster.c
(virStorageFileBackendGluster): Likewise.
* src/vbox/vbox_tmpl.c (vboxDomainGetXMLDesc, vboxAttachDrives)
(vboxDomainAttachDeviceImpl, vboxDomainDetachDevice): Likewise.
* src/vmware/vmware_conf.c (vmwareVmxPath): Likewise.
* src/vmx/vmx.c (virVMXParseDisk, virVMXFormatDisk)
(virVMXFormatFloppy): Likewise.
* src/xenxs/xen_sxpr.c (xenParseSxprDisks, xenParseSxpr)
(xenFormatSxprDisk): Likewise.
* src/xenxs/xen_xm.c (xenParseXM, xenFormatXMDisk): Likewise.
* tests/securityselinuxlabeltest.c (testSELinuxLoadDef):
Likewise.
* src/libvirt_private.syms (domain_conf.h): Move symbols...
(virstoragefile.h): ...as appropriate.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-04-01 10:38:13 -06:00
Eric Blake
3e92938656 conf: split security label structs to util/
In order to reuse the newly-created host-side disk struct in
the virstoragefile backing chain code, I first have to move
it to util/.  This starts the process, by first moving the
security label structures.

* src/conf/domain_conf.h (virDomainDefGenSecurityLabelDef)
(virDomainDiskDefGenSecurityLabelDef, virSecurityLabelDefFree)
(virSecurityDeviceLabelDefFree, virSecurityLabelDef)
(virSecurityDeviceLabelDef): Move...
* src/util/virseclabel.h: ...to new file.
(virSecurityLabelDefNew, virSecurityDeviceLabelDefNew): Rename the
GenSecurity functions.
* src/qemu/qemu_process.c (qemuProcessAttach): Adjust callers.
* src/security/security_manager.c (virSecurityManagerGenLabel):
Likewise.
* src/security/security_selinux.c
(virSecuritySELinuxSetSecurityFileLabel): Likewise.
* src/util/virseclabel.c: New file.
* src/conf/domain_conf.c: Move security code, and fix fallout.
* src/Makefile.am (UTIL_SOURCES): Build new file.
* src/libvirt_private.syms (domain_conf.h): Move symbols...
(virseclabel.h): ...to new section.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-04-01 10:38:12 -06:00
Cédric Bosdonnat
74e86b6b25 Fix apparmor profile to make vfio pci passthrough work
See lp#1276719 for the bug description. As virt-aa-helper doesn't know
the VFIO groups to use for the guest, allow access to all
/dev/vfio/[0-9]* and /dev/vfio/vfio files if there is a potential need
for vfio

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-03-27 09:09:23 -06:00
Cédric Bosdonnat
0500fbd4b6 Fixed regression in apparmor profiles for qemu brought by 43c030f 2014-03-27 09:04:08 -06:00
Ján Tomko
9e7ecabf94 Indent top-level labels by one space in the rest of src/ 2014-03-25 14:58:40 +01:00
Peter Krempa
ccef7d7876 apparmor: Fix build after split of disk source metadata
Commit 4f20226664 breaks build with
AppArmor enabled as it missed the refactor to the new accessors.
2014-03-24 20:00:11 +01:00
Eric Blake
4f20226664 conf: prepare to track multiple host source files per <disk>
It's finally time to start tracking disk backing chains in
<domain> XML.  The first step is to start refactoring code
so that we have an object more convenient for representing
each host source resource in the context of a single guest
<disk>.  Ultimately, I plan to move the new type into src/util
where it can be reused by virStorageFile, but to make the
transition easier to review, this patch just creates the
new type then fixes everything until it compiles again.

* src/conf/domain_conf.h (_virDomainDiskDef): Split...
(_virDomainDiskSourceDef): ...to new struct.
(virDomainDiskAuthClear): Use new type.
* src/conf/domain_conf.c (virDomainDiskDefFree): Split...
(virDomainDiskSourceDefClear): ...to new function.
(virDomainDiskGetType, virDomainDiskSetType)
(virDomainDiskGetSource, virDomainDiskSetSource)
(virDomainDiskGetDriver, virDomainDiskSetDriver)
(virDomainDiskGetFormat, virDomainDiskSetFormat)
(virDomainDiskAuthClear, virDomainDiskGetActualType)
(virDomainDiskDefParseXML, virDomainDiskSourceDefFormat)
(virDomainDiskDefFormat, virDomainDiskDefForeachPath)
(virDomainDiskDefGetSecurityLabelDef)
(virDomainDiskSourceIsBlockType): Adjust all users.
* src/lxc/lxc_controller.c (virLXCControllerSetupDisk):
Likewise.
* src/lxc/lxc_driver.c (lxcDomainAttachDeviceMknodHelper):
Likewise.
* src/qemu/qemu_command.c (qemuAddRBDHost, qemuParseRBDString)
(qemuParseDriveURIString, qemuParseGlusterString)
(qemuParseISCSIString, qemuParseNBDString)
(qemuDomainDiskGetSourceString, qemuBuildDriveStr)
(qemuBuildCommandLine, qemuParseCommandLineDisk)
(qemuParseCommandLine): Likewise.
* src/qemu/qemu_conf.c (qemuCheckSharedDevice)
(qemuAddISCSIPoolSourceHost, qemuTranslateDiskSourcePool):
Likewise.
* src/qemu/qemu_driver.c (qemuDomainUpdateDeviceConfig)
(qemuDomainPrepareDiskChainElement)
(qemuDomainSnapshotCreateInactiveExternal)
(qemuDomainSnapshotPrepareDiskExternalBackingInactive)
(qemuDomainSnapshotPrepareDiskInternal)
(qemuDomainSnapshotPrepare)
(qemuDomainSnapshotCreateSingleDiskActive)
(qemuDomainSnapshotUndoSingleDiskActive)
(qemuDomainBlockPivot, qemuDomainBlockJobImpl)
(qemuDomainBlockCopy, qemuDomainBlockCommit): Likewise.
* src/qemu/qemu_migration.c (qemuMigrationIsSafe): Likewise.
* src/qemu/qemu_process.c (qemuProcessGetVolumeQcowPassphrase)
(qemuProcessInitPasswords): Likewise.
* src/security/security_selinux.c
(virSecuritySELinuxSetSecurityFileLabel): Likewise.
* src/storage/storage_driver.c (virStorageFileInitFromDiskDef):
Likewise.
* tests/securityselinuxlabeltest.c (testSELinuxLoadDef):
Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-03-24 12:18:34 -06:00
Eric Blake
2aad0ebe2d conf: use disk source accessors in security/
Part of a series of cleanups to use new accessor methods.

* src/security/security_dac.c (virSecurityDACSetSecurityImageLabel)
(virSecurityDACRestoreSecurityImageLabelInt)
(virSecurityDACSetSecurityAllLabel): Use accessors.
* src/security/security_selinux.c
(virSecuritySELinuxRestoreSecurityImageLabelInt)
(virSecuritySELinuxSetSecurityImageLabel)
(virSecuritySELinuxSetSecurityAllLabel): Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-03-24 11:59:50 -06:00
Martin Kletzander
95aed7febc Use K&R style for curly braces in remaining files
Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2014-03-20 17:27:17 +01:00
Scott Sullivan
0099a4ae2b is_selinux_enabled() returns -1 on error, account for this.
Per the documentation, is_selinux_enabled() returns -1 on error.
Account for this. Previously when -1 was being returned the condition
would still be true. I was noticing this because on my system that has
selinux disabled I was getting this in the libvirt.log every 5
seconds:

error : virIdentityGetSystem:173 : Unable to lookup SELinux process context: Invalid argument

With this patch applied, I no longer get these messages every 5
seconds. I am submitting this in case its deemed useful for inclusion.
Anyone have any comments on this change? This is a patch off current
master.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2014-03-20 16:26:55 +01:00
Daniel P. Berrange
2835c1e730 Add virLogSource variables to all source files
Any source file which calls the logging APIs now needs
to have a VIR_LOG_INIT("source.name") declaration at
the start of the file. This provides a static variable
of the virLogSource type.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-18 14:29:22 +00:00
Martin Kletzander
14fc041f69 Don't leave empty first line in C source files
If there should be some sort of separator it is better to use comment
with the filename, copyright, description, license information and
authors.

Found by:

git grep -nH '^$' | grep '\.[ch]:1:'

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2014-03-18 12:17:12 +01:00
Felix Geyer
29ea8a9b64 virt-aa-helper: handle 9pfs
Make virt-aa-helper create rules to allow VMs access to filesystem
mounts from the host.

Signed-off-by: Felix Geyer <debfx@fobos.de>
Signed-off-by: Hiroshi Miura <miurahr@linux.com>
Signed-off-by: Serge Hallyn <serge.hallyn@ubuntu.com>
Signed-off-by: Guido Günther <agx@sigxcpu.org>
2014-03-17 20:53:39 +01:00
Michal Privoznik
f5796b61cc virSecurityDACSetSecurityImageLabel: Unmark @def as unused
The @def is clearly used just a few lines below. There's no need to use
ATTRIBUTE_UNUSED for it.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2014-03-11 11:18:06 +01:00
Cédric Bosdonnat
9194ccecf1 apparmor: handle "none" type 2014-03-04 11:26:59 +00:00
Cédric Bosdonnat
500b2e9655 apparmor: add debug traces when changing profile.
The reason for these is that aa-status doesn't show the process using
the profile as they are in another namespace.
2014-03-04 11:07:05 +00:00
Cédric Bosdonnat
43c030f046 LXC driver: generate apparmor profiles for guests
use_apparmor() was first designed to be called from withing libvirtd,
but libvirt_lxc also uses it. in libvirt_lxc, there is no need to check
whether to use apparmor or not: just use it if possible.
2014-03-04 11:07:05 +00:00
Ján Tomko
0db9b0883c Generate a valid imagelabel even for type 'none'
Commit 2ce63c1 added imagelabel generation when relabeling is turned
off. But we weren't filling out the sensitivity for type 'none' labels,
resulting in an invalid label:

$ virsh managedsave domain
error: unable to set security context 'system_u:object_r:svirt_image_t'
on fd 28: Invalid argument
2014-02-05 19:47:30 +01:00
Osier Yang
10c9ceff6d util: Add one argument for several scsi utils
To support passing the path of the test data to the utils, one
more argument is added to virSCSIDeviceGetSgName,
virSCSIDeviceGetDevName, and virSCSIDeviceNew, and the related
code is changed accordingly.

Later tests for the scsi utils will be based on this patch.

Signed-off-by: Osier Yang <jyang@redhat.com>
2014-01-30 15:48:28 +08:00
Osier Yang
2b66504ded util: Add "shareable" field for virSCSIDevice struct
Unlike the host devices of other types, SCSI host device XML supports
"shareable" tag. This patch introduces it for the virSCSIDevice struct
for a later patch use (to detect if the SCSI device is shareable when
preparing the SCSI host device in QEMU driver).
2014-01-23 17:52:33 +08:00
Michal Privoznik
d1fdecb624 virSecuritySELinuxSetFileconHelper: Don't fail on read-only NFS
https://bugzilla.redhat.com/show_bug.cgi?id=996543

When starting up a domain, the SELinux labeling is done depending on
current configuration. If the labeling fails we check for possible
causes, as not all labeling failures are fatal. For example, if the
labeled file is on NFS which lacks SELinux support, the file can still
be readable to qemu process. These cases are distinguished by the errno
code: NFS without SELinux support returns EOPNOTSUPP. However, we were
missing one scenario. In case there's a read-only disk on a read-only
NFS (and possibly any FS) and the labeling is just optional (not
explicitly requested in the XML) there's no need to make the labeling
error fatal. In other words, read-only file on read-only NFS can fail to
be labeled, but be readable at the same time.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2014-01-17 13:35:01 +01:00
Eric Blake
baa7244951 maint: improve VIR_ERR_NO_SUPPORT usage
We weren't very consistent in our use of VIR_ERR_NO_SUPPORT; many
users just passed __FUNCTION__ on, while others passed "%s" to
silence over-eager compilers that warn about __FUNCTION__ not
containing any %.  It's nicer to route all these uses through
a single macro, so that if we ever need to change the reporting,
we can do it in one place.

I verified that 'virsh -c test:///default qemu-monitor-command test foo'
gives the same error message before and after this patch:
error: this function is not supported by the connection driver: virDomainQemuMonitorCommand

Note that in libvirt.c, we were inconsistent on whether virDomain*
API used virLibConnError() (with VIR_FROM_NONE) or virLibDomainError()
(with VIR_FROM_DOMAIN); this patch unifies these errors to all use
VIR_FROM_NONE, on the grounds that it is unlikely that a caller
learning that a call is unimplemented can do anything in particular
with extra knowledge of which error domain it belongs to.

One particular change to note is virDomainOpenGraphics which was
trying to fail with VIR_ERR_NO_SUPPORT after a failed
VIR_DRV_SUPPORTS_FEATURE check; all other places that fail a
feature check report VIR_ERR_ARGUMENT_UNSUPPORTED.

* src/util/virerror.h (virReportUnsupportedError): New macro.
* src/libvirt-qemu.c: Use new macro.
* src/libvirt-lxc.c: Likewise.
* src/lxc/lxc_driver.c: Likewise.
* src/security/security_manager.c: Likewise.
* src/util/virinitctl.c: Likewise.
* src/libvirt.c: Likewise.
(virDomainOpenGraphics): Use correct error for unsupported feature.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-01-04 12:15:08 -07:00
Daniel P. Berrange
d75d8b46f8 Don't overwrite errors from virConfReadFile
The SELinux security driver would overwrite errors from the
virConfReadFile function.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-12-04 15:40:23 +00:00
Daniel P. Berrange
2b510e4903 Fix off-by-1 in default SELinux MCS range
For a while we're have random failures of 'securityselinuxtest'
which were not at all reproducible. Fortunately we finally
caught a failure with VIR_TEST_DEBUG=1 enabled. This revealed

TEST: securityselinuxtest
 1) GenLabel "dynamic unconfined, s0, c0.c1023"                       ... OK
 2) GenLabel "dynamic unconfined, s0, c0.c1023"                       ... OK
 3) GenLabel "dynamic unconfined, s0, c0.c1023"                       ... OK
 4) GenLabel "dynamic virtd, s0, c0.c1023"                            ... OK
 5) GenLabel "dynamic virtd, s0, c0.c10"                              ... OK
 6) GenLabel "dynamic virtd, s2-s3, c0.c1023"                         ... OK
 7) GenLabel "dynamic virtd, missing range"                           ... Category two 1024 is out of range 0-1023
FAILED
FAIL: securityselinuxtest

And sure enough we had an off-by-1 in the MCS range code when
the current process has no range set. The test suite randomly
allocates 2 categories from 0->1024 so the chances of hitting
this in the test suite were slim indeed :-)

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-11-20 13:09:00 +00:00
Eric Blake
fb8613525d maint: avoid further typedef accidents
To make it easier to forbid future attempts at a confusing typedef
name ending in Ptr that isn't actually a pointer, insist that we
follow our preferred style of 'typedef foo *fooPtr'.

* cfg.mk (sc_forbid_const_pointer_typedef): Enforce consistent
style, to prevent issue fixed in previous storage patch.
* src/conf/capabilities.h (virCapsPtr): Fix offender.
* src/security/security_stack.c (virSecurityStackItemPtr):
Likewise.
* tests/qemucapabilitiestest.c (testQemuDataPtr): Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-10-30 17:02:12 -06:00
John Ferlan
aa42bb1700 Add '+' to uid/gid printing for label processing
To ensure proper processing by virGetUserID() and virGetGroupID()
of a uid/gid add a "+" prior to the uid/gid to denote it's really
a uid/gid for the label.
2013-10-29 17:10:15 -04:00
Peter Krempa
8e362a8955 apparmor: Fix typo in function name in driver struct initialization
Commit 64a68a4a introduced a typo in the initialization of the apparmor
driver structure breaking the build with apparmor enabled.
2013-10-29 17:01:22 +01:00
Giuseppe Scrivano
64a68a4a09 security: add new internal function "virSecurityManagerGetBaseLabel"
virSecurityManagerGetBaseLabel queries the default settings used by
a security model.

Signed-off-by: Giuseppe Scrivano <gscrivan@redhat.com>
2013-10-29 06:57:07 -06:00
Giuseppe Scrivano
4387132f31 security: use a single function to set DAC user and group
Merge the functions 'virSecurityDACSetUser' and
'virSecurityDACSetGroup' into 'virSecurityDACSetUserAndGroup'.

Signed-off-by: Giuseppe Scrivano <gscrivan@redhat.com>
2013-10-29 06:55:09 -06:00
Eric Blake
84e8091796 maint: avoid 'const fooPtr' in security
'const fooPtr' is the same as 'foo * const' (the pointer won't
change, but it's contents can).  But in general, if an interface
is trying to be const-correct, it should be using 'const foo *'
(the pointer is to data that can't be changed).

Fix up offenders in src/security.

* src/security/security_apparmor.c (reload_profile)
(AppArmorSetSecurityHostdevLabelHelper)
(AppArmorReleaseSecurityLabel, AppArmorRestoreSecurityAllLabel)
(AppArmorSetSecurityProcessLabel)
(AppArmorSetSecurityChildProcessLabel)
(AppArmorSetSecurityImageLabel, AppArmorSecurityVerify)
(AppArmorSetSecurityHostdevLabel)
(AppArmorRestoreSecurityHostdevLabel, AppArmorSetFDLabel): Drop
needless const.
* src/security/security_selinux.c
(virSecuritySELinuxSetSecurityFileLabel): Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-10-14 14:34:38 -06:00
Ján Tomko
f1bdcb2be9 selinux: Only close the selabel_handle once
On selinux driver initialization failure (missing/incorrectly
formatted contexts file), selabel_handle was closed twice.

Introduced by 6159710.
2013-10-01 15:00:07 +02:00
Michal Privoznik
32d7e2481b AppArmorSetSecurityImageLabel: Avoid use of uninitialized variable
The @profile_name variable can be used uninitialized.
2013-09-04 08:47:00 +02:00
Eric Blake
745aa55fbf security: provide supplemental groups even when parsing label (CVE-2013-4291)
Commit 29fe5d7 (released in 1.1.1) introduced a latent problem
for any caller of virSecurityManagerSetProcessLabel and where
the domain already had a uid:gid label to be parsed.  Such a
setup would collect the list of supplementary groups during
virSecurityManagerPreFork, but then ignores that information,
and thus fails to call setgroups() to adjust the supplementary
groups of the process.

Upstream does not use virSecurityManagerSetProcessLabel for
qemu (it uses virSecurityManagerSetChildProcessLabel instead),
so this problem remained latent until backporting the initial
commit into v0.10.2-maint (commit c061ff5, released in 0.10.2.7),
where virSecurityManagerSetChildProcessLabel has not been
backported.  As a result of using a different code path in the
backport, attempts to start a qemu domain that runs as qemu:qemu
will end up with supplementary groups unchanged from the libvirtd
parent process, rather than the desired supplementary groups of
the qemu user.  This can lead to failure to start a domain
(typical Fedora setup assigns user 107 'qemu' to both group 107
'qemu' and group 36 'kvm', so a disk image that is only readable
under kvm group rights is locked out).  Worse, it is a security
hole (the qemu process will inherit supplemental group rights
from the parent libvirtd process, which means it has access
rights to files owned by group 0 even when such files should
not normally be visible to user qemu).

LXC does not use the DAC security driver, so it is not vulnerable
at this time.  Still, it is better to plug the latent hole on
the master branch first, before cherry-picking it to the only
vulnerable branch v0.10.2-maint.

* src/security/security_dac.c (virSecurityDACGetIds): Always populate
groups and ngroups, rather than only when no label is parsed.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-08-29 08:43:03 -06:00
Eric Blake
0f082e699e selinux: distinguish failure to label from request to avoid label
https://bugzilla.redhat.com/show_bug.cgi?id=924153

Commit 904e05a2 (v0.9.9) added a per-<disk> seclabel element with
an attribute relabel='no' in order to try and minimize the
impact of shutdown delays when an NFS server disappears.  The idea
was that if a disk is on NFS and can't be labeled in the first
place, there is no need to attempt the (no-op) relabel on domain
shutdown.  Unfortunately, the way this was implemented was by
modifying the domain XML so that the optimization would survive
libvirtd restart, but in a way that is indistinguishable from an
explicit user setting.  Furthermore, once the setting is turned
on, libvirt avoids attempts at labeling, even for operations like
snapshot or blockcopy where the chain is being extended or pivoted
onto non-NFS, where SELinux labeling is once again possible.  As
a result, it was impossible to do a blockcopy to pivot from an
NFS image file onto a local file.

The solution is to separate the semantics of a chain that must
not be labeled (which the user can set even on persistent domains)
vs. the optimization of not attempting a relabel on cleanup (a
live-only annotation), and using only the user's explicit notation
rather than the optimization as the decision on whether to skip
a label attempt in the first place.  When upgrading an older
libvirtd to a newer, an NFS volume will still attempt the relabel;
but as the avoidance of a relabel was only an optimization, this
shouldn't cause any problems.

In the ideal future, libvirt will eventually have XML describing
EVERY file in the backing chain, with each file having a separate
<seclabel> element.  At that point, libvirt will be able to track
more closely which files need a relabel attempt at shutdown.  But
until we reach that point, the single <seclabel> for the entire
<disk> chain is treated as a hint - when a chain has only one
file, then we know it is accurate; but if the chain has more than
one file, we have to attempt relabel in spite of the attribute,
in case part of the chain is local and SELinux mattered for that
portion of the chain.

* src/conf/domain_conf.h (_virSecurityDeviceLabelDef): Add new
member.
* src/conf/domain_conf.c (virSecurityDeviceLabelDefParseXML):
Parse it, for live images only.
(virSecurityDeviceLabelDefFormat): Output it.
(virDomainDiskDefParseXML, virDomainChrSourceDefParseXML)
(virDomainDiskSourceDefFormat, virDomainChrDefFormat)
(virDomainDiskDefFormat): Pass flags on through.
* src/security/security_selinux.c
(virSecuritySELinuxRestoreSecurityImageLabelInt): Honor labelskip
when possible.
(virSecuritySELinuxSetSecurityFileLabel): Set labelskip, not
norelabel, if labeling fails.
(virSecuritySELinuxSetFileconHelper): Fix indentation.
* docs/formatdomain.html.in (seclabel): Document new xml.
* docs/schemas/domaincommon.rng (devSeclabel): Allow it in RNG.
* tests/qemuxml2argvdata/qemuxml2argv-seclabel-*-labelskip.xml:
* tests/qemuxml2argvdata/qemuxml2argv-seclabel-*-labelskip.args:
* tests/qemuxml2xmloutdata/qemuxml2xmlout-seclabel-*-labelskip.xml:
New test files.
* tests/qemuxml2argvtest.c (mymain): Run the new tests.
* tests/qemuxml2xmltest.c (mymain): Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-08-20 10:39:03 -06:00
Martin Kletzander
bba579b6e0 Expose ownership ID parsing
Parsing 'user:group' is useful even outside the DAC security driver,
so expose the most abstract function which has no DAC security driver
bits in itself.
2013-07-24 14:29:11 +02:00
Eric Blake
bfc183c1e3 security: fix deadlock with prefork
Attempts to start a domain with both SELinux and DAC security
modules loaded will deadlock; latent problem introduced in commit
fdb3bde and exposed in commit 29fe5d7.  Basically, when recursing
into the security manager for other driver's prefork, we have to
undo the asymmetric lock taken at the manager level.

Reported by Jiri Denemark, with diagnosis help from Dan Berrange.

* src/security/security_stack.c (virSecurityStackPreFork): Undo
extra lock grabbed during recursion.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-07-19 09:15:22 -06:00
Eric Blake
29fe5d745f security_dac: compute supplemental groups before fork
Commit 75c1256 states that virGetGroupList must not be called
between fork and exec, then commit ee777e99 promptly violated
that for lxc's use of virSecurityManagerSetProcessLabel.  Hoist
the supplemental group detection to the time that the security
manager needs to fork.  Qemu is safe, as it uses
virSecurityManagerSetChildProcessLabel which in turn uses
virCommand to determine supplemental groups.

This does not fix the fact that virSecurityManagerSetProcessLabel
calls virSecurityDACParseIds calls parseIds which eventually
calls getpwnam_r, which also violates fork/exec async-signal-safe
safety rules, but so far no one has complained of hitting
deadlock in that case.

* src/security/security_dac.c (_virSecurityDACData): Track groups
in private data.
(virSecurityDACPreFork): New function, to set them.
(virSecurityDACClose): Clean up new fields.
(virSecurityDACGetIds): Alter signature.
(virSecurityDACSetSecurityHostdevLabelHelper)
(virSecurityDACSetChardevLabel, virSecurityDACSetProcessLabel)
(virSecurityDACSetChildProcessLabel): Update callers.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-07-18 15:35:30 -06:00
Eric Blake
fdb3bde31c security: framework for driver PreFork handler
A future patch wants the DAC security manager to be able to safely
get the supplemental group list for a given uid, but at the time
of a fork rather than during initialization so as to pick up on
live changes to the system's group database.  This patch adds the
framework, including the possibility of a pre-fork callback
failing.

For now, any driver that implements a prefork callback must be
robust against the possibility of being part of a security stack
where a later element in the chain fails prefork.  This means
that drivers cannot do any action that requires a call to postfork
for proper cleanup (no grabbing a mutex, for example).  If this
is too prohibitive in the future, we would have to switch to a
transactioning sequence, where each driver has (up to) 3 callbacks:
PreForkPrepare, PreForkCommit, and PreForkAbort, to either clean
up or commit changes made during prepare.

* src/security/security_driver.h (virSecurityDriverPreFork): New
callback.
* src/security/security_manager.h (virSecurityManagerPreFork):
Change signature.
* src/security/security_manager.c (virSecurityManagerPreFork):
Optionally call into driver, and allow returning failure.
* src/security/security_stack.c (virSecurityDriverStack):
Wrap the handler for the stack driver.
* src/qemu/qemu_process.c (qemuProcessStart): Adjust caller.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-07-18 15:19:36 -06:00
Michal Privoznik
ba44dd2453 virSecurityManagerGenLabel: Skip seclabels without model
While generating seclabels, we check the seclabel stack if required
driver is in the stack. If not, an error is returned. However, it is
possible for a seclabel to not have any model set (happens with LXC
domains that have just <seclabel type='none'>). If that's the case,
we should just skip the iteration instead of calling STREQ(NULL, ...)
and SIGSEGV-ing subsequently.
2013-07-17 12:36:47 +02:00
Eric Blake
ee777e9949 util: make virSetUIDGID async-signal-safe
https://bugzilla.redhat.com/show_bug.cgi?id=964358

POSIX states that multi-threaded apps should not use functions
that are not async-signal-safe between fork and exec, yet we
were using getpwuid_r and initgroups.  Although rare, it is
possible to hit deadlock in the child, when it tries to grab
a mutex that was already held by another thread in the parent.
I actually hit this deadlock when testing multiple domains
being started in parallel with a command hook, with the following
backtrace in the child:

 Thread 1 (Thread 0x7fd56bbf2700 (LWP 3212)):
 #0  __lll_lock_wait ()
     at ../nptl/sysdeps/unix/sysv/linux/x86_64/lowlevellock.S:136
 #1  0x00007fd5761e7388 in _L_lock_854 () from /lib64/libpthread.so.0
 #2  0x00007fd5761e7257 in __pthread_mutex_lock (mutex=0x7fd56be00360)
     at pthread_mutex_lock.c:61
 #3  0x00007fd56bbf9fc5 in _nss_files_getpwuid_r (uid=0, result=0x7fd56bbf0c70,
     buffer=0x7fd55c2a65f0 "", buflen=1024, errnop=0x7fd56bbf25b8)
     at nss_files/files-pwd.c:40
 #4  0x00007fd575aeff1d in __getpwuid_r (uid=0, resbuf=0x7fd56bbf0c70,
     buffer=0x7fd55c2a65f0 "", buflen=1024, result=0x7fd56bbf0cb0)
     at ../nss/getXXbyYY_r.c:253
 #5  0x00007fd578aebafc in virSetUIDGID (uid=0, gid=0) at util/virutil.c:1031
 #6  0x00007fd578aebf43 in virSetUIDGIDWithCaps (uid=0, gid=0, capBits=0,
     clearExistingCaps=true) at util/virutil.c:1388
 #7  0x00007fd578a9a20b in virExec (cmd=0x7fd55c231f10) at util/vircommand.c:654
 #8  0x00007fd578a9dfa2 in virCommandRunAsync (cmd=0x7fd55c231f10, pid=0x0)
     at util/vircommand.c:2247
 #9  0x00007fd578a9d74e in virCommandRun (cmd=0x7fd55c231f10, exitstatus=0x0)
     at util/vircommand.c:2100
 #10 0x00007fd56326fde5 in qemuProcessStart (conn=0x7fd53c000df0,
     driver=0x7fd55c0dc4f0, vm=0x7fd54800b100, migrateFrom=0x0, stdin_fd=-1,
     stdin_path=0x0, snapshot=0x0, vmop=VIR_NETDEV_VPORT_PROFILE_OP_CREATE,
     flags=1) at qemu/qemu_process.c:3694
 ...

The solution is to split the work of getpwuid_r/initgroups into the
unsafe portions (getgrouplist, called pre-fork) and safe portions
(setgroups, called post-fork).

* src/util/virutil.h (virSetUIDGID, virSetUIDGIDWithCaps): Adjust
signature.
* src/util/virutil.c (virSetUIDGID): Add parameters.
(virSetUIDGIDWithCaps): Adjust clients.
* src/util/vircommand.c (virExec): Likewise.
* src/util/virfile.c (virFileAccessibleAs, virFileOpenForked)
(virDirCreate): Likewise.
* src/security/security_dac.c (virSecurityDACSetProcessLabel):
Likewise.
* src/lxc/lxc_container.c (lxcContainerSetID): Likewise.
* configure.ac (AC_CHECK_FUNCS_ONCE): Check for setgroups, not
initgroups.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-07-11 15:46:42 -06:00
Daniel P. Berrange
716961372e Convert 'int i' to 'size_t i' in src/security files
Convert the type of loop iterators named 'i', 'j', k',
'ii', 'jj', 'kk', to be 'size_t' instead of 'int' or
'unsigned int', also santizing 'ii', 'jj', 'kk' to use
the normal 'i', 'j', 'k' naming

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-07-10 17:40:14 +01:00
Michal Privoznik
a72715e0a8 Adapt to VIR_ALLOC and virAsprintf in src/security/* 2013-07-10 11:07:32 +02:00
Michal Privoznik
8290cbbc38 viralloc: Report OOM error on failure
Similarly to VIR_STRDUP, we want the OOM error to be reported in
VIR_ALLOC and friends.
2013-07-10 11:07:31 +02:00
Peter Krempa
2ce63c1611 selinux: Always generate imagelabel
The imagelabel SELinux label was only generated when relabeling was
enabled. This prohibited labeling of files created by libvirt that need
to be labeled even if relabeling is turned off.

The only codepath this change has direct impact on is labeling of FDs
passed to qemu which is always safe in current state.
2013-07-08 15:04:20 +02:00
Peter Krempa
e45ee23c59 selinux: Cleanup coding style 2013-07-08 15:04:07 +02:00
Laine Stump
1d829e1306 pci: rename virPCIDeviceGetVFIOGroupDev to virPCIDeviceGetIOMMUGroupDev
I realized after the fact that it's probably better in the long run to
give this function a name that matches the name of the link used in
sysfs to hold the group (iommu_group).

I'm changing it now because I'm about to add several more functions
that deal with iommu groups.
2013-06-25 18:07:38 -04:00
Ján Tomko
0b466db29b selinux: assume 's0' if the range is empty
This fixes a crash:
https://bugzilla.redhat.com/show_bug.cgi?id=969878
2013-06-11 13:13:43 +02:00
Eric Blake
146ba114a5 syntax: prefer space after semicolon in for loop
I noticed several unusual spacings in for loops, and decided to
fix them up.  See the next commit for the syntax check that found
all of these.

* examples/domsuspend/suspend.c (main): Fix spacing.
* python/libvirt-override.c: Likewise.
* src/conf/interface_conf.c: Likewise.
* src/security/virt-aa-helper.c: Likewise.
* src/util/virconf.c: Likewise.
* src/util/virhook.c: Likewise.
* src/util/virlog.c: Likewise.
* src/util/virsocketaddr.c: Likewise.
* src/util/virsysinfo.c: Likewise.
* src/util/viruuid.c: Likewise.
* src/vbox/vbox_tmpl.c: Likewise.
* src/xen/xen_hypervisor.c: Likewise.
* tools/virsh-domain-monitor.c (vshDomainStateToString): Drop
default case, to let compiler check us.
* tools/virsh-domain.c (vshDomainVcpuStateToString): Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-05-28 07:56:07 -06:00
Osier Yang
fb6a05e75d security_dac: Fix the coding style
Pushed under trivial rule.
2013-05-24 23:33:09 +08:00
Michal Privoznik
aaa42912ae Adapt to VIR_STRDUP and VIR_STRNDUP in src/security/* 2013-05-23 09:56:38 +02:00
Osier Yang
3de80af28a src/security: Remove the whitespace before ';' 2013-05-21 23:41:44 +08:00
Michal Privoznik
23fbda20a7 security_apparmor.c: Include virscsi.h
After introducing AppArmorSetSecuritySCSILabel() in 2691cd5f
we are using virSCSIDevicePtr type without proper include.
2013-05-13 14:01:14 +02:00
Osier Yang
2691cd5fe8 security: Manage the security label for scsi host device
To not introduce more redundant code, helpers are added for
both "selinux", "dac", and "apparmor" backends.

Signed-off-by: Han Cheng <hanc.fnst@cn.fujitsu.com>
Signed-off-by: Osier Yang <jyang@redhat>

v2.5 - v3:
  * Splitted from 8/10 of v2.5
  * Don't forget the other backends (DAC, and apparmor)
2013-05-13 19:08:40 +08:00
Laine Stump
bfe7721d50 util: move virFile* functions from virutil.c to virfile.c
These all existed before virfile.c was created, and for some reason
weren't moved.

This is mostly straightfoward, although the syntax rule prohibiting
write() had to be changed to have an exception for virfile.c instead
of virutil.c.

This movement pointed out that there is a function called
virBuildPath(), and another almost identical function called
virFileBuildPath(). They really should be a single function, which
I'll take care of as soon as I figure out what the arglist should look
like.
2013-05-10 13:09:30 -04:00
Daniel P. Berrange
0454a7cd3d Replace 'goto clean' with 'goto cleanup' in apparmor code
Some of the apparmor code files did not follow the normal
goto label naming pratices

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-09 17:18:44 +01:00
Ján Tomko
dcea5a492f get rid of virBufferAsprintf where possible
Use virBufferAddLit or virBufferAddChar instead.
2013-05-07 17:38:58 +02:00
Michal Privoznik
7c9a2d88cd virutil: Move string related functions to virstring.c
The source code base needs to be adapted as well. Some files
include virutil.h just for the string related functions (here,
the include is substituted to match the new file), some include
virutil.h without any need (here, the include is removed), and
some require both.
2013-05-02 16:56:55 +02:00
Laine Stump
ed12bbee81 security driver: eliminate memory leaks in failure paths
If virPCIDeviceGetVFIOGroupDev() failed,
virSecurity*(Set|Restore)HostdevLabel() would fail to free a
virPCIDevice that had been allocated.

These leaks were all introduced (by me) very recently, in commit
f0bd70a.
2013-04-30 11:22:32 -04:00
Laine Stump
19635f7d0d conf: remove extraneous _TYPE from driver backend enums
This isn't strictly speaking a bugfix, but I realized I'd gotten a bit
too verbose when I chose the names for
VIR_DOMAIN_HOSTDEV_PCI_BACKEND_TYPE_*. This shortens them all a bit.
2013-04-26 21:51:12 -04:00
Laine Stump
f0bd70a940 security: update hostdev labelling functions for VFIO
Legacy kvm style pci device assignment requires changes to the
labelling of several sysfs files for each device, but for vfio device
assignment, the only thing that needs to be relabelled/chowned is the
"group" device for the group that contains the device to be assigned.
2013-04-25 21:28:43 -04:00
Laine Stump
9f80fc1bd5 conf: put hostdev pci address in a struct
There will soon be other items related to pci hostdevs that need to be
in the same part of the hostdevsubsys union as the pci address (which
is currently a single member called "pci". This patch replaces the
single member named pci with a struct named pci that contains a single
member named "addr".
2013-04-25 21:23:38 -04:00
Peter Krempa
4165ea9663 selinux: Don't mask errors of virSecuritySELinuxGenNewContext
Since cbe67ff9b0
virSecuritySELinuxGenNewContext reports good error messages. Fix callers
that mask the errors by generic error message.
2013-04-24 16:03:35 +02:00
Osier Yang
bc95be5dea cleanup: Remove the duplicate header
Detected by a simple Shell script:

for i in $(git ls-files -- '*.[ch]'); do
    awk 'BEGIN {
        fail=0
    }
    /# *include.*\.h/{
        match($0, /["<][^">]*[">]/)
        arr[substr($0, RSTART+1, RLENGTH-2)]++
    }
    END {
        for (key in arr) {
            if (arr[key] > 1) {
                fail=1
                printf("%d %s\n", arr[key], key)
            }
        }
        if (fail == 1)
            exit 1
    }' $i

    if test $? != 0; then
        echo "Duplicate header(s) in $i"
    fi
done;

A later patch will add the syntax-check to avoid duplicate
headers.
2013-04-17 15:49:35 +08:00
Stefan Berger
2a40a09220 Add SELinux and DAC labeling support for TPM passthrough
Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
Reviewed-by: Corey Bryant <coreyb@linux.vnet.ibm.com>
Tested-by: Corey Bryant <coreyb@linux.vnet.ibm.com>
2013-04-12 16:55:46 -04:00
Peter Krempa
482e5f159c virCaps: get rid of defaultConsoleTargetType callback
This patch refactors various places to allow removing of the
defaultConsoleTargetType callback from the virCaps structure.

A new console character device target type is introduced -
VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_NONE - to mark that no type was
specified in the XML. This type is at the end converted to the standard
VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL. Other types that are
different from this default have to be processed separately in the
device post parse callback.
2013-04-04 22:42:39 +02:00
Peter Krempa
ad0d10b2b1 conf callback: Rearrange function parameters
Move the xmlopt and caps arguments to the end of the argument list.
2013-04-04 22:41:19 +02:00
Peter Krempa
43b99fc4c0 conf: Add post XML parse callbacks and prepare for cleaning of virCaps
This patch adds instrumentation that will allow hypervisor drivers to
fill and validate domain and device definitions after parsed by the XML
parser.

With this patch, after the XML is parsed, a callback to the driver is
issued requesting to fill and validate driver specific details of the
configuration. This allows to use sensible defaults and checks on a per
driver basis at the time the XML is parsed.

Two callback pointers are stored in the new virDomainXMLConf object:
* virDomainDeviceDefPostParseCallback (devicesPostParseCallback)
  - called for a single device parsed and for every single device in a
    domain config. A virDomainDeviceDefPtr is passed along with the
    domain definition and virCaps.

* virDomainDefPostParseCallback, (domainPostParseCallback)
  - A callback that is meant to process the domain config after it's
  parsed.  A virDomainDefPtr is passed along with virCaps.

Both types of callbacks support arbitrary opaque data passed for the
callback functions.

Errors may be reported in those callbacks resulting in a XML parsing
failure.
2013-04-04 22:29:48 +02:00
Peter Krempa
e84b19316a maint: Rename xmlconf to xmlopt and virDomainXMLConfig to virDomainXMLOption
This patch is the result of running:

for i in $(git ls-files | grep -v html | grep -v \.po$ ); do
  sed -i -e "s/virDomainXMLConf/virDomainXMLOption/g" -e "s/xmlconf/xmlopt/g" $i
done

and a few manual tweaks.
2013-04-04 22:18:56 +02:00
Guido Günther
ea151935bb security_manager: fix comparison
otherwise we crash later on if we don't find a match like:

 #0  0xb72c2b4f in virSecurityManagerGenLabel (mgr=0xb8e42d20, vm=0xb8ef40c0) at security/security_manager.c:424
 #1  0xb18811f3 in qemuProcessStart (conn=conn@entry=0xb8eed880, driver=driver@entry=0xb8e3b1e0, vm=vm@entry=0xb8ef58f0,
     migrateFrom=migrateFrom@entry=0xb18f6088 "stdio", stdin_fd=18,
     stdin_path=stdin_path@entry=0xb8ea7798 "/var/lib/jenkins/jobs/libvirt-tck-build/workspace/tck.img", snapshot=snapshot@entry=0x0,
     vmop=vmop@entry=VIR_NETDEV_VPORT_PROFILE_OP_RESTORE, flags=flags@entry=2) at qemu/qemu_process.c:3364
 #2  0xb18d6cb2 in qemuDomainSaveImageStartVM (conn=conn@entry=0xb8eed880, driver=driver@entry=0xb8e3b1e0, vm=0xb8ef58f0, fd=fd@entry=0xb6bf3f98,
     header=header@entry=0xb6bf3fa0, path=path@entry=0xb8ea7798 "/var/lib/jenkins/jobs/libvirt-tck-build/workspace/tck.img",
     start_paused=start_paused@entry=false) at qemu/qemu_driver.c:4843
 #3  0xb18d7eeb in qemuDomainRestoreFlags (conn=conn@entry=0xb8eed880,
     path=path@entry=0xb8ea7798 "/var/lib/jenkins/jobs/libvirt-tck-build/workspace/tck.img", dxml=dxml@entry=0x0, flags=flags@entry=0)
     at qemu/qemu_driver.c:4962
 #4  0xb18d8123 in qemuDomainRestore (conn=0xb8eed880, path=0xb8ea7798 "/var/lib/jenkins/jobs/libvirt-tck-build/workspace/tck.img")
     at qemu/qemu_driver.c:4987
 #5  0xb718d186 in virDomainRestore (conn=0xb8eed880, from=0xb8ea87d8 "/var/lib/jenkins/jobs/libvirt-tck-build/workspace/tck.img") at libvirt.c:2768
 #6  0xb7736363 in remoteDispatchDomainRestore (args=<optimized out>, rerr=0xb6bf41f0, client=0xb8eedaf0, server=<optimized out>, msg=<optimized out>)
     at remote_dispatch.h:4679
 #7  remoteDispatchDomainRestoreHelper (server=0xb8e1a3e0, client=0xb8eedaf0, msg=0xb8ee72c8, rerr=0xb6bf41f0, args=0xb8ea8968, ret=0xb8ef5330)
     at remote_dispatch.h:4661
 #8  0xb720db01 in virNetServerProgramDispatchCall (msg=0xb8ee72c8, client=0xb8eedaf0, server=0xb8e1a3e0, prog=0xb8e216b0)
     at rpc/virnetserverprogram.c:439
 #9  virNetServerProgramDispatch (prog=0xb8e216b0, server=server@entry=0xb8e1a3e0, client=0xb8eedaf0, msg=0xb8ee72c8) at rpc/virnetserverprogram.c:305
 #10 0xb7206e97 in virNetServerProcessMsg (msg=<optimized out>, prog=<optimized out>, client=<optimized out>, srv=0xb8e1a3e0) at rpc/virnetserver.c:162
 #11 virNetServerHandleJob (jobOpaque=0xb8ea7720, opaque=0xb8e1a3e0) at rpc/virnetserver.c:183
 #12 0xb70f9f78 in virThreadPoolWorker (opaque=opaque@entry=0xb8e1a540) at util/virthreadpool.c:144
 #13 0xb70f94a5 in virThreadHelper (data=0xb8e0e558) at util/virthreadpthread.c:161
 #14 0xb705d954 in start_thread (arg=0xb6bf4b70) at pthread_create.c:304
 #15 0xb6fd595e in clone () at ../sysdeps/unix/sysv/linux/i386/clone.S:130

This unbreaks libvirt-tck's domain/100-transient-save-restore.t with
qemu:///session and selinux compiled in but disabled.

Introduced by 8d68cbeaa8
2013-04-03 22:57:31 +02:00
Michal Privoznik
8d68cbeaa8 sec_manager: Refuse to start domain with unsupported seclabel
https://bugzilla.redhat.com/show_bug.cgi?id=947387

If a user configures a domain to use a seclabel of a specific type,
but the appropriate driver is not accessible, we should refuse to
start the domain. For instance, if user requires selinux, but it is
either non present in the system, or is just disabled, we should not
start the domain. Moreover, since we are touching only those labels we
have a security driver for, the other labels may confuse libvirt when
reconnecting to a domain on libvirtd restart. In our selinux example,
when starting up a domain, missing security label is okay, as we
auto-generate one. But later, when libvirt is re-connecting to a live
qemu instance, we parse a state XML, where security label is required
and it is an error if missing:

  error : virSecurityLabelDefParseXML:3228 : XML error: security label
  is missing

This results in a qemu process left behind without any libvirt control.
2013-04-03 10:19:46 +02:00
Michal Privoznik
a1c68a1fcb security_manager.c: Append seclabel iff generated
With my previous patches, we unconditionally appended a seclabel,
even if it wasn't generated but found in array of defined seclabels.
This resulted in double free later when doing virDomainDefFree
and iterating over the array of defined seclabels.

Moreover, there was another possibility of double free, if the
seclabel was generated in the last iteration of the process of
walking trough security managers array.
2013-03-28 16:13:01 +01:00
Michal Privoznik
e4a28a3281 security: Don't add seclabel of type none if there's already a seclabel
https://bugzilla.redhat.com/show_bug.cgi?id=923946

The <seclabel type='none'/> should be added iff there is no other
seclabel defined within a domain. This bug can be easily reproduced:
1) configure selinux seclabel for a domain
2) disable system's selinux and restart libvirtd
3) observe <seclabel type='none'/> being appended to a domain on its
   startup
2013-03-28 10:01:06 +01:00
Michal Privoznik
6c4de11614 security_manager: Don't manipulate domain XML in virDomainDefGetSecurityLabelDef
The virDomainDefGetSecurityLabelDef was modifying the domain XML.
It tried to find a seclabel corresponding to given sec driver. If the
label wasn't found, the function created one which is wrong. In fact
it's security manager which should modify this part of domain XML.
2013-03-28 10:01:06 +01:00
Olivia Yin
26705e02c1 selinux: deal with dtb file 2013-03-19 15:48:59 -06:00
Daniel P. Berrange
1732c1c629 Fix parsing of SELinux ranges without a category
Normally libvirtd should run with a SELinux label

  system_u:system_r:virtd_t:s0-s0:c0.c1023

If a user manually runs libvirtd though, it is sometimes
possible to get into a situation where it is running

  system_u:system_r:init_t:s0

The SELinux security driver isn't expecting this and can't
parse the security label since it lacks the ':c0.c1023' part
causing it to complain

  internal error Cannot parse sensitivity level in s0

This updates the parser to cope with this, so if no category
is present, libvirtd will hardcode the equivalent of c0.c1023.

Now this won't work if SELinux is in Enforcing mode, but that's
not an issue, because the user can only get into this problem
if in Permissive mode. This means they can now start VMs in
Permissive mode without hitting that parsing error

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-03-14 12:42:21 +00:00
Daniel P. Berrange
4a92fe4413 Separate MCS range parsing from MCS range checking
Pull the code which parses the current process MCS range
out of virSecuritySELinuxMCSFind and into a new method
virSecuritySELinuxMCSGetProcessRange.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-03-14 12:42:21 +00:00
Daniel P. Berrange
f2d8190cfb Fix memory leak on OOM in virSecuritySELinuxMCSFind
The body of the loop in virSecuritySELinuxMCSFind would
directly 'return NULL' on OOM, instead of jumping to the
cleanup label. This caused a leak of several local vars.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-03-14 12:42:21 +00:00
Peter Krempa
27cf98e2d1 virCaps: conf: start splitting out irrelevat data
The virCaps structure gathered a ton of irrelevant data over time that.
The original reason is that it was propagated to the XML parser
functions.

This patch aims to create a new data structure virDomainXMLConf that
will contain immutable data that are used by the XML parser. This will
allow two things we need:

1) Get rid of the stuff from virCaps

2) Allow us to add callbacks to check and add driver specific stuff
after domain XML is parsed.

This first attempt removes pointers to private data allocation functions
to this new structure and update all callers and function that require
them.
2013-03-13 09:27:14 +01:00
Guannan Ren
ce4557c3ab apparmor: use AppArmorSetFDLabel for both imageFD and tapFD
Rename AppArmorSetImageFDLabel to AppArmorSetFDLabel which could
be used as a common function for *ALL* fd relabelling in Linux.

In apparmor profile for specific vm with uuid cdbebdfa-1d6d-65c3-be0f-fd74b978a773
Path: /etc/apparmor.d/libvirt/libvirt-cdbebdfa-1d6d-65c3-be0f-fd74b978a773.files
The last line is for the tapfd relabelling.

 # DO NOT EDIT THIS FILE DIRECTLY. IT IS MANAGED BY LIBVIRT.
  "/var/log/libvirt/**/rhel6qcow2.log" w,
  "/var/lib/libvirt/**/rhel6qcow2.monitor" rw,
  "/var/run/libvirt/**/rhel6qcow2.pid" rwk,
  "/run/libvirt/**/rhel6qcow2.pid" rwk,
  "/var/run/libvirt/**/*.tunnelmigrate.dest.rhel6qcow2" rw,
  "/run/libvirt/**/*.tunnelmigrate.dest.rhel6qcow2" rw,
  "/var/lib/libvirt/images/rhel6u3qcow2.img" rw,
  "/dev/tap45" rw,
2013-03-08 10:56:07 +08:00
Jim Fehlig
438a3850db Fix starting qemu instances when apparmor driver is enabled
With the apparmor security driver enabled, qemu instances fail
to start

# grep ^security_driver /etc/libvirt/qemu.conf
security_driver = "apparmor"
# virsh start test-kvm
error: Failed to start domain test-kvm
error: internal error security label already defined for VM

The model field of virSecurityLabelDef object is always populated
by virDomainDefGetSecurityLabelDef(), so remove the check for a
NULL model when verifying if a label is already defined for the
instance.

Checking for a NULL model and populating it later in
AppArmorGenSecurityLabel() has been left in the code to be
consistent with virSecuritySELinuxGenSecurityLabel().
2013-02-28 17:35:59 -07:00
John Ferlan
676688b69b security: Remove unnecessary checks for mgr == NULL
Coverity found the DACGenLabel was checking for mgr == NULL after a
possible dereference; however, in order to get into the function the
virSecurityManagerGenLabel would have already dereferenced sec_managers[i]
so the check was unnecessary. Same check is made in SELinuxGenSecurityLabel.
2013-02-16 07:44:35 -05:00
Laine Stump
7bf1aa0b9b security: add new virSecurityManagerSetChildProcessLabel API
The existing virSecurityManagerSetProcessLabel() API is designed so
that it must be called after forking the child process, but before
exec'ing the child. Due to the way the virCommand API works, that
means it needs to be put in a "hook" function that virCommand is told
to call out to at that time.

Setting the child process label is a basic enough need when executing
any process that virCommand should have a method of doing that. But
virCommand must be told what label to set, and only the security
driver knows the answer to that question.

The new virSecurityManagerSet*Child*ProcessLabel() API is the way to
transfer the knowledge about what label to set from the security
driver to the virCommand object. It is given a virCommandPtr, and each
security driver calls the appropriate virCommand* API to tell
virCommand what to do between fork and exec.

1) in the case of the DAC security driver, it calls
virCommandSetUID/GID() to set a uid and gid that must be set for the
child process.

2) for the SELinux security driver, it calls
virCommandSetSELinuxLabel() to save a copy of the char* that will be
sent to setexeccon_raw() *after forking the child process*.

3) for the AppArmor security drivers, it calls
virCommandSetAppArmorProfile() to save a copy of the char* that will
be sent to aa_change_profile() *after forking the child process*.

With this new API in place, we will be able to remove
virSecurityManagerSetProcessLabel() from any virCommand pre-exec
hooks.

(Unfortunately, the LXC driver uses clone() rather than virCommand, so
it can't take advantage of this new security driver API, meaning that
we need to keep around the older virSecurityManagerSetProcessLabel(),
at least for now.)
2013-02-13 16:11:16 -05:00
Daniel P. Berrange
61b52d2e38 Fix potential deadlock across fork() in QEMU driver
The hook scripts used by virCommand must be careful wrt
accessing any mutexes that may have been held by other
threads in the parent process. With the recent refactoring
there are 2 potential flaws lurking, which will become real
deadlock bugs once the global QEMU driver lock is removed.

Remove use of the QEMU driver lock from the hook function
by passing in the 'virQEMUDriverConfigPtr' instance directly.

Add functions to the virSecurityManager to be invoked before
and after fork, to ensure the mutex is held by the current
thread. This allows it to be safely used in the hook script
in the child process.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-02-12 11:05:31 +00:00
Eric Blake
736a87b916 build: fix compilation of selinux on RHEL 5
On RHEL 5, I got:

security/security_selinux.c: In function 'getContext':
security/security_selinux.c:971: warning: unused parameter 'mgr' [-Wunused-parameter]

* src/security/security_selinux.c (getContext): Mark potentially
unused parameter.
2013-02-11 17:12:25 -07:00