diff --git a/crates/openshell-core/Cargo.toml b/crates/openshell-core/Cargo.toml index 8157c9b219..1cba62e2d6 100644 --- a/crates/openshell-core/Cargo.toml +++ b/crates/openshell-core/Cargo.toml @@ -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] diff --git a/crates/openshell-core/src/lib.rs b/crates/openshell-core/src/lib.rs index 4bc48e01d1..8f3a78ef40 100644 --- a/crates/openshell-core/src/lib.rs +++ b/crates/openshell-core/src/lib.rs @@ -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; diff --git a/crates/openshell-core/src/socket_root.rs b/crates/openshell-core/src/socket_root.rs new file mode 100644 index 0000000000..3e81f928ef --- /dev/null +++ b/crates/openshell-core/src/socket_root.rs @@ -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--<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, +) -> 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}"); + } +} diff --git a/crates/openshell-driver-vm/README.md b/crates/openshell-driver-vm/README.md index ff2ed322e2..8ebf20c172 100644 --- a/crates/openshell-driver-vm/README.md +++ b/crates/openshell-driver-vm/README.md @@ -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. @@ -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:` 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//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. | @@ -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 `//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 `/run//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 `/sandboxes//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 `/run//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 `//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--run//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 `/sandboxes//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--run//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 diff --git a/crates/openshell-driver-vm/src/driver.rs b/crates/openshell-driver-vm/src/driver.rs index 89a2103adf..1cad6ee10d 100644 --- a/crates/openshell-driver-vm/src/driver.rs +++ b/crates/openshell-driver-vm/src/driver.rs @@ -1240,7 +1240,7 @@ impl VmDriver { None }; - let (socket_root, socket_root_fd) = allocate_socket_root() + let (socket_root, socket_root_fd) = openshell_core::socket_root::allocate() .map_err(|err| format!("failed to allocate socket root in /tmp: {err}"))?; let (events, _) = broadcast::channel(WATCH_BUFFER); @@ -6792,70 +6792,18 @@ async fn restrict_owner_only_dir(_path: &Path) -> Result<(), std::io::Error> { Ok(()) } -const SOCKET_ROOT_ALLOC_RETRIES: usize = 16; -/// macOS `sun_path` is 104 bytes including the NUL terminator. -const MAX_SUN_PATH_LEN: usize = 103; - fn sandbox_socket_dir(socket_root: &Path, sandbox_id: &str) -> PathBuf { socket_root.join(sandbox_id) } -fn allocate_socket_root() -> Result<(PathBuf, OwnedFd), std::io::Error> { - let uid = rustix::process::geteuid().as_raw(); - allocate_socket_root_with(Path::new("/tmp"), || { - let random = u128::from_ne_bytes( - openshell_crypto::random_bytes::<16>().map_err(std::io::Error::other)?, - ); - Ok(format!("os-{uid}-{random:032x}")) - }) -} - -fn allocate_socket_root_with( - base: &Path, - mut gen_name: impl FnMut() -> Result, -) -> Result<(PathBuf, OwnedFd), std::io::Error> { - for _ in 0..SOCKET_ROOT_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(std::io::Error::from)?; - return Ok((root, fd)); - } - Err(rustix::io::Errno::EXIST) => {} - Err(e) => return Err(e.into()), - } - } - Err(std::io::Error::new( - std::io::ErrorKind::AlreadyExists, - format!( - "failed to allocate socket root under {} after {SOCKET_ROOT_ALLOC_RETRIES} attempts", - base.display() - ), - )) -} - fn create_sandbox_socket_dir( root_fd: &OwnedFd, socket_root: &Path, sandbox_id: &str, ) -> Result { - let longest = socket_root.join(sandbox_id).join(VM_CONTROL_SOCKET); - if longest.as_os_str().len() > MAX_SUN_PATH_LEN { - return Err(std::io::Error::new( - std::io::ErrorKind::InvalidInput, - format!( - "socket path {} exceeds sun_path limit ({MAX_SUN_PATH_LEN} bytes)", - longest.display() - ), - )); - } + openshell_core::socket_root::check_path_len( + &socket_root.join(sandbox_id).join(VM_CONTROL_SOCKET), + )?; match rustix::fs::mkdirat(root_fd, sandbox_id, rustix::fs::Mode::from_raw_mode(0o700)) { Ok(()) | Err(rustix::io::Errno::EXIST) => {} Err(e) => return Err(e.into()), @@ -10594,89 +10542,6 @@ mod tests { ); } - #[test] - fn allocate_socket_root_returns_distinct_roots() { - let tmp = tempfile::tempdir().unwrap(); - let mut counter = 0u64; - let (root_a, _fd_a) = allocate_socket_root_with(tmp.path(), || { - counter += 1; - Ok(format!("root-{counter}")) - }) - .unwrap(); - let (root_b, _fd_b) = allocate_socket_root_with(tmp.path(), || { - counter += 1; - Ok(format!("root-{counter}")) - }) - .unwrap(); - assert_ne!( - root_a, root_b, - "two allocations must produce distinct roots" - ); - } - - #[test] - fn allocate_socket_root_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_socket_root_with(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_socket_root_propagates_name_generation_failure() { - let tmp = tempfile::tempdir().unwrap(); - let err = allocate_socket_root_with(tmp.path(), || { - Err(std::io::Error::other(openshell_crypto::CryptoError::Random)) - }) - .expect_err("entropy failure must stop allocation"); - assert_eq!(err.kind(), std::io::ErrorKind::Other); - assert_eq!(std::fs::read_dir(tmp.path()).unwrap().count(), 0); - } - - #[test] - fn allocate_socket_root_exhaustion_returns_error() { - let tmp = tempfile::tempdir().unwrap(); - let blocked = tmp.path().join("blocked"); - std::fs::create_dir(&blocked).unwrap(); - - let err = allocate_socket_root_with(tmp.path(), || Ok("blocked".to_string())) - .expect_err("should fail when all names are occupied"); - assert_eq!(err.kind(), std::io::ErrorKind::AlreadyExists); - } - #[test] fn sandbox_state_dir_rejects_path_unsafe_ids() { let err = sandbox_state_dir(Path::new("/tmp/openshell-vm"), "../escape") diff --git a/crates/openshell-gateway/src/vm.rs b/crates/openshell-gateway/src/vm.rs index cd388c85d1..2bb8c37a98 100644 --- a/crates/openshell-gateway/src/vm.rs +++ b/crates/openshell-gateway/src/vm.rs @@ -17,7 +17,6 @@ use openshell_server::AcquiredRemoteDriverEndpoint; use crate::launcher::{self, ConfigureInputs, LaunchOutcome, LaunchRequest, PreflightFailure}; const DRIVER_BIN_NAME: &str = "openshell-driver-vm"; -const COMPUTE_DRIVER_SOCKET_RUN_DIR: &str = "run"; const DRIVER_BIN_HINT: &str = "set driver_dir in [openshell.gateway], install it in a conventional libexec path such as ~/.local/libexec/openshell, /usr/libexec/openshell, or /usr/local/libexec{,/openshell}, or place it next to the gateway binary"; /// The gateway's view of the `[openshell.drivers.vm]` table. @@ -25,8 +24,7 @@ const DRIVER_BIN_HINT: &str = "set driver_dir in [openshell.gateway], install it pub struct VmLaunchPlan { /// Where to look for the driver binary before the conventional locations. pub driver_dir: Option, - /// The driver's state directory, under which the gateway keeps the - /// private socket directory. + /// The driver's state directory. pub state_dir: PathBuf, /// The table to forward, without gateway-owned keys. pub table: String, @@ -83,8 +81,15 @@ impl VmLaunchPlan { ) } - fn socket_dir(&self) -> PathBuf { - self.state_dir.join(COMPUTE_DRIVER_SOCKET_RUN_DIR) + /// Per-user base for each launch's private socket directory. + /// + /// It lives under `/tmp`, not `state_dir`, so the socket path fits the + /// `sun_path` limit however deep `state_dir` is. + fn socket_dir() -> PathBuf { + PathBuf::from(format!( + "/tmp/os-{}-run", + rustix::process::geteuid().as_raw() + )) } } @@ -191,7 +196,7 @@ pub async fn spawn( name: "vm", binary: &binary, table: &plan.table, - socket_dir: &plan.socket_dir(), + socket_dir: &VmLaunchPlan::socket_dir(), log_level: gateway_log_level, }, configure, diff --git a/crates/openshell-gateway/src/vm/tests.rs b/crates/openshell-gateway/src/vm/tests.rs index 45554db430..f0460ef093 100644 --- a/crates/openshell-gateway/src/vm/tests.rs +++ b/crates/openshell-gateway/src/vm/tests.rs @@ -47,13 +47,10 @@ fn a_non_string_gateway_key_is_rejected() { } #[test] -fn socket_dir_is_the_private_run_dir_under_the_state_dir() { - let plan = - VmLaunchPlan::from_table(table("state_dir = \"/tmp/openshell-vm-state\""), None).unwrap(); - assert_eq!( - plan.socket_dir(), - PathBuf::from("/tmp/openshell-vm-state/run") - ); +fn socket_dir_is_short_and_outside_the_state_dir() { + assert!(VmLaunchPlan::socket_dir().starts_with("/tmp")); + let worst_case = PathBuf::from("/tmp/os-4294967295-run/abcdef/driver.sock"); + openshell_core::socket_root::check_path_len(&worst_case).unwrap(); } #[test]