Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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: 1 addition & 1 deletion crates/openshell-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ clap = { workspace = true, optional = true }

[target.'cfg(unix)'.dependencies]
nix = { workspace = true }
rustix = { workspace = true }
rustix = { workspace = true, features = ["fs"] }
libc = "0.2"

[features]
Expand Down
2 changes: 2 additions & 0 deletions crates/openshell-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ pub mod sandbox_update;
pub mod secrets;
pub mod settings;
pub mod shell;
#[cfg(unix)]
pub mod socket_root;
pub mod ssh_handoff;
pub mod ssh_host_key;
pub mod telemetry;
Expand Down
194 changes: 194 additions & 0 deletions crates/openshell-core/src/socket_root.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Short private directories for Unix domain sockets.
//!
//! `sun_path` is 104 bytes on macOS, so a socket under a deep state directory
//! can fail to bind. Sockets that do not need to persist live in a short,
//! random, owner-only directory under `/tmp` instead.

use std::io;
use std::os::fd::OwnedFd;
use std::path::{Path, PathBuf};

const ALLOC_RETRIES: usize = 16;

/// macOS `sun_path` is 104 bytes including the NUL terminator.
pub const MAX_SUN_PATH_LEN: usize = 103;

/// Create `/tmp/os-<euid>-<128-bit hex>` with mode `0700` and return it with
/// an open directory handle.
///
/// `/tmp` is hardcoded because macOS `TMPDIR` is already about 50 bytes long.
pub fn allocate() -> io::Result<(PathBuf, OwnedFd)> {
let uid = rustix::process::geteuid().as_raw();
allocate_in(Path::new("/tmp"), || {
let random =
u128::from_ne_bytes(openshell_crypto::random_bytes::<16>().map_err(io::Error::other)?);
Ok(format!("os-{uid}-{random:032x}"))
})
}

/// Create a new `0700` directory named by `gen_name` under `base`.
///
/// A name that already exists is never inspected or reused: a fresh name is
/// generated instead, so a pre-created entry cannot redirect the socket.
pub fn allocate_in(
base: &Path,
mut gen_name: impl FnMut() -> io::Result<String>,
) -> io::Result<(PathBuf, OwnedFd)> {
for _ in 0..ALLOC_RETRIES {
let root = base.join(gen_name()?);
match rustix::fs::mkdir(&root, rustix::fs::Mode::from_raw_mode(0o700)) {
Ok(()) => {
let fd = rustix::fs::open(
&root,
rustix::fs::OFlags::RDONLY
| rustix::fs::OFlags::DIRECTORY
| rustix::fs::OFlags::NOFOLLOW,
rustix::fs::Mode::empty(),
)
.map_err(io::Error::from)?;
return Ok((root, fd));
}
Err(rustix::io::Errno::EXIST) => {}
Err(e) => return Err(e.into()),
}
}
Err(io::Error::new(
io::ErrorKind::AlreadyExists,
format!(
"failed to allocate socket root under {} after {ALLOC_RETRIES} attempts",
base.display()
),
))
}

/// Reject a socket path that cannot be bound, naming the path, its length,
/// and the limit.
pub fn check_path_len(path: &Path) -> io::Result<()> {
let len = path.as_os_str().len();
if len > MAX_SUN_PATH_LEN {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!(
"socket path {} is {len} bytes, over the {MAX_SUN_PATH_LEN} byte sun_path limit",
path.display()
),
));
}
Ok(())
}

#[cfg(test)]
mod tests {
use super::*;
use std::os::unix::fs::PermissionsExt as _;
use std::sync::atomic::{AtomicUsize, Ordering};

#[test]
fn allocate_returns_private_distinct_roots_that_fit_sun_path() {
let (root_a, _fd_a) = allocate().unwrap();
let (root_b, _fd_b) = allocate().unwrap();
assert_ne!(root_a, root_b);
for root in [&root_a, &root_b] {
let mode = std::fs::metadata(root).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o700);
check_path_len(&root.join("compute-driver.sock")).unwrap();
let _ = std::fs::remove_dir(root);
}
}

#[test]
fn worst_case_root_fits_macos_sun_path() {
let worst_root = "/tmp/os-4294967295-00000000000000000000000000000000";
let socket = Path::new(worst_root).join("compute-driver.sock");
check_path_len(&socket).unwrap();
}

#[test]
fn allocate_in_returns_distinct_roots() {
let tmp = tempfile::tempdir().unwrap();
let mut counter = 0u64;
let mut name = || {
counter += 1;
Ok(format!("root-{counter}"))
};
let (root_a, _fd_a) = allocate_in(tmp.path(), &mut name).unwrap();
let (root_b, _fd_b) = allocate_in(tmp.path(), &mut name).unwrap();
assert_ne!(root_a, root_b);
}

