Skip to content
Closed
Show file tree
Hide file tree
Changes from 7 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 @@ -1642,12 +1642,14 @@ dependencies = [
"disk_backend_resources",
"guestmem",
"inspect",
"pal",
"pal_async",
"scsi_buffers",
"storage_tests",
"tempfile",
"thiserror 2.0.16",
"vm_resource",
"windows-sys 0.61.0",
]

[[package]]
Expand Down
4 changes: 3 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,9 @@ 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. `HandleDisk.handle_name` names a host
physical disk handle, such as `\\.\PhysicalDriveN`, opened for synchronous
(non-overlapped) I/O.

Clients register these handles over the same socket using the
[resource-passing protocol]. Because Windows Unix sockets cannot carry handles,
Expand Down
120 changes: 116 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,7 +3174,24 @@ 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::Handle(vmservice::HandleDisk { handle_name })) =
backend.kind
{
#[cfg(windows)]
{
let handle = registry
.resolve(&handle_name)
.with_context(|| format!("failed to resolve disk handle '{handle_name}'"))?;
return Ok(disk_backend_resources::PhysicalDiskHandle(handle.into()).into_resource());
}
#[cfg(not(windows))]
{
let _ = (handle_name, registry);
anyhow::bail!("handle disk backends are only supported on Windows")
}
}
crate::disk_open(&disk_backend_from_proto(backend)?, read_only).await
}

Expand All @@ -3187,6 +3210,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::Handle(_) => {
anyhow::bail!("handle disk backends require a standalone disk")
}
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 +3819,92 @@ mod tests {
}
}

#[test]
fn unregistered_handle_disk_backend_is_rejected() {
DefaultPool::run_with(async |_driver| {
let registry = ResourceRegistry::default();
for name in ["", "missing"] {
let backend = vmservice::DiskBackend {
kind: Some(vmservice::disk_backend::Kind::Handle(
vmservice::HandleDisk {
handle_name: name.into(),
},
)),
};
let error = build_disk_backend(backend, false, &registry)
.await
.unwrap_err();
#[cfg(windows)]
assert_eq!(
format!("{error:#}"),
format!(
"failed to resolve disk handle '{name}': no handle registered under name '{name}'"
)
);
#[cfg(not(windows))]
assert_eq!(
error.to_string(),
"handle disk backends are only supported on Windows"
);
}
});
}

#[cfg(windows)]
#[test]
fn registered_handle_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 = || vmservice::DiskBackend {
kind: Some(vmservice::disk_backend::Kind::Handle(
vmservice::HandleDisk {
handle_name: "disk".into(),
},
)),
};

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 physical disks, not files.
let disk = build_disk_backend(backend(), true, &registry)
.await
.unwrap();
assert_eq!(disk.id(), "physical_disk");

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

