diff --git a/crates/sandlock-cli/src/learn.rs b/crates/sandlock-cli/src/learn.rs index 0a0b93aed..d5c70e837 100644 --- a/crates/sandlock-cli/src/learn.rs +++ b/crates/sandlock-cli/src/learn.rs @@ -383,9 +383,13 @@ impl LearnObserver { match event.syscall.as_str() { "execve" | "execveat" => { - // event.path may be a symlink; canonical real path comes from /proc//exe in pending_maps. + // event.path may be a symlink; canonicalize it like any other path. + // The running binary is also recorded from /proc//exe via pending_maps. if let Some(path) = event.path { - self.reads.lock().unwrap().insert(path); + self.reads + .lock() + .unwrap() + .insert(canonicalize_or_keep(path, event.pid)); } // When a non-leader thread calls execve, the new process runs under the TGID, diff --git a/crates/sandlock-cli/tests/learn_integration.rs b/crates/sandlock-cli/tests/learn_integration.rs index 6293d08fa..f3313d752 100644 --- a/crates/sandlock-cli/tests/learn_integration.rs +++ b/crates/sandlock-cli/tests/learn_integration.rs @@ -603,6 +603,52 @@ fn test_learn_then_run_mknod() { let _ = std::fs::remove_file(&fifo); } +/// A program that re-execs itself through /proc/self/exe must get a profile +/// that names its real binary, not the /proc link run refuses. +#[test] +fn test_learn_then_run_exec_proc_self_exe() { + let profile = tempfile::NamedTempFile::new().expect("tempfile"); + let profile_path = profile.path().to_str().unwrap().to_owned(); + let script = "import os, sys; os.execv('/proc/self/exe', [sys.executable, '-c', 'pass'])"; + + learn_then_run_script(&profile_path, script); + + let profile_toml = std::fs::read_to_string(&profile_path).expect("read profile"); + // The command itself is recorded too, so check only the grants. + assert!( + !profile_toml + .lines() + .filter(|l| l.starts_with("read =") || l.starts_with("write =")) + .any(|l| l.contains("/proc/self/exe")), + "profile grants the /proc/self/exe link:\n{profile_toml}" + ); +} + +/// A file read only through legacy open(2), as musl does, must be recorded. +#[cfg(target_arch = "x86_64")] +#[test] +fn test_learn_then_run_legacy_open() { + let profile = tempfile::NamedTempFile::new().expect("tempfile"); + let profile_path = profile.path().to_str().unwrap().to_owned(); + let dir = tempfile::TempDir::new_in("/var/tmp").expect("tempdir in /var/tmp"); + let file = dir.path().join("legacy.txt"); + std::fs::write(&file, "x").unwrap(); + let file_str = file.to_str().unwrap(); + let script = format!( + "import ctypes; libc = ctypes.CDLL(None, use_errno=True); \ + fd = libc.syscall(2, b'{file_str}', 0); \ + assert fd >= 0, ctypes.get_errno()" + ); + + learn_then_run_script(&profile_path, &script); + + let profile_toml = std::fs::read_to_string(&profile_path).expect("read profile"); + assert!( + profile_toml.contains(file_str), + "legacy open target missing from profile:\n{profile_toml}" + ); +} + /// Merged profile covers paths from both learn runs. #[test] fn test_learn_then_run_merge() { diff --git a/crates/sandlock-core/src/cow/deletions.rs b/crates/sandlock-core/src/cow/deletions.rs index feb9811fb..563766375 100644 --- a/crates/sandlock-core/src/cow/deletions.rs +++ b/crates/sandlock-core/src/cow/deletions.rs @@ -145,6 +145,19 @@ impl DeletionSet { false } + /// True when some deleted path lies strictly beneath directory `rel`. + /// An empty or "." `rel` is the workdir root, so any deletion counts. + pub fn has_deleted_under(&self, rel: &str) -> bool { + if rel.is_empty() || rel == "." { + return !self.entries.is_empty(); + } + let prefix = format!("{}/", rel.trim_end_matches('/')); + self.entries + .range(prefix.clone()..) + .next() + .is_some_and(|e| e.starts_with(&prefix)) + } + pub fn iter(&self) -> impl Iterator { self.entries.iter().map(String::as_str) } @@ -175,6 +188,33 @@ mod tests { assert!(!s.covers("a/bc")); } + #[test] + fn has_deleted_under_matches_descendants_only() { + let mut s = DeletionSet::create(None); + assert!(!s.has_deleted_under("")); + s.insert("d/x"); + assert!(s.has_deleted_under("d")); + assert!(s.has_deleted_under("d/")); + assert!(!s.has_deleted_under("d/x")); + assert!(!s.has_deleted_under("d2")); + assert!(!s.has_deleted_under("e")); + // The workdir root sees every deletion. + assert!(s.has_deleted_under("")); + assert!(s.has_deleted_under(".")); + } + + /// Names that sort right around "d/" ('.' and '-' before '/', '0' after) + /// must not be mistaken for entries beneath "d". + #[test] + fn has_deleted_under_ignores_prefix_siblings() { + let mut s = DeletionSet::create(None); + s.insert("d.x"); + s.insert("d-x"); + s.insert("d0/x"); + s.insert("d"); + assert!(!s.has_deleted_under("d")); + } + #[test] fn insert_is_idempotent() { let mut s = DeletionSet::create(None); diff --git a/crates/sandlock-core/src/cow/dispatch.rs b/crates/sandlock-core/src/cow/dispatch.rs index e3871969c..54d91b9aa 100644 --- a/crates/sandlock-core/src/cow/dispatch.rs +++ b/crates/sandlock-core/src/cow/dispatch.rs @@ -1475,7 +1475,7 @@ pub(crate) async fn handle_cow_getdents( // Compute rel_path under the global COW lock, but do not hold it // across the per-process lock acquired below. - let rel_path = { + let (rel_path, needs_merge) = { let st = cow_state.lock().await; let cow = match st.branch.as_ref() { Some(c) => c, @@ -1486,14 +1486,16 @@ pub(crate) async fn handle_cow_getdents( } let target_path = Path::new(&target); if cow.matches(&target) { - cow.safe_rel(&target).unwrap_or_else(|| ".".to_string()) + let rel = cow.safe_rel(&target).unwrap_or_else(|| ".".to_string()); + (rel, cow.needs_dir_intercept(&target)) } else if let Ok(rel) = target_path.strip_prefix(cow.upper_dir()) { let rel = rel.to_string_lossy(); - if rel.is_empty() { + let rel = if rel.is_empty() { ".".to_string() } else { rel.into_owned() - } + }; + (rel, true) } else { return NotifAction::Continue; } @@ -1517,6 +1519,13 @@ pub(crate) async fn handle_cow_getdents( } } + // An unchanged directory is the kernel's listing exactly, unless this fd + // is already being served from the cache: switching midway would mix + // kernel and merged offsets. + if !needs_merge && !perproc.cow_dir_cache.contains_key(&child_fd) { + return NotifAction::Continue; + } + // Build cache on first call. if !perproc.cow_dir_cache.contains_key(&child_fd) { let entries = { diff --git a/crates/sandlock-core/src/cow/seccomp.rs b/crates/sandlock-core/src/cow/seccomp.rs index e602a8296..778ec2487 100644 --- a/crates/sandlock-core/src/cow/seccomp.rs +++ b/crates/sandlock-core/src/cow/seccomp.rs @@ -1106,6 +1106,16 @@ impl SeccompCowBranch { } } + /// Check if listing directory `path` has to merge upper and lower: the + /// directory itself is staged or whited out, or a deletion inside it must + /// hide a lower entry. A deleted child need not leave an upper directory. + pub fn needs_dir_intercept(&self, path: &str) -> bool { + match self.safe_rel(path) { + Some(rel) => self.needs_read_intercept(path) || self.deleted.has_deleted_under(&rel), + None => false, + } + } + /// Compute relative path from workdir. Returns None if path escapes. pub fn safe_rel(&self, path: &str) -> Option { let rel = pathdiff::diff_paths(path, &self.workdir)?; @@ -3986,6 +3996,59 @@ mod tests { assert!(branch.needs_read_intercept(&lnk)); } + /// A write elsewhere leaves a directory's listing to the kernel. + #[test] + fn needs_dir_intercept_ignores_a_write_elsewhere() { + let (workdir, storage) = setup_workdir(); + let mut branch = SeccompCowBranch::create(workdir.path(), Some(storage.path()), 0).unwrap(); + let subdir = abs(&branch, "subdir"); + + branch + .handle_open(&abs(&branch, "other.txt"), O_CREAT | O_WRONLY) + .unwrap(); + assert!(branch.has_changes()); + assert!(!branch.needs_dir_intercept(&subdir)); + } + + #[test] + fn needs_dir_intercept_sees_a_file_staged_inside() { + let (workdir, storage) = setup_workdir(); + let mut branch = SeccompCowBranch::create(workdir.path(), Some(storage.path()), 0).unwrap(); + let subdir = abs(&branch, "subdir"); + + branch + .handle_open(&abs(&branch, "subdir/new.txt"), O_CREAT | O_WRONLY) + .unwrap(); + assert!(branch.needs_dir_intercept(&subdir)); + } + + /// Deleting a lower child records a whiteout for it; the listing must + /// merge to hide it even if no upper directory was created. + #[test] + fn needs_dir_intercept_sees_a_deleted_child() { + let (workdir, storage) = setup_workdir(); + let mut branch = SeccompCowBranch::create(workdir.path(), Some(storage.path()), 0).unwrap(); + let subdir = abs(&branch, "subdir"); + + branch + .handle_unlink(&abs(&branch, "subdir/nested.txt"), false) + .unwrap(); + assert!(!branch.upper_dir().join("subdir").exists()); + assert!(!branch.needs_read_intercept(&subdir)); + assert!(branch.needs_dir_intercept(&subdir)); + } + + #[test] + fn needs_dir_intercept_sees_the_directory_deleted() { + let (workdir, storage) = setup_workdir(); + fs::create_dir(workdir.path().join("emptydir")).unwrap(); + let mut branch = SeccompCowBranch::create(workdir.path(), Some(storage.path()), 0).unwrap(); + let emptydir = abs(&branch, "emptydir"); + + branch.handle_unlink(&emptydir, true).unwrap(); + assert!(branch.needs_dir_intercept(&emptydir)); + } + /// Nothing outside the workdir may be mapped into the upper. `safe_rel` is /// the only thing standing between a host path and a COW copy of it, so it /// must reject both an ordinary escape and the string-prefix trap — a diff --git a/crates/sandlock-core/src/freeze.rs b/crates/sandlock-core/src/freeze.rs index 03ee11017..3df279368 100644 --- a/crates/sandlock-core/src/freeze.rs +++ b/crates/sandlock-core/src/freeze.rs @@ -194,7 +194,37 @@ fn seize_and_interrupt(tid: i32) -> io::Result { /// progress when a later task refuses to be frozen, and to release /// peer tasks after the kernel has re-read execve argv. fn detach(tid: i32) { - let _ = unsafe { libc::ptrace(libc::PTRACE_DETACH, tid, 0, 0) }; + release_tracee(tid); +} + +/// End this thread's ptrace attachment to `tid`. +/// +/// `PTRACE_DETACH` only works on a tracee in ptrace-stop. One that died while +/// attached is a zombie only its tracer can release: until the tracer waits +/// for it, its real parent cannot reap it and gets no SIGCHLD, so a session +/// reaper waiting for the last process never finishes. Waiting for it here +/// hands it back to that parent. Bounded, for a tracee still on its way out. +pub(crate) fn release_tracee(tid: i32) { + let deadline = std::time::Instant::now() + std::time::Duration::from_millis(100); + loop { + if unsafe { libc::ptrace(libc::PTRACE_DETACH, tid, 0, 0) } == 0 { + return; + } + // Not stopped. If dead, this wait hands the zombie to its parent. + let mut status: i32 = 0; + let r = unsafe { libc::waitpid(tid, &mut status, libc::__WALL | libc::WNOHANG) }; + if r == tid && (libc::WIFEXITED(status) || libc::WIFSIGNALED(status)) { + return; + } + if r < 0 && io::Error::last_os_error().raw_os_error() != Some(libc::EINTR) { + return; // not attached to this thread, or already gone + } + // Killed but not a zombie yet, or just stopped: retry. + if std::time::Instant::now() >= deadline { + return; + } + std::thread::sleep(std::time::Duration::from_millis(1)); + } } /// Enumerate every TID in a TGID via `/proc//task/`. Linux diff --git a/crates/sandlock-core/src/resource.rs b/crates/sandlock-core/src/resource.rs index 0f6a4ab35..4b001c33e 100644 --- a/crates/sandlock-core/src/resource.rs +++ b/crates/sandlock-core/src/resource.rs @@ -335,7 +335,7 @@ fn process_creation_worker( } fn detach_traced(tid: i32) { - let _ = unsafe { libc::ptrace(libc::PTRACE_DETACH, tid, 0, 0) }; + crate::freeze::release_tracee(tid); } fn wait_for_ptrace_stop(tid: i32) -> io::Result { diff --git a/crates/sandlock-core/src/seccomp/notif.rs b/crates/sandlock-core/src/seccomp/notif.rs index e25db2593..e3720f484 100644 --- a/crates/sandlock-core/src/seccomp/notif.rs +++ b/crates/sandlock-core/src/seccomp/notif.rs @@ -2191,6 +2191,7 @@ fn syscall_name(nr: i64) -> &'static str { n if n == libc::SYS_symlinkat => "symlinkat", n if n == libc::SYS_truncate => "truncate", // Legacy single-path variants (x86_64 only). + n if Some(n) == arch::sys_open() => "openat", n if Some(n) == arch::sys_mkdir() => "mkdirat", n if Some(n) == arch::sys_mknod() => "mknodat", n if Some(n) == arch::sys_rmdir() => "unlinkat",