Skip to content

Commit a1f7b8e

Browse files
damanm24Daman Mulye
andauthored
rpc: accept client-opened virtual disks via registered handle (#5196)
This PR adds support for attaching a VHD or VHDX that the client has already opened to a VM through the ttrpc/gRPC interface on Windows, so the image is accessed with the client's rights rather than OpenVMM's. Callers open the image with `OpenVirtualDisk`, attach it for raw access, register the handle through the resource-passing protocol, and reference it by name with `DiskBackend.virtual_disk.handle_name`. OpenVMM wraps the handle as a VHDMP disk, so I/O, discard and read-only handling match disks that OpenVMM opens by path. Virtual disks can back virtio-blk devices and NVMe namespaces. Handles that are not attached for raw access are rejected with a specific error. Co-authored-by: Daman Mulye <damanmulye@microsoft.com>
1 parent bf35346 commit a1f7b8e

10 files changed

Lines changed: 585 additions & 101 deletions

File tree

‎Cargo.lock‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6224,6 +6224,7 @@ dependencies = [
62246224
"dirs",
62256225
"disk_backend_resources",
62266226
"disk_crypt_resources",
6227+
"disk_vhdmp",
62276228
"firmware_uefi_resources",
62286229
"floppy_resources",
62296230
"framebuffer",
@@ -11377,6 +11378,7 @@ dependencies = [
1137711378
"disk_backend",
1137811379
"disk_backend_resources",
1137911380
"disk_vhd1",
11381+
"disk_vhdmp",
1138011382
"disk_vmdk",
1138111383
"fs-err",
1138211384
"futures",

‎Guide/src/reference/openvmm/management/grpc.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,10 @@ or reopen the file.
112112

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

117120
Clients register these handles over the same socket using the
118121
[resource-passing protocol]. Because Windows Unix sockets cannot carry handles,

‎openvmm/openvmm_entry/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ unicycle.workspace = true
108108
net_tap.workspace = true
109109

110110
[target.'cfg(windows)'.dependencies]
111+
disk_vhdmp.workspace = true
111112
vmswitch.workspace = true
112113
virt_whp.workspace = true
113114
vmbus_proxy.workspace = true

‎openvmm/openvmm_entry/src/ttrpc/mod.rs‎

Lines changed: 127 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2880,7 +2880,7 @@ async fn build_pci_device(
28802880
let resource = build_virtio_device(virtio, registry).await?;
28812881
VirtioPciDeviceHandle(resource).into_resource()
28822882
}
2883-
Kind::Nvme(nvme) => build_nvme_controller(nvme).await?,
2883+
Kind::Nvme(nvme) => build_nvme_controller(nvme, registry).await?,
28842884
Kind::Vfio(vfio) => build_vfio_device(vfio, iommufds)?,
28852885
})
28862886
}
@@ -2999,6 +2999,7 @@ fn build_vfio_device(
29992999
/// Builds an NVMe controller resource from the proto `NvmeConfig`.
30003000
async fn build_nvme_controller(
30013001
nvme: vmservice::NvmeConfig,
3002+
registry: &ResourceRegistry,
30023003
) -> anyhow::Result<Resource<PciDeviceHandleKind>> {
30033004
let vmservice::NvmeConfig {
30043005
controller_id,
@@ -3011,8 +3012,12 @@ async fn build_nvme_controller(
30113012
backend,
30123013
read_only,
30133014
} = ns;
3014-
let disk =
3015-
build_disk_backend(backend.context("missing namespace backend")?, read_only).await?;
3015+
let disk = build_disk_backend(
3016+
backend.context("missing namespace backend")?,
3017+
read_only,
3018+
registry,
3019+
)
3020+
.await?;
30163021
namespaces.push(nvme_resources::NamespaceDefinition {
30173022
nsid,
30183023
read_only,
@@ -3044,7 +3049,8 @@ async fn build_virtio_device(
30443049
serial,
30453050
}) => {
30463051
let disk =
3047-
build_disk_backend(backend.context("missing blk backend")?, read_only).await?;
3052+
build_disk_backend(backend.context("missing blk backend")?, read_only, registry)
3053+
.await?;
30483054
virtio_resources::blk::VirtioBlkHandle {
30493055
disk,
30503056
read_only,
@@ -3173,10 +3179,34 @@ fn build_virtio_fs_windows_options(
31733179
async fn build_disk_backend(
31743180
backend: vmservice::DiskBackend,
31753181
read_only: bool,
3182+
registry: &ResourceRegistry,
31763183
) -> anyhow::Result<Resource<DiskHandleKind>> {
3184+
if let Some(vmservice::disk_backend::Kind::VirtualDisk(disk)) = &backend.kind {
3185+
return virtual_disk_backend(&disk.handle_name, registry);
3186+
}
31773187
crate::disk_open(&disk_backend_from_proto(backend)?, read_only).await
31783188
}
31793189

3190+
/// Resolves the VHD or VHDX handle registered as `handle_name`.
3191+
fn virtual_disk_backend(
3192+
handle_name: &str,
3193+
registry: &ResourceRegistry,
3194+
) -> anyhow::Result<Resource<DiskHandleKind>> {
3195+
#[cfg(windows)]
3196+
{
3197+
let file: File = registry
3198+
.resolve(handle_name)
3199+
.with_context(|| format!("failed to resolve virtual disk '{handle_name}'"))?
3200+
.into();
3201+
Ok(disk_vhdmp::OpenVhdmpDiskConfig(disk_vhdmp::Vhd::from_file(file)).into_resource())
3202+
}
3203+
#[cfg(not(windows))]
3204+
{
3205+
let _ = (handle_name, registry);
3206+
anyhow::bail!("virtual disk backends are only supported on Windows")
3207+
}
3208+
}
3209+
31803210
fn disk_backend_from_proto(backend: vmservice::DiskBackend) -> anyhow::Result<DiskCliKind> {
31813211
let vmservice::DiskBackend { kind } = backend;
31823212
Ok(match kind.context("missing disk backend kind")? {
@@ -3192,6 +3222,9 @@ fn disk_backend_from_proto(backend: vmservice::DiskBackend) -> anyhow::Result<Di
31923222
vmservice::disk_backend::Kind::Memory(vmservice::MemoryDisk { size_bytes }) => {
31933223
DiskCliKind::Memory(size_bytes)
31943224
}
3225+
vmservice::disk_backend::Kind::VirtualDisk(_) => {
3226+
anyhow::bail!("virtual disk backends must be a storage device's own backend")
3227+
}
31953228
vmservice::disk_backend::Kind::MemoryDiff(overlay) => DiskCliKind::MemoryDiff(Box::new(
31963229
disk_backend_from_proto(*overlay.lower.context("missing memory diff lower disk")?)?,
31973230
)),
@@ -3798,6 +3831,96 @@ mod tests {
37983831
}
37993832
}
38003833

3834+
fn virtual_disk(name: &str) -> vmservice::DiskBackend {
3835+
vmservice::DiskBackend {
3836+
kind: Some(vmservice::disk_backend::Kind::VirtualDisk(
3837+
vmservice::VirtualDisk {
3838+
handle_name: name.into(),
3839+
},
3840+
)),
3841+
}
3842+
}
3843+
3844+
#[cfg(windows)]
3845+
#[test]
3846+
fn registered_virtual_disk_backends() {
3847+
DefaultPool::run_with(async |_driver| {
3848+
let registry = ResourceRegistry::default();
3849+
let file = tempfile::tempfile().unwrap();
3850+
registry.register("disk".into(), file.into()).unwrap();
3851+
let backend = || virtual_disk("disk");
3852+
3853+
build_nvme_controller(
3854+
vmservice::NvmeConfig {
3855+
namespaces: vec![vmservice::NvmeNamespace {
3856+
nsid: 1,
3857+
backend: Some(backend()),
3858+
read_only: true,
3859+
}],
3860+
..Default::default()
3861+
},
3862+
&registry,
3863+
)
3864+
.await
3865+
.unwrap();
3866+
build_virtio_device(
3867+
vmservice::VirtioDevice {
3868+
kind: Some(vmservice::virtio_device::Kind::Blk(vmservice::VirtioBlk {
3869+
backend: Some(backend()),
3870+
read_only: true,
3871+
..Default::default()
3872+
})),
3873+
},
3874+
&registry,
3875+
)
3876+
.await
3877+
.unwrap();
3878+
// Registered handles are resolved as VHDMP disks, not files.
3879+
let disk = build_disk_backend(backend(), true, &registry)
3880+
.await
3881+
.unwrap();
3882+
assert_eq!(disk.id(), "vhdmp");
3883+
3884+
// Names are resolved when the device is built, so a deregistered
3885+
// name no longer resolves.
3886+
registry.deregister("disk");
3887+
let error = build_disk_backend(backend(), true, &registry)
3888+
.await
3889+
.unwrap_err();
3890+
assert_eq!(
3891+
format!("{error:#}"),
3892+
"failed to resolve virtual disk 'disk': no handle registered under name 'disk'"
3893+
);
3894+
});
3895+
}
3896+
3897+
/// Virtual disks can only be a storage device's own backend, not, for
3898+
/// example, a VMGS backend or the lower disk of a memory diff overlay.
3899+
#[test]
3900+
fn virtual_disk_backend_must_be_used_directly() {
3901+
DefaultPool::run_with(async |_driver| {
3902+
let registry = ResourceRegistry::default();
3903+
let diff = vmservice::DiskBackend {
3904+
kind: Some(vmservice::disk_backend::Kind::MemoryDiff(Box::new(
3905+
vmservice::MemoryDiffDisk {
3906+
lower: Some(Box::new(virtual_disk("disk"))),
3907+
},
3908+
))),
3909+
};
3910+
for error in [
3911+
disk_backend_from_proto(virtual_disk("disk")).unwrap_err(),
3912+
build_disk_backend(diff, false, &registry)
3913+
.await
3914+
.unwrap_err(),
3915+
] {
3916+
assert_eq!(
3917+
error.to_string(),
3918+
"virtual disk backends must be a storage device's own backend"
3919+
);
3920+
}
3921+
});
3922+
}
3923+
38013924
#[test]
38023925
fn shutdown_request_acceptance_does_not_halt_or_teardown_vm() {
38033926
DefaultPool::run_with(async |driver| {

‎openvmm/openvmm_ttrpc_vmservice/src/resource_passing.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,7 @@ the RPC. Once the RPC succeeds, the name may be deregistered.
232232
| Field | Host | Resource |
233233
|-------|------|----------|
234234
| `TapBackend.fd_name` | Linux | tap device fd, used instead of opening `/dev/net/tun` |
235+
| `DiskBackend.virtual_disk.handle_name` | Windows | VHD or VHDX handle opened with `OpenVirtualDisk` and attached for raw access |
235236
| `VirtioFs.WindowsOptions.user_token_name` | Windows | access token that virtio-fs impersonates for host file access |
236237

237238
## Wire format examples

‎openvmm/openvmm_ttrpc_vmservice/src/vmservice.proto‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -375,6 +375,8 @@ message DiskBackend {
375375
MemoryDisk memory = 2;
376376
// A memory-backed writable overlay over a read-only lower disk.
377377
MemoryDiffDisk memory_diff = 3;
378+
// A VHD or VHDX opened by the client (Windows only).
379+
VirtualDisk virtual_disk = 4;
378380
}
379381
}
380382

@@ -384,10 +386,23 @@ message MemoryDisk {
384386
}
385387

386388
message MemoryDiffDisk {
387-
// Read-only lower disk.
389+
// Read-only lower disk. Registered disk handles cannot be used here.
388390
DiskBackend lower = 1;
389391
}
390392

393+
// A VHD or VHDX that the client opened with `OpenVirtualDisk` and attached for
394+
// raw access with `ATTACH_VIRTUAL_DISK_FLAG_NO_LOCAL_HOST` (plus
395+
// `ATTACH_VIRTUAL_DISK_FLAG_READ_ONLY` for a read-only disk), so OpenVMM
396+
// accesses the image with the client's rights rather than its own.
397+
//
398+
// The client registers the handle using the resource-passing protocol (see
399+
// resource_passing.md). OpenVMM duplicates the registered handle while
400+
// processing the request; the name may be deregistered after the RPC succeeds.
401+
message VirtualDisk {
402+
// Name of the registered virtual disk handle.
403+
string handle_name = 1;
404+
}
405+
391406
// A disk backed by a host file.
392407
message FileDisk {
393408
// Path to the backing file.

‎vm/devices/storage/disk_vhdmp/src/lib.rs‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,12 @@ mod virtdisk {
394394
/// Handle for an open VHD file.
395395
pub struct Vhd(fs::File);
396396

397+
impl AsHandle for Vhd {
398+
fn as_handle(&self) -> BorrowedHandle<'_> {
399+
self.0.as_handle()
400+
}
401+
}
402+
397403
fn chk_win32(err: u32) -> std::io::Result<()> {
398404
if err == 0 {
399405
Ok(())
@@ -479,6 +485,15 @@ impl OpenOptions {
479485
}
480486

481487
impl Vhd {
488+
/// Wraps a virtual disk handle opened by another component, such as a
489+
/// client that passed it to this process.
490+
///
491+
/// `file` must have been opened with `OpenVirtualDisk` and attached for
492+
/// raw access, as [`OpenOptions::open()`] does.
493+
pub fn from_file(file: fs::File) -> Self {
494+
Self(file)
495+
}
496+
482497
/// Create a new dynamic VHD
483498
pub fn create_dynamic(path: &Path, max_size_mb: u64, vhdx: bool) -> std::io::Result<Self> {
484499
let mut path16: Vec<_> = path.as_os_str().encode_wide().collect();
@@ -659,6 +674,17 @@ impl Vhd {
659674
.into())
660675
}
661676
}
677+
678+
fn is_attached(&self) -> std::io::Result<bool> {
679+
// SAFETY: Accessing the right union field for this call.
680+
unsafe {
681+
Ok(self
682+
.info_static(virtdisk::GET_VIRTUAL_DISK_INFO_IS_LOADED)?
683+
.u
684+
.IsLoaded
685+
!= 0)
686+
}
687+
}
662688
}
663689

664690
#[derive(MeshPayload)]
@@ -730,6 +756,9 @@ pub enum Error {
730756
#[error("failed to query VHD metadata")]
731757
/// Error querying disk metadata
732758
Query(#[source] std::io::Error),
759+
#[error("VHD is not attached for raw access")]
760+
/// The disk was opened without being attached for raw access.
761+
NotAttached,
733762
}
734763

735764
impl VhdmpDisk {
@@ -745,6 +774,11 @@ impl VhdmpDisk {
745774

746775
/// Creates a disk from an open VHD handle. `vhd` should have been opened via [`OpenOptions::open()`].
747776
pub fn new(vhd: Vhd, read_only: bool) -> Result<Self, Error> {
777+
// A handle passed in by a client may not have been attached, and
778+
// metadata queries would then fail with an unrelated error.
779+
if !vhd.is_attached().map_err(Error::Query)? {
780+
return Err(Error::NotAttached);
781+
}
748782
let size = vhd.get_size().map_err(Error::Query)?;
749783
let disk_id = vhd.get_disk_id().map_err(Error::Query)?;
750784
let unmap_cap = scsi::unmap_capabilities(vhd.0.as_handle()).map_err(Error::Query)?;
@@ -985,6 +1019,16 @@ mod tests {
9851019
assert_eq!(read_bytes(&disk, 0, 512).await, vec![0x5a; 512]);
9861020
}
9871021

1022+
#[test]
1023+
fn unattached_handle_is_rejected() {
1024+
let path = make_test_vhd();
1025+
let vhd = VhdmpDisk::options().open_raw(path.as_ref()).unwrap();
1026+
assert!(matches!(
1027+
VhdmpDisk::new(vhd, false),
1028+
Err(super::Error::NotAttached)
1029+
));
1030+
}
1031+
9881032
#[test]
9891033
fn open_readonly() {
9901034
let path = make_test_vhd();

‎vmm_tests/vmm_tests/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ virt_mshv.workspace = true
9292

9393
[target.'cfg(windows)'.dev-dependencies]
9494
der.workspace = true
95+
disk_vhdmp.workspace = true
9596
virt_whp.workspace = true
9697
windows-sys = { workspace = true, features = ["Win32_Security"] }
9798
x509-cert.workspace = true

0 commit comments

Comments
 (0)