#[test]
fn shutdown_request_acceptance_does_not_halt_or_teardown_vm() {
DefaultPool::run_with(async |driver| {
Expand Down
2 changes: 2 additions & 0 deletions openvmm/openvmm_resources/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ vm_resource::register_static_resolvers! {
#[cfg(feature = "disk_crypt")]
disk_crypt::resolver::DiskCryptResolver,
disk_file::FileDiskResolver,
#[cfg(windows)]
disk_file::PhysicalDiskResolver,
#[cfg(target_os = "linux")]
disk_blockdevice::resolver::StaticBlockDeviceResolver,
disk_prwrap::DiskWithReservationsResolver,
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` |
| `HandleDisk.handle_name` | Windows | host physical disk handle opened for synchronous (non-overlapped) I/O |
| `VirtioFs.WindowsOptions.user_token_name` | Windows | access token that virtio-fs impersonates for host file access |

## Wire format examples
Expand Down
13 changes: 13 additions & 0 deletions 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 host physical disk opened by the client (Windows only).
HandleDisk handle = 4;
}
}

Expand All @@ -388,6 +390,17 @@ message MemoryDiffDisk {
DiskBackend lower = 1;
}

// A disk backed by a host physical disk handle, such as `\\.\PhysicalDriveN`.
//
// The client opens the disk for synchronous (non-overlapped) I/O and
// registers its 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 HandleDisk {
// Name of the registered physical disk handle (Windows only).
string handle_name = 1;
}

// A disk backed by a host file.
message FileDisk {
// Path to the backing file.
Expand Down
2 changes: 2 additions & 0 deletions support/pal/src/windows/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
pub mod relative;
pub mod sparse;

pub use relative::ensure_synchronous;

use super::chk_status;
use super::dos_to_nt_path;
use std::ffi::c_void;
Expand Down
6 changes: 4 additions & 2 deletions support/pal/src/windows/fs/relative.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,9 @@ impl PendingIoStatus {
}
}

fn ensure_synchronous(file: &fs::File) -> io::Result<()> {
/// Fails with [`io::ErrorKind::InvalidInput`] unless `file` was opened for
/// synchronous I/O, that is, without `FILE_FLAG_OVERLAPPED`.
pub fn ensure_synchronous(file: &fs::File) -> io::Result<()> {
let mut mode = ntioapi::FILE_MODE_INFORMATION::default();
let io_status = PendingIoStatus::new();
let mut status = unsafe {
Expand All @@ -98,7 +100,7 @@ fn ensure_synchronous(file: &fs::File) -> io::Result<()> {
{
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"relative file operation requires a synchronous handle",
"handle must be opened for synchronous I/O",
));
}
Ok(())
Expand Down
24 changes: 24 additions & 0 deletions support/pal/src/windows/security.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,11 @@ use windows_sys::Win32::Security::SECURITY_CAPABILITIES;
use windows_sys::Win32::Security::SID_AND_ATTRIBUTES;
use windows_sys::Win32::Security::SecurityImpersonation;
use windows_sys::Win32::Security::TOKEN_DUPLICATE;
use windows_sys::Win32::Security::TOKEN_ELEVATION;
use windows_sys::Win32::Security::TOKEN_IMPERSONATE;
use windows_sys::Win32::Security::TOKEN_QUERY;
use windows_sys::Win32::Security::TOKEN_USER;
use windows_sys::Win32::Security::TokenElevation;
use windows_sys::Win32::Security::TokenImpersonation;
use windows_sys::Win32::Security::TokenUser;
use windows_sys::Win32::Storage::FileSystem::CREATE_NEW;
Expand Down Expand Up @@ -441,6 +443,28 @@ pub fn open_process_token(access: u32) -> std::io::Result<OwnedHandle> {
}
}

/// Returns whether the current process token is elevated.
pub fn is_process_elevated() -> std::io::Result<bool> {
let token = open_process_token(TOKEN_QUERY)?;
let mut elevation = TOKEN_ELEVATION { TokenIsElevated: 0 };
let mut returned = 0;
// SAFETY: The token handle is valid for TOKEN_QUERY, and the output buffer
// is a properly sized and aligned TOKEN_ELEVATION.
let ok = unsafe {
GetTokenInformation(
token.as_raw_handle(),
TokenElevation,
std::ptr::from_mut(&mut elevation).cast(),
size_of::<TOKEN_ELEVATION>() as u32,
&mut returned,
)
};
if ok == 0 {
return Err(std::io::Error::last_os_error());
}
Ok(elevation.TokenIsElevated != 0)
}

/// Creates an impersonation token, owned by this process, from `token`, with
/// `TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_DUPLICATE` access.
///
Expand Down
11 changes: 11 additions & 0 deletions vm/devices/storage/disk_backend_resources/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,17 @@ impl ResourceId<DiskHandleKind> for BlockDeviceDiskHandle {
const ID: &'static str = "block";
}

/// Physical-disk-backed disk handle (Windows), such as `\\.\PhysicalDriveN`.
///
/// The handle must be opened for synchronous I/O. Size and sector geometry
/// are queried from the disk.
#[derive(MeshPayload)]
pub struct PhysicalDiskHandle(pub std::fs::File);

impl ResourceId<DiskHandleKind> for PhysicalDiskHandle {
const ID: &'static str = "physical_disk";
}

/// Disk handle for a disk that emulates persistent reservation support.
#[derive(MeshPayload)]
pub struct DiskWithReservationsHandle(pub Resource<DiskHandleKind>);
Expand Down
4 changes: 4 additions & 0 deletions vm/devices/storage/disk_file/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ inspect = { workspace = true, features = ["filepath"] }
blocking.workspace = true
thiserror.workspace = true

[target.'cfg(windows)'.dependencies]
pal.workspace = true
windows-sys = { workspace = true, features = ["Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Ioctl"] }

[dev-dependencies]
pal_async.workspace = true
storage_tests.workspace = true
Expand Down
Loading
Loading