Skip to content

Commit e67fc75

Browse files
ppennaCopilot
andcommitted
sandbox: remove the VM directories that terminated runs left
A `sandbox run` or a cold `nvx run` that is terminated, as when a supervisor ends `nvx.exe`, cannot remove its temporary VM directory, `nvx-sandbox-run-` or `nvx-run-` and 32 hexadecimal digits in the temporary directory, which then stays behind with OpenVMM's log (#1910, case 1). Only another process can remove it, and only once it is sure that no run or OpenVMM still uses it. On Windows, where a run's OpenVMM now ends with the run, a run first removes the directories of the user's earlier runs that hold nothing but NVX's files and whose log no process holds open any longer: an open of the log that shares nothing succeeds only once both the run, which now keeps a handle of its log until it returns, and its OpenVMM, which holds the log as its standard output until it exits, are gone. It leaves any other directory, such as one without a log, one that holds another file, or one that is not private. A run whose directory another run removed first, in the moment after it released its log, takes the directory for removed. Other hosts keep their behavior, since a terminated run leaves its OpenVMM running there. Evidence on Windows 11 with WHP: after `nvx.exe` was killed during `sandbox run`, `%TEMP%\nvx-sandbox-run-805fa5be...` held its log; the next run removes such a directory. Tests: the removal takes only the directories that runs abandoned, and a `sandbox run` removes the directory that a killed run left. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent ac8b6b4 commit e67fc75

11 files changed

Lines changed: 221 additions & 19 deletions

File tree

‎doc/run.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1043,7 +1043,11 @@ nothing. On Windows, OpenVMM runs in a job object that only the run holds and
10431043
that ends OpenVMM once it closes, so the VM ends with the run, whatever ends
10441044
the run, as when a supervisor terminates `nvx.exe`. OpenVMM also stays in the
10451045
jobs of `nvx.exe`, as its other child processes do, unless a job lets them
1046-
leave it silently, so that such a job can end it too.
1046+
leave it silently, so that such a job can end it too. A run that is terminated
1047+
cannot remove its VM directory, `nvx-sandbox-run-` and 32 hexadecimal digits in
1048+
the temporary directory: the next run of the user removes it, once no process
1049+
holds its `openvmm.log` any longer, as no run or OpenVMM that still runs leaves
1050+
it.
10471051

10481052
CI runs `/sbin/nvx-sandbox-smoke`, with `--arg init`, as below, as the workload
10491053
of `sandbox run` and `sandbox exec`, to verify the security profile of the

