Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6224,6 +6224,7 @@ dependencies = [
"dirs",
"disk_backend_resources",
"disk_crypt_resources",
"disk_vhdmp",
"firmware_uefi_resources",
"floppy_resources",
"framebuffer",
Expand Down Expand Up @@ -11376,6 +11377,7 @@ dependencies = [
"disk_backend",
"disk_backend_resources",
"disk_vhd1",
"disk_vhdmp",
"disk_vmdk",
"fs-err",
"futures",
Expand Down
5 changes: 4 additions & 1 deletion Guide/src/reference/openvmm/management/grpc.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,10 @@ or reopen the file.

Some API fields reference OS handles by name. For example,
`VirtioFs.WindowsOptions.user_token_name` names an access token that virtio-fs
impersonates for host file access.
impersonates for host file access. `DiskBackend.virtual_disk` names a VHD or
VHDX handle that the client opened with `OpenVirtualDisk` and attached for raw
access, so OpenVMM accesses the image with the client's rights rather than its
own.

Clients register these handles over the same socket using the
[resource-passing protocol]. Because Windows Unix sockets cannot carry handles,
Expand Down
1 change: 1 addition & 0 deletions openvmm/openvmm_entry/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ unicycle.workspace = true
net_tap.workspace = true

[target.'cfg(windows)'.dependencies]
disk_vhdmp.workspace = true
vmswitch.workspace = true
virt_whp.workspace = true
vmbus_proxy.workspace = true
Expand Down
151 changes: 147 additions & 4 deletions openvmm/openvmm_entry/src/ttrpc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2876,7 +2876,7 @@ async fn build_pci_device(
let resource = build_virtio_device(virtio, registry).await?;
VirtioPciDeviceHandle(resource).into_resource()
}
Kind::Nvme(nvme) => build_nvme_controller(nvme).await?,
Kind::Nvme(nvme) => build_nvme_controller(nvme, registry).await?,
Kind::Vfio(vfio) => build_vfio_device(vfio, iommufds)?,
})
}
Expand Down Expand Up @@ -2995,6 +2995,7 @@ fn build_vfio_device(
/// Builds an NVMe controller resource from the proto `NvmeConfig`.
async fn build_nvme_controller(
nvme: vmservice::NvmeConfig,
registry: &ResourceRegistry,
) -> anyhow::Result<Resource<PciDeviceHandleKind>> {
let vmservice::NvmeConfig {
controller_id,
Expand All @@ -3007,8 +3008,12 @@ async fn build_nvme_controller(
backend,
read_only,
} = ns;
let disk =
build_disk_backend(backend.context("missing namespace backend")?, read_only).await?;
let disk = build_disk_backend(
backend.context("missing namespace backend")?,
read_only,
registry,
)
.await?;
namespaces.push(nvme_resources::NamespaceDefinition {
nsid,
read_only,
Expand Down Expand Up @@ -3040,7 +3045,8 @@ async fn build_virtio_device(
serial,
}) => {
let disk =
build_disk_backend(backend.context("missing blk backend")?, read_only).await?;
build_disk_backend(backend.context("missing blk backend")?, read_only, registry)
.await?;
virtio_resources::blk::VirtioBlkHandle {
disk,
read_only,
Expand Down Expand Up @@ -3168,10 +3174,34 @@ fn build_virtio_fs_windows_options(
async fn build_disk_backend(
backend: vmservice::DiskBackend,
read_only: bool,
registry: &ResourceRegistry,
) -> anyhow::Result<Resource<DiskHandleKind>> {
if let Some(vmservice::disk_backend::Kind::VirtualDisk(disk)) = &backend.kind {
return virtual_disk_backend(&disk.handle_name, registry);
}
crate::disk_open(&disk_backend_from_proto(backend)?, read_only).await
}

/// Resolves the VHD or VHDX handle registered as `handle_name`.
fn virtual_disk_backend(
handle_name: &str,
registry: &ResourceRegistry,
) -> anyhow::Result<Resource<DiskHandleKind>> {
#[cfg(windows)]
{
let file: File = registry
.resolve(handle_name)
.with_context(|| format!("failed to resolve virtual disk '{handle_name}'"))?
.into();
Ok(disk_vhdmp::OpenVhdmpDiskConfig(disk_vhdmp::Vhd::from_file(file)).into_resource())
}
#[cfg(not(windows))]
{
let _ = (handle_name, registry);
anyhow::bail!("virtual disk backends are only supported on Windows")
}
}

fn disk_backend_from_proto(backend: vmservice::DiskBackend) -> anyhow::Result<DiskCliKind> {
let vmservice::DiskBackend { kind } = backend;
Ok(match kind.context("missing disk backend kind")? {
Expand All @@ -3187,6 +3217,9 @@ fn disk_backend_from_proto(backend: vmservice::DiskBackend) -> anyhow::Result<Di
vmservice::disk_backend::Kind::Memory(vmservice::MemoryDisk { size_bytes }) => {
DiskCliKind::Memory(size_bytes)
}
vmservice::disk_backend::Kind::VirtualDisk(_) => {
anyhow::bail!("virtual disk backends must be a storage device's own backend")
}
vmservice::disk_backend::Kind::MemoryDiff(overlay) => DiskCliKind::MemoryDiff(Box::new(
disk_backend_from_proto(*overlay.lower.context("missing memory diff lower disk")?)?,
)),
Expand Down Expand Up @@ -3793,6 +3826,116 @@ mod tests {
}
}

fn virtual_disk(name: &str) -> vmservice::DiskBackend {
vmservice::DiskBackend {
kind: Some(vmservice::disk_backend::Kind::VirtualDisk(
vmservice::VirtualDisk {
handle_name: name.into(),
},
)),
}
}

#[test]
fn unregistered_virtual_disk_backend_is_rejected() {
DefaultPool::run_with(async |_driver| {
let registry = ResourceRegistry::default();
for name in ["", "missing"] {
let error = build_disk_backend(virtual_disk(name), false, &registry)
.await
.unwrap_err();
#[cfg(windows)]
assert_eq!(
format!("{error:#}"),
format!(
"failed to resolve virtual disk '{name}': no handle registered under name '{name}'"
)
);
#[cfg(not(windows))]
assert_eq!(
error.to_string(),
"virtual disk backends are only supported on Windows"
);
}
});
}

#[cfg(windows)]
#[test]
fn registered_virtual_disk_backends() {
DefaultPool::run_with(async |_driver| {
let registry = ResourceRegistry::default();
let file = tempfile::tempfile().unwrap();
registry.register("disk".into(), file.into()).unwrap();
let backend = || virtual_disk("disk");

build_nvme_controller(
vmservice::NvmeConfig {
namespaces: vec![vmservice::NvmeNamespace {
nsid: 1,
backend: Some(backend()),
read_only: true,
}],
..Default::default()
},
&registry,
)
.await
.unwrap();
build_virtio_device(
vmservice::VirtioDevice {
kind: Some(vmservice::virtio_device::Kind::Blk(vmservice::VirtioBlk {
backend: Some(backend()),
read_only: true,
..Default::default()
})),
},
&registry,
)
.await
.unwrap();
// Registered handles are resolved as VHDMP disks, not files.
let disk = build_disk_backend(backend(), true, &registry)
.await
.unwrap();
assert_eq!(disk.id(), "vhdmp");

registry.deregister("disk");
assert!(
build_disk_backend(backend(), true, &registry)
.await
.is_err()
);
});
}

/// Virtual disks can only be a storage device's own backend, not, for
/// example, a VMGS backend or the lower disk of a memory diff overlay.
#[test]
fn virtual_disk_backend_must_be_used_directly() {
DefaultPool::run_with(async |_driver| {
let registry = ResourceRegistry::default();
let diff = vmservice::DiskBackend {
kind: Some(vmservice::disk_backend::Kind::MemoryDiff(Box::new(
vmservice::MemoryDiffDisk {
lower: Some(Box::new(virtual_disk("disk"))),
},
))),
};
for error in [
disk_backend_from_proto(virtual_disk("disk")).unwrap_err(),
build_disk_backend(diff, false, &registry)
.await
.unwrap_err(),
] {
assert_eq!(
error.to_string(),
"virtual disk backends must be a storage device's own backend"
);
}
});
}

#[test]
fn shutdown_request_acceptance_does_not_halt_or_teardown_vm() {
DefaultPool::run_with(async |driver| {
Expand Down
1 change: 1 addition & 0 deletions openvmm/openvmm_ttrpc_vmservice/src/resource_passing.md
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ the RPC. Once the RPC succeeds, the name may be deregistered.
| Field | Host | Resource |
|-------|------|----------|
| `TapBackend.fd_name` | Linux | tap device fd, used instead of opening `/dev/net/tun` |
| `DiskBackend.virtual_disk.handle_name` | Windows | VHD or VHDX handle opened with `OpenVirtualDisk` and attached for raw access |
| `VirtioFs.WindowsOptions.user_token_name` | Windows | access token that virtio-fs impersonates for host file access |

## Wire format examples
Expand Down
17 changes: 16 additions & 1 deletion openvmm/openvmm_ttrpc_vmservice/src/vmservice.proto
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,8 @@ message DiskBackend {
MemoryDisk memory = 2;
// A memory-backed writable overlay over a read-only lower disk.
MemoryDiffDisk memory_diff = 3;
// A VHD or VHDX opened by the client (Windows only).
VirtualDisk virtual_disk = 4;
}
}

Expand All @@ -384,10 +386,23 @@ message MemoryDisk {
}

message MemoryDiffDisk {
// Read-only lower disk.
// Read-only lower disk. Registered disk handles cannot be used here.
DiskBackend lower = 1;
}

// A VHD or VHDX that the client opened with `OpenVirtualDisk` and attached for
// raw access with `ATTACH_VIRTUAL_DISK_FLAG_NO_LOCAL_HOST` (plus
// `ATTACH_VIRTUAL_DISK_FLAG_READ_ONLY` for a read-only disk), so OpenVMM
// accesses the image with the client's rights rather than its own.
//
// The client registers the handle using the resource-passing protocol (see
// resource_passing.md). OpenVMM duplicates the registered handle while
// processing the request; the name may be deregistered after the RPC succeeds.
message VirtualDisk {
// Name of the registered virtual disk handle.
string handle_name = 1;
}

// A disk backed by a host file.
message FileDisk {
// Path to the backing file.
Expand Down
76 changes: 76 additions & 0 deletions vm/devices/storage/disk_vhdmp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,12 @@ mod virtdisk {
/// Handle for an open VHD file.
pub struct Vhd(fs::File);

impl AsHandle for Vhd {
fn as_handle(&self) -> BorrowedHandle<'_> {
self.0.as_handle()
}
}

fn chk_win32(err: u32) -> std::io::Result<()> {
if err == 0 {
Ok(())
Expand Down Expand Up @@ -479,6 +485,15 @@ impl OpenOptions {
}

impl Vhd {
/// Wraps a virtual disk handle opened by another component, such as a
/// client that passed it to this process.
///
/// `file` must have been opened with `OpenVirtualDisk` and attached for
/// raw access, as [`OpenOptions::open()`] does.
pub fn from_file(file: fs::File) -> Self {
Self(file)
}

/// Create a new dynamic VHD
pub fn create_dynamic(path: &Path, max_size_mb: u64, vhdx: bool) -> std::io::Result<Self> {
let mut path16: Vec<_> = path.as_os_str().encode_wide().collect();
Expand Down Expand Up @@ -659,6 +674,17 @@ impl Vhd {
.into())
}
}

fn is_attached(&self) -> std::io::Result<bool> {
// SAFETY: Accessing the right union field for this call.
unsafe {
Ok(self
.info_static(virtdisk::GET_VIRTUAL_DISK_INFO_IS_LOADED)?
.u
.IsLoaded
!= 0)
}
}
}

#[derive(MeshPayload)]
Expand Down Expand Up @@ -730,6 +756,12 @@ pub enum Error {
#[error("failed to query VHD metadata")]
/// Error querying disk metadata
Query(#[source] std::io::Error),
#[error("VHD is not attached for raw access")]
/// The disk was opened without being attached for raw access.
NotAttached,
#[error("VHD is attached read-only but the disk is writable")]
/// The disk was attached read-only, but was configured as writable.
AttachedReadOnly,
}

impl VhdmpDisk {
Expand All @@ -745,6 +777,17 @@ impl VhdmpDisk {

/// Creates a disk from an open VHD handle. `vhd` should have been opened via [`OpenOptions::open()`].
pub fn new(vhd: Vhd, read_only: bool) -> Result<Self, Error> {
// A handle passed in by a client may not have been attached, and
// metadata queries would then fail with an unrelated error.
if !vhd.is_attached().map_err(Error::Query)? {
return Err(Error::NotAttached);
}
// Likewise, a handle attached read-only would fail every guest write.
if !read_only
&& scsi::is_write_protected(vhd.0.as_handle()).map_err(Error::Query)? == Some(true)
{
return Err(Error::AttachedReadOnly);
}
let size = vhd.get_size().map_err(Error::Query)?;
let disk_id = vhd.get_disk_id().map_err(Error::Query)?;
let unmap_cap = scsi::unmap_capabilities(vhd.0.as_handle()).map_err(Error::Query)?;
Expand Down Expand Up @@ -985,6 +1028,39 @@ mod tests {
assert_eq!(read_bytes(&disk, 0, 512).await, vec![0x5a; 512]);
}

#[test]
fn unattached_handle_is_rejected() {
let path = make_test_vhd();
let vhd = VhdmpDisk::options().open_raw(path.as_ref()).unwrap();
assert!(matches!(
VhdmpDisk::new(vhd, false),
Err(super::Error::NotAttached)
));
}

/// A handle attached read-only can back a read-only disk but not a
/// writable one.
#[test]
fn read_only_attach_requires_read_only_disk() {
let path = make_test_vhd();
let open = || {
VhdmpDisk::options()
.read_only(true)
.open(path.as_ref())
.unwrap()
};
assert!(matches!(
VhdmpDisk::new(open(), false),
Err(super::Error::AttachedReadOnly)
));
VhdmpDisk::new(open(), true).unwrap();
let vhd = VhdmpDisk::options()
.read_only(false)
.open(path.as_ref())
.unwrap();
VhdmpDisk::new(vhd, false).unwrap();
}

#[test]
fn open_readonly() {
let path = make_test_vhd();
Expand Down
Loading
Loading