#[test]
fn allocate_in_retries_on_occupied_name() {
let tmp = tempfile::tempdir().unwrap();
let victim = tmp.path().join("victim");
std::fs::create_dir(&victim).unwrap();
let original_mode = std::fs::metadata(&victim).unwrap().permissions().mode() & 0o777;

// attempt-0: symlink to victim directory
std::os::unix::fs::symlink(&victim, tmp.path().join("attempt-0")).unwrap();
// attempt-1: existing directory (simulates foreign-owned pre-creation)
std::fs::create_dir(tmp.path().join("attempt-1")).unwrap();

let call_count = AtomicUsize::new(0);
let (root, _fd) = allocate_in(tmp.path(), || {
let n = call_count.fetch_add(1, Ordering::SeqCst);
Ok(format!("attempt-{n}"))
})
.expect("should succeed after retries");

assert_eq!(root, tmp.path().join("attempt-2"));
assert_eq!(call_count.load(Ordering::SeqCst), 3);
assert!(
tmp.path()
.join("attempt-0")
.symlink_metadata()
.unwrap()
.file_type()
.is_symlink(),
"pre-created symlink must not be removed"
);
assert!(
tmp.path().join("attempt-1").exists(),
"pre-created directory must not be removed"
);
let after_mode = std::fs::metadata(&victim).unwrap().permissions().mode() & 0o777;
assert_eq!(
original_mode, after_mode,
"victim directory permissions must not change"
);
}

#[test]
fn allocate_in_propagates_name_generation_failure() {
let tmp = tempfile::tempdir().unwrap();
let err = allocate_in(tmp.path(), || {
Err(io::Error::other(openshell_crypto::CryptoError::Random))
})
.expect_err("entropy failure must stop allocation");
assert_eq!(err.kind(), io::ErrorKind::Other);
assert_eq!(std::fs::read_dir(tmp.path()).unwrap().count(), 0);
}

#[test]
fn allocate_in_exhaustion_returns_error() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir(tmp.path().join("blocked")).unwrap();

let err = allocate_in(tmp.path(), || Ok("blocked".to_string()))
.expect_err("should fail when all names are occupied");
assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
}

#[test]
fn check_path_len_names_path_length_and_limit() {
let long = PathBuf::from(format!("/tmp/{}", "x".repeat(MAX_SUN_PATH_LEN)));
let err = check_path_len(&long).expect_err("over-long path must be rejected");
assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
let message = err.to_string();
assert!(message.contains(long.to_str().unwrap()), "{message}");
assert!(message.contains(&format!("{} bytes", long.as_os_str().len())));
assert!(message.contains(&MAX_SUN_PATH_LEN.to_string()), "{message}");
}
}
8 changes: 4 additions & 4 deletions crates/openshell-driver-vm/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ By default `mise run gateway:vm`:
`~/.config/openshell/gateways/vm-dev/metadata.json`. It does not modify the
workspace `.env`.
- Persists the gateway SQLite DB under `.cache/gateway-vm/gateway.db`.
- Places the VM driver state (per-sandbox `overlay.ext4`, image cache, and the private `run/` socket directories) under `/tmp/openshell-vm-driver-$USER-vm-dev/` so the AF_UNIX socket path stays under macOS `SUN_LEN`.
- Places the VM driver state (per-sandbox `overlay.ext4` and image cache) under `/tmp/openshell-vm-driver-$USER-vm-dev/`.
- Writes `.cache/gateway-vm/gateway.toml` with `[openshell.gateway].driver_dir = "$PWD/target/debug"` so the freshly built `openshell-driver-vm` is used instead of an older installed copy from `~/.local/libexec/openshell`, `/usr/libexec/openshell`, or `/usr/local/libexec`.
- Enables OTLP trace export, OCSF log export, and the agent trace relay only when `OPENSHELL_DEV_OTLP_ENDPOINT` names a collector, for example `http://127.0.0.1:4317`. Otherwise, it omits the OTLP configuration.