‎doc/usage.md‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -210,11 +210,12 @@ after `>> `, and unless `--dry-run` is given, runs OpenVMM in a private
210210
temporary VM directory, which it removes once OpenVMM has exited, on the
211211
terminal. On Windows, a cold boot's OpenVMM ends with `nvx run`, whatever ends
212212
it, in a job object that only the run holds, as the OpenVMM of a
213-
[`sandbox run`](#sandbox) does. A cold boot attaches the guest's console, the
214-
boot console `hvc1`, to the standard streams, so that the terminal's input
215-
reaches the guest through it rather than through the byte channel, `hvc0`,
216-
whose output, such as the kernel's early messages, goes to standard error with
217-
OpenVMM's log. It exits
213+
[`sandbox run`](#sandbox) does, and the next cold boot removes the VM
214+
directory that one that was terminated left. A cold boot attaches the guest's
215+
console, the boot console `hvc1`, to the standard streams, so that the
216+
terminal's input reaches the guest through it rather than through the byte
217+
channel, `hvc0`, whose output, such as the kernel's early messages, goes to
218+
standard error with OpenVMM's log. It exits
218219
with status 1 for an error, 2 for a usage error, and 130 after Ctrl-C, and
219220
otherwise with the status that OpenVMM returns. Its errors and usage errors
220221
carry their [error codes](#error-codes), as `error[CODE]: MESSAGE` and
@@ -398,7 +399,8 @@ launch, in a temporary VM directory that it removes, executes its workload
398399
once, as `exec` does, with its streams, has the guest shut the VM down, which
399400
it terminates if it does not exit within `--timeout` seconds, as it terminates
400401
the VM of a workload that outlives `--timeout`, and exits with the workload's
401-
status. On Windows, its VM ends with it, whatever ends it; see
402+
status. On Windows, its VM ends with it, whatever ends it, and the next `run`
403+
removes the VM directory of one that was terminated; see
402404
[Experimental single-workload sandbox](run.md#experimental-single-workload-sandbox).
403405

404406
See [Run](run.md) for artifact preparation, the security boundary, the

‎nvx/README.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1527,7 +1527,8 @@ streams, so that the guest's console and the terminal settings that OpenVMM
15271527
restores behave as they do for OpenVMM itself, and exits with OpenVMM's
15281528
status; a restore does none of these, as the second item says. On Windows, a
15291529
cold boot's OpenVMM runs in a job object that only `nvx` holds, as that of a
1530-
`sandbox run` does, which ends OpenVMM with `nvx`, whatever ends it.
1530+
`sandbox run` does, which ends OpenVMM with `nvx`, whatever ends it, and the
1531+
next cold boot removes the VM directory that one that was terminated left.
15311532

15321533
- A cold boot runs the kernel and the initramfs of `--guest`, `alpine` by
15331534
default, with `--memory-mib` or else the guest's default, 128 MiB for Alpine
@@ -1614,7 +1615,9 @@ before them.
16141615
which says that OpenVMM is stuck exiting, if it has not. On Windows, OpenVMM
16151616
runs in a job object that only the run holds, which ends OpenVMM once it
16161617
closes, so that the VM never outlives the run, whatever ends the run, and in
1617-
the jobs of `nvx` that keep their processes' children.
1618+
the jobs of `nvx` that keep their processes' children; the next run removes
1619+
the VM directory that a run that was terminated left, once no process holds
1620+
its log, which a run holds until it returns and its OpenVMM until it exits.
16181621
- `provision` records the sandbox in its state directory. `start` launches
16191622
OpenVMM detached with the managed lifecycle, passes it a fresh capability
16201623
through its standard input, and waits until the guest answers. `exec` runs a

‎nvx/src/host/cli/run.rs‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,9 @@ const MACHINES: [&str; 1] = ["microvm"];
180180
/// The choices of `--processors`, the processor counts that a microVM takes.
181181
const PROCESSORS: [&str; 4] = ["1", "2", "4", "8"];
182182

183+
/// The name of a cold run's temporary VM directory, before 32 random lowercase hexadecimal digits.
184+
const RUN_DIRECTORY: &str = "nvx-run-";
185+
183186
/// The options of `snapshot restore` that a restore of `run` takes, which `sandbox` defines and
184187
/// parses for both: the sandbox's state directory, the image, its upper, the workload, and the
185188
/// timeout of the restore.
@@ -677,7 +680,9 @@ fn cold_vm_config(
677680

678681
/// Removes the temporary VM directory of a cold run, with what its VM left in it: OpenVMM's log
679682
/// and outcome report, its control and boot-console sockets on Linux, and the staging file of a
680-
/// report that OpenVMM did not finish writing, which [`StateFile::owns_temporary`] names.
683+
/// report that OpenVMM did not finish writing, which [`StateFile::owns_temporary`] names. A
684+
/// directory that is gone already, as another run on Windows removes one whose log nothing holds
685+
/// any longer, is removed.
681686
fn remove_vm_directory(dir: &VmDir) -> Result {
682687
let remove = |path: &Path| match fs::remove_file(path) {
683688
Ok(()) => Ok(()),
@@ -692,7 +697,12 @@ fn remove_vm_directory(dir: &VmDir) -> Result {
692697
] {
693698
remove(&dir.path().join(name))?;
694699
}
695-
for entry in fs::read_dir(dir.path()).map_err(Exit::from_os_error)? {
700+
let entries = match fs::read_dir(dir.path()) {
701+
Ok(entries) => entries,
702+
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
703+
Err(error) => return Err(Exit::from_os_error(error)),
704+
};
705+
for entry in entries {
696706
let entry = entry.map_err(Exit::from_os_error)?;
697707
if entry
698708
.file_name()
@@ -702,7 +712,10 @@ fn remove_vm_directory(dir: &VmDir) -> Result {
702712
remove(&entry.path())?;
703713
}
704714
}
705-
fs::remove_dir(dir.path()).map_err(Exit::from_os_error)
715+
match fs::remove_dir(dir.path()) {
716+
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
717+
removed => removed.map_err(Exit::from_os_error),
718+
}
706719
}
707720

708721
fn connect_running(
@@ -1162,13 +1175,20 @@ fn run_cold(
11621175
windows_breakaway: false,
11631176
options: LaunchOptions::default(),
11641177
};
1165-
let path = std::env::temp_dir().join(format!("nvx-run-{name}"));
1178+
let path = std::env::temp_dir().join(format!("{RUN_DIRECTORY}{name}"));
11661179
if path.try_exists().map_err(Exit::from_os_error)? {
11671180
return Err(Exit::error(
11681181
ErrorCode::Io,
11691182
"the temporary VM directory already exists",
11701183
));
11711184
}
1185+
// A run that ended without removing its VM directory, as one that was terminated does, leaves
1186+
// it to the next run, which tells it by its log, which no process holds any longer: this run
1187+
// reads its own until it returns.
1188+
#[cfg(windows)]
1189+
if !options.dry_run {
1190+
sandbox::remove_abandoned_vm_directories(&std::env::temp_dir(), RUN_DIRECTORY);
1191+
}
11721192
vm::create_private_dir(&path)?;
11731193
let vm_dir = VmDir::open(&path)?;
11741194
let mut cleanup = true;

‎nvx/src/host/cli/sandbox/lifecycle/mod.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ pub(crate) use self::directory::{create_state_directory, prepare_state_directory
5050
pub(crate) use self::outcome::{
5151
copy_openvmm_outcome, validate_outcome_destination, write_exec_outcome,
5252
};
53+
#[cfg(windows)]
54+
pub(crate) use self::start::remove_abandoned_vm_directories;
5355
pub(crate) use self::start::{exec_workload, run, start};
5456
pub(crate) use self::stop::{deprovision, stop};
5557

‎nvx/src/host/cli/sandbox/lifecycle/start.rs‎

Lines changed: 78 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -646,7 +646,7 @@ pub(crate) fn run(
646646
artifacts.require()?;
647647
let (config, vm_config) = recorded?;
648648
let name = hex(&random_bytes::<16>()?);
649-
let path = std::env::temp_dir().join(format!("nvx-sandbox-run-{name}"));
649+
let path = std::env::temp_dir().join(format!("{RUN_DIRECTORY}{name}"));
650650
refuse_own_files(
651651
Some(("VM directory", &path)),
652652
config.distro().path(),
@@ -694,6 +694,10 @@ pub(crate) fn run(
694694
"the temporary VM directory already exists",
695695
));
696696
}
697+
#[cfg(windows)]
698+
if !options.dry_run {
699+
remove_abandoned_vm_directories(&std::env::temp_dir(), RUN_DIRECTORY);
700+
}
697701
vm::create_private_dir(&path).map_err(error_with_cause)?;
698702
let dir = VmDir::open(&path).map_err(error_with_cause)?;
699703
let timeout = options.timeout;
@@ -724,6 +728,10 @@ pub(crate) fn run(
724728
#[cfg(windows)]
725729
prepared.inherit(scratch.claim().try_clone().map_err(Exit::from_os_error)?);
726730
}
731+
// The run holds its log until it returns, before it removes the VM directory, as OpenVMM
732+
// holds it until it exits, so that no other run takes the directory for an abandoned one.
733+
#[cfg(windows)]
734+
let _log = prepared.log().try_clone().map_err(Exit::from_os_error)?;
727735
let launched = vm::spawn(prepared).map_err(|error| {
728736
cleanup = error.kind() != ErrorKind::StillRunning;
729737
error_with_cause(error)
@@ -957,7 +965,8 @@ fn check_command_line(config: &Config, vm: &VmConfig) -> Result {
957965

958966
/// Removes the temporary VM directory of a run, with what its VM left in it: OpenVMM's log and
959967
/// outcome report, its control socket on Linux, and the staging file of a report that OpenVMM
960-
/// did not finish writing, which [`StateFile::owns_temporary`] names.
968+
/// did not finish writing, which [`StateFile::owns_temporary`] names. A directory that is gone
969+
/// already, as another run on Windows removes one whose log nothing holds any longer, is removed.
961970
fn remove_vm_directory(dir: &VmDir) -> Result {
962971
let remove = |path: &Path| match fs::remove_file(path) {
963972
Ok(()) => Ok(()),
@@ -968,7 +977,12 @@ fn remove_vm_directory(dir: &VmDir) -> Result {
968977
remove(&dir.path().join(file.name()))?;
969978
}
970979
let failed = |error: io::Error| io_error(ErrorCode::Io, &error, dir.path());
971-
for entry in fs::read_dir(dir.path()).map_err(failed)? {
980+
let entries = match fs::read_dir(dir.path()) {
981+
Ok(entries) => entries,
982+
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
983+
Err(error) => return Err(failed(error)),
984+
};
985+
for entry in entries {
972986
let entry = entry.map_err(failed)?;
973987
if entry
974988
.file_name()
@@ -978,7 +992,67 @@ fn remove_vm_directory(dir: &VmDir) -> Result {
978992
remove(&entry.path())?;
979993
}
980994
}
981-
fs::remove_dir(dir.path()).map_err(failed)
995+
match fs::remove_dir(dir.path()) {
996+
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
997+
removed => removed.map_err(failed),
998+
}
999+
}
1000+
1001+
/// The name of a run's temporary VM directory, before 32 random lowercase hexadecimal digits.
1002+
const RUN_DIRECTORY: &str = "nvx-sandbox-run-";
1003+
1004+
/// Removes the temporary VM directories in `parent` that runs left when they ended without
1005+
/// removing them, as a run that is terminated does, whose OpenVMM its job ends with it on Windows:
1006+
/// each directory whose name is `prefix` and 32 lowercase hexadecimal digits, which is private to
1007+
/// the user, as [`VmDir::open`] requires, which holds nothing but what [`remove_vm_directory`]
1008+
/// removes, and whose log no process holds open any longer, as [`platform::log_released`] tells,
1009+
/// neither the run, which holds its log until it returns, nor its OpenVMM, which holds it until it
1010+
/// exits. It leaves any other directory as it is, such as one without a log, which a run creates
1011+
/// before its log, or one that holds a file of another name.
1012+
#[cfg(windows)]
1013+
pub(crate) fn remove_abandoned_vm_directories(parent: &Path, prefix: &str) {
1014+
let Ok(entries) = fs::read_dir(parent) else {
1015+
return;
1016+
};
1017+
for entry in entries.flatten() {
1018+
let name = entry.file_name();
1019+
let Some(digits) = name.to_str().and_then(|name| name.strip_prefix(prefix)) else {
1020+
continue;
1021+
};
1022+
if digits.len() != 32
1023+
|| !digits
1024+
.bytes()
1025+
.all(|digit| matches!(digit, b'0'..=b'9' | b'a'..=b'f'))
1026+
{
1027+
continue;
1028+
}
1029+
// A link or another reparse point is no directory of a run, which `VmDir::open` refuses
1030+
// too.
1031+
if !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
1032+
continue;
1033+
}
1034+
let Ok(dir) = VmDir::open(&entry.path()) else {
1035+
continue;
1036+
};
1037+
let Ok(files) = fs::read_dir(dir.path()) else {
1038+
continue;
1039+
};
1040+
let nvx_files_only = files.into_iter().all(|file| {
1041+
file.is_ok_and(|file| {
1042+
file.file_name().to_str().is_some_and(|name| {
1043+
[StateFile::Log, StateFile::Outcome, StateFile::Socket]
1044+
.iter()
1045+
.any(|owned| owned.name() == name)
1046+
|| StateFile::owns_temporary(name)
1047+
})
1048+
})
1049+
});
1050+
if nvx_files_only
1051+
&& platform::log_released(&dir.path().join(StateFile::Log.name())).unwrap_or(false)
1052+
{
1053+
let _ = remove_vm_directory(&dir);
1054+
}
1055+
}
9821056
}
9831057

9841058
#[cfg(test)]

‎nvx/src/host/cli/sandbox/lifecycle/start/tests.rs‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,3 +296,51 @@ fn a_run_removes_its_vm_directory_with_a_report_s_staging_file() {
296296
}
297297
}
298298
}
299+
300+
/// A run removes the VM directories of runs that ended without removing them, whose logs no
301+
/// process holds any longer, and leaves every other directory as it is: one whose log a process
302+
/// holds, as a run that still runs or its OpenVMM does, one without a log, one that holds a file
303+
/// of another name, one that is not private, and one of another name.
304+
#[cfg(windows)]
305+
#[test]
306+
fn a_run_removes_only_the_vm_directories_that_runs_abandoned() {
307+
let directory = tempfile::tempdir().unwrap();
308+
let parent = directory.path();
309+
let digits = |digit: char| digit.to_string().repeat(32);
310+
let private = |name: &str, files: &[&str]| {
311+
let path = parent.join(name);
312+
vm::create_private_dir(&path).unwrap();
313+
for file in files {
314+
fs::write(path.join(file), "").unwrap();
315+
}
316+
path
317+
};
318+
let log = StateFile::Log.name();
319+
let outcome = StateFile::Outcome.name();
320+
let abandoned = private(
321+
&format!("{RUN_DIRECTORY}{}", digits('a')),
322+
&[log, outcome, ".tmpA1b2C3"],
323+
);
324+
let running = private(&format!("{RUN_DIRECTORY}{}", digits('b')), &[log]);
325+
let held = fs::File::open(running.join(log)).unwrap();
326+
let starting = private(&format!("{RUN_DIRECTORY}{}", digits('c')), &[]);
327+
let foreign = private(&format!("{RUN_DIRECTORY}{}", digits('d')), &[log, "other"]);
328+
let shared = parent.join(format!("{RUN_DIRECTORY}{}", digits('e')));
329+
fs::create_dir(&shared).unwrap();
330+
fs::write(shared.join(log), "").unwrap();
331+
let uppercase = private(&format!("{RUN_DIRECTORY}{}", digits('F')), &[log]);
332+
let short = private(&format!("{RUN_DIRECTORY}{}", "0".repeat(31)), &[log]);
333+
let other = private(&format!("nvx-run-{}", digits('0')), &[log]);
334+
remove_abandoned_vm_directories(parent, RUN_DIRECTORY);
335+
drop(held);
336+
assert!(!abandoned.exists(), "an abandoned directory was kept");
337+
for kept in [
338+
&running, &starting, &foreign, &shared, &uppercase, &short, &other,
339+
] {
340+
assert!(kept.exists(), "{}", kept.display());
341+
}
342+
for kept in [&running, &foreign, &shared, &uppercase, &short, &other] {
343+
assert!(kept.join(log).exists(), "{}", kept.display());
344+
}
345+
assert!(foreign.join("other").exists());
346+
}

‎nvx/src/host/cli/sandbox/mod.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ use crate::protocol::export::{EXPORT_DIRECTORY, ExportMode};
4040
use crate::protocol::root::RootUpper;
4141

4242
pub(crate) use self::lifecycle::ProvisionConfig;
43+
#[cfg(windows)]
44+
pub(super) use self::lifecycle::remove_abandoned_vm_directories;
4345
pub(super) use self::lifecycle::{copy_openvmm_outcome, validate_outcome_destination};
4446
pub(super) use self::options::sandbox_network;
4547
pub(super) use self::options::{

‎nvx/src/host/platform/windows/log_claim.rs‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,24 @@ pub(crate) fn log_claim_held(path: &Path, identity: (u64, u64)) -> io::Result<bo
386386
}
387387
}
388388

389+
/// Returns whether no process holds the log at `path` open any longer: whether an open of the
390+
/// log that shares nothing succeeds, rather than failing with a sharing violation, as it does
391+
/// while a VMM, which holds its log as its standard output and error until it exits, or the
392+
/// caller of its launch, if it keeps a handle of the log, still runs. The open follows no link.
393+
#[cfg(feature = "cli")]
394+
pub(crate) fn log_released(path: &Path) -> io::Result<bool> {
395+
let exclusive = OpenOptions::new()
396+
.read(true)
397+
.share_mode(0)
398+
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
399+
.open(path);
400+
match exclusive {
401+
Ok(_) => Ok(true),
402+
Err(error) if error.raw_os_error() == Some(ERROR_SHARING_VIOLATION as i32) => Ok(false),
403+
Err(error) => Err(error),
404+
}
405+
}
406+
389407
/// Returns whether the live process `pid` that started at `start_time`, which serves the control
390408
/// endpoint of a launch whose log is the file `log`, is that launch's VMM.
391409
///

‎nvx/src/host/platform/windows/mod.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ pub(crate) use self::identity::{
4040
pub(crate) use self::interrupt::{interrupted, watch_interrupts};
4141
pub(crate) use self::log_claim::create_log_job;
4242
#[cfg(feature = "cli")]
43-
pub(crate) use self::log_claim::{claim_log, log_claim_held, serves_launch};
43+
pub(crate) use self::log_claim::{claim_log, log_claim_held, log_released, serves_launch};
4444
pub(crate) use self::private::{
4545
check_snapshot_dir, check_vm_dir, create_vm_dir, make_sparse, private_file_problem,
4646
};

0 commit comments

Comments
 (0)