Skip to content

Commit 09a64b6

Browse files
Enrique SaurezCopilot
authored andcommitted
sandbox: refuse shares of a sandbox's own files
A managed sandbox could share its own files with its guest: a --mount whose host path is, holds, or lies inside the sandbox's state directory, image, or scratch image, or the OpenVMM, kernel, or initramfs that its VM runs. Through such a share, the workload could read or change the sandbox's records and storage, or what the host runs at the next start (#818). provision now refuses such a share before it records the sandbox, and before it creates anything, and start refuses it again, from the recorded configuration, before it claims or launches anything. Both compare each share's host path with the sandbox's own files once host::paths::resolve has resolved them, component by component, so start also refuses a share that came to reach one of them through a link since provision. The comparison drops the Windows verbatim prefix that resolve keeps for a path that only it names, such as that of a directory whose name ends in a period. A provision that finds no artifact root, which it does not need, leaves the artifacts to start. Both protect the artifact root's OpenVMM, which start runs, whatever NVX_OPENVMM names. Hard links and bind mounts of these files are not detected, as the documentation says. The new CLI tests cover each refusal at provision and at start, a state directory that provision would create, a state directory that only a verbatim path names on Windows, the root's OpenVMM with NVX_OPENVMM set, a share that a link redirected after provision, and shares beside the sandbox's files whose names only start as theirs do. The refusals fail without the check, the verbatim case without the prefix's removal, and the last test with a textual prefix comparison. provision_and_deprovision_need_no_artifact_root now provisions a share too. This replays esaurez's first implementation, b1f1446 and 3a3a5a7, adapted to the typed record and the CLI-owned lifecycle. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 3340bbd commit 09a64b6

7 files changed

Lines changed: 291 additions & 10 deletions

File tree

‎doc/run.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1170,6 +1170,18 @@ as through a hard link or a bind mount. NVX no longer reads earlier
11701170
configuration formats, including those that recorded the shares as requested;
11711171
deprovision such a sandbox and provision it again.
11721172

1173+
A share must not reach the sandbox's own files, which the workload could
1174+
otherwise read or change: `provision` refuses a share whose resolved host path
1175+
equals, contains, or lies inside the sandbox's state directory, its image, its
1176+
scratch image, or the OpenVMM, kernel, or initramfs of the artifact root, before
1177+
it records the sandbox, and `start` refuses one again before it launches the VM.
1178+
`start` resolves the recorded host paths again, so a share that came to reach
1179+
one of these files through a link since `provision` is refused too. A
1180+
`provision` that finds no artifact root leaves the artifacts to `start`. Only
1181+
resolved paths are compared, so don't share a directory that holds a link
1182+
through which the host reaches one of these files, nor a hard link or bind
1183+
mount of one.
1184+
11731185
#### Access policy
11741186

11751187
Each share can narrow what the workload can see and modify inside it. OpenVMM

‎doc/usage.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -321,7 +321,7 @@ do, and their names cannot be abbreviated either.
321321
| `--environment-file PATH` | omitted | Read the exact managed `exec` environment from a strict UTF-8 JSON array of `KEY=VALUE` strings, limited to 1 MiB of input. Invalid JSON, non-finite numbers, and unpaired surrogate escapes are refused. An empty array requests an empty environment. This option is mutually exclusive with `--environment`; omitting both preserves guest defaults. |
322322
| `--inherit-default-environment` | off | Layer the managed `exec` environment from `--environment` or `--environment-file` over the guest default environment instead of replacing it; an entry replaces the default variable of the same name. Without either option the workload already receives the defaults, so the flag has no effect. |
323323
| `--hypervisor {auto,whp,kvm,mshv}` | `auto` | Select the host hypervisor. |
324-
| `--mount GUEST_TARGET,HOST_PATH[,ro\|rw]` | none | Live-share a host directory, or a single regular host file without its directory, at the absolute target inside the container rootfs for `run` or `provision`; defaults to `ro`. The target cannot contain whitespace, control characters, double quotes, backslashes, `=`, or any UTF-8 byte that Linux treats as whitespace, such as the `0xa0` in `à`, so that it stays one kernel command-line token in the shares of a one-shot `run`. The mode follows the last comma, so `HOST_PATH` may contain commas when the mode is given. Repeat to attach more shares, each with its own target and mode, for example a read-write workspace and a read-only tool cache, as the children of an aggregate that the guest binds at their targets; a shared file always uses the aggregate, and so does every share of a managed sandbox. Targets and host paths must not overlap. A one-shot `run` describes its shares in kernel command-line tokens that count toward the sandbox's 1024-byte budget; a managed sandbox announces only their number and sends their mapping table once its guest agent is ready, for at most 256 shares. An `rw` share accepts guest-created symbolic links, which the host never follows. `/`, `/etc`, `/run`, and `/run/nvx`, and the `/etc/machine-id`, `/etc/resolv.conf`, `/proc`, `/sys`, `/dev`, `/.nvx-agent`, and `/run/nvx/time` trees, are reserved. |
324+
| `--mount GUEST_TARGET,HOST_PATH[,ro\|rw]` | none | Live-share a host directory, or a single regular host file without its directory, at the absolute target inside the container rootfs for `run` or `provision`; defaults to `ro`. The target cannot contain whitespace, control characters, double quotes, backslashes, `=`, or any UTF-8 byte that Linux treats as whitespace, such as the `0xa0` in `à`, so that it stays one kernel command-line token in the shares of a one-shot `run`. The mode follows the last comma, so `HOST_PATH` may contain commas when the mode is given. Repeat to attach more shares, each with its own target and mode, for example a read-write workspace and a read-only tool cache, as the children of an aggregate that the guest binds at their targets; a shared file always uses the aggregate, and so does every share of a managed sandbox. Targets and host paths must not overlap, and `provision` and `start` refuse a host path that equals, contains, or lies inside the sandbox's state directory, image, scratch image, OpenVMM, kernel, or initramfs; see [Live host shares](run.md#live-host-shares). A one-shot `run` describes its shares in kernel command-line tokens that count toward the sandbox's 1024-byte budget; a managed sandbox announces only their number and sends their mapping table once its guest agent is ready, for at most 256 shares. An `rw` share accepts guest-created symbolic links, which the host never follows. `/`, `/etc`, `/run`, and `/run/nvx`, and the `/etc/machine-id`, `/etc/resolv.conf`, `/proc`, `/sys`, `/dev`, `/.nvx-agent`, and `/run/nvx/time` trees, are reserved. |
325325
| `--mount-deny HOST_PATH` | none | Hide one existing file or directory inside a `--mount` host directory; relative paths are resolved inside it. It may name the directory itself when `--mount-allow` paths inside it remain. With several shares, it applies to the `--mount` before it, which must share a directory. Repeat to deny multiple paths. |
326326
| `--mount-allow HOST_PATH` | none | Expose one existing file or directory inside a `--mount-deny` path of the same share again, for example a readable `mcp-payloads` directory inside hidden logs. The hidden directories on the way list only the entries that lead to it, and the workload cannot modify them. Relative paths are resolved inside the share; with several shares, it applies to the `--mount` before it. Repeat to allow multiple paths. See [Access policy](run.md#access-policy). |
327327
| `--mount-write HOST_PATH` | none | Make one existing file or directory one of the only writable parts of an `rw` share; the workload's writes anywhere else in the share fail with `EROFS`. Relative paths are resolved inside the share; with several shares, it applies to the `--mount` before it, which must be `rw`. Repeat to declare multiple writable paths. `provision` persists the denied, allowed, and writable paths. |

‎nvx-rs/README.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3042,6 +3042,11 @@ guest agents of NVX advertise bits 0, 4, and 6 in sandbox mode.
30423042
reported the exit.
30433043
- `exec` refuses more than 1 MiB of workload output, which the guest agent
30443044
never forwards.
3045+
- `provision`, and `start` again, refuse a share whose resolved host path
3046+
equals, contains, or lies inside the sandbox's state directory, image, or
3047+
scratch image, or the OpenVMM, kernel, or initramfs of the artifact root, as
3048+
[Live host shares](../doc/run.md#live-host-shares) describes, where `nvx.py`
3049+
shared them.
30453050
- The state directory holds the store's files: `sandbox.lock` replaces the
30463051
`lifecycle.lock` of `nvx.py`, `runtime.json` has the store's format, and each
30473052
start replaces `openvmm.log`, which `nvx.py` appended to. `exec` holds the

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,12 @@ use super::{
1010
CONFIG_NAME, Found, REQUIRED_FEATURES, connect, find_vm, mismatched, require_config,
1111
running_vm, runtime_for,
1212
};
13+
use crate::host::cli::artifacts::locate;
1314
use crate::host::cli::deadline::{Deadline, RETRY_INTERVAL};
1415
use crate::host::cli::exec_lock::ExecLock;
1516
use crate::host::cli::sandbox::lock::LifecycleLock;
1617
use crate::host::cli::sandbox::state::{Config, read_config};
17-
use crate::host::cli::sandbox::{Artifacts, error_with_cause};
18+
use crate::host::cli::sandbox::{Artifacts, error_with_cause, refuse_own_files};
1819
use crate::host::cli::session::{ExecRequest, ExecResult, Session};
1920
use crate::host::cli::{Exit, Result, output};
2021
use crate::host::process::KILL_TIMEOUT;
@@ -63,6 +64,7 @@ fn start_locked(
6364
}
6465
let config = Config::new(config)?;
6566
let launch = config.launch()?;
67+
refuse_own_files(state_dir, &launch, Some(&locate(artifacts.root)?.dir))?;
6668
let binding = config.distro_binding();
6769
let scratch_binding = config.scratch_binding()?;
6870
let distro = binding

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

Lines changed: 85 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,16 @@ mod one_shot;
2222
mod options;
2323
mod state;
2424

25+
use std::path::{Path, PathBuf};
2526
use std::time::Instant;
2627

2728
use super::artifacts::{Located, OPENVMM_VARIABLE, locate};
2829
use super::download::{self, Hold};
2930
use super::shell::format_command;
30-
use super::{Exit, Result, output};
31+
use super::{Exit, Result, io_error, output};
3132
use crate::ErrorCode;
32-
use crate::host::artifacts::{Guest, KERNEL_NAME, require_artifact};
33+
use crate::host::artifacts::{ArtifactDir, Guest, KERNEL_NAME, require_artifact};
34+
use crate::host::paths;
3335
use crate::host::sandbox::distro::{DISTRO_POLICY_REVISION, DistroBinding, DistroFormat};
3436
use crate::host::sandbox::mount::{plan_mounts, validate_mounts};
3537
use crate::host::sandbox::options::{
@@ -250,6 +252,14 @@ pub(super) fn run(root: Option<&str>, options: Options) -> Result {
250252
// binding, with the manifest beside that path.
251253
let distro = RecordedDistro::new(&launch, binding)?;
252254
let state_dir = state_dir("provision")?;
255+
// A provision runs no artifact, so it needs no artifact root; without one, `start`
256+
// checks the shares against the artifacts that it runs.
257+
let located = locate(root).ok();
258+
refuse_own_files(
259+
Path::new(state_dir),
260+
&launch,
261+
located.as_ref().map(|located| &located.dir),
262+
)?;
253263
lifecycle::provision(
254264
state_dir,
255265
&launch,
@@ -386,6 +396,79 @@ pub(super) fn run(root: Option<&str>, options: Options) -> Result {
386396
}
387397
}
388398

399+
/// Refuses a share of the sandbox's own files: one whose host path equals, contains, or lies
400+
/// inside the state directory `state_dir`, the image or scratch image of `launch`, or the OpenVMM,
401+
/// kernel, or Alpine initramfs of `artifacts`, if known. Through it, the guest could read or
402+
/// change the sandbox's records, its storage, or what the host runs.
403+
///
404+
/// The paths are compared once [`paths::resolve`] has resolved them, without a Windows verbatim
405+
/// prefix. Resolution follows symbolic links and junctions, but not hard links or bind mounts.
406+
/// `provision` checks before it records the sandbox, and `start` again before it launches it,
407+
/// since the shares' paths may have come to resolve elsewhere.
408+
fn refuse_own_files(
409+
state_dir: &Path,
410+
launch: &SandboxLaunch,
411+
artifacts: Option<&ArtifactDir>,
412+
) -> Result {
413+
let Some(export) = launch.export() else {
414+
return Ok(());
415+
};
416+
let mut owned = vec![
417+
("state directory", state_dir.to_owned()),
418+
("image", launch.distro().path().to_owned()),
419+
];
420+
owned.extend(
421+
launch
422+
.scratch()
423+
.map(|path| ("scratch image", path.to_owned())),
424+
);
425+
if let Some(dir) = artifacts {
426+
owned.extend([
427+
("OpenVMM", dir.openvmm()),
428+
("kernel", dir.kernel()),
429+
("initramfs", dir.initramfs(Guest::Alpine)),
430+
]);
431+
}
432+
let resolve = |path: &Path| {
433+
paths::resolve(path)
434+
.map(without_verbatim_prefix)
435+
.map_err(|error| io_error(ErrorCode::Io, &error, path))
436+
};
437+
let owned = owned
438+
.into_iter()
439+
.map(|(name, path)| Ok((name, resolve(&path)?)))
440+
.collect::<Result<Vec<_>>>()?;
441+
for child in &export.children {
442+
let shared = resolve(&child.root)?;
443+
let overlap = owned
444+
.iter()
445+
.find(|(_, path)| shared.starts_with(path) || path.starts_with(&shared));
446+
if let Some((name, path)) = overlap {
447+
return Err(Exit::error(
448+
ErrorCode::Unsupported,
449+
format!(
450+
"sandbox mount host path {} overlaps the sandbox's {name} {}; a share cannot \
451+
expose the sandbox's own files",
452+
shared.display(),
453+
path.display()
454+
),
455+
));
456+
}
457+
}
458+
Ok(())
459+
}
460+
461+
/// Returns `path` without the verbatim prefix, `\\?\`, with which [`paths::resolve`] keeps a
462+
/// Windows path that only that prefix names, such as one whose name ends in a period: its
463+
/// components would otherwise differ from those of a path that it lies inside. A network path
464+
/// keeps its prefix, since no share is one.
465+
fn without_verbatim_prefix(path: PathBuf) -> PathBuf {
466+
match path.to_str().and_then(|text| text.strip_prefix(r"\\?\")) {
467+
Some(rest) if !rest.starts_with(r"UNC\") => PathBuf::from(rest),
468+
_ => path,
469+
}
470+
}
471+
389472
/// Checks the launch of a one-shot run again, and returns its plan with the format and identity of
390473
/// the distro layer that `binding`, which the run's verification of the layer made, records.
391474
///

‎nvx-rs/tests/cli/download.rs‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -201,9 +201,10 @@ fn restores_download_nothing_for_snapshots_that_they_cannot_read() {
201201

202202
#[test]
203203
fn provision_and_deprovision_need_no_artifact_root() {
204-
// A provision runs no artifact, and a deprovision of a sandbox that records no launch reads
205-
// none, so both succeed where nvx-rs finds no artifact root: from an executable outside any
206-
// release or checkout, without --root.
204+
// A provision runs no artifact, and checks its shares against the artifacts only where it
205+
// finds them, and a deprovision of a sandbox that records no launch reads none, so both
206+
// succeed where nvx-rs finds no artifact root: from an executable outside any release or
207+
// checkout, without --root.
207208
let root = Root::new();
208209
let elsewhere = tempfile::tempdir().unwrap();
209210
let executable = elsewhere
@@ -239,10 +240,11 @@ fn provision_and_deprovision_need_no_artifact_root() {
239240
String::from_utf8_lossy(&output.stderr)
240241
);
241242
};
242-
let provision: Vec<String> = crate::provision(&root, "state", "")
243+
let mut provision: Vec<String> = crate::provision(&root, "state", "")
243244
.iter()
244245
.map(|argument| root.expand(argument))
245246
.collect();
247+
provision.extend(["--mount".to_owned(), root.expand("/data,{root/share}")]);
246248
nvx_rs(&provision);
247249
nvx_rs(&crate::lifecycle("deprovision", &root, "state"));
248250
assert!(!root.below("state").exists());

0 commit comments

Comments
 (0)