diff --git a/crates/axis-cli/src/main.rs b/crates/axis-cli/src/main.rs index a7410bd7..67bb4142 100644 --- a/crates/axis-cli/src/main.rs +++ b/crates/axis-cli/src/main.rs @@ -899,6 +899,10 @@ async fn run_command( startup_trace: None, }; + // Registered before the create, which already makes the tmpdir on + // some backends, so a SIGTERM from then on stops the sandbox + // instead of ending AXIS without its cleanup. + let terminated = terminate_signal()?; let mut sandbox = axis_sandbox::Sandbox::create(config).map_err(|e| anyhow::anyhow!("{e}"))?; sandbox.start().map_err(|e| anyhow::anyhow!("{e}"))?; @@ -915,14 +919,18 @@ async fn run_command( // Don't install a Ctrl+C handler, because it steals the // TTY from the child process and breaks TUI apps like // Claude Code (setRawMode fails). - let code = wait_for_interactive_standalone_sandbox(&mut sandbox).await?; + let code = + wait_for_interactive_standalone_sandbox(&mut sandbox, terminated).await?; sandbox.destroy().ok(); std::process::exit(code); } else { - // Non-interactive: wait for process or Ctrl+C. destroy() - // MUST run after the wait too: wait() only kills the local - // frontend (e.g. on timeout), so without an explicit - // destroy() the backend's VM/DomU would be orphaned. + // Non-interactive: wait for process, Ctrl+C or SIGTERM. + // destroy() MUST run after the wait too: wait() only kills + // the local frontend (e.g. on timeout), so without an + // explicit destroy() the backend's VM/DomU would be orphaned. + // A caller's timeout sends SIGTERM: destroy() then stops the + // command and removes the sandbox's tmpdir, which the next + // run in this workspace needs gone. tokio::select! { code = sandbox.wait() => { let code = code.map_err(|e| anyhow::anyhow!("{e}"))?; @@ -932,6 +940,10 @@ async fn run_command( _ = tokio::signal::ctrl_c() => { sandbox.destroy().map_err(|e| anyhow::anyhow!("{e}"))?; } + () = terminated => { + sandbox.destroy().map_err(|e| anyhow::anyhow!("{e}"))?; + std::process::exit(TERMINATED_EXIT_CODE); + } } } } @@ -984,25 +996,38 @@ fn resolve_policy_yaml(policy: &std::path::Path) -> anyhow::Result { Ok(yaml.to_string()) } -#[cfg(unix)] async fn wait_for_interactive_standalone_sandbox( sandbox: &mut axis_sandbox::Sandbox, + terminated: impl std::future::Future, ) -> Result { - let mut terminate = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?; tokio::select! { code = sandbox.wait() => Ok(code.map_err(|e| anyhow::anyhow!("{e}"))?), - _ = terminate.recv() => { + () = terminated => { sandbox.destroy().map_err(|e| anyhow::anyhow!("{e}"))?; - Ok(128 + libc::SIGTERM) + Ok(TERMINATED_EXIT_CODE) } } } +/// The status `axis run` exits with when SIGTERM stopped its sandbox. +#[cfg(unix)] +const TERMINATED_EXIT_CODE: i32 = 128 + libc::SIGTERM; #[cfg(not(unix))] -async fn wait_for_interactive_standalone_sandbox( - sandbox: &mut axis_sandbox::Sandbox, -) -> Result { - sandbox.wait().await.map_err(|e| anyhow::anyhow!("{e}")) +const TERMINATED_EXIT_CODE: i32 = 1; + +/// Settles when this process gets SIGTERM, from the call on; never where +/// there is no SIGTERM. +#[cfg(unix)] +fn terminate_signal() -> Result> { + let mut terminate = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?; + Ok(async move { + terminate.recv().await; + }) +} + +#[cfg(not(unix))] +fn terminate_signal() -> Result> { + Ok(std::future::pending()) } /// Git-style subcommand extension. diff --git a/crates/axis-sandbox/src/linux/identity.rs b/crates/axis-sandbox/src/linux/identity.rs index b09a462c..a8119b98 100644 --- a/crates/axis-sandbox/src/linux/identity.rs +++ b/crates/axis-sandbox/src/linux/identity.rs @@ -308,6 +308,17 @@ fn ensure_owned_private_directory_fd( Ok(()) } +/// Opens `path` as a directory without following a symlink in any component. +pub(crate) fn open_directory_no_symlinks(path: &Path) -> Result { + use std::os::fd::FromRawFd; + + let fd = open_directory_tree_no_symlinks(path)?; + let raw = fd.raw(); + std::mem::forget(fd); + // SAFETY: `raw` is an open descriptor that `fd` owned and no longer closes. + Ok(unsafe { std::fs::File::from_raw_fd(raw) }) +} + struct DirectoryFd(RawFd); impl DirectoryFd { diff --git a/crates/axis-sandbox/src/linux/landlock.rs b/crates/axis-sandbox/src/linux/landlock.rs index 2ae0de76..2990748f 100644 --- a/crates/axis-sandbox/src/linux/landlock.rs +++ b/crates/axis-sandbox/src/linux/landlock.rs @@ -247,6 +247,174 @@ pub(crate) fn policy_uses_tmpdir(policy: &FilesystemPolicy) -> bool { .any(|path| path.contains(TMPDIR_PLACEHOLDER)) } +/// One sandbox's hold on its workspace's `{tmpdir}`, from before the tmpdir +/// is created until after it is removed: an exclusive `flock` on the +/// workspace directory, which the kernel releases when the AXIS process that +/// holds it ends, however it ends. The descriptor is close-on-exec, so the +/// sandboxed command never holds it. +#[derive(Debug)] +pub(crate) struct TmpdirClaim { + _lock: Option, +} + +/// Takes the workspace's tmpdir for one sandbox. Another sandbox holding it +/// fails the launch. A tmpdir already there while this holds it was left by a +/// sandbox whose AXIS ended without removing it (killed), and every later +/// launch would fail on it, so it is removed when it is a directory, not a +/// link, owned by the uid the sandbox's tmpdir is created for: `identity`'s +/// for `run_as_user`, otherwise this process's. Anything else there is left, +/// and the exclusive create still refuses it. +/// +/// With `identity` the workspace is opened without following a symlink in any +/// component, as the `run_as_user` setup requires, so a workspace it would +/// refuse is refused before anything is removed. Everything after the open +/// goes through that descriptor: the lock, the filesystem check, and the +/// removal, which follows no symlink. +/// +/// On a filesystem without `flock` no launch there can hold the claim, so +/// none removes anything; any other locking error fails the launch, since a +/// later launch that does get the lock could remove this one's tmpdir. +pub(crate) fn claim_tmpdir( + workspace: &Path, + identity: Option<&super::identity::ResolvedIdentity>, +) -> Result { + match identity { + Some(identity) => claim_tmpdir_for(workspace, identity.uid, true), + None => claim_tmpdir_for(workspace, unsafe { libc::geteuid() }, false), + } +} + +fn claim_tmpdir_for( + workspace: &Path, + owner: libc::uid_t, + refuse_symlinks: bool, +) -> Result { + use std::os::unix::io::AsRawFd; + + let tmpdir = sandbox_tmpdir(workspace); + let dir = if refuse_symlinks { + super::identity::open_directory_no_symlinks(workspace) + } else { + std::fs::File::open(workspace).map_err(|e| e.to_string()) + } + .map_err(|e| { + format!( + "cannot open workspace {} to lock its tmpdir: {e}", + workspace.display() + ) + })?; + if unsafe { libc::flock(dir.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 { + let error = std::io::Error::last_os_error(); + match error.raw_os_error() { + Some(libc::EWOULDBLOCK) => { + return Err(format!( + "cannot create exclusive tmpdir {}: another sandbox in this workspace holds it", + tmpdir.display() + )); + } + Some(libc::EOPNOTSUPP | libc::EINVAL) => { + tracing::debug!( + "workspace {} does not support flock ({error}); a tmpdir left there is not removed", + workspace.display() + ); + return Ok(TmpdirClaim { _lock: None }); + } + _ => { + return Err(format!( + "cannot lock workspace {} for its tmpdir: {error}", + workspace.display() + )); + } + } + } + remove_leftover_tmpdir(&dir, &tmpdir, owner, filesystem_magic(&dir)); + Ok(TmpdirClaim { _lock: Some(dir) }) +} + +/// Filesystems where a lock may be local to one host: another host that +/// mounts the same workspace can hold the tmpdir without this host seeing its +/// lock, so a tmpdir found there may be live and is left in place. +const NETWORK_FILESYSTEM_MAGIC: &[u32] = &[ + 0x0000_6969, // NFS + 0x0000_517b, // SMB + 0xfe53_4d42, // SMB2 + 0xff53_4d42, // CIFS + 0x6573_5546, // FUSE, such as sshfs + 0x0102_1997, // 9P + 0x00c3_6400, // Ceph + 0x5346_414f, // AFS + 0x6b41_4653, // kAFS + 0x7375_7245, // Coda + 0x0bd0_0bd0, // Lustre +]; + +fn filesystem_magic(dir: &std::fs::File) -> Option { + use std::os::unix::io::AsRawFd; + + let mut stat = std::mem::MaybeUninit::::uninit(); + if unsafe { libc::fstatfs(dir.as_raw_fd(), stat.as_mut_ptr()) } != 0 { + return None; + } + // Filesystem magic numbers are 32-bit; f_type is wider on some targets. + Some(unsafe { stat.assume_init() }.f_type as u32) +} + +/// Removes a leftover tmpdir in the locked workspace `dir`. `tmpdir` names it +/// for messages only; every lookup is relative to `dir` and follows no link. +fn remove_leftover_tmpdir( + dir: &std::fs::File, + tmpdir: &Path, + owner: libc::uid_t, + filesystem: Option, +) { + use std::os::unix::io::AsRawFd; + + let name = std::ffi::CString::new(SANDBOX_TMPDIR_NAME).expect("static tmpdir name has no NUL"); + let mut stat = std::mem::MaybeUninit::::uninit(); + if unsafe { + libc::fstatat( + dir.as_raw_fd(), + name.as_ptr(), + stat.as_mut_ptr(), + libc::AT_SYMLINK_NOFOLLOW, + ) + } != 0 + { + return; + } + let stat = unsafe { stat.assume_init() }; + match filesystem { + Some(magic) if !NETWORK_FILESYSTEM_MAGIC.contains(&magic) => {} + _ => { + tracing::warn!( + "tmpdir {} is on a network or unknown filesystem, where another host may be using it; it is not removed", + tmpdir.display() + ); + return; + } + } + if stat.st_mode & libc::S_IFMT != libc::S_IFDIR || stat.st_uid != owner { + tracing::warn!( + "tmpdir {} is not a directory owned by uid {owner}; it is not removed", + tmpdir.display() + ); + return; + } + // The magic link resolves to the locked directory itself, not to the + // workspace path, and remove_dir_all neither follows nor descends into + // a symlink below it. + let anchored = Path::new("/proc/self/fd") + .join(dir.as_raw_fd().to_string()) + .join(SANDBOX_TMPDIR_NAME); + match std::fs::remove_dir_all(&anchored) { + Ok(()) => tracing::warn!( + "removed tmpdir {} left by a sandbox that did not stop cleanly", + tmpdir.display() + ), + Err(e) => tracing::warn!("cannot remove leftover tmpdir {}: {e}", tmpdir.display()), + } +} + pub(crate) fn create_tmpdir(workspace: &Path) -> Result<(), String> { let tmpdir = sandbox_tmpdir(workspace); let mut builder = std::fs::DirBuilder::new(); @@ -1740,6 +1908,129 @@ mod tests { assert!(err.contains("cannot create exclusive tmpdir")); } + #[test] + fn claim_tmpdir_removes_a_leftover_only_while_no_other_sandbox_holds_it() { + let dir = tempfile::tempdir().unwrap(); + let tmpdir = sandbox_tmpdir(dir.path()); + + let held = claim_tmpdir(dir.path(), None).unwrap(); + create_tmpdir(dir.path()).unwrap(); + std::fs::write(tmpdir.join("scratch"), b"scratch").unwrap(); + let err = claim_tmpdir(dir.path(), None).unwrap_err(); + assert!( + err.contains("another sandbox in this workspace holds it"), + "{err}" + ); + assert!(tmpdir.join("scratch").exists()); + + // The holder ended without removing it, as a killed AXIS does. + drop(held); + let _claim = claim_tmpdir(dir.path(), None).unwrap(); + assert!(!tmpdir.exists()); + create_tmpdir(dir.path()).unwrap(); + } + + #[test] + fn claim_tmpdir_leaves_a_link_or_another_owners_directory_for_the_create_to_refuse() { + let dir = tempfile::tempdir().unwrap(); + let outside = tempfile::tempdir().unwrap(); + std::fs::write(outside.path().join("keep"), b"keep").unwrap(); + let tmpdir = sandbox_tmpdir(dir.path()); + let owner = unsafe { libc::geteuid() }; + + std::os::unix::fs::symlink(outside.path(), &tmpdir).unwrap(); + let claim = claim_tmpdir(dir.path(), None).unwrap(); + assert!( + std::fs::symlink_metadata(&tmpdir) + .unwrap() + .file_type() + .is_symlink() + ); + assert!(outside.path().join("keep").exists()); + assert!( + create_tmpdir(dir.path()) + .unwrap_err() + .contains("cannot create exclusive tmpdir") + ); + drop(claim); + + std::fs::remove_file(&tmpdir).unwrap(); + std::fs::create_dir(&tmpdir).unwrap(); + let _claim = claim_tmpdir_for(dir.path(), owner.wrapping_add(1), false).unwrap(); + assert!(tmpdir.is_dir()); + assert!( + create_tmpdir(dir.path()) + .unwrap_err() + .contains("cannot create exclusive tmpdir") + ); + } + + #[test] + fn claim_tmpdir_removes_nothing_below_a_link_inside_the_leftover() { + let dir = tempfile::tempdir().unwrap(); + let outside = tempfile::tempdir().unwrap(); + std::fs::write(outside.path().join("keep"), b"keep").unwrap(); + let tmpdir = sandbox_tmpdir(dir.path()); + std::fs::create_dir(&tmpdir).unwrap(); + std::os::unix::fs::symlink(outside.path(), tmpdir.join("link")).unwrap(); + + let _claim = claim_tmpdir(dir.path(), None).unwrap(); + assert!(!tmpdir.exists()); + assert!(outside.path().join("keep").exists()); + } + + #[test] + fn claim_tmpdir_for_run_as_user_refuses_a_linked_workspace_before_removing_anything() { + let parent = tempfile::tempdir().unwrap(); + let real = parent.path().join("real"); + let link = parent.path().join("link"); + std::fs::create_dir(&real).unwrap(); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let leftover = sandbox_tmpdir(&real); + std::fs::create_dir(&leftover).unwrap(); + + let err = claim_tmpdir_for(&link, unsafe { libc::geteuid() }, true).unwrap_err(); + assert!(err.contains("cannot open workspace"), "{err}"); + assert!(leftover.is_dir()); + // Without run_as_user a linked workspace is still the workspace. + let _claim = claim_tmpdir(&link, None).unwrap(); + assert!(!leftover.exists()); + } + + #[test] + fn claim_tmpdir_leaves_a_leftover_on_a_network_or_unknown_filesystem() { + let dir = tempfile::tempdir().unwrap(); + let tmpdir = sandbox_tmpdir(dir.path()); + std::fs::create_dir(&tmpdir).unwrap(); + let workspace = std::fs::File::open(dir.path()).unwrap(); + let owner = unsafe { libc::geteuid() }; + + for filesystem in [Some(0x6969), Some(0xff53_4d42), Some(0x6573_5546), None] { + remove_leftover_tmpdir(&workspace, &tmpdir, owner, filesystem); + assert!(tmpdir.is_dir(), "{filesystem:?}"); + } + remove_leftover_tmpdir(&workspace, &tmpdir, owner, Some(0x0102_1994)); // tmpfs + assert!(!tmpdir.exists()); + } + + #[test] + fn claim_tmpdir_is_free_once_only_a_spawned_command_has_descriptors() { + let dir = tempfile::tempdir().unwrap(); + for identity in [false, true] { + let claim = claim_tmpdir_for(dir.path(), unsafe { libc::geteuid() }, identity).unwrap(); + let mut command = std::process::Command::new("/bin/sleep") + .arg("30") + .spawn() + .unwrap(); + drop(claim); + // Only an inherited lock descriptor could keep the workspace locked. + let reclaimed = claim_tmpdir(dir.path(), None); + let _ = command.kill(); + let _ = command.wait(); + assert!(reclaimed.is_ok(), "{identity}: {reclaimed:?}"); + } + } + #[test] fn policy_uses_tmpdir_detects_all_filesystem_sections() { for policy in [ diff --git a/crates/axis-sandbox/src/linux/mod.rs b/crates/axis-sandbox/src/linux/mod.rs index 3dcb890c..e9bbed4c 100644 --- a/crates/axis-sandbox/src/linux/mod.rs +++ b/crates/axis-sandbox/src/linux/mod.rs @@ -231,7 +231,7 @@ impl ParentDeathGuard { } if monitor_pid == 0 { unsafe { - libc::close(pipe.write_fd); + close_inherited_fds_except(pipe.read_fd); libc::setpgid(0, 0); run_parent_death_monitor(pipe.read_fd, process_group); } @@ -359,6 +359,9 @@ pub(crate) struct LinuxSandbox { config: SandboxConfig, plan: strategy::LinuxIsolationPlan, child: Option, + /// Process group of a child that `wait()` took and has not reaped yet. + /// A cancelled `wait()` leaves it set, so `destroy()` can still stop it. + waited_process_group: Option, parent_death_guard: Option, exit_code: Option, netns_name: Option, @@ -366,6 +369,7 @@ pub(crate) struct LinuxSandbox { cgroup: Option, connect_supervisor: Option, tmpdir_active: bool, + tmpdir_claim: Option, } impl LinuxSandbox { @@ -386,6 +390,7 @@ impl LinuxSandbox { config, plan, child: None, + waited_process_group: None, parent_death_guard: None, exit_code: None, netns_name: None, @@ -393,6 +398,7 @@ impl LinuxSandbox { cgroup: None, connect_supervisor: None, tmpdir_active: false, + tmpdir_claim: None, }) } @@ -679,6 +685,7 @@ impl LinuxSandbox { let sandbox_id = self.config.id; let tmpdir_required = landlock::policy_uses_tmpdir(&self.config.policy.filesystem); if tmpdir_required { + self.claim_tmpdir(None)?; match landlock::create_tmpdir(&self.config.workspace_dir) { Ok(()) => self.tmpdir_active = true, Err(e) => return Err(SandboxError::IsolationFailed(e)), @@ -1204,12 +1211,19 @@ impl LinuxSandbox { self.cleanup_tmpdir().err() } + fn claim_tmpdir(&mut self, identity: Option<&ResolvedIdentity>) -> Result<(), SandboxError> { + let claim = landlock::claim_tmpdir(&self.config.workspace_dir, identity) + .map_err(SandboxError::IsolationFailed)?; + self.tmpdir_claim = Some(claim); + Ok(()) + } + fn cleanup_tmpdir(&mut self) -> Result<(), String> { - if !self.tmpdir_active { - return Ok(()); + if self.tmpdir_active { + landlock::cleanup_tmpdir(&self.config.workspace_dir)?; + self.tmpdir_active = false; } - landlock::cleanup_tmpdir(&self.config.workspace_dir)?; - self.tmpdir_active = false; + self.tmpdir_claim = None; Ok(()) } @@ -1656,6 +1670,35 @@ fn current_errno() -> i32 { unsafe { *libc::__errno_location() } } +/// The monitor outlives a killed AXIS by up to about a second, so it must not +/// keep descriptors AXIS opened, such as the lock on a workspace tmpdir. +/// Runs in a forked child: only async-signal-safe calls. +unsafe fn close_inherited_fds_except(keep: i32) { + let close_range = |first: u32, last: u32| close_child_fd_range(first, last, 0).is_ok(); + let keep = keep as u32; + let closed = (keep <= 3 || close_range(3, keep - 1)) && close_range(keep + 1, u32::MAX); + if closed { + return; + } + // close_range needs Linux 5.9. + let mut limit = libc::rlimit { + rlim_cur: 0, + rlim_max: 0, + }; + let max = if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) } == 0 { + limit.rlim_cur.min(1 << 20) as i32 + } else { + 1024 + }; + for fd in 3..max { + if fd != keep as i32 { + unsafe { + libc::close(fd); + } + } + } +} + fn run_parent_death_monitor(read_fd: i32, process_group: libc::pid_t) -> ! { let mut byte = 0u8; let mut disarmed = false; @@ -1754,6 +1797,11 @@ impl SandboxImpl for LinuxSandbox { self.resolve_identity() })?; let tmpdir_required = landlock::policy_uses_tmpdir(&self.config.policy.filesystem); + if tmpdir_required { + crate::sandbox::record_startup_result(&trace, "support_files.tmpdir_claim", || { + self.claim_tmpdir(resolved_identity.as_ref()) + })?; + } if let Some(identity) = &resolved_identity { if tmpdir_required { crate::sandbox::record_startup_result(&trace, "support_files.tmpdir", || { @@ -2322,8 +2370,11 @@ impl SandboxImpl for LinuxSandbox { .take() .ok_or_else(|| SandboxError::SpawnFailed("no child process".into()))?; let pid = child.id() as i32; + self.waited_process_group = Some(pid); - let status = match wait_child_with_timeout(child, self.config.timeout_sec).await { + let status = wait_child_with_timeout(child, self.config.timeout_sec).await; + self.waited_process_group = None; + let status = match status { Ok(status) => status, Err(e) => { self.exit_code = Some(-1); @@ -2390,6 +2441,8 @@ impl SandboxImpl for LinuxSandbox { } self.exit_code = Some(wait_for_killed_child(&mut child, pid)); kill_process_group(pid); + } else if let Some(process_group) = self.waited_process_group.take() { + kill_process_group(process_group); } self.finish_parent_death_guard(); self.stop_connect_supervisor(); @@ -2819,6 +2872,80 @@ mod tests { sandbox.destroy().unwrap(); } + #[tokio::test(flavor = "multi_thread")] + async fn destroy_after_cancelled_wait_kills_the_process_group() { + if !Path::new("/bin/sh").exists() { + eprintln!("/bin/sh unavailable (test skipped)"); + return; + } + + let workspace = tempfile::tempdir().unwrap(); + let pid_path = workspace.path().join("background.pid"); + let mut cmd = Command::new("/bin/sh"); + cmd.arg("-c") + .arg("sleep 30 & echo $! > \"$PID_PATH\"; wait") + .env("PID_PATH", &pid_path); + unsafe { + cmd.pre_exec(|| { + if libc::setpgid(0, 0) < 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } + let mut child = cmd.spawn().unwrap(); + let process_group = child.id() as libc::pid_t; + let background_pid = wait_for_recorded_test_pid(&pid_path, &mut child, process_group); + let mut sandbox = test_sandbox(SandboxId::new(), workspace.path(), Some(child)); + + // What `axis run` does on SIGTERM: the select drops the pending wait(). + let waited = tokio::time::timeout( + std::time::Duration::from_millis(200), + SandboxImpl::wait(&mut sandbox), + ) + .await; + assert!(waited.is_err(), "the sandbox command exited early"); + assert!(sandbox.child.is_none()); + sandbox.destroy().unwrap(); + + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while process_exists(background_pid) { + if std::time::Instant::now() >= deadline { + kill_process_group(process_group); + panic!( + "background process {background_pid} survived destroy after a cancelled wait" + ); + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } + } + + #[test] + fn parent_death_monitor_does_not_keep_the_tmpdir_claim() { + let workspace = tempfile::tempdir().unwrap(); + let claim = landlock::claim_tmpdir(workspace.path(), None).unwrap(); + let mut child = Command::new("/bin/sleep").arg("30").spawn().unwrap(); + let process_group = child.id() as libc::pid_t; + let pipe = ParentDeathGuardPipe::new().unwrap(); + let mut guard = ParentDeathGuard::spawn_for_process_group(process_group, pipe).unwrap(); + drop(claim); + + // The monitor is still running; only its inherited descriptor could + // keep the workspace locked. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(1); + let reclaimed = loop { + match landlock::claim_tmpdir(workspace.path(), None) { + Ok(claim) => break Ok(claim), + Err(err) if std::time::Instant::now() >= deadline => break Err(err), + Err(_) => std::thread::sleep(std::time::Duration::from_millis(10)), + } + }; + guard.finish(); + let _ = child.kill(); + let _ = child.wait(); + assert!(reclaimed.is_ok(), "{reclaimed:?}"); + } + #[test] fn parent_death_guard_kills_process_group_descendants_on_owner_close() { if !Path::new("/bin/sh").exists() { @@ -3641,6 +3768,60 @@ mod tests { sandbox.destroy().unwrap(); } + #[tokio::test(flavor = "multi_thread")] + async fn native_sandbox_reclaims_a_leftover_tmpdir_and_refuses_a_second_sandbox() { + if !contract_landlock_available() { + return; + } + let Some(sh) = find_on_path("sh").and_then(|path| std::fs::canonicalize(path).ok()) else { + eprintln!("sh unavailable (test skipped)"); + return; + }; + let workspace = tempfile::tempdir().unwrap(); + let tmpdir = landlock::sandbox_tmpdir(workspace.path()); + // What a killed run leaves behind. + std::fs::create_dir(&tmpdir).unwrap(); + std::fs::write(tmpdir.join("stale"), b"stale").unwrap(); + let tmpdir_sandbox = |script: String| { + let mut sandbox = test_sandbox(SandboxId::new(), workspace.path(), None); + sandbox.config.command = sh.to_string_lossy().into_owned(); + sandbox.config.args = vec!["-c".into(), script]; + sandbox.config.capture_output = true; + sandbox.config.policy.network.mode = NetworkMode::Block; + sandbox.config.policy.filesystem = FilesystemPolicy { + read_only: runtime_read_only_paths_for(&sh), + read_write: vec!["{tmpdir}".into()], + ..Default::default() + }; + sandbox.plan.network = strategy::NetworkStrategy::BlockedBySeccomp; + sandbox.plan.proxy = strategy::ProxyStrategy::None; + sandbox + }; + + let mut first = tmpdir_sandbox(format!( + "test -d '{0}' && test ! -e '{0}/stale' && sleep 2", + tmpdir.display() + )); + SandboxImpl::start(&mut first).unwrap(); + let mut second = tmpdir_sandbox("true".into()); + let err = SandboxImpl::start(&mut second).unwrap_err().to_string(); + assert!( + err.contains("another sandbox in this workspace holds it"), + "{err}" + ); + let code = SandboxImpl::wait(&mut first).await.unwrap(); + let stderr = + std::fs::read_to_string(workspace.path().join("stderr.log")).unwrap_or_default(); + first.destroy().unwrap(); + assert_eq!(code, 0, "the leftover was not replaced; stderr:\n{stderr}"); + assert!(!tmpdir.exists()); + + let mut third = tmpdir_sandbox("true".into()); + SandboxImpl::start(&mut third).unwrap(); + assert_eq!(SandboxImpl::wait(&mut third).await.unwrap(), 0); + third.destroy().unwrap(); + } + async fn run_shell_with_deny_paths(sh: &Path, script: &str, deny: &[&str]) -> (i32, String) { let workspace = tempfile::tempdir().unwrap(); let mut sandbox = test_sandbox(SandboxId::new(), workspace.path(), None); @@ -4146,6 +4327,7 @@ mod tests { }, plan: test_plan(id, workspace), child, + waited_process_group: None, parent_death_guard: None, exit_code: None, netns_name: None, @@ -4153,6 +4335,7 @@ mod tests { cgroup: None, connect_supervisor: None, tmpdir_active: false, + tmpdir_claim: None, } } diff --git a/crates/axis-sandbox/src/linux/mxc.rs b/crates/axis-sandbox/src/linux/mxc.rs index b61e652b..29521362 100644 --- a/crates/axis-sandbox/src/linux/mxc.rs +++ b/crates/axis-sandbox/src/linux/mxc.rs @@ -443,6 +443,9 @@ pub(crate) struct MxcLinuxSandbox { proxy_strategy: super::strategy::ProxyStrategy, resource_strategy: super::strategy::ResourceStrategy, child: Option, + /// Process group of a child that `wait()` took and has not reaped yet. + /// A cancelled `wait()` leaves it set, so `destroy()` can still stop it. + waited_process_group: Option, parent_death_guard: Option, exit_code: Option, config_file: Option, @@ -460,6 +463,7 @@ pub(crate) struct MxcLinuxSandbox { capture_output: bool, timeout_sec: Option, tmpdir_active: bool, + tmpdir_claim: Option, startup_trace: Option, } @@ -941,6 +945,18 @@ impl MxcLinuxSandbox { })?; let mut tmpdir_active = false; let tmpdir_required = super::landlock::policy_uses_tmpdir(&config.policy.filesystem); + let tmpdir_claim = if tmpdir_required { + Some(crate::sandbox::record_startup_result( + &trace, + "support_files.tmpdir_claim", + || { + super::landlock::claim_tmpdir(&config.workspace_dir, resolved_identity.as_ref()) + .map_err(|err| SandboxError::IsolationFailed(format!("MXC tmpdir: {err}"))) + }, + )?) + } else { + None + }; if let Some(identity) = &resolved_identity { if tmpdir_required { crate::sandbox::record_startup_result(&trace, "support_files.tmpdir", || { @@ -1062,6 +1078,7 @@ impl MxcLinuxSandbox { proxy_strategy, resource_strategy, child: None, + waited_process_group: None, parent_death_guard: None, exit_code: None, config_file: None, @@ -1079,6 +1096,7 @@ impl MxcLinuxSandbox { capture_output: config.capture_output, timeout_sec: config.timeout_sec, tmpdir_active, + tmpdir_claim, startup_trace: config.startup_trace.clone(), }) } @@ -1114,12 +1132,13 @@ impl MxcLinuxSandbox { } fn cleanup_tmpdir(&mut self) -> Result<(), SandboxError> { - if !self.tmpdir_active { - return Ok(()); + if self.tmpdir_active { + super::landlock::cleanup_tmpdir(&self.workspace_dir).map_err(|err| { + SandboxError::IsolationFailed(format!("MXC tmpdir cleanup: {err}")) + })?; + self.tmpdir_active = false; } - super::landlock::cleanup_tmpdir(&self.workspace_dir) - .map_err(|err| SandboxError::IsolationFailed(format!("MXC tmpdir cleanup: {err}")))?; - self.tmpdir_active = false; + self.tmpdir_claim = None; Ok(()) } @@ -2154,7 +2173,10 @@ impl SandboxImpl for MxcLinuxSandbox { .take() .ok_or_else(|| SandboxError::SpawnFailed("no MXC child process".into()))?; let pid = child.id() as i32; - let status = match wait_runtime_child_with_timeout(child, self.timeout_sec).await { + self.waited_process_group = Some(pid); + let status = wait_runtime_child_with_timeout(child, self.timeout_sec).await; + self.waited_process_group = None; + let status = match status { Ok(status) => status, Err(err) => { self.exit_code = Some(-1); @@ -2210,6 +2232,8 @@ impl SandboxImpl for MxcLinuxSandbox { } self.exit_code = Some(wait_for_killed_child(&mut child, pid)); kill_process_group(pid); + } else if let Some(process_group) = self.waited_process_group.take() { + kill_process_group(process_group); } self.cleanup_after_stop()?; tracing::info!("sandbox {} destroyed via MXC Linux backend", self.id); diff --git a/docs/axis-isolation-contract.md b/docs/axis-isolation-contract.md index 8c4e5b91..511c6c67 100644 --- a/docs/axis-isolation-contract.md +++ b/docs/axis-isolation-contract.md @@ -391,6 +391,20 @@ Required behavior: failure. - Stateful backends must make persisted state explicit in policy or launch options. Hidden state reuse is not allowed. +- `{tmpdir}` is `/.axis-tmp`. AXIS creates it empty for one + sandbox and removes it when the sandbox stops; `axis run` also stops its + sandbox on SIGTERM and exits 143. On Linux the sandbox holds a lock on the + workspace for as long as the tmpdir exists, so: + - a second sandbox in the same workspace is refused while the first runs; + - a `.axis-tmp` left by a run that was killed is deleted by the next run in + that workspace when it is a directory owned by the user the tmpdir is + for. A link or another user's directory is left, and the launch fails; + - on a network filesystem (NFS, SMB, FUSE, 9P and similar), where another + host's lock may not be visible, a leftover is never deleted, and the + launch fails until it is removed. + + On Windows a leftover `.axis-tmp` still fails the launch until it is + removed. - axisd accepts IPC and gateway requests only with the per-user token in `axisd.token`, so a sandboxed process cannot ask it for a less restricted sandbox. axisd replaces the token on every start and deletes it on clean