Expand Down Expand Up @@ -166,7 +166,7 @@ Select the VM driver with `--compute-driver vm`, `OPENSHELL_COMPUTE_DRIVER=vm`,
| Configuration key | Default | Purpose |
|---|---|---|
| `grpc_endpoint` | empty | Required. URL the native host supervisor uses to reach the gateway. Host loopback such as `http://127.0.0.1:<port>` is valid. Legacy guest aliases are normalized to host loopback. This endpoint is never sent into the VM. |
| `state_dir` | `target/openshell-vm-driver` | Per-sandbox overlay disks, console logs, image cache, and the private `run/<random>/driver.sock` UDS, one directory per launch. Relative paths are resolved to absolute paths at driver startup. |
| `state_dir` | `target/openshell-vm-driver` | Per-sandbox overlay disks, console logs, and image cache. Relative paths are resolved to absolute paths at driver startup. |
| `driver_dir` | unset | Deprecated in this table: set `driver_dir` in `[openshell.gateway]`. The directory is searched before the standard locations. |
| `default_image` | OpenShell base image | Sandbox image used when a create request omits one. |
| `bootstrap_image` | unset | VM runtime image used as the immutable bootstrap root disk. Falls back only to the operator-configured `default_image`; the driver refuses to start when both are empty. |
Expand Down Expand Up @@ -283,8 +283,8 @@ RUST_LOG=openshell_server=debug,openshell_driver_vm=debug \
mise run gateway:vm
```

The VM guest's serial console is appended to `<state-dir>/<sandbox-id>/console.log`. Sandbox IDs must match `[A-Za-z0-9._-]{1,128}` before the driver uses them in host paths. The gateway-owned compute-driver socket lives at `<state-dir>/run/<random>/driver.sock`; each launch gets its own directory under `run/`, created with owner-only permissions and removed with the driver's handle. On clean shutdown, the gateway finishes its work through the driver, releases it with the launch protocol's `Shutdown` call, and waits up to ten seconds for it to flush telemetry and exit. It then falls back to `SIGTERM`, waits five seconds, force-kills the driver if necessary, and removes the socket. A stop signal that reaches the driver from elsewhere, such as a service manager signalling every process of the gateway's unit, is deferred until the gateway releases the driver, the gateway exits, or 30 seconds pass. UDS clients must match the driver UID and provide the expected gateway process PID by default. Standalone same-UID UDS mode requires the explicit `--allow-same-uid-peer` development flag. TCP mode is disabled by default because it is unauthenticated; use `--allow-unauthenticated-tcp --bind-address 127.0.0.1:50061` only for local development.
The VM serial console is appended to `<state-dir>/sandboxes/<sandbox-id>/rootfs-console.log`. Host-supervisor stdout and stderr are written beside it as `supervisor.log` and `supervisor.err.log`. Sandbox IDs must match `[A-Za-z0-9._-]{1,128}` before the driver uses them in host paths. The gateway-owned compute-driver socket lives at `<state-dir>/run/<random>/driver.sock`; each launch gets its own directory under `run/`, created with owner-only permissions, and the gateway removes it on clean shutdown via `ManagedDriverProcess::drop`. UDS clients must match the driver UID and provide the expected gateway process PID by default. Standalone same-UID UDS mode requires the explicit `--allow-same-uid-peer` development flag. TCP mode is disabled by default because it is unauthenticated; use `--allow-unauthenticated-tcp --bind-address 127.0.0.1:50061` only for local development.
The VM guest's serial console is appended to `<state-dir>/<sandbox-id>/console.log`. Sandbox IDs must match `[A-Za-z0-9._-]{1,128}` before the driver uses them in host paths. The gateway-owned compute-driver socket lives at `/tmp/os-<uid>-run/<random>/driver.sock`, so its path fits the macOS `sun_path` limit whatever `state_dir` is; each launch gets its own directory, created with owner-only permissions and removed with the driver's handle. On clean shutdown, the gateway finishes its work through the driver, releases it with the launch protocol's `Shutdown` call, and waits up to ten seconds for it to flush telemetry and exit. It then falls back to `SIGTERM`, waits five seconds, force-kills the driver if necessary, and removes the socket. A stop signal that reaches the driver from elsewhere, such as a service manager signalling every process of the gateway's unit, is deferred until the gateway releases the driver, the gateway exits, or 30 seconds pass. UDS clients must match the driver UID and provide the expected gateway process PID by default. Standalone same-UID UDS mode requires the explicit `--allow-same-uid-peer` development flag. TCP mode is disabled by default because it is unauthenticated; use `--allow-unauthenticated-tcp --bind-address 127.0.0.1:50061` only for local development.
The VM serial console is appended to `<state-dir>/sandboxes/<sandbox-id>/rootfs-console.log`. Host-supervisor stdout and stderr are written beside it as `supervisor.log` and `supervisor.err.log`. Sandbox IDs must match `[A-Za-z0-9._-]{1,128}` before the driver uses them in host paths. The gateway-owned compute-driver socket lives at `/tmp/os-<uid>-run/<random>/driver.sock`, so its path fits the macOS `sun_path` limit whatever `state_dir` is; each launch gets its own directory, created with owner-only permissions, and the gateway removes it on clean shutdown via `ManagedDriverProcess::drop`. UDS clients must match the driver UID and provide the expected gateway process PID by default. Standalone same-UID UDS mode requires the explicit `--allow-same-uid-peer` development flag. TCP mode is disabled by default because it is unauthenticated; use `--allow-unauthenticated-tcp --bind-address 127.0.0.1:50061` only for local development.

## Network isolation

Expand Down
Loading