Skip to content

Commit cf5f914

Browse files
Enrique SaurezCopilot
authored andcommitted
host: open strict private snapshot directories
Validate the fixed snapshot layout, private regular files, bounded metadata and key/manifest agreement without reading snapshot.json. Retain the caller immutability contract and cover Linux/Windows refusal cases. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 6789d491-7d13-4929-bc64-4edfec93ba60
1 parent b253a3d commit cf5f914

9 files changed

Lines changed: 657 additions & 10 deletions

File tree

‎nvx-rs/README.md‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ changes only when the module's purpose does.
125125
| [`nvx::exec`](#nvxexec) | The execution engine: the streams, credit, and outcome of an execution's two sides, without I/O, for any framing |
126126
| [`nvx::host::runtime`](#nvxhostruntime) | `Runtime`: what every launch shares, the runtime's files and their identity, the hypervisor and its probe, and the launch options |
127127
| [`nvx::host::vm`](#nvxhostvm) | A private VM directory, cold preparation, verified detached launch, confirmed stop, and caller-saved reattachment |
128-
| [`nvx::host::snapshot`](#nvxhostsnapshot) | Snapshot compatibility keys, strict manifests, restore-time eligibility, and the opaque input of a future VM restore |
128+
| [`nvx::host::snapshot`](#nvxhostsnapshot) | Strict private snapshot directories, verified keys and manifests, time eligibility, and the input of a future VM restore |
129129
| [`nvx::host::config`](#nvxhostconfig) | `VmConfig` and `CaptureConfig`: pure configuration, cold-boot kernel/OpenVMM arguments, portable length checks, and capture identity |
130130
| [`nvx::host::restore`](#nvxhostrestore) | A caller-driven restore to Ready without I/O or a clock, and its peer-verified restore-ready listener |
131131
| [`nvx::host::artifacts`](#nvxhostartifacts) | Locating the OpenVMM executable and the guest artifacts that a VM runs, and their runtime identity |
@@ -579,9 +579,19 @@ The key's canonical encoding and identity use the snapshot names and omit
579579
and no reader or migration of the prior encoding is supported. `CaptureClass`
580580
still records the legacy capture inputs, including its guest build.
581581

582-
`Snapshot` is an opaque input of a future restore. `vm::create` currently
583-
refuses `Some(snapshot)` with `ErrorKind::Unsupported`; only cold boots are
584-
supported.
582+
`Snapshot::open` checks exactly `key.bin`, `snapshot.json` and
583+
`openvmm/{manifest.bin,memory.bin,state.bin}`. Directories are private, files
584+
are regular and private to their owner, artifact lengths equal the strict
585+
manifest's, and the canonical key is consistent with that manifest.
586+
`KEY_FILE`, `DESCRIPTION_FILE` and `OPENVMM_DIR` name the root entries.
587+
The description must exist, but its contents are never read, parsed or
588+
trusted. `Snapshot::key` and `manifest` expose the verified metadata.
589+
590+
The caller keeps the directory and every entry private and immutable while
591+
using the snapshot; opening checks them once and retains no file handles
592+
or lock. `Snapshot` remains an opaque input of a future restore:
593+
`vm::create` still refuses `Some(snapshot)` with `ErrorKind::Unsupported`;
594+
only cold boots are supported.
585595

586596
### `nvx::host::config`
587597

‎nvx-rs/public-api/linux.txt‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3040,6 +3040,7 @@ method nvx::host::snapshot::CaptureClass::to_bytes
30403040
struct nvx::host::snapshot::ClassIdentity
30413041
method nvx::host::snapshot::ClassIdentity::as_bytes
30423042
method nvx::host::snapshot::ClassIdentity::from_bytes
3043+
const nvx::host::snapshot::DESCRIPTION_FILE
30433044
struct nvx::host::snapshot::Downtime
30443045
field nvx::host::snapshot::Downtime::nanos
30453046
field nvx::host::snapshot::Downtime::source
@@ -3077,13 +3078,18 @@ method nvx::host::snapshot::Invariants::iter
30773078
method nvx::host::snapshot::Invariants::len
30783079
method nvx::host::snapshot::Invariants::new
30793080
method nvx::host::snapshot::Invariants::with
3081+
const nvx::host::snapshot::KEY_FILE
30803082
struct nvx::host::snapshot::KeyIdentity
30813083
method nvx::host::snapshot::KeyIdentity::as_bytes
30823084
method nvx::host::snapshot::KeyIdentity::from_bytes
30833085
const nvx::host::snapshot::MANIFEST_NAME
30843086
const nvx::host::snapshot::MAX_DOWNTIME_NS
30853087
const nvx::host::snapshot::MAX_MANIFEST_LEN
3088+
const nvx::host::snapshot::OPENVMM_DIR
30863089
struct nvx::host::snapshot::Snapshot
3090+
method nvx::host::snapshot::Snapshot::key
3091+
method nvx::host::snapshot::Snapshot::manifest
3092+
method nvx::host::snapshot::Snapshot::open
30873093
struct nvx::host::snapshot::SnapshotKey
30883094
const nvx::host::snapshot::SnapshotKey::MAX_LEN
30893095
const nvx::host::snapshot::SnapshotKey::VERSION

‎nvx-rs/public-api/windows.txt‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1626,6 +1626,7 @@ method nvx::host::snapshot::CaptureClass::to_bytes
16261626
struct nvx::host::snapshot::ClassIdentity
16271627
method nvx::host::snapshot::ClassIdentity::as_bytes
16281628
method nvx::host::snapshot::ClassIdentity::from_bytes
1629+
const nvx::host::snapshot::DESCRIPTION_FILE
16291630
struct nvx::host::snapshot::Downtime
16301631
field nvx::host::snapshot::Downtime::nanos
16311632
field nvx::host::snapshot::Downtime::source
@@ -1663,13 +1664,18 @@ method nvx::host::snapshot::Invariants::iter
16631664
method nvx::host::snapshot::Invariants::len
16641665
method nvx::host::snapshot::Invariants::new
16651666
method nvx::host::snapshot::Invariants::with
1667+
const nvx::host::snapshot::KEY_FILE
16661668
struct nvx::host::snapshot::KeyIdentity
16671669
method nvx::host::snapshot::KeyIdentity::as_bytes
16681670
method nvx::host::snapshot::KeyIdentity::from_bytes
16691671
const nvx::host::snapshot::MANIFEST_NAME
16701672
const nvx::host::snapshot::MAX_DOWNTIME_NS
16711673
const nvx::host::snapshot::MAX_MANIFEST_LEN
1674+
const nvx::host::snapshot::OPENVMM_DIR
16721675
struct nvx::host::snapshot::Snapshot
1676+
method nvx::host::snapshot::Snapshot::key
1677+
method nvx::host::snapshot::Snapshot::manifest
1678+
method nvx::host::snapshot::Snapshot::open
16731679
struct nvx::host::snapshot::SnapshotKey
16741680
const nvx::host::snapshot::SnapshotKey::MAX_LEN
16751681
const nvx::host::snapshot::SnapshotKey::VERSION

‎nvx-rs/src/host/snapshot.rs‎

Lines changed: 185 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
//! Snapshot metadata and the opaque input of a future VM restore.
1+
//! Strict snapshot directories, compatibility keys, manifests and restore-time eligibility.
2+
//!
3+
//! [`Snapshot::open`] checks the one snapshot format without reading its informational
4+
//! description. The caller keeps the directory and its entries private and immutable while
5+
//! using the opened snapshot.
26
//!
37
//! [`SnapshotKey`] derives a compatibility key from a capture's class and manifest.
48
//! [`SnapshotManifest::read`] reads the manifest that OpenVMM wrote, and
@@ -31,15 +35,192 @@ pub(super) mod manifest;
3135
pub(crate) mod tests;
3236
mod wire;
3337

38+
use std::ffi::OsString;
39+
use std::fs;
40+
use std::io;
41+
use std::path::{Path, PathBuf};
42+
43+
use crate::host::paths::{absolute, normalized};
44+
use crate::host::store::regular;
45+
use crate::host::{filesystem, platform};
46+
use crate::{Error, Result};
47+
3448
pub use self::eligibility::{Downtime, DowntimeSource, Eligibility, HostTime, MAX_DOWNTIME_NS};
3549
pub use self::key::{CaptureClass, ClassIdentity, Invariants, KeyIdentity, SnapshotKey};
3650
pub use self::manifest::{
3751
BlockGeometry, HostClock, MANIFEST_NAME, MAX_MANIFEST_LEN, SnapshotManifest, TimeContract,
3852
};
3953

40-
/// An opaque snapshot input. Creating a VM from a snapshot is not supported yet.
54+
/// The canonical snapshot key.
55+
pub const KEY_FILE: &str = "key.bin";
56+
/// The informational description, whose contents [`Snapshot::open`] never reads.
57+
pub const DESCRIPTION_FILE: &str = "snapshot.json";
58+
/// The directory of OpenVMM's manifest, RAM and saved state.
59+
pub const OPENVMM_DIR: &str = "openvmm";
60+
61+
/// A checked snapshot directory and its verified metadata, for a future VM restore.
62+
///
63+
/// The caller must keep the directory and its entries private and immutable while using this
64+
/// value. Opening checks them once; it neither watches them nor holds their files open.
4165
#[derive(Debug)]
4266
pub struct Snapshot {
43-
/// Reserved for snapshot metadata.
44-
pub(crate) _private: (),
67+
/// The absolute directory path, with its components preserved rather than its links resolved.
68+
#[cfg_attr(
69+
not(test),
70+
expect(dead_code, reason = "SL2.15 uses the snapshot directory (#1103)")
71+
)]
72+
pub(crate) dir: PathBuf,
73+
/// The bounded canonical key checked against the manifest.
74+
key: SnapshotKey,
75+
/// The strictly parsed metadata of OpenVMM's snapshot.
76+
manifest: SnapshotManifest,
77+
}
78+
79+
impl Snapshot {
80+
/// Opens the one strict snapshot format without changing any entry.
81+
///
82+
/// `dir` must be a private directory containing exactly [`KEY_FILE`], [`DESCRIPTION_FILE`]
83+
/// and [`OPENVMM_DIR`]. The latter must be a private directory containing exactly
84+
/// [`MANIFEST_NAME`], `memory.bin` and `state.bin`. Every file must be regular, not a link or
85+
/// reparse point, and private to its owner. The manifest is read by
86+
/// [`SnapshotManifest::read`], its artifact lengths must match, and the bounded canonical
87+
/// key must be consistent with it. The description is required but its contents are never
88+
/// read, parsed or trusted.
89+
///
90+
/// The caller must keep the directory and its entries private and immutable while using
91+
/// the returned snapshot. This check retains no open file handles or lock.
92+
///
93+
/// Fails with [`ErrorKind::Io`](crate::ErrorKind::Io) for an unreadable or invalid directory,
94+
/// entry, length or key relationship, and otherwise as [`SnapshotManifest::read`] and
95+
/// [`SnapshotKey::from_bytes`] do.
96+
pub fn open(dir: &Path) -> Result<Self> {
97+
let dir = absolute(&normalized(dir)).map_err(|error| entry_error(dir, error))?;
98+
check_directory(&dir, &[KEY_FILE, DESCRIPTION_FILE, OPENVMM_DIR])?;
99+
let openvmm = dir.join(OPENVMM_DIR);
100+
check_directory(&openvmm, &[MANIFEST_NAME, "memory.bin", "state.bin"])?;
101+
for path in [
102+
dir.join(KEY_FILE),
103+
dir.join(DESCRIPTION_FILE),
104+
openvmm.join(MANIFEST_NAME),
105+
] {
106+
check_file(&path)?;
107+
}
108+
let manifest = SnapshotManifest::read(&openvmm)?;
109+
for (name, expected) in [
110+
("memory.bin", manifest.memory_len()),
111+
("state.bin", manifest.state_len()),
112+
] {
113+
let path = openvmm.join(name);
114+
let found = check_file(&path)?.len();
115+
if found != expected {
116+
return Err(Error::io(format!(
117+
"the snapshot artifact {} is {found} bytes long, not the {expected} bytes \
118+
that its manifest records",
119+
path.display()
120+
)));
121+
}
122+
}
123+
let path = dir.join(KEY_FILE);
124+
let bytes = regular::open_regular(&path)
125+
.and_then(|file| {
126+
regular::read_at_most(file, SnapshotKey::MAX_LEN as u64, "a snapshot key")
127+
})
128+
.map_err(|error| entry_error(&path, error))?;
129+
let key = SnapshotKey::from_bytes(&bytes)?;
130+
key.check_manifest(&manifest)?;
131+
Ok(Self { dir, key, manifest })
132+
}
133+
134+
/// Returns the verified snapshot key.
135+
pub fn key(&self) -> &SnapshotKey {
136+
&self.key
137+
}
138+
139+
/// Returns the strictly parsed OpenVMM manifest.
140+
pub fn manifest(&self) -> &SnapshotManifest {
141+
&self.manifest
142+
}
143+
}
144+
145+
/// Names the failing snapshot entry while retaining its I/O error.
146+
fn entry_error(path: &Path, error: io::Error) -> Error {
147+
Error::io(format!("cannot examine snapshot entry {}", path.display())).with_source(error)
148+
}
149+
150+
/// Checks one private directory and its exact fixed entry-name inventory.
151+
fn check_directory(path: &Path, expected: &[&str]) -> Result<()> {
152+
if let Some(problem) =
153+
platform::check_snapshot_dir(path).map_err(|error| entry_error(path, error))?
154+
{
155+
return Err(Error::io(format!(
156+
"the snapshot directory {} {problem}",
157+
path.display()
158+
)));
159+
}
160+
let mut found = fs::read_dir(path)
161+
.and_then(|entries| {
162+
entries
163+
.map(|entry| Ok(entry?.file_name()))
164+
.collect::<io::Result<Vec<_>>>()
165+
})
166+
.map_err(|error| entry_error(path, error))?;
167+
let mut expected: Vec<OsString> = expected.iter().map(|name| OsString::from(*name)).collect();
168+
found.sort();
169+
expected.sort();
170+
if found != expected {
171+
return Err(Error::io(format!(
172+
"the snapshot directory {} holds {found:?}, not exactly {expected:?}",
173+
path.display()
174+
)));
175+
}
176+
Ok(())
177+
}
178+
179+
/// Checks a regular private file from metadata alone, without reading its contents.
180+
fn check_file(path: &Path) -> Result<fs::Metadata> {
181+
#[cfg(windows)]
182+
let file = {
183+
use std::os::windows::fs::OpenOptionsExt;
184+
use windows_sys::Win32::Storage::FileSystem::{
185+
FILE_FLAG_OPEN_REPARSE_POINT, FILE_READ_ATTRIBUTES, READ_CONTROL,
186+
};
187+
188+
fs::OpenOptions::new()
189+
.access_mode(READ_CONTROL | FILE_READ_ATTRIBUTES)
190+
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
191+
.open(path)
192+
.map_err(|error| entry_error(path, error))?
193+
};
194+
#[cfg(windows)]
195+
let metadata = file.metadata().map_err(|error| entry_error(path, error))?;
196+
#[cfg(not(windows))]
197+
let metadata = fs::symlink_metadata(path).map_err(|error| entry_error(path, error))?;
198+
if !metadata.is_file() || filesystem::is_reparse_point(&metadata) {
199+
return Err(Error::io(format!(
200+
"the snapshot entry {} is not a regular file, or is a link or reparse point",
201+
path.display()
202+
)));
203+
}
204+
#[cfg(unix)]
205+
{
206+
use std::os::unix::fs::MetadataExt;
207+
208+
if metadata.uid() != nix::unistd::Uid::effective().as_raw() || metadata.mode() & 0o077 != 0
209+
{
210+
return Err(Error::io(format!(
211+
"the snapshot file {} is not private to the current user",
212+
path.display()
213+
)));
214+
}
215+
}
216+
#[cfg(windows)]
217+
if let Some(problem) =
218+
platform::private_file_problem(&file).map_err(|error| entry_error(path, error))?
219+
{
220+
return Err(Error::io(format!(
221+
"the snapshot file {} {problem}",
222+
path.display()
223+
)));
224+
}
225+
Ok(metadata)
45226
}

‎nvx-rs/src/host/snapshot/key.rs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -634,6 +634,19 @@ impl SnapshotKey {
634634
self.contracts == Contracts::CURRENT
635635
}
636636

637+
/// Checks the manifest's complete machine, the current key contracts and the filesystem tag.
638+
pub(super) fn check_manifest(&self, manifest: &SnapshotManifest) -> Result<()> {
639+
if self.machine != manifest.machine
640+
|| !self.speaks_current_contracts()
641+
|| self.filesystem_tag != MOUNT_TAG
642+
{
643+
return Err(Error::io(
644+
"the snapshot key is not consistent with its manifest and this format's contracts",
645+
));
646+
}
647+
Ok(())
648+
}
649+
637650
/// Returns the backend.
638651
pub fn hypervisor(&self) -> Hypervisor {
639652
self.machine.hypervisor

‎nvx-rs/src/host/snapshot/key/tests.rs‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -709,6 +709,29 @@ fn key_refusal(bytes: &[u8], code: ErrorCode) -> String {
709709
error.message().to_owned()
710710
}
711711

712+
#[cfg(any(target_os = "linux", windows))]
713+
#[test]
714+
fn snapshot_open_refuses_other_key_contracts_and_filesystem_tags() {
715+
use crate::host::snapshot::{KEY_FILE, Snapshot};
716+
use crate::host::store::files::write_private;
717+
718+
let changes: [fn(&mut SnapshotKey); 2] = [
719+
|key| key.contracts.snapshot += 1,
720+
|key| key.filesystem_tag.push_str("-other"),
721+
];
722+
for change in changes {
723+
let fixture = support::SnapshotFixture::new();
724+
let mut key = Snapshot::open(&fixture.dir).unwrap().key().clone();
725+
change(&mut key);
726+
let bytes = key.to_bytes();
727+
assert!(SnapshotKey::from_bytes(&bytes).is_ok());
728+
write_private(&fixture.dir.join(KEY_FILE), &bytes).unwrap();
729+
let error = Snapshot::open(&fixture.dir).unwrap_err();
730+
assert_eq!(error.code(), ErrorCode::Io, "{error}");
731+
assert!(error.message().contains("not consistent"), "{error}");
732+
}
733+
}
734+
712735
#[test]
713736
fn other_encodings_of_a_key_are_refused() {
714737
let key = network_key();

0 commit comments

Comments
 (0)