diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e7d508cca..d5d101cbd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -67,8 +67,8 @@ jobs: # --locked: verify Cargo.lock is up to date (replaces the removed `cargo check --locked`) - run: cargo clippy --locked --all-targets --all-features -- -D warnings - run: | - cargo clippy --locked -p fspy_elf_loader -p fspy_elf_loader_test_launcher --target x86_64-unknown-none -- -D warnings - cargo clippy --locked -p fspy_elf_loader -p fspy_elf_loader_test_launcher --target aarch64-unknown-none-softfloat -- -D warnings + cargo clippy --locked -p fspy_elf_loader -p fspy_elf_loader_test_launcher -p fspy_preload_linux --target x86_64-unknown-none -- -D warnings + cargo clippy --locked -p fspy_elf_loader -p fspy_elf_loader_test_launcher -p fspy_preload_linux --target aarch64-unknown-none-softfloat -- -D warnings # fspy builds only on Windows, macOS, and Linux, but vp must still build # without it on other platforms. Cross-building `vt_bin` for FreeBSD catches @@ -156,6 +156,10 @@ jobs: if: ${{ env.TEST_TARGET == 'x86_64-unknown-linux-gnu' }} run: $TEST_CARGO_CMD test --release -p fspy_elf_loader_tests --target $TEST_BUILD_TARGET + - name: Run fspy hardening tests (release) + if: ${{ env.TEST_TARGET == 'x86_64-unknown-linux-gnu' }} + run: $TEST_CARGO_CMD test --release -p fspy --test linux_hardening --test linux_syscalls --test untracked_fallback --target $TEST_BUILD_TARGET + # x86_64-apple-darwin runs on arm64 runner under Rosetta; install x64 Node # so fspy's x86_64 preload dylib can be injected into spawned node procs. - uses: oxc-project/setup-node@f46a72f95efdc55273fcd042d61c84e723b2892c # v1.4.1 @@ -388,11 +392,49 @@ jobs: - name: Run ELF loader tests (release) run: cargo test --release -p fspy_elf_loader_tests + - name: Run fspy hardening tests (release) + run: cargo test --release -p fspy --test linux_hardening --test linux_syscalls --test untracked_fallback + - uses: oxc-project/setup-node@f46a72f95efdc55273fcd042d61c84e723b2892c # v1.4.1 + # Run only Bun's postinstall on musl (`deno` and `workerd` do not ship + # musl binaries and their tests are filtered out on `target_env = "musl"`). + - name: Install Bun runtime binary + run: pnpm --filter vite-task-tools rebuild bun + - name: Run ignored tests run: cargo test -- --ignored + test-linux-arm64: + needs: detect-changes + if: needs.detect-changes.outputs.code-changed == 'true' + name: Test (linux-arm64) + runs-on: ubuntu-24.04-arm + steps: + - uses: taiki-e/checkout-action@7d1e50e93dc4fb3bba58f85018fadf77898aee8b # v1.4.2 + + - name: Update submodules + run: git submodule update --init --recursive + + - uses: oxc-project/setup-rust@3d6fb132fbe7cdcb66bf8ec193911c2945369d12 # v1.0.17 + with: + save-cache: ${{ github.ref_name == 'main' }} + cache-key: test-linux-arm64 + + - run: rustup target add aarch64-unknown-linux-musl aarch64-unknown-none-softfloat + + - name: Run ELF loader tests (debug) + run: cargo test -p fspy_elf_loader -p fspy_elf_loader_tests + + - name: Run ELF loader tests (release) + run: cargo test --release -p fspy_elf_loader -p fspy_elf_loader_tests + + - name: Run fspy tests (debug) + run: cargo test -p fspy + + - name: Run fspy hardening tests (release) + run: cargo test --release -p fspy --test linux_hardening --test linux_syscalls --test untracked_fallback + fmt: name: Format and Check Deps runs-on: namespace-profile-linux-x64-default @@ -440,6 +482,7 @@ jobs: - clippy - build-freebsd - test + - test-linux-arm64 - test-macos-x64 - test-musl - build-windows-tests diff --git a/.github/workflows/fspy-benchmark.yml b/.github/workflows/fspy-benchmark.yml index db3ec05e4..fe653e5b7 100644 --- a/.github/workflows/fspy-benchmark.yml +++ b/.github/workflows/fspy-benchmark.yml @@ -94,8 +94,14 @@ jobs: [[ "$RUNNER_OS" == "Windows" ]] && exe=.exe cp "$CARGO_TARGET_DIR/release/fspy_benchmark_launcher$exe" "$RUNNER_TEMP/fspy-base-launcher$exe" # A baseline worktree created after the head can leave newer - # workspace artifacts that Cargo considers fresh for the head. + # workspace artifacts that Cargo considers fresh for the head, + # including cross-target artifact dependencies like fspy_preload_linux. cargo clean --release --workspace + for target in x86_64-unknown-none aarch64-unknown-none-softfloat; do + if [[ -d "$CARGO_TARGET_DIR/$target" ]]; then + cargo clean --release --workspace --target "$target" + fi + done - name: Run benchmark run: | diff --git a/CHANGELOG.md b/CHANGELOG.md index ad334a2d7..6891e10d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,6 @@ # Changelog +- **Changed** On Linux, automatic file-access tracking now uses an in-process ELF launcher and `SIGSYS` syscall tracker instead of `LD_PRELOAD` and `seccomp_unotify`, unifying tracking across glibc, musl, static binaries, and direct-syscall runtimes such as Bun. Tracked Linux processes run with `no_new_privs`, fall back from `io_uring` to standard filesystem syscalls, and require native ELF64 executables ([#1026](https://github.com/voidzero-dev/vite-task/pull/1026), [#1027](https://github.com/voidzero-dev/vite-task/pull/1027), [#1028](https://github.com/voidzero-dev/vite-task/pull/1028), [#1029](https://github.com/voidzero-dev/vite-task/pull/1029)). - **Fixed** Remote cache operations now cap concurrent uploads to 4 per endpoint, use pooled HTTP/1.1 connections instead of multiplexing all reads and uploads over one HTTP/2 connection, retry transient `5xx`/`429`/`408` and network failures with jittered backoff, and back off briefly during sustained endpoint outages, preventing `503` upload bursts and Windows connection-reset drops ([#1016](https://github.com/voidzero-dev/vite-task/pull/1016)). - **Fixed** Tasks that list `node_modules`, the workspace root, or `node_modules/.vite` no longer miss the cache when pnpm's `node_modules/.pnpm-workspace-state-*.json`, Vite's `node_modules/.vite-temp`, the workspace root's `.git`, or the task cache directory appear or disappear. Direct accesses to `node_modules/.vite-temp` and `.DS_Store` are now skipped as well, so they are neither tracked as inputs nor archived as outputs ([#1014](https://github.com/voidzero-dev/vite-task/pull/1014)). - **Fixed** When a command handler sets a working directory for a command it generates, `vp run` now runs that command in the selected directory and includes the directory in its cache fingerprint ([#1005](https://github.com/voidzero-dev/vite-task/pull/1005)). diff --git a/Cargo.lock b/Cargo.lock index 0ecd7c080..22acfaf5e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -161,16 +161,6 @@ dependencies = [ "syn 2.0.117", ] -[[package]] -name = "assertables" -version = "10.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b3cadd448c7cd878da49dac40adcd0f7248d2911afe5102267f68c352d87882" -dependencies = [ - "regex", - "walkdir", -] - [[package]] name = "async-trait" version = "0.1.89" @@ -1373,28 +1363,33 @@ dependencies = [ "csv-async", "ctor", "derive_more", + "elf", "flate2", "fspy_detours_sys", - "fspy_preload_unix", + "fspy_elf_loader", + "fspy_preload_linux", + "fspy_preload_macos", "fspy_preload_windows", - "fspy_seccomp_unotify", "fspy_shared", "fspy_shared_unix", "fspy_test_bin", "futures-util", "libc", + "linux-raw-sys 0.12.1", "nix 0.31.2", "ntapi", "ntest", "ouroboros", "rustc-hash", "sha2 0.11.0", + "syscalls", "tar", "tempfile", "test-log", "thiserror 2.0.18", "tokio", "tokio-util", + "tracing", "vt_casefold", "vt_materialized_artifact", "vt_subprocess_test", @@ -1430,22 +1425,6 @@ version = "0.0.0" name = "fspy_benchmark_target" version = "0.0.0" -[[package]] -name = "fspy_client_unix" -version = "0.0.0" -dependencies = [ - "allocator-api2", - "anyhow", - "bstr", - "fspy_nostd", - "fspy_nostd_alloc", - "fspy_shared", - "fspy_shared_unix", - "itoa", - "libc", - "nix 0.31.2", -] - [[package]] name = "fspy_detours_sys" version = "0.0.0" @@ -1527,20 +1506,33 @@ dependencies = [ ] [[package]] -name = "fspy_preload_unix" +name = "fspy_preload_linux" version = "0.0.0" dependencies = [ "allocator-api2", + "bstr", + "fspy_elf_loader", + "fspy_nostd", + "fspy_nostd_alloc", + "fspy_shared", + "fspy_shared_unix", + "linux-raw-sys 0.12.1", + "syscalls", +] + +[[package]] +name = "fspy_preload_macos" +version = "0.0.0" +dependencies = [ + "allocator-api2", + "bstr", "ctor", - "fspy_client_unix", "fspy_nostd", "fspy_nostd_alloc", "fspy_shared", "fspy_shared_unix", "libc", - "nix 0.31.2", "static_cell", - "syscalls", ] [[package]] @@ -1563,24 +1555,6 @@ dependencies = [ "winsafe 0.0.27", ] -[[package]] -name = "fspy_seccomp_unotify" -version = "0.1.0" -dependencies = [ - "assertables", - "futures-util", - "libc", - "nix 0.31.2", - "passfd", - "seccompiler", - "syscalls", - "tempfile", - "test-log", - "tokio", - "tracing", - "wincode", -] - [[package]] name = "fspy_shared" version = "0.0.0" @@ -1611,17 +1585,15 @@ name = "fspy_shared_unix" version = "0.0.0" dependencies = [ "allocator-api2", - "anyhow", "base64 0.22.1", + "bitflags 2.13.2", "bstr", - "elf", "fspy_nostd", "fspy_nostd_alloc", - "fspy_seccomp_unotify", "fspy_shared", - "memmap2", - "nix 0.31.2", + "linux-raw-sys 0.12.1", "phf 0.13.1", + "tempfile", "wincode", ] @@ -2511,15 +2483,6 @@ version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" -[[package]] -name = "memmap2" -version = "0.9.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" -dependencies = [ - "libc", -] - [[package]] name = "memmem" version = "0.1.1" @@ -2694,7 +2657,6 @@ dependencies = [ "cfg-if", "cfg_aliases 0.2.1", "libc", - "memoffset", ] [[package]] @@ -3029,16 +2991,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "passfd" -version = "0.2.0" -source = "git+https://github.com/polachok/passfd?rev=d55881752c16aced1a49a75f9c428d38d3767213#d55881752c16aced1a49a75f9c428d38d3767213" -dependencies = [ - "futures-core", - "libc", - "tokio", -] - [[package]] name = "pastey" version = "0.2.3" @@ -3857,14 +3809,6 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" -[[package]] -name = "seccompiler" -version = "0.5.0" -source = "git+https://github.com/rust-vmm/seccompiler?rev=08587106340b8e3cb361c7561411510039436857#08587106340b8e3cb361c7561411510039436857" -dependencies = [ - "libc", -] - [[package]] name = "security-framework" version = "3.7.0" diff --git a/Cargo.toml b/Cargo.toml index 20f0880b2..5238a6526 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,9 +43,8 @@ allocator-api2 = { version = "0.2", default-features = false } anstream = "1.0.0" anyhow = "1.0.103" assert2 = "0.4.0" -assertables = "10.0.0" async-trait = "0.1.89" -base64 = "0.22.1" +base64 = { version = "0.22.1", default-features = false } bytes = "1.11.1" url = "2.5.8" wincode = { version = "0.6.0", default-features = false, features = ["alloc"] } @@ -80,11 +79,10 @@ flate2 = "1.0.35" fspy = { path = "crates/fspy" } fspy_benchmark_launcher = { path = "crates/fspy_benchmark_launcher", artifact = "bin" } fspy_benchmark_target = { path = "crates/fspy_benchmark_target", artifact = "bin" } -fspy_client_unix = { path = "crates/fspy_client_unix" } fspy_detours_sys = { path = "crates/fspy_detours_sys" } -fspy_preload_unix = { path = "crates/fspy_preload_unix", artifact = "cdylib" } +fspy_elf_loader = { path = "crates/fspy_elf_loader" } +fspy_preload_macos = { path = "crates/fspy_preload_macos", artifact = "cdylib" } fspy_preload_windows = { path = "crates/fspy_preload_windows", artifact = "cdylib" } -fspy_seccomp_unotify = { path = "crates/fspy_seccomp_unotify" } fspy_shm = { path = "crates/fspy_shm" } fspy_shared = { path = "crates/fspy_shared" } fspy_shared_unix = { path = "crates/fspy_shared_unix" } @@ -93,12 +91,10 @@ futures-util = "0.3.31" globset = "0.4.18" getrandom = "0.4.2" hashbrown = { version = "0.16.1", default-features = false, features = ["inline-more"] } -itoa = "1.0.17" jsonc-parser = "0.32.0" libc = "0.2.185" linux-raw-sys = { version = "0.12", default-features = false } libtest-mimic = "0.8.2" -memmap2 = "0.9.11" monostate = "1.0.2" napi = "3" napi-build = "2" @@ -111,7 +107,6 @@ once_cell = "1.19" os_str_bytes = "7.1.1" ouroboros = "0.18.5" owo-colors = "4.1.0" -passfd = { git = "https://github.com/polachok/passfd", rev = "d55881752c16aced1a49a75f9c428d38d3767213", default-features = false } notify = "8.0.0" path-clean = "1.0.1" pathdiff = "0.2.3" @@ -130,8 +125,6 @@ rusqlite = "0.41.0" rustc-hash = "2.1.1" rustls = { version = "0.23.44", default-features = false } schemars = "1.2.3" -# SeccompAction::UserNotif (SECCOMP_RET_USER_NOTIF) was added after the latest published release (v0.5.0) -seccompiler = { git = "https://github.com/rust-vmm/seccompiler", rev = "08587106340b8e3cb361c7561411510039436857" } serde = "1.0.219" serde-untagged = "0.1.9" serde_bytes = "0.11.19" @@ -200,12 +193,11 @@ xxhash-rust = "0.8.15" ntest = "0.9.5" terminal_size = "0.4" zstd = "0.14" -fspy_elf_loader = { path = "crates/fspy_elf_loader" } [workspace.metadata.cargo-shear] ignored = [ # These are artifact dependencies. They are not directly `use`d in Rust code. - "fspy_preload_unix", + "fspy_preload_macos", "fspy_preload_windows", "vt_client_napi", ] diff --git a/crates/fspy/Cargo.toml b/crates/fspy/Cargo.toml index 049050ac6..14d7e603c 100644 --- a/crates/fspy/Cargo.toml +++ b/crates/fspy/Cargo.toml @@ -7,44 +7,45 @@ publish = false [dependencies] allocator-api2 = { workspace = true, features = ["alloc"] } -wincode = { workspace = true } -bumpalo = { workspace = true, features = ["allocator-api2", "collections"] } derive_more = { workspace = true, features = ["debug"] } -vt_materialized_artifact = { workspace = true } fspy_shared = { workspace = true } futures-util = { workspace = true } libc = { workspace = true } -ouroboros = { workspace = true } rustc-hash = { workspace = true } tempfile = { workspace = true } thiserror = { workspace = true } tokio = { workspace = true, features = ["macros", "net", "process", "io-util", "sync", "rt"] } tokio-util = { workspace = true } vt_casefold = { workspace = true } +vt_materialized_artifact = { workspace = true } which = { workspace = true, features = ["tracing"] } - -[target.'cfg(target_os = "linux")'.dependencies] -fspy_seccomp_unotify = { workspace = true, features = ["supervisor"] } -nix = { workspace = true, features = ["uio"] } -tokio = { workspace = true, features = ["bytes"] } +wincode = { workspace = true } [target.'cfg(unix)'.dependencies] +bumpalo = { workspace = true, features = ["allocator-api2", "collections"] } fspy_shared_unix = { workspace = true } -nix = { workspace = true, features = ["fs", "process", "socket", "feature"] } # The preload artifact deps live under `[dependencies]` — not # `[build-dependencies]`, where Cargo would compile them with the # build-override profile (opt-level 0 in release; see # https://github.com/rust-lang/cargo/issues/16719) — so they get the normal # profile, in this workspace and downstream ones, with no per-package profile -# overrides. Cargo provides `CARGO_CDYLIB_FILE_*` while compiling this crate -# for `artifact!` to embed. Each dep is scoped to the targets whose code -# embeds it, so other targets (e.g. musl, which never dynamically links a -# preload) don't build a useless empty cdylib. Scoping artifact deps under -# `[target.cfg…]` is only safe for normal deps: the same shape under -# `[target.cfg….build-dependencies]` panics cargo's resolver on cross-compile. -[target.'cfg(all(unix, not(target_env = "musl")))'.dependencies] -fspy_preload_unix = { workspace = true } +# overrides. Cargo provides `CARGO_BIN_FILE_*` / `CARGO_CDYLIB_FILE_*` while +# compiling this crate for `artifact!` to embed. +[target.'cfg(target_os = "linux")'.dependencies] +linux-raw-sys = { workspace = true, features = ["general", "prctl", "ptrace"] } +syscalls = { workspace = true } +tracing = { workspace = true } + +[target.'cfg(all(target_os = "linux", target_arch = "x86_64"))'.dependencies] +fspy_preload_linux = { path = "../fspy_preload_linux", artifact = "bin", target = "x86_64-unknown-none" } + +[target.'cfg(all(target_os = "linux", target_arch = "aarch64"))'.dependencies] +fspy_preload_linux = { path = "../fspy_preload_linux", artifact = "bin", target = "aarch64-unknown-none-softfloat" } + +[target.'cfg(target_os = "macos")'.dependencies] +fspy_preload_macos = { workspace = true } +ouroboros = { workspace = true } [target.'cfg(target_os = "windows")'.dependencies] fspy_detours_sys = { workspace = true } @@ -53,17 +54,21 @@ ntapi = { workspace = true } winapi = { workspace = true, features = ["winbase", "securitybaseapi", "handleapi"] } winsafe = { workspace = true, features = ["kernel"] } -[target.'cfg(target_os = "macos")'.dev-dependencies] -tempfile = { workspace = true } - [dev-dependencies] anyhow = { workspace = true } csv-async = { workspace = true, features = ["tokio"] } ctor = { workspace = true } ntest = { workspace = true } -vt_subprocess_test = { workspace = true, features = ["fspy"] } test-log = { workspace = true, features = ["trace"] } tokio = { workspace = true, features = ["rt-multi-thread", "macros", "fs", "io-std"] } +vt_subprocess_test = { workspace = true, features = ["fspy"] } + +[target.'cfg(unix)'.dev-dependencies] +nix = { workspace = true, features = ["fs"] } + +[target.'cfg(target_os = "linux")'.dev-dependencies] +elf = { workspace = true } +fspy_elf_loader = { workspace = true } [target.'cfg(all(target_os = "linux", target_arch = "aarch64"))'.dev-dependencies] fspy_test_bin = { path = "../fspy_test_bin", artifact = "bin", target = "aarch64-unknown-linux-musl" } @@ -84,4 +89,10 @@ workspace = true doctest = false [package.metadata.cargo-shear] -ignored = ["ctor", "fspy_test_bin", "fspy_preload_unix", "fspy_preload_windows"] +ignored = [ + "ctor", + "fspy_test_bin", + "fspy_preload_linux", + "fspy_preload_macos", + "fspy_preload_windows", +] diff --git a/crates/fspy/README.md b/crates/fspy/README.md index e80355d9b..08ddb9a02 100644 --- a/crates/fspy/README.md +++ b/crates/fspy/README.md @@ -2,27 +2,32 @@ Run a command and capture all the paths it tries to access. -## macOS/Linux (glibc) implementation - -It uses `DYLD_INSERT_LIBRARIES` on macOS and `LD_PRELOAD` on Linux to inject a shared library that intercepts file system calls. -The injection process is almost identical on both platforms other than the environment variable name. The implementation is in `src/unix`. - -## Linux-specific implementation for fully static binaries - -For fully static binaries (such as `esbuild`), `LD_PRELOAD` does not work. In this case, `seccomp_unotify` is used to intercept direct system calls. The handler is implemented in `src/unix/syscall_handler`. It records accesses into the same shared-memory channel as the preload library (`fspy_shared::ipc::channel`). - -## Linux musl implementation - -On musl targets, only `seccomp_unotify`-based tracking is used (no preload library). +## Linux implementation + +Linux uses `fspy_preload_linux` (`src/linux`), a freestanding fixed-address ELF64 +loader (`x86_64-unknown-none` / `aarch64-unknown-none-softfloat`) built on +`fspy_elf_loader`. `fspy` spawns `fspy_preload_linux`, which maps the target +executable (dynamic glibc, musl, static, or custom runtime) in-process and +installs a `SECCOMP_RET_TRAP` (`SIGSYS`) filter to record filesystem syscalls +into the shared-memory IPC channel (`fspy_shared::ipc::channel`) and chain child +`execve`/`execveat` calls. When `seccomp` is unavailable (such as in a +restricted sandbox), `fspy` falls back to running the command untracked and +reports `TrackingIncomplete`. Because seccomp sets `PR_SET_NO_NEW_PRIVS` and +userland ELF mapping opens target binaries read-only, setuid/setgid and +file-capability escalations do not apply, and execute-only (`chmod 0111`) +binaries cannot be mapped and fail with `EACCES`. + +## macOS implementation + +macOS uses `DYLD_INSERT_LIBRARIES` with `fspy_preload_macos` (`src/macos`) to +interpose libc file-access and exec calls, substituting bundled shells and +coreutils for SIP-protected `/bin`/`/usr/bin` binaries. ## Windows implementation -It uses [Detours](https://github.com/microsoft/Detours) to intercept file system calls. The implementation is in `src/windows`. +Windows uses [Detours](https://github.com/microsoft/Detours) with +`fspy_preload_windows` (`src/windows`) to intercept Win32/NT file system calls. ## Unified interface The unified interface of `Command` is in `src/command.rs`. - -## Preload Libraries - -`DYLD_INSERT_LIBRARIES`, `LD_PRELOAD`, `Detours` all require a shared library to be injected. The shared libraries of macOS/Linux are in the `fspy_preload_unix` crate, and the shared library of Windows is in the `fspy_preload_windows` crate. diff --git a/crates/fspy/src/command.rs b/crates/fspy/src/command.rs index 295a3c2d2..abd6d234c 100644 --- a/crates/fspy/src/command.rs +++ b/crates/fspy/src/command.rs @@ -4,10 +4,10 @@ use std::{ process::Stdio, }; -#[cfg(unix)] -use allocator_api2::alloc::Global; -#[cfg(unix)] -use fspy_shared_unix::exec::{Exec, to_vec_in}; +#[cfg(target_os = "macos")] +use allocator_api2::{alloc::Global, vec::Vec as AllocVec}; +#[cfg(target_os = "macos")] +use fspy_shared_unix::Exec; use rustc_hash::FxHashMap; use tokio::process::Command as TokioCommand; use tokio_util::sync::CancellationToken; @@ -53,32 +53,29 @@ impl Command { } } - #[cfg(unix)] + #[cfg(target_os = "macos")] #[must_use] pub(crate) fn get_exec(&self) -> Exec { use std::{iter::once, os::unix::ffi::OsStrExt}; + let copy = |bytes: &[u8]| { + let mut out = AllocVec::with_capacity_in(bytes.len(), Global); + out.extend_from_slice(bytes); + out + }; let arg0 = self.arg0.as_ref().unwrap_or(&self.program); Exec { - program: to_vec_in(self.program.as_bytes(), Global), - args: once(arg0) - .chain(&self.args) - .map(|arg| to_vec_in(arg.as_bytes(), Global)) - .collect(), + program: copy(self.program.as_bytes()), + args: once(arg0).chain(&self.args).map(|arg| copy(arg.as_bytes())).collect(), envs: self .envs .iter() - .map(|(name, value)| { - ( - to_vec_in(name.inner().as_bytes(), Global), - Some(to_vec_in(value.as_bytes(), Global)), - ) - }) + .map(|(name, value)| (copy(name.inner().as_bytes()), Some(copy(value.as_bytes())))) .collect(), } } - #[cfg(unix)] + #[cfg(target_os = "macos")] pub(crate) fn set_exec(&mut self, mut exec: Exec) { use std::os::unix::ffi::OsStrExt; @@ -98,6 +95,20 @@ impl Command { .collect(); } + #[cfg(target_os = "linux")] + #[must_use] + pub(crate) fn target_program(&self) -> &OsStr { + &self.program + } + + #[cfg(target_os = "linux")] + pub(crate) fn redirect_program(&mut self, loader_program: &OsStr) { + if self.arg0.is_none() { + self.arg0 = Some(self.program.clone()); + } + self.program = loader_program.to_os_string(); + } + pub fn env_remove>(&mut self, key: K) -> &mut Self { self.envs.remove(EnvName::from_ref(key.as_ref())); self diff --git a/crates/fspy/src/error.rs b/crates/fspy/src/error.rs index e47f84d42..847a1ec02 100644 --- a/crates/fspy/src/error.rs +++ b/crates/fspy/src/error.rs @@ -16,9 +16,6 @@ pub enum SpawnError { cause: which::Error, }, - #[error("failed to initialize seccomp_unotify supervisor: {0}")] - Supervisor(std::io::Error), - #[error("failed to create IPC channel: {0}")] ChannelCreation(std::io::Error), diff --git a/crates/fspy/src/lib.rs b/crates/fspy/src/lib.rs index 6f47bf749..67db8736b 100644 --- a/crates/fspy/src/lib.rs +++ b/crates/fspy/src/lib.rs @@ -2,15 +2,19 @@ pub mod error; mod ipc; -#[cfg(unix)] -#[path = "./unix/mod.rs"] +#[cfg(target_os = "linux")] +#[path = "./linux/mod.rs"] +mod os_impl; + +#[cfg(target_os = "macos")] +#[path = "./macos/mod.rs"] mod os_impl; #[cfg(target_os = "windows")] #[path = "./windows/mod.rs"] mod os_impl; -#[cfg(unix)] +#[cfg(target_os = "macos")] mod arena; mod command; diff --git a/crates/fspy/src/linux/mod.rs b/crates/fspy/src/linux/mod.rs new file mode 100644 index 000000000..57ee46a0e --- /dev/null +++ b/crates/fspy/src/linux/mod.rs @@ -0,0 +1,411 @@ +use std::{ + io, + mem::offset_of, + os::fd::{AsRawFd as _, FromRawFd as _, OwnedFd}, + path::Path, + sync::RwLock, +}; + +use fspy_shared::ipc::{IpcStr, PathAccess, channel::channel}; +use fspy_shared_unix::linux::{BOOTSTRAP_ENV_NAME, Bootstrap, Target, encode_bootstrap}; +use futures_util::FutureExt as _; +use linux_raw_sys::{ + prctl::PR_SET_NO_NEW_PRIVS, + ptrace::{ + BPF_ABS, BPF_JEQ, BPF_JMP, BPF_K, BPF_LD, BPF_RET, BPF_W, SECCOMP_RET_ALLOW, + SECCOMP_RET_TRAP, SECCOMP_SET_MODE_FILTER, seccomp_data, sock_filter, sock_fprog, + }, +}; +use syscalls::Sysno; +use tokio::io::AsyncReadExt as _; +use tokio_util::sync::CancellationToken; +use vt_materialized_artifact::{Artifact, artifact}; + +use crate::{ + ChildTermination, Command, TrackedChild, TrackingIncomplete, error::SpawnError, + ipc::ChannelAccesses, +}; + +const PRELOAD_LINUX: Artifact = artifact!("fspy_preload", "CARGO_BIN_FILE_FSPY_PRELOAD_LINUX"); + +#[derive(Debug)] +pub struct SpyImpl { + /// Materialized executable path to `fspy_preload_linux`, or `None` when + /// seccomp is unavailable or materialization failed (in which case `spawn` + /// falls back to untracked execution). Wrapped in `RwLock` so a file reaped + /// from the temp directory (e.g. by `systemd-tmpfiles`) can be lazily + /// re-materialized on `ENOENT`. + preload_path: RwLock>>, + seccomp_available: bool, +} + +impl SpyImpl { + /// Materializes `fspy_preload_linux` into the user's temp directory and + /// probes whether this environment permits installing a seccomp filter. + #[expect( + clippy::unnecessary_wraps, + reason = "matches cross-platform SpyImpl::init() -> io::Result signature" + )] + pub fn init() -> io::Result { + let seccomp_available = probe_seccomp_available(); + let preload_path = if seccomp_available { + let materialized = materialize_preload(); + if materialized.is_none() { + tracing::warn!( + "failed to materialize the Linux task tracker binary, so Linux task \ + tracking is off and caching is disabled" + ); + } + materialized + } else { + None + }; + Ok(Self { preload_path: RwLock::new(preload_path), seccomp_available }) + } + + fn preload_path(&self) -> Option> { + if !self.seccomp_available { + return None; + } + self.preload_path + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .as_deref() + .map(clone_ipc_str) + } + + fn rematerialize_preload(&self, failed_path: &IpcStr) -> Option> { + let mut guard = + self.preload_path.write().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(current) = guard.as_deref() + && (current.as_bytes() != failed_path.as_bytes() + || Path::new(current.as_os_str()).exists()) + { + return Some(clone_ipc_str(current)); + } + let new_path = materialize_preload(); + *guard = new_path.as_deref().map(clone_ipc_str); + new_path + } + + pub(crate) async fn spawn( + &self, + mut command: Command, + cancellation_token: CancellationToken, + ) -> Result { + let Some(mut preload_path) = self.preload_path() else { + return spawn_untracked(command, cancellation_token); + }; + // If the cached launcher binary was removed mid-process (e.g. by + // `systemd-tmpfiles`), re-materialize before building `tokio_command` + // so both `Bootstrap` and `redirect_program` pick up any new fallback + // directory path. + if !Path::new(preload_path.as_os_str()).exists() { + match self.rematerialize_preload(&preload_path) { + Some(new_path) => preload_path = new_path, + None => return spawn_untracked(command, cancellation_token), + } + } + + let ipc_receiver = channel(crate::ipc::shm_capacity(), allocator_api2::alloc::Global) + .map_err(SpawnError::ChannelCreation)?; + + let (read_end, write_end) = create_error_pipe().map_err(SpawnError::OsSpawn)?; + let pipe_reader = tokio::net::unix::pipe::Receiver::from_owned_fd(read_end) + .map_err(SpawnError::OsSpawn)?; + let write_raw_fd = write_end.as_raw_fd(); + + let target_path: &IpcStr = command.target_program().into(); + let bootstrap = Bootstrap { + ipc_channel_conf: ipc_receiver.conf(), + preload_path: &preload_path, + target: Target::Unresolved { path: target_path, error_pipe_fd: write_raw_fd }, + }; + let bump = bumpalo::Bump::new(); + let encoded = encode_bootstrap(&bootstrap, &bump); + + command.redirect_program(preload_path.as_os_str()); + command.env("FSPY", "1"); + command.env(BOOTSTRAP_ENV_NAME, encoded); + + let mut tokio_command = command.into_tokio_command(); + // SAFETY: `fcntl(F_SETFD, 0)` is async-signal-safe, and `write_raw_fd` + // remains open in the parent until `spawn()` finishes. + unsafe { + tokio_command.pre_exec(move || { + if libc::fcntl(write_raw_fd, libc::F_SETFD, 0) == -1 { + return Err(io::Error::last_os_error()); + } + Ok(()) + }); + } + + let mut child = match tokio_command.spawn() { + Ok(child) => child, + Err(err) + if err.kind() == io::ErrorKind::NotFound + && !Path::new(preload_path.as_os_str()).exists() => + { + match self.rematerialize_preload(&preload_path) { + Some(new_path) if new_path.as_bytes() == preload_path.as_bytes() => { + tokio_command.spawn().map_err(SpawnError::OsSpawn)? + } + _ => { + return Err(SpawnError::OsSpawn(io::Error::other(format!( + "fspy launcher vanished during spawn and could not be rematerialized at {}: {err}", + preload_path.as_os_str().to_string_lossy() + )))); + } + } + } + Err(err) => return Err(SpawnError::OsSpawn(err)), + }; + // Close the parent's copy of the write end immediately so EOF fires if + // `fspy_preload_linux` terminates before writing a status code. + drop(write_end); + + await_startup_handshake(pipe_reader, &mut child, &cancellation_token).await?; + + Ok(TrackedChild { + stdin: child.stdin.take(), + stdout: child.stdout.take(), + stderr: child.stderr.take(), + wait_handle: tokio::spawn(async move { + let status = tokio::select! { + status = child.wait() => status?, + () = cancellation_token.cancelled() => { + child.start_kill()?; + child.wait().await? + } + }; + + let path_accesses = ChannelAccesses::try_from(ipc_receiver) + .map(|ipc_accesses| PathAccessIterable { ipc_accesses }); + io::Result::Ok(ChildTermination { status, path_accesses }) + }) + .map(|f| f?) + .boxed(), + }) + } +} + +async fn await_startup_handshake( + mut pipe_reader: tokio::net::unix::pipe::Receiver, + child: &mut tokio::process::Child, + cancellation_token: &CancellationToken, +) -> Result<(), SpawnError> { + let mut buf = [0u8; 4]; + let mut filled = 0usize; + while filled < buf.len() { + tokio::select! { + read_res = pipe_reader.read(&mut buf[filled..]) => match read_res { + Ok(0) => break, + Ok(n) => filled += n, + Err(err) if err.kind() == io::ErrorKind::Interrupted => {} + Err(err) => { + drop(pipe_reader); + let _ = child.start_kill(); + let _ = child.wait().await; + return Err(SpawnError::OsSpawn(err)); + } + }, + () = cancellation_token.cancelled() => { + drop(pipe_reader); + let _ = child.start_kill(); + let _ = child.wait().await; + return Err(SpawnError::OsSpawn(io::Error::new( + io::ErrorKind::Interrupted, + "spawn cancelled", + ))); + } + } + } + drop(pipe_reader); + + if filled < buf.len() { + let _ = child.wait().await; + return Err(SpawnError::OsSpawn(io::Error::new( + io::ErrorKind::UnexpectedEof, + "launcher exited before reporting exec status", + ))); + } + let code = i32::from_ne_bytes(buf); + if code != 0 { + let _ = child.wait().await; + return Err(SpawnError::OsSpawn(io::Error::from_raw_os_error(code))); + } + Ok(()) +} + +fn spawn_untracked( + command: Command, + cancellation_token: CancellationToken, +) -> Result { + let mut tokio_command = command.into_tokio_command(); + let mut child = tokio_command.spawn().map_err(SpawnError::OsSpawn)?; + Ok(TrackedChild { + stdin: child.stdin.take(), + stdout: child.stdout.take(), + stderr: child.stderr.take(), + wait_handle: tokio::spawn(async move { + let status = tokio::select! { + status = child.wait() => status?, + () = cancellation_token.cancelled() => { + child.start_kill()?; + child.wait().await? + } + }; + io::Result::Ok(ChildTermination { status, path_accesses: Err(TrackingIncomplete) }) + }) + .map(|f| f?) + .boxed(), + }) +} + +fn clone_ipc_str(s: &IpcStr) -> Box { + Path::new(s.as_os_str()).into() +} + +fn materialize_preload() -> Option> { + let path = PRELOAD_LINUX.materialize().executable().at_user_temp_dir("vp_run").ok()?; + // Every tracked exec re-enters the launcher by this path, so a relative + // `TMPDIR` must not be resolved against a tracked process's own cwd. + std::path::absolute(&path).ok().map(|path| path.as_path().into()) +} + +/// Probes once on a dedicated short-lived OS thread whether +/// `PR_SET_NO_NEW_PRIVS` and `seccomp(SECCOMP_SET_MODE_FILTER)` with +/// `SECCOMP_RET_TRAP` are permitted in the current environment. +/// +/// Both `PR_SET_NO_NEW_PRIVS` and `SECCOMP_SET_MODE_FILTER` (without +/// `SECCOMP_FILTER_FLAG_TSYNC`) are per-thread in Linux, so running the probe +/// on a dedicated thread avoids `fork()` in multi-threaded processes while +/// leaving every other thread completely unaffected. +fn probe_seccomp_available() -> bool { + const SENTINEL_SYSNO: u32 = 0x7fff_ffff; + + let Ok(handle) = std::thread::Builder::new().name("fspy-seccomp-probe".into()).spawn(|| { + #[expect( + clippy::cast_possible_truncation, + reason = "cBPF opcodes and seccomp_data offsets fit in u16/u32" + )] + let filter = [ + sock_filter { + code: (BPF_LD | BPF_W | BPF_ABS) as u16, + jt: 0, + jf: 0, + k: offset_of!(seccomp_data, nr) as u32, + }, + sock_filter { + code: (BPF_JMP | BPF_JEQ | BPF_K) as u16, + jt: 0, + jf: 1, + k: SENTINEL_SYSNO, + }, + sock_filter { code: (BPF_RET | BPF_K) as u16, jt: 0, jf: 0, k: SECCOMP_RET_TRAP }, + sock_filter { code: (BPF_RET | BPF_K) as u16, jt: 0, jf: 0, k: SECCOMP_RET_ALLOW }, + ]; + let prog = sock_fprog { len: 4, filter: filter.as_ptr().cast_mut() }; + // SAFETY: installs a per-thread seccomp filter on this short-lived + // probe thread using a valid stack-local cBPF program. + unsafe { + syscalls::syscall!(Sysno::prctl, PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0).is_ok() + && syscalls::syscall!(Sysno::seccomp, SECCOMP_SET_MODE_FILTER, 0, &raw const prog) + .is_ok() + } + }) else { + return false; + }; + handle.join().unwrap_or(false) +} + +/// Creates a `CLOEXEC` pipe whose read end is non-blocking (for tokio's async +/// pipe receiver) and whose write end stays blocking and at FD `>= 3` (so child +/// stdio `dup2` onto FD 0/1/2 never collides with `error_pipe_fd`). +fn create_error_pipe() -> io::Result<(OwnedFd, OwnedFd)> { + let mut fds = [-1; 2]; + // SAFETY: `fds` is a valid 2-element array for `pipe2`. + if unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) } == -1 { + return Err(io::Error::last_os_error()); + } + // SAFETY: `pipe2` returned two newly opened descriptors. + let read_end = unsafe { OwnedFd::from_raw_fd(fds[0]) }; + // SAFETY: `pipe2` returned two newly opened descriptors. + let write_end = unsafe { OwnedFd::from_raw_fd(fds[1]) }; + + let write_end = if write_end.as_raw_fd() < 3 { + // SAFETY: `write_end` is a valid open descriptor; duplicating to `>= 3` + // prevents child stdio `dup2` from clobbering `error_pipe_fd`. + let dup = unsafe { libc::fcntl(write_end.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 3) }; + if dup == -1 { + return Err(io::Error::last_os_error()); + } + // SAFETY: `F_DUPFD_CLOEXEC` returned a newly opened descriptor. + unsafe { OwnedFd::from_raw_fd(dup) } + } else { + write_end + }; + + // SAFETY: `read_end` is a valid open descriptor. + let flags = unsafe { libc::fcntl(read_end.as_raw_fd(), libc::F_GETFL) }; + if flags == -1 { + return Err(io::Error::last_os_error()); + } + // SAFETY: setting `O_NONBLOCK` on our owned pipe read end. + if unsafe { libc::fcntl(read_end.as_raw_fd(), libc::F_SETFL, flags | libc::O_NONBLOCK) } == -1 { + return Err(io::Error::last_os_error()); + } + Ok((read_end, write_end)) +} + +pub struct PathAccessIterable { + ipc_accesses: ChannelAccesses, +} + +impl PathAccessIterable { + /// Iterates over the path accesses in the order they were made. + /// + /// Accesses made at the same time by different threads or processes + /// appear in an unspecified order relative to each other. + pub fn iter(&self) -> impl Iterator> { + self.ipc_accesses.iter_path_accesses() + } +} + +#[cfg(test)] +mod tests { + use elf::{ElfBytes, abi, endian::LittleEndian, file::Class}; + + const PRELOAD_LINUX_BYTES: &[u8] = include_bytes!(env!("CARGO_BIN_FILE_FSPY_PRELOAD_LINUX")); + + #[test] + fn preload_linux_image_uses_high_fixed_addresses_without_runtime_relocations() { + let image = ElfBytes::::minimal_parse(PRELOAD_LINUX_BYTES).unwrap(); + assert_eq!(image.ehdr.class, Class::ELF64); + assert_eq!(image.ehdr.e_type, abi::ET_EXEC); + let (base, limit) = match image.ehdr.e_machine { + abi::EM_X86_64 => fspy_elf_loader::LAUNCHER_REGION_X86_64, + abi::EM_AARCH64 => fspy_elf_loader::LAUNCHER_REGION_AARCH64, + machine => panic!("unsupported preload machine: {machine}"), + }; + let segments: Vec<_> = image.segments().unwrap().iter().collect(); + assert!( + !segments + .iter() + .any(|ph| matches!(ph.p_type, abi::PT_INTERP | abi::PT_DYNAMIC | abi::PT_TLS)) + ); + let first_load = segments.iter().find(|ph| ph.p_type == abi::PT_LOAD).unwrap(); + assert_eq!((first_load.p_vaddr, first_load.p_offset), (base, 0)); + for segment in segments.iter().filter(|ph| ph.p_type == abi::PT_LOAD) { + assert!(segment.p_vaddr >= base); + assert!(segment.p_vaddr.checked_add(segment.p_memsz).unwrap() <= limit); + } + assert!(segments.iter().any(|ph| { + ph.p_type == abi::PT_LOAD + && ph.p_flags & abi::PF_X != 0 + && ph.p_vaddr <= image.ehdr.e_entry + && image.ehdr.e_entry < ph.p_vaddr + ph.p_memsz + })); + assert!(image.dynamic().unwrap().is_none()); + } +} diff --git a/crates/fspy/src/unix/macos_artifacts.rs b/crates/fspy/src/macos/macos_artifacts.rs similarity index 87% rename from crates/fspy/src/unix/macos_artifacts.rs rename to crates/fspy/src/macos/macos_artifacts.rs index c348f0649..5976ff355 100644 --- a/crates/fspy/src/unix/macos_artifacts.rs +++ b/crates/fspy/src/macos/macos_artifacts.rs @@ -7,7 +7,7 @@ pub const OILS_BINARY: Artifact = artifact!("oils_for_unix", "FSPY_MACOS_ARTIFAC mod tests { use std::{process::Command, str::from_utf8}; - use fspy_shared_unix::spawn::COREUTILS_FUNCTIONS_FOR_TEST; + use fspy_shared_unix::macos::COREUTILS_FUNCTIONS; use super::*; @@ -25,7 +25,7 @@ mod tests { }) .collect(); let mut actual_functions: Vec<&str> = - COREUTILS_FUNCTIONS_FOR_TEST.iter().copied().map(|f| from_utf8(f).unwrap()).collect(); + COREUTILS_FUNCTIONS.iter().copied().map(|f| from_utf8(f).unwrap()).collect(); expected_functions.sort_unstable(); actual_functions.sort_unstable(); diff --git a/crates/fspy/src/macos/mod.rs b/crates/fspy/src/macos/mod.rs new file mode 100644 index 000000000..4fa6d1434 --- /dev/null +++ b/crates/fspy/src/macos/mod.rs @@ -0,0 +1,128 @@ +mod macos_artifacts; + +use std::io; + +use fspy_shared::ipc::{IpcPath, IpcStr, PathAccess, channel::channel}; +use fspy_shared_unix::macos::{EncodedPayload, Payload}; +use futures_util::FutureExt as _; +use tokio_util::sync::CancellationToken; +use vt_materialized_artifact::{Artifact, artifact}; + +use crate::{ + ChildTermination, Command, TrackedChild, arena::PathAccessArena, error::SpawnError, + ipc::ChannelAccesses, +}; + +#[derive(Debug)] +#[expect(clippy::struct_field_names, reason = "each field names a distinct injected path")] +pub struct SpyImpl { + bash_path: Box, + coreutils_path: Box, + preload_path: Box, +} + +impl SpyImpl { + /// Materializes `fspy_preload_macos`, `oils_for_unix`, and `coreutils` into + /// the current user's `vp_run` folder in the system temp dir. + pub fn init() -> io::Result { + const PRELOAD_CDYLIB: Artifact = + artifact!("fspy_preload", "CARGO_CDYLIB_FILE_FSPY_PRELOAD_MACOS"); + + let preload_cdylib_path = + PRELOAD_CDYLIB.materialize().suffix(".dylib").at_user_temp_dir("vp_run")?; + + Ok(Self { + preload_path: preload_cdylib_path.as_path().into(), + bash_path: macos_artifacts::OILS_BINARY + .materialize() + .executable() + .at_user_temp_dir("vp_run")? + .as_path() + .into(), + coreutils_path: macos_artifacts::COREUTILS_BINARY + .materialize() + .executable() + .at_user_temp_dir("vp_run")? + .as_path() + .into(), + }) + } + + pub(crate) fn spawn( + &self, + command: Command, + cancellation_token: CancellationToken, + ) -> std::future::Ready> { + std::future::ready(self.spawn_inner(command, cancellation_token)) + } + + fn spawn_inner( + &self, + mut command: Command, + cancellation_token: CancellationToken, + ) -> Result { + let ipc_receiver = channel(crate::ipc::shm_capacity(), allocator_api2::alloc::Global) + .map_err(SpawnError::ChannelCreation)?; + + let payload = Payload { + ipc_channel_conf: ipc_receiver.conf(), + preload_path: &self.preload_path, + bash_path: &self.bash_path, + coreutils_path: &self.coreutils_path, + }; + + let payload_bump = bumpalo::Bump::new(); + let encoded_payload = EncodedPayload::encode(payload, &payload_bump); + + let mut exec = command.get_exec(); + let mut exec_resolve_accesses = PathAccessArena::default(); + encoded_payload + .prepare_exec(&mut exec, |path| { + exec_resolve_accesses.add(PathAccess::Read(IpcPath::from_bytes(path.as_ref()))); + }) + .map_err(|err| SpawnError::OsSpawn(io::Error::from_raw_os_error(err.raw_os_error())))?; + command.set_exec(exec); + command.env("FSPY", "1"); + + let mut tokio_command = command.into_tokio_command(); + let mut child = tokio_command.spawn().map_err(SpawnError::OsSpawn)?; + + Ok(TrackedChild { + stdin: child.stdin.take(), + stdout: child.stdout.take(), + stderr: child.stderr.take(), + wait_handle: tokio::spawn(async move { + let status = tokio::select! { + status = child.wait() => status?, + () = cancellation_token.cancelled() => { + child.start_kill()?; + child.wait().await? + } + }; + + let path_accesses = ChannelAccesses::try_from(ipc_receiver) + .map(|ipc_accesses| PathAccessIterable { exec_resolve_accesses, ipc_accesses }); + io::Result::Ok(ChildTermination { status, path_accesses }) + }) + .map(|f| f?) + .boxed(), + }) + } +} + +pub struct PathAccessIterable { + exec_resolve_accesses: PathAccessArena, + ipc_accesses: ChannelAccesses, +} + +impl PathAccessIterable { + /// Iterates over the path accesses in the order they were made. + /// + /// Accesses made at the same time by different threads or processes + /// appear in an unspecified order relative to each other. + pub fn iter(&self) -> impl Iterator> { + let accesses_in_arena = self.exec_resolve_accesses.borrow_accesses().iter().copied(); + let accesses_in_shm = self.ipc_accesses.iter_path_accesses(); + accesses_in_arena.chain(accesses_in_shm) + } +} diff --git a/crates/fspy/src/unix/mod.rs b/crates/fspy/src/unix/mod.rs deleted file mode 100644 index e0e850037..000000000 --- a/crates/fspy/src/unix/mod.rs +++ /dev/null @@ -1,210 +0,0 @@ -#[cfg(target_os = "linux")] -mod syscall_handler; - -#[cfg(target_os = "macos")] -mod macos_artifacts; - -use std::io; -#[cfg(target_os = "linux")] -use std::sync::Arc; - -#[cfg(target_os = "linux")] -use fspy_seccomp_unotify::supervisor::supervise; -#[cfg(not(target_env = "musl"))] -use fspy_shared::ipc::IpcStr; -use fspy_shared::ipc::{PathAccess, channel::channel}; -use fspy_shared_unix::{ - exec::ExecResolveConfig, - payload::{Payload, encode_payload}, - spawn::handle_exec, -}; -use futures_util::FutureExt; -#[cfg(target_os = "linux")] -use syscall_handler::SyscallHandler; -use tokio::task::spawn_blocking; -use tokio_util::sync::CancellationToken; - -use crate::{ - ChildTermination, Command, TrackedChild, arena::PathAccessArena, error::SpawnError, - ipc::ChannelAccesses, -}; - -#[derive(Debug)] -#[cfg_attr( - target_os = "macos", - expect(clippy::struct_field_names, reason = "each field names a distinct injected path") -)] -pub struct SpyImpl { - #[cfg(target_os = "macos")] - bash_path: Box, - #[cfg(target_os = "macos")] - coreutils_path: Box, - - #[cfg(not(target_env = "musl"))] - preload_path: Box, -} - -impl SpyImpl { - /// Initialize the fs access spy by writing the preload library on disk, in - /// the current user's own `vp_run` folder in the system temp dir. - /// - /// On musl targets, we don't build a preload library — - /// only seccomp-based tracking is used. - pub fn init() -> io::Result { - #[cfg(not(target_env = "musl"))] - let preload_path = { - use vt_materialized_artifact::{Artifact, artifact}; - - const PRELOAD_CDYLIB: Artifact = - artifact!("fspy_preload", "CARGO_CDYLIB_FILE_FSPY_PRELOAD_UNIX"); - - let preload_cdylib_path = - PRELOAD_CDYLIB.materialize().suffix(".dylib").at_user_temp_dir("vp_run")?; - preload_cdylib_path.as_path().into() - }; - - Ok(Self { - #[cfg(not(target_env = "musl"))] - preload_path, - #[cfg(target_os = "macos")] - bash_path: macos_artifacts::OILS_BINARY - .materialize() - .executable() - .at_user_temp_dir("vp_run")? - .as_path() - .into(), - #[cfg(target_os = "macos")] - coreutils_path: macos_artifacts::COREUTILS_BINARY - .materialize() - .executable() - .at_user_temp_dir("vp_run")? - .as_path() - .into(), - }) - } - - pub(crate) async fn spawn( - &self, - mut command: Command, - cancellation_token: CancellationToken, - ) -> Result { - let ipc_receiver = channel(crate::ipc::shm_capacity(), allocator_api2::alloc::Global) - .map_err(SpawnError::ChannelCreation)?; - - // The supervisor records the accesses it intercepts into the same - // channel as the preload library. - #[cfg(target_os = "linux")] - let supervisor = { - let ipc_sender = Arc::new(ipc_receiver.sender().map_err(SpawnError::ChannelCreation)?); - supervise(move || SyscallHandler::new(Arc::clone(&ipc_sender))) - .map_err(SpawnError::Supervisor)? - }; - - let payload = Payload { - #[cfg(not(target_env = "musl"))] - ipc_channel_conf: ipc_receiver.conf(), - #[cfg(target_env = "musl")] - ipc_channel_conf: core::marker::PhantomData, - - #[cfg(not(target_env = "musl"))] - preload_path: &self.preload_path, - - #[cfg(target_os = "macos")] - artifacts: fspy_shared_unix::payload::Artifacts { - bash_path: &self.bash_path, - coreutils_path: &self.coreutils_path, - }, - - #[cfg(target_os = "linux")] - seccomp_payload: supervisor.payload().clone(), - }; - - // Spawn-scoped storage for the encoded payload, freed when this - // spawn returns. - let payload_bump = bumpalo::Bump::new(); - let encoded_payload = encode_payload(payload, &payload_bump); - - let mut exec = command.get_exec(); - let mut exec_resolve_accesses = PathAccessArena::default(); - let pre_exec = handle_exec( - &mut exec, - ExecResolveConfig::search_path_enabled(None), - &encoded_payload, - |path| { - exec_resolve_accesses.add(PathAccess::Read(path.into())); - }, - ) - .map_err(|err| SpawnError::Injection(err.into()))?; - command.set_exec(exec); - command.env("FSPY", "1"); - - let mut tokio_command = command.into_tokio_command(); - - // SAFETY: the pre_exec closure only calls pre_exec.run() which is safe to call in a fork context - unsafe { - tokio_command.pre_exec(move || { - if let Some(pre_exec) = pre_exec.as_ref() { - pre_exec.run()?; - } - Ok(()) - }); - } - - // tokio_command.spawn blocks while executing the `pre_exec` closure. - // Run it inside spawn_blocking to avoid blocking the tokio runtime, especially the supervisor loop, - // which needs to accept incoming connections while `pre_exec` is connecting to it. - let mut child = spawn_blocking(move || tokio_command.spawn()) - .await - .map_err(|err| SpawnError::OsSpawn(err.into()))? - .map_err(SpawnError::OsSpawn)?; - - Ok(TrackedChild { - stdin: child.stdin.take(), - stdout: child.stdout.take(), - stderr: child.stderr.take(), - // Keep polling for the child to exit in the background even if `wait_handle` is not awaited, - // because we need to stop the supervisor and close the channel as soon as the child exits. - wait_handle: tokio::spawn(async move { - let status = tokio::select! { - status = child.wait() => status?, - () = cancellation_token.cancelled() => { - child.start_kill()?; - child.wait().await? - } - }; - - // Stop the supervisor before closing the channel, so the - // accesses it intercepted are all recorded in the channel. - #[cfg(target_os = "linux")] - supervisor.stop().await?; - - // Close the ipc channel after the child has exited. - // We are not interested in path accesses from descendants after the main child has exited. - let path_accesses = ChannelAccesses::try_from(ipc_receiver) - .map(|ipc_accesses| PathAccessIterable { exec_resolve_accesses, ipc_accesses }); - - io::Result::Ok(ChildTermination { status, path_accesses }) - }) - .map(|f| f?) // flatten JoinError and io::Result - .boxed(), - }) - } -} - -pub struct PathAccessIterable { - exec_resolve_accesses: PathAccessArena, - ipc_accesses: ChannelAccesses, -} - -impl PathAccessIterable { - /// Iterates over the path accesses in the order they were made. - /// - /// Accesses made at the same time by different threads or processes - /// appear in an unspecified order relative to each other. - pub fn iter(&self) -> impl Iterator> { - // Resolving the program happens before the child is spawned. - let accesses_in_arena = self.exec_resolve_accesses.borrow_accesses().iter().copied(); - let accesses_in_shm = self.ipc_accesses.iter_path_accesses(); - accesses_in_arena.chain(accesses_in_shm) - } -} diff --git a/crates/fspy/src/unix/syscall_handler/execve.rs b/crates/fspy/src/unix/syscall_handler/execve.rs deleted file mode 100644 index d34ac8c2d..000000000 --- a/crates/fspy/src/unix/syscall_handler/execve.rs +++ /dev/null @@ -1,24 +0,0 @@ -use std::io; - -use fspy_seccomp_unotify::supervisor::handler::arg::{CStrPtr, Caller, Fd}; - -use super::SyscallHandler; - -impl SyscallHandler { - fn handle_execve(&mut self, caller: Caller, fd: Fd, path_ptr: CStrPtr) -> io::Result<()> { - // TODO: parse shebangs to track reading interpreters - self.handle_open(caller, fd, path_ptr, libc::O_RDONLY) - } - - pub(super) fn execveat( - &mut self, - caller: Caller, - (fd, path_ptr): (Fd, CStrPtr), - ) -> io::Result<()> { - self.handle_execve(caller, fd, path_ptr) - } - - pub(super) fn execve(&mut self, caller: Caller, (path_ptr,): (CStrPtr,)) -> io::Result<()> { - self.handle_execve(caller, Fd::cwd(), path_ptr) - } -} diff --git a/crates/fspy/src/unix/syscall_handler/getdents.rs b/crates/fspy/src/unix/syscall_handler/getdents.rs deleted file mode 100644 index 45eec5320..000000000 --- a/crates/fspy/src/unix/syscall_handler/getdents.rs +++ /dev/null @@ -1,16 +0,0 @@ -use std::io; - -use fspy_seccomp_unotify::supervisor::handler::arg::{Caller, Fd}; - -use super::SyscallHandler; - -impl SyscallHandler { - #[cfg(target_arch = "x86_64")] - pub(super) fn getdents(&mut self, caller: Caller, (fd,): (Fd,)) -> io::Result<()> { - self.handle_open_dir(caller, fd) - } - - pub(super) fn getdents64(&mut self, caller: Caller, (fd,): (Fd,)) -> io::Result<()> { - self.handle_open_dir(caller, fd) - } -} diff --git a/crates/fspy/src/unix/syscall_handler/mod.rs b/crates/fspy/src/unix/syscall_handler/mod.rs deleted file mode 100644 index d55ce8fbb..000000000 --- a/crates/fspy/src/unix/syscall_handler/mod.rs +++ /dev/null @@ -1,120 +0,0 @@ -mod execve; -mod getdents; -mod namespace; -mod open; -mod stat; - -use std::{ - borrow::Cow, - ffi::{OsStr, c_int}, - io, - os::unix::ffi::OsStrExt, - path::{Path, PathBuf}, - sync::Arc, -}; - -use fspy_seccomp_unotify::{ - impl_handler, - supervisor::handler::arg::{CStrPtr, Caller, Fd}, -}; -use fspy_shared::ipc::{AccessMode, PathAccess, channel::Sender}; - -const PATH_MAX: usize = libc::PATH_MAX as usize; - -/// Records the accesses of intercepted syscalls into the IPC channel. -/// -/// The supervisor lets a syscall continue only after its handler returns, so -/// every record is published before the access it describes, as the channel -/// requires of its senders. -pub struct SyscallHandler { - ipc_sender: Arc, - path_read_buf: [u8; PATH_MAX], -} - -impl SyscallHandler { - pub const fn new(ipc_sender: Arc) -> Self { - Self { ipc_sender, path_read_buf: [0; PATH_MAX] } - } - - fn handle_open( - &mut self, - caller: Caller, - dir_fd: Fd, - path_ptr: CStrPtr, - flags: c_int, - ) -> io::Result<()> { - let mode = match flags & libc::O_ACCMODE { - libc::O_RDWR => AccessMode::ReadWrite, - libc::O_WRONLY => AccessMode::Write, - _ => AccessMode::Read, - }; - self.handle_path(caller, dir_fd, path_ptr, mode) - } - - fn handle_path( - &mut self, - caller: Caller, - dir_fd: Fd, - path_ptr: CStrPtr, - mode: AccessMode, - ) -> io::Result<()> { - let Some(path_len) = path_ptr.read(caller, &mut self.path_read_buf)? else { - // Ignore paths that are too long to fit in PATH_MAX - return Ok(()); - }; - let mut path = Cow::Borrowed(Path::new(OsStr::from_bytes(&self.path_read_buf[..path_len]))); - if !path.is_absolute() { - let mut resolved_path = PathBuf::from(dir_fd.get_path(caller)?); - if !nix::NixPath::is_empty(path.as_ref()) { - resolved_path.push(&path); - } - path = Cow::Owned(resolved_path); - } - self.ipc_sender.send(&mode.with_path(path.as_os_str().into())); - Ok(()) - } - - #[expect( - clippy::needless_pass_by_ref_mut, - reason = "same receiver as `handle_open`, which writes `path_read_buf`" - )] - fn handle_open_dir(&mut self, caller: Caller, fd: Fd) -> io::Result<()> { - let path = fd.get_path(caller)?; - self.ipc_sender.send(&PathAccess::ReadDir(OsStr::from_bytes(path.as_bytes()).into())); - Ok(()) - } -} - -impl_handler!( - SyscallHandler: - - #[cfg(target_arch = "x86_64")] open, - openat, - openat2, - - #[cfg(target_arch = "x86_64")] getdents, - getdents64, - - #[cfg(target_arch = "x86_64")] stat, - #[cfg(target_arch = "x86_64")] lstat, - #[cfg(target_arch = "x86_64")] newfstatat, - #[cfg(target_arch = "aarch64")] fstatat, - statx, - - #[cfg(target_arch = "x86_64")] access, - faccessat, - faccessat2, - - #[cfg(target_arch = "x86_64")] mkdir, - mkdirat, - #[cfg(target_arch = "x86_64")] rename, - renameat, - renameat2, - #[cfg(target_arch = "x86_64")] link, - linkat, - #[cfg(target_arch = "x86_64")] symlink, - symlinkat, - - execve, - execveat, -); diff --git a/crates/fspy/src/unix/syscall_handler/namespace.rs b/crates/fspy/src/unix/syscall_handler/namespace.rs deleted file mode 100644 index 2eccd1f4b..000000000 --- a/crates/fspy/src/unix/syscall_handler/namespace.rs +++ /dev/null @@ -1,91 +0,0 @@ -//! Syscalls that make an entry at a path without opening it: mkdir, symlink, -//! and rename and hard link, which put an existing file or folder at a new -//! path. The path of a mkdir is recorded as a mkdir, whether or not the -//! folder is there already; the new path of a rename as a rename target, -//! which may be a whole folder; and that of a symlink, and of a hard link, -//! always a file, as a write. The source of a rename needs no record, and -//! neither does the target of a symlink, which is stored as text, not -//! accessed. - -use std::io; - -use fspy_seccomp_unotify::supervisor::handler::arg::{CStrPtr, Caller, Fd, Ignored}; -use fspy_shared::ipc::AccessMode; - -use super::SyscallHandler; - -impl SyscallHandler { - #[cfg(target_arch = "x86_64")] - pub(super) fn mkdir(&mut self, caller: Caller, (path,): (CStrPtr,)) -> io::Result<()> { - self.handle_path(caller, Fd::cwd(), path, AccessMode::Mkdir) - } - - pub(super) fn mkdirat( - &mut self, - caller: Caller, - (dir_fd, path): (Fd, CStrPtr), - ) -> io::Result<()> { - self.handle_path(caller, dir_fd, path, AccessMode::Mkdir) - } - - #[cfg(target_arch = "x86_64")] - pub(super) fn rename( - &mut self, - caller: Caller, - (_old, new): (Ignored, CStrPtr), - ) -> io::Result<()> { - self.handle_path(caller, Fd::cwd(), new, AccessMode::RenameTarget) - } - - pub(super) fn renameat( - &mut self, - caller: Caller, - (_old_dir_fd, _old, new_dir_fd, new): (Ignored, Ignored, Fd, CStrPtr), - ) -> io::Result<()> { - self.handle_path(caller, new_dir_fd, new, AccessMode::RenameTarget) - } - - /// With `RENAME_EXCHANGE` both paths change; only the destination is - /// recorded, as for a plain rename. - pub(super) fn renameat2( - &mut self, - caller: Caller, - (_old_dir_fd, _old, new_dir_fd, new): (Ignored, Ignored, Fd, CStrPtr), - ) -> io::Result<()> { - self.handle_path(caller, new_dir_fd, new, AccessMode::RenameTarget) - } - - #[cfg(target_arch = "x86_64")] - pub(super) fn link( - &mut self, - caller: Caller, - (_old, new): (Ignored, CStrPtr), - ) -> io::Result<()> { - self.handle_path(caller, Fd::cwd(), new, AccessMode::Write) - } - - pub(super) fn linkat( - &mut self, - caller: Caller, - (_old_dir_fd, _old, new_dir_fd, new): (Ignored, Ignored, Fd, CStrPtr), - ) -> io::Result<()> { - self.handle_path(caller, new_dir_fd, new, AccessMode::Write) - } - - #[cfg(target_arch = "x86_64")] - pub(super) fn symlink( - &mut self, - caller: Caller, - (_target, link): (Ignored, CStrPtr), - ) -> io::Result<()> { - self.handle_path(caller, Fd::cwd(), link, AccessMode::Write) - } - - pub(super) fn symlinkat( - &mut self, - caller: Caller, - (_target, new_dir_fd, link): (Ignored, Fd, CStrPtr), - ) -> io::Result<()> { - self.handle_path(caller, new_dir_fd, link, AccessMode::Write) - } -} diff --git a/crates/fspy/src/unix/syscall_handler/open.rs b/crates/fspy/src/unix/syscall_handler/open.rs deleted file mode 100644 index be7ae157e..000000000 --- a/crates/fspy/src/unix/syscall_handler/open.rs +++ /dev/null @@ -1,35 +0,0 @@ -use std::{ffi::c_int, io}; - -use fspy_seccomp_unotify::supervisor::handler::arg::{CStrPtr, Caller, Fd, Ptr}; - -use super::SyscallHandler; - -impl SyscallHandler { - #[cfg(target_arch = "x86_64")] - pub(super) fn open( - &mut self, - caller: Caller, - (path, flags): (CStrPtr, c_int), - ) -> io::Result<()> { - self.handle_open(caller, Fd::cwd(), path, flags) - } - - pub(super) fn openat( - &mut self, - caller: Caller, - (dir_fd, path, flags): (Fd, CStrPtr, c_int), - ) -> io::Result<()> { - self.handle_open(caller, dir_fd, path, flags) - } - - pub(super) fn openat2( - &mut self, - caller: Caller, - // open_how is a pointer to struct `open_how`, but we only care about flags here, so use `Ptr` - (dir_fd, path, open_how): (Fd, CStrPtr, Ptr), - ) -> io::Result<()> { - // SAFETY: open_how is a valid pointer to struct `open_how` in the target process, which has `flags` as the first field of type `u64` - let flags = unsafe { open_how.read(caller) }?; - self.handle_open(caller, dir_fd, path, c_int::try_from(flags).unwrap_or(libc::O_RDWR)) - } -} diff --git a/crates/fspy/src/unix/syscall_handler/stat.rs b/crates/fspy/src/unix/syscall_handler/stat.rs deleted file mode 100644 index 40d9f76f1..000000000 --- a/crates/fspy/src/unix/syscall_handler/stat.rs +++ /dev/null @@ -1,68 +0,0 @@ -use std::io; - -use fspy_seccomp_unotify::supervisor::handler::arg::{CStrPtr, Caller, Fd}; - -use super::SyscallHandler; - -impl SyscallHandler { - #[cfg(target_arch = "x86_64")] - pub(super) fn stat(&mut self, caller: Caller, (path,): (CStrPtr,)) -> io::Result<()> { - self.handle_open(caller, Fd::cwd(), path, libc::O_RDONLY) - } - - #[cfg(target_arch = "x86_64")] - pub(super) fn lstat(&mut self, caller: Caller, (path,): (CStrPtr,)) -> io::Result<()> { - self.handle_open(caller, Fd::cwd(), path, libc::O_RDONLY) - } - - #[cfg(target_arch = "aarch64")] - pub(super) fn fstatat( - &mut self, - caller: Caller, - (dir_fd, path_ptr): (Fd, CStrPtr), - ) -> io::Result<()> { - self.handle_open(caller, dir_fd, path_ptr, libc::O_RDONLY) - } - - #[cfg(target_arch = "x86_64")] - pub(super) fn newfstatat( - &mut self, - caller: Caller, - (dir_fd, path_ptr): (Fd, CStrPtr), - ) -> io::Result<()> { - self.handle_open(caller, dir_fd, path_ptr, libc::O_RDONLY) - } - - /// statx(2) — modern replacement for stat/fstatat used by newer glibc. - pub(super) fn statx( - &mut self, - caller: Caller, - (dir_fd, path_ptr): (Fd, CStrPtr), - ) -> io::Result<()> { - self.handle_open(caller, dir_fd, path_ptr, libc::O_RDONLY) - } - - /// access(2) — check file accessibility (e.g. existsSync in Node.js). - #[cfg(target_arch = "x86_64")] - pub(super) fn access(&mut self, caller: Caller, (path,): (CStrPtr,)) -> io::Result<()> { - self.handle_open(caller, Fd::cwd(), path, libc::O_RDONLY) - } - - /// faccessat(2) — check file accessibility relative to directory fd. - pub(super) fn faccessat( - &mut self, - caller: Caller, - (dir_fd, path_ptr): (Fd, CStrPtr), - ) -> io::Result<()> { - self.handle_open(caller, dir_fd, path_ptr, libc::O_RDONLY) - } - - /// faccessat2(2) — extended faccessat with flags parameter. - pub(super) fn faccessat2( - &mut self, - caller: Caller, - (dir_fd, path_ptr): (Fd, CStrPtr), - ) -> io::Result<()> { - self.handle_open(caller, dir_fd, path_ptr, libc::O_RDONLY) - } -} diff --git a/crates/fspy/tests/exec_empty_path.rs b/crates/fspy/tests/exec_empty_path.rs index d8ad11d3d..529181cab 100644 --- a/crates/fspy/tests/exec_empty_path.rs +++ b/crates/fspy/tests/exec_empty_path.rs @@ -94,10 +94,6 @@ async fn exec_empty_path_fails_like_untraced() -> anyhow::Result<()> { assert_eq!(exec_empty_path(), untraced); }) .await?; - // Seccomp tracking, used on musl, reports the directory an empty path - // is relative to. - if cfg!(not(target_env = "musl")) { - assert_not_contains(&accesses, ¤t_dir()?); - } + assert_not_contains(&accesses, ¤t_dir()?); Ok(()) } diff --git a/crates/fspy/tests/invalid_dirfd.rs b/crates/fspy/tests/invalid_dirfd.rs index 6dfc802a5..f3b275302 100644 --- a/crates/fspy/tests/invalid_dirfd.rs +++ b/crates/fspy/tests/invalid_dirfd.rs @@ -30,7 +30,7 @@ const STATX_BASIC_STATS: libc::c_uint = 0x7ff; #[repr(C, align(8))] struct StatxBuf([u8; 256]); -/// Calls `statx` through `syscall`, which fspy intercepts on glibc. +/// Calls `statx` directly through `syscall(2)`. /// /// The libc `statx` wrapper is not called directly: glibc added it in 2.28, /// so a test built for an older glibc fails to link. @@ -55,8 +55,7 @@ fn syscall_statx( } } -/// Calls the glibc `statx` wrapper, resolved at run time. With `LD_PRELOAD`, -/// the lookup finds the fspy interposer first. +/// Calls the glibc `statx` wrapper, resolved at run time. /// /// # Panics /// @@ -191,3 +190,65 @@ async fn absolute_path_at_invalid_dirfd() -> anyhow::Result<()> { Ok(()) } + +/// An unopened positive descriptor passes `BorrowedFd::try_borrow_raw` and +/// exercises `fd_path` returning `Ok(None)` (`EBADF` / `ENOENT`) on both Linux +/// and macOS. +#[test(tokio::test)] +async fn relative_path_at_unopened_positive_dirfd() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let tmp_path = std::fs::canonicalize(tmp_dir.path())?.join("abs_via_unopened"); + std::fs::write(&tmp_path, "")?; + + let accesses = track_fn!(tmp_path.to_str().unwrap().to_owned(), |tmp_path: String| { + let unopened_fd: libc::c_int = 9999; + // Confirm `9999` is not open in this process. + // SAFETY: `F_GETFD` on a closed descriptor simply fails with `EBADF`. + assert_eq!(unsafe { libc::fcntl(unopened_fd, libc::F_GETFD) }, -1); + assert_eq!(errno(), libc::EBADF); + + let path = c"hello_unopened"; + // SAFETY: valid C strings and output buffers; kernel rejects the unopened fd. + unsafe { + assert_eq!(libc::openat(unopened_fd, path.as_ptr(), libc::O_RDONLY), -1); + assert_eq!(errno(), libc::EBADF); + + let mut stat = std::mem::MaybeUninit::::uninit(); + assert_eq!(libc::fstatat(unopened_fd, path.as_ptr(), stat.as_mut_ptr(), 0), -1); + assert_eq!(errno(), libc::EBADF); + + assert_eq!(libc::faccessat(unopened_fd, path.as_ptr(), libc::F_OK, 0), -1); + assert_eq!(errno(), libc::EBADF); + + assert!(libc::fdopendir(unopened_fd).is_null()); + assert_eq!(errno(), libc::EBADF); + } + #[cfg(target_os = "linux")] + { + assert_eq!(syscall_statx(unopened_fd, path.as_ptr(), 0), -1); + assert_eq!(errno(), libc::EBADF); + } + #[cfg(all(target_os = "linux", target_env = "gnu"))] + { + assert_eq!(glibc_statx(unopened_fd, path.as_ptr(), 0), -1); + assert_eq!(errno(), libc::EBADF); + + assert_eq!(glibc_execveat(unopened_fd, path), -1); + assert_eq!(errno(), libc::EBADF); + } + + // An absolute path ignores the unopened positive dirfd and succeeds. + let abs = std::ffi::CString::new(tmp_path).unwrap(); + // SAFETY: `abs` is a valid C string; absolute paths ignore `dirfd`. + let fd = unsafe { libc::openat(unopened_fd, abs.as_ptr(), libc::O_RDONLY) }; + assert!(fd >= 0, "openat with absolute path failed with errno {}", errno()); + // SAFETY: `fd` was opened above. + unsafe { libc::close(fd) }; + }) + .await?; + + assert_not_contains(&accesses, &std::env::current_dir()?.join("hello_unopened")); + assert_contains(&accesses, &tmp_path, PathAccess::Read); + + Ok(()) +} diff --git a/crates/fspy/tests/linux_hardening.rs b/crates/fspy/tests/linux_hardening.rs new file mode 100644 index 000000000..cd55d65e2 --- /dev/null +++ b/crates/fspy/tests/linux_hardening.rs @@ -0,0 +1,840 @@ +//! Linux hardening tests covering `vfork`/`posix_spawn` memory reclamation, +//! `memfd_create` + `execveat(AT_EMPTY_PATH)`, `execve("/proc/self/fd/N")`, +//! and deep `execve` chain FD/env/filter hygiene. +#![cfg(target_os = "linux")] + +mod test_utils; + +use std::path::Path; + +use test_log::test; + +use crate::test_utils::{assert_contains, test_bin_path}; + +#[test(tokio::test)] +async fn posix_spawn_parent_rss_stays_bounded() -> anyhow::Result<()> { + let cmd = vt_subprocess_test::command_for_fn!((), |()| { + use std::ffi::CString; + + fn vm_rss_kib() -> usize { + let status = std::fs::read_to_string("/proc/self/status").unwrap(); + for line in status.lines() { + if let Some(rest) = line.strip_prefix("VmRSS:") { + return rest.split_whitespace().next().unwrap().parse::().unwrap(); + } + } + panic!("VmRSS not found in /proc/self/status"); + } + + let prog = CString::new("/bin/true").unwrap(); + let arg0 = CString::new("true").unwrap(); + let argv = [arg0.as_ptr().cast_mut(), std::ptr::null_mut()]; + + let mut env_cstrs = Vec::new(); + for (k, v) in std::env::vars() { + env_cstrs.push(CString::new(format!("{k}={v}")).unwrap()); + } + let mut envp: Vec<*mut libc::c_char> = + env_cstrs.iter().map(|s| s.as_ptr().cast_mut()).collect(); + envp.push(std::ptr::null_mut()); + + let mut baseline_rss = 0usize; + for i in 0..200 { + let mut pid: libc::pid_t = 0; + // SAFETY: `prog`, `argv`, and `envp` are valid NUL-terminated arrays. + let rc = unsafe { + libc::posix_spawn( + &raw mut pid, + prog.as_ptr(), + std::ptr::null(), + std::ptr::null(), + argv.as_ptr(), + envp.as_ptr(), + ) + }; + assert_eq!(rc, 0, "posix_spawn iteration {i} failed with errno {rc}"); + let mut status: libc::c_int = 0; + // SAFETY: `pid` is our child and `status` is valid writable storage. + let waited = unsafe { libc::waitpid(pid, &raw mut status, 0) }; + assert_eq!(waited, pid); + assert!(libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0); + if i == 10 { + baseline_rss = vm_rss_kib(); + } + } + + let final_rss = vm_rss_kib(); + let growth = final_rss.saturating_sub(baseline_rss); + assert!( + growth < 4096, + "parent VmRSS grew by {growth} KiB across 190 posix_spawns \ + (baseline={baseline_rss} KiB, final={final_rss} KiB)" + ); + }); + + let _accesses = test_utils::spawn_command(cmd).await?; + Ok(()) +} + +#[test(tokio::test)] +async fn memfd_execveat_empty_path_tracks_child_accesses() -> anyhow::Result<()> { + let probe_path = Path::new("/fspy-memfd-execveat-probe"); + let cmd = vt_subprocess_test::command_for_fn!( + (test_bin_path().to_str().unwrap().to_owned(), probe_path.to_str().unwrap().to_owned()), + |(static_bin, probe_path): (String, String)| { + use std::ffi::CString; + + let bin_bytes = std::fs::read(&static_bin).unwrap(); + let name = CString::new("fspy-memfd-test").unwrap(); + // SAFETY: `memfd_create` takes a valid NUL-terminated name and flags. + let fd = libc::c_int::try_from(unsafe { + libc::syscall(libc::SYS_memfd_create, name.as_ptr(), libc::MFD_CLOEXEC) + }) + .unwrap(); + assert!(fd >= 0, "memfd_create failed: {}", std::io::Error::last_os_error()); + + let mut written = 0usize; + while written < bin_bytes.len() { + // SAFETY: `fd` is our open memfd and slice is valid. + let n = unsafe { + libc::write(fd, bin_bytes[written..].as_ptr().cast(), bin_bytes.len() - written) + }; + assert!(n > 0, "write memfd failed: {}", std::io::Error::last_os_error()); + written += usize::try_from(n).unwrap(); + } + + let empty = CString::new("").unwrap(); + let arg0 = CString::new("memfd-bin").unwrap(); + let arg1 = CString::new("open_read").unwrap(); + let arg2 = CString::new(probe_path).unwrap(); + let argv = [arg0.as_ptr(), arg1.as_ptr(), arg2.as_ptr(), std::ptr::null()]; + let envp = [std::ptr::null::()]; + + // SAFETY: `fork()` followed by async-signal-safe `execveat` + `_exit`. + let pid = unsafe { libc::fork() }; + assert!(pid >= 0, "fork failed"); + if pid == 0 { + // SAFETY: `fd` is open and arguments are valid NUL-terminated arrays. + unsafe { + libc::syscall( + libc::SYS_execveat, + fd, + empty.as_ptr(), + argv.as_ptr(), + envp.as_ptr(), + libc::AT_EMPTY_PATH, + ); + libc::_exit(127); + } + } + + let mut status: libc::c_int = 0; + // SAFETY: `pid` is our child and `status` is writable. + let waited = unsafe { libc::waitpid(pid, &raw mut status, 0) }; + assert_eq!(waited, pid); + assert!( + libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, + "memfd execveat child failed with status {status}" + ); + // SAFETY: closing our owned memfd. + unsafe { libc::close(fd) }; + } + ); + + let accesses = test_utils::spawn_command(cmd).await?; + assert_contains(&accesses, probe_path, fspy::PathAccess::Read); + Ok(()) +} + +#[test(tokio::test)] +async fn execve_proc_self_fd_of_cloexec_descriptor_runs_and_tracks() -> anyhow::Result<()> { + // `execve("/proc/self/fd/N")` on an `O_CLOEXEC` descriptor (glibc's + // `fexecve` fallback, memfd launchers): the kernel opens the image before + // closing CLOEXEC descriptors, so the launcher must hand the image over by + // descriptor rather than reopen the path after exec. + let probe_path = Path::new("/fspy-proc-self-fd-exec-probe"); + let cmd = vt_subprocess_test::command_for_fn!( + (test_bin_path().to_str().unwrap().to_owned(), probe_path.to_str().unwrap().to_owned()), + |(static_bin, probe_path): (String, String)| { + use std::{ffi::CString, os::fd::AsRawFd as _}; + + // Rust opens files with `O_CLOEXEC`. + let file = std::fs::File::open(&static_bin).unwrap(); + let path = CString::new(format!("/proc/self/fd/{}", file.as_raw_fd())).unwrap(); + let arg0 = CString::new("fd-bin").unwrap(); + let arg1 = CString::new("open_read").unwrap(); + let arg2 = CString::new(probe_path).unwrap(); + let argv = [arg0.as_ptr(), arg1.as_ptr(), arg2.as_ptr(), std::ptr::null()]; + let envp = [std::ptr::null::()]; + + // SAFETY: `fork()` followed by async-signal-safe `execve` + `_exit`. + let pid = unsafe { libc::fork() }; + assert!(pid >= 0, "fork failed"); + if pid == 0 { + // SAFETY: `path`, `argv`, and `envp` are valid NUL-terminated arrays. + unsafe { + libc::execve(path.as_ptr(), argv.as_ptr(), envp.as_ptr()); + libc::_exit(127); + } + } + + let mut status: libc::c_int = 0; + // SAFETY: `pid` is our child and `status` is writable. + let waited = unsafe { libc::waitpid(pid, &raw mut status, 0) }; + assert_eq!(waited, pid); + assert!( + libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, + "/proc/self/fd execve child failed with status {status}" + ); + } + ); + + let accesses = test_utils::spawn_command(cmd).await?; + assert_contains(&accesses, probe_path, fspy::PathAccess::Read); + Ok(()) +} + +#[test(tokio::test)] +async fn deep_exec_chain_preserves_fd_env_and_seccomp_filter_hygiene() -> anyhow::Result<()> { + // Capture any ambient non-CLOEXEC FDs inherited by the test runner itself + // (e.g. CI runner or jobserver descriptors) so we strictly assert zero + // leaked FDs introduced by `fspy` across the exec chain. + let mut inherited_fds: Vec = std::fs::read_dir("/proc/self/fd") + .unwrap() + .filter_map(|e| e.ok()?.file_name().to_str()?.parse::().ok()) + .collect(); + inherited_fds.retain(|&fd| { + if fd <= 2 { + return false; + } + // SAFETY: `F_GETFD` only queries flags and returns `-1` for the + // already-closed `read_dir("/proc/self/fd")` descriptor. + let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) }; + flags >= 0 && (flags & libc::FD_CLOEXEC) == 0 + }); + inherited_fds.sort_unstable(); + + let cmd = vt_subprocess_test::command_for_fn!(inherited_fds, |inherited_fds: Vec| { + use std::{ffi::CString, os::unix::ffi::OsStrExt as _}; + + fn seccomp_filters() -> usize { + let status = std::fs::read_to_string("/proc/self/status").unwrap(); + for line in status.lines() { + if let Some(rest) = line.strip_prefix("Seccomp_filters:") { + return rest.trim().parse::().unwrap(); + } + } + panic!("Seccomp_filters not found"); + } + + // Verify `__FSPY_BOOTSTRAP` was stripped before entering the target. + assert!( + std::env::var_os("__FSPY_BOOTSTRAP").is_none(), + "__FSPY_BOOTSTRAP leaked into child environment" + ); + + let depth: usize = + std::env::var("FSPY_TEST_EXEC_DEPTH").ok().and_then(|s| s.parse().ok()).unwrap_or(0); + + let cur_filters = seccomp_filters(); + assert!(cur_filters >= 1, "expected at least one seccomp filter"); + + if let Ok(expected) = std::env::var("FSPY_TEST_EXPECTED_FILTERS") { + let expected: usize = expected.parse().unwrap(); + assert_eq!( + cur_filters, expected, + "Seccomp_filters grew across exec chain ({expected} -> {cur_filters})" + ); + } + + // Verify no FDs leaked from the launcher handoff or across execs + // (ignoring stdin/stdout/stderr, the already-closed `/proc/self/fd` + // directory handle, and ambient non-CLOEXEC FDs inherited from the + // parent test runner). + let open_fds: Vec = std::fs::read_dir("/proc/self/fd") + .unwrap() + .filter_map(|e| e.ok()?.file_name().to_str()?.parse::().ok()) + .collect(); + let leaked_fds: Vec = open_fds + .into_iter() + .filter(|&fd| fd > 2 && !inherited_fds.contains(&fd)) + .filter(|&fd| { + // SAFETY: `F_GETFD` only queries descriptor flags and returns + // `-1` for the now-closed `read_dir("/proc/self/fd")` handle. + unsafe { libc::fcntl(fd, libc::F_GETFD) >= 0 } + }) + .collect(); + assert!( + leaked_fds.is_empty(), + "unexpected leaked open FDs at depth {depth} (inherited={inherited_fds:?}): {leaked_fds:?}" + ); + + if depth >= 5 { + return; + } + + let exe = std::fs::read_link("/proc/self/exe").unwrap(); + let prog = CString::new(exe.as_os_str().as_bytes()).unwrap(); + // `vt_subprocess_test` runs inside `.init_array`, where `std::env::args_os()` + // is empty on musl; fall back to `/proc/self/cmdline` just like `vt_subprocess_test`. + let mut args: Vec = + std::env::args_os().map(|a| CString::new(a.as_bytes()).unwrap()).collect(); + if args.is_empty() { + let cmdline = std::fs::read("/proc/self/cmdline").unwrap(); + let mut parts: Vec<&[u8]> = cmdline.split(|&b| b == 0).collect(); + if parts.last().is_some_and(|s| s.is_empty()) { + parts.pop(); + } + args = parts.into_iter().map(|p| CString::new(p).unwrap()).collect(); + } + let mut argv: Vec<*const libc::c_char> = args.iter().map(|s| s.as_ptr()).collect(); + argv.push(std::ptr::null()); + + let mut env_cstrs: Vec = std::env::vars_os() + .filter(|(k, _)| k != "FSPY_TEST_EXEC_DEPTH" && k != "FSPY_TEST_EXPECTED_FILTERS") + .map(|(k, v)| { + let mut bytes = k.as_bytes().to_vec(); + bytes.push(b'='); + bytes.extend_from_slice(v.as_bytes()); + CString::new(bytes).unwrap() + }) + .collect(); + env_cstrs.push(CString::new(format!("FSPY_TEST_EXEC_DEPTH={}", depth + 1)).unwrap()); + env_cstrs.push(CString::new(format!("FSPY_TEST_EXPECTED_FILTERS={cur_filters}")).unwrap()); + let mut envp: Vec<*const libc::c_char> = env_cstrs.iter().map(|s| s.as_ptr()).collect(); + envp.push(std::ptr::null()); + + // SAFETY: `prog`, `argv`, and `envp` are valid NUL-terminated arrays. + unsafe { libc::execve(prog.as_ptr(), argv.as_ptr(), envp.as_ptr()) }; + panic!("execve failed at depth {depth}: {}", std::io::Error::last_os_error()); + }); + + let _accesses = test_utils::spawn_command(cmd).await?; + Ok(()) +} + +#[test(tokio::test)] +async fn e2big_on_execve_and_posix_spawn_cleans_up_scratch_without_leaking() -> anyhow::Result<()> { + let cmd = vt_subprocess_test::command_for_fn!((), |()| { + use std::ffi::CString; + + fn count_open_fds() -> usize { + std::fs::read_dir("/proc/self/fd") + .unwrap() + .filter_map(|e| e.ok()?.file_name().to_str()?.parse::().ok()) + .filter(|&fd| { + // SAFETY: `F_GETFD` only queries flags and returns `-1` for + // the already-closed `read_dir` descriptor. + unsafe { libc::fcntl(fd, libc::F_GETFD) >= 0 } + }) + .count() + } + + let prog = CString::new("/bin/true").unwrap(); + let arg0 = CString::new("true").unwrap(); + let argv = [arg0.as_ptr(), std::ptr::null()]; + + // Exceeds Linux `MAX_ARG_STRLEN` (32 * PAGE_SIZE) on both 4 KiB and + // 64 KiB page kernels so `SYS_execve` fails cleanly with `E2BIG`. + let mut big = Vec::with_capacity(4 + 3 * 1024 * 1024 + 1); + big.extend_from_slice(b"BIG="); + big.resize(4 + 3 * 1024 * 1024, b'x'); + let big_cstr = CString::new(big).unwrap(); + let huge_envp = [big_cstr.as_ptr(), std::ptr::null()]; + + let fds_before = count_open_fds(); + + // 1. Direct `execve` returns `-1` / `E2BIG` and runs `cleanup_exec_scratch`. + // SAFETY: `prog`, `argv`, and `huge_envp` are valid NUL/NULL-terminated arrays. + let rc = unsafe { libc::execve(prog.as_ptr(), argv.as_ptr(), huge_envp.as_ptr()) }; + assert_eq!(rc, -1, "oversized execve unexpectedly succeeded"); + assert_eq!( + std::io::Error::last_os_error().raw_os_error(), + Some(libc::E2BIG), + "expected E2BIG from oversized execve" + ); + assert_eq!(count_open_fds(), fds_before, "execve E2BIG leaked an open FD"); + + // 2. `posix_spawn` (`CLONE_VM | CLONE_VFORK`) returns `E2BIG` cleanly + // and releases its parked `ExecScratch` and duped FD without crashing. + let mut pid: libc::pid_t = 0; + let argv_mut = [arg0.as_ptr().cast_mut(), std::ptr::null_mut()]; + let huge_envp_mut = [big_cstr.as_ptr().cast_mut(), std::ptr::null_mut()]; + // SAFETY: `prog`, `argv_mut`, and `huge_envp_mut` are valid arrays. + let spawn_rc = unsafe { + libc::posix_spawn( + &raw mut pid, + prog.as_ptr(), + std::ptr::null(), + std::ptr::null(), + argv_mut.as_ptr(), + huge_envp_mut.as_ptr(), + ) + }; + assert_eq!(spawn_rc, libc::E2BIG, "expected E2BIG from oversized posix_spawn"); + assert_eq!(count_open_fds(), fds_before, "posix_spawn E2BIG leaked an open FD"); + + // 3. Process remains healthy: a normal `posix_spawn` still succeeds. + let empty_envp = [std::ptr::null_mut::()]; + let mut ok_pid: libc::pid_t = 0; + // SAFETY: `prog`, `argv_mut`, and `empty_envp` are valid arrays. + let ok_rc = unsafe { + libc::posix_spawn( + &raw mut ok_pid, + prog.as_ptr(), + std::ptr::null(), + std::ptr::null(), + argv_mut.as_ptr(), + empty_envp.as_ptr(), + ) + }; + assert_eq!(ok_rc, 0, "follow-up posix_spawn failed with errno {ok_rc}"); + let mut status: libc::c_int = 0; + // SAFETY: `ok_pid` is our child and `status` is writable. + assert_eq!(unsafe { libc::waitpid(ok_pid, &raw mut status, 0) }, ok_pid); + assert!(libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0); + }); + + let _accesses = test_utils::spawn_command(cmd).await?; + Ok(()) +} + +#[test(tokio::test)] +async fn inherited_sigsys_ign_and_blocked_mask_survive_execve() -> anyhow::Result<()> { + let probe_path = Path::new("/fspy-inherited-sigsys-probe"); + let cmd = vt_subprocess_test::command_for_fn!( + probe_path.to_str().unwrap().to_owned(), + |probe_path: String| { + use std::{ffi::CString, os::unix::ffi::OsStrExt as _}; + + if std::env::var_os("FSPY_TEST_SIGSYS_STAGE").is_some() { + // Verify `SIGSYS` is still virtually `SIG_IGN`. + // SAFETY: `libc::sigaction` is a plain C struct valid when zeroed. + let mut old: libc::sigaction = unsafe { std::mem::zeroed() }; + // SAFETY: querying current disposition for `SIGSYS`. + let rc = unsafe { libc::sigaction(libc::SIGSYS, std::ptr::null(), &raw mut old) }; + assert_eq!(rc, 0); + assert_eq!( + old.sa_sigaction, + libc::SIG_IGN, + "inherited SIGSYS SIG_IGN was not preserved across execve" + ); + + // Verify both `SIGSYS` and `SIGUSR1` remain blocked in the signal mask. + // SAFETY: `sigset_t` is a plain C struct valid when zeroed. + let mut cur_mask: libc::sigset_t = unsafe { std::mem::zeroed() }; + // SAFETY: querying current thread signal mask. + let mask_rc = unsafe { + libc::sigprocmask(libc::SIG_SETMASK, std::ptr::null(), &raw mut cur_mask) + }; + assert_eq!(mask_rc, 0); + // SAFETY: `cur_mask` was initialized by `sigprocmask`. + let sigsys_blocked = + unsafe { libc::sigismember(&raw const cur_mask, libc::SIGSYS) }; + assert_eq!(sigsys_blocked, 1, "inherited blocked SIGSYS was lost across execve"); + // SAFETY: `cur_mask` was initialized by `sigprocmask`. + let sigusr1_blocked = + unsafe { libc::sigismember(&raw const cur_mask, libc::SIGUSR1) }; + assert_eq!(sigusr1_blocked, 1, "inherited blocked SIGUSR1 was lost across execve"); + + // Verify syscall tracking still works with virtualized SIGSYS ignored+blocked. + let _ = std::fs::File::open(&probe_path); + return; + } + + // Stage 0: set `SIGSYS` to `SIG_IGN` and block `SIGSYS` + `SIGUSR1`. + // SAFETY: `libc::sigaction` is a plain C struct valid when zeroed. + let mut ign: libc::sigaction = unsafe { std::mem::zeroed() }; + ign.sa_sigaction = libc::SIG_IGN; + // SAFETY: installing `SIG_IGN` for `SIGSYS`. + let ign_rc = + unsafe { libc::sigaction(libc::SIGSYS, &raw const ign, std::ptr::null_mut()) }; + assert_eq!(ign_rc, 0); + + // SAFETY: `sigset_t` is initialized via `sigemptyset`/`sigaddset`. + let mut block_set: libc::sigset_t = unsafe { std::mem::zeroed() }; + // SAFETY: valid stack-local `sigset_t`. + unsafe { + libc::sigemptyset(&raw mut block_set); + libc::sigaddset(&raw mut block_set, libc::SIGSYS); + libc::sigaddset(&raw mut block_set, libc::SIGUSR1); + assert_eq!( + libc::sigprocmask(libc::SIG_BLOCK, &raw const block_set, std::ptr::null_mut()), + 0 + ); + } + + let exe = std::fs::read_link("/proc/self/exe").unwrap(); + let prog = CString::new(exe.as_os_str().as_bytes()).unwrap(); + let mut args: Vec = + std::env::args_os().map(|a| CString::new(a.as_bytes()).unwrap()).collect(); + if args.is_empty() { + let cmdline = std::fs::read("/proc/self/cmdline").unwrap(); + let mut parts: Vec<&[u8]> = cmdline.split(|&b| b == 0).collect(); + if parts.last().is_some_and(|s| s.is_empty()) { + parts.pop(); + } + args = parts.into_iter().map(|p| CString::new(p).unwrap()).collect(); + } + let mut argv: Vec<*const libc::c_char> = args.iter().map(|s| s.as_ptr()).collect(); + argv.push(std::ptr::null()); + + let mut env_cstrs: Vec = std::env::vars_os() + .map(|(k, v)| { + let mut bytes = k.as_bytes().to_vec(); + bytes.push(b'='); + bytes.extend_from_slice(v.as_bytes()); + CString::new(bytes).unwrap() + }) + .collect(); + env_cstrs.push(CString::new("FSPY_TEST_SIGSYS_STAGE=1").unwrap()); + let mut envp: Vec<*const libc::c_char> = env_cstrs.iter().map(|s| s.as_ptr()).collect(); + envp.push(std::ptr::null()); + + // SAFETY: `prog`, `argv`, and `envp` are valid NUL/NULL-terminated arrays. + unsafe { libc::execve(prog.as_ptr(), argv.as_ptr(), envp.as_ptr()) }; + panic!("execve failed: {}", std::io::Error::last_os_error()); + } + ); + + let accesses = test_utils::spawn_command(cmd).await?; + assert_contains(&accesses, probe_path, fspy::PathAccess::Read); + Ok(()) +} + +#[test(tokio::test)] +async fn proc_self_environ_does_not_expose_fspy_bootstrap() -> anyhow::Result<()> { + let cmd = vt_subprocess_test::command_for_fn!((), |()| { + fn assert_bootstrap_scrubbed(label: &str) { + assert!( + std::env::var_os("__FSPY_BOOTSTRAP").is_none(), + "{label}: __FSPY_BOOTSTRAP present in process env" + ); + let raw = std::fs::read("/proc/self/environ").unwrap(); + let needle = b"__FSPY_BOOTSTRAP"; + assert!( + !raw.windows(needle.len()).any(|w| w == needle), + "{label}: __FSPY_BOOTSTRAP found in /proc/self/environ" + ); + } + + // Check initial spawn (`Target::Unresolved`). + assert_bootstrap_scrubbed("initial spawn"); + + // Also check a child spawned via `execve` (`Target::ResolvedFd`). + let output = std::process::Command::new("/bin/cat") + .arg("/proc/self/environ") + .output() + .expect("failed to run /bin/cat /proc/self/environ"); + assert!(output.status.success()); + let needle = b"__FSPY_BOOTSTRAP"; + assert!( + !output.stdout.windows(needle.len()).any(|w| w == needle), + "child execve: __FSPY_BOOTSTRAP found in /proc/self/environ" + ); + }); + + let _accesses = test_utils::spawn_command(cmd).await?; + Ok(()) +} + +#[test(tokio::test)] +async fn child_execve_with_stale_bootstrap_env_succeeds() -> anyhow::Result<()> { + let probe_path = Path::new("/fspy-stale-bootstrap-probe"); + let cmd = vt_subprocess_test::command_for_fn!( + (test_bin_path().to_str().unwrap().to_owned(), probe_path.to_str().unwrap().to_owned()), + |(static_bin, probe_path): (String, String)| { + use std::ffi::CString; + + // 1. Exec static test binary with duplicate stale `__FSPY_BOOTSTRAP` + // entries in `envp` — must overwrite/deduplicate cleanly instead + // of failing with `EINVAL`. + let prog = CString::new(static_bin).unwrap(); + let arg0 = CString::new("test_bin").unwrap(); + let arg1 = CString::new("open_read").unwrap(); + let arg2 = CString::new(probe_path).unwrap(); + let argv = [arg0.as_ptr(), arg1.as_ptr(), arg2.as_ptr(), std::ptr::null()]; + let envp = [ + c"__FSPY_BOOTSTRAP=stale".as_ptr(), + c"__FSPY_BOOTSTRAP=stale2".as_ptr(), + c"KEEP=yes".as_ptr(), + std::ptr::null(), + ]; + + // SAFETY: `fork()` followed by async-signal-safe `execve` + `_exit`. + let pid = unsafe { libc::fork() }; + assert!(pid >= 0, "fork failed"); + if pid == 0 { + // SAFETY: `prog`, `argv`, and `envp` are valid arrays. + unsafe { + libc::execve(prog.as_ptr(), argv.as_ptr(), envp.as_ptr()); + libc::_exit(127); + } + } + let mut status: libc::c_int = 0; + // SAFETY: `pid` is our child and `status` is writable. + assert_eq!(unsafe { libc::waitpid(pid, &raw mut status, 0) }, pid); + assert!( + libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, + "child execve with stale __FSPY_BOOTSTRAP failed with status {status}" + ); + + // 2. Exec `/bin/sh` with stale `__FSPY_BOOTSTRAP=stale` and verify + // the child sees `KEEP=yes` and no `__FSPY_BOOTSTRAP`. + let sh_argv = [ + c"/bin/sh".as_ptr(), + c"-c".as_ptr(), + c"test -z \"${__FSPY_BOOTSTRAP+x}\" && test \"$KEEP\" = \"yes\"".as_ptr(), + std::ptr::null(), + ]; + // SAFETY: `fork()` followed by async-signal-safe `execve` + `_exit`. + let pid2 = unsafe { libc::fork() }; + assert!(pid2 >= 0, "fork failed"); + if pid2 == 0 { + // SAFETY: `sh_argv` and `envp` are valid arrays. + unsafe { + libc::execve(c"/bin/sh".as_ptr(), sh_argv.as_ptr(), envp.as_ptr()); + libc::_exit(127); + } + } + let mut status2: libc::c_int = 0; + // SAFETY: `pid2` is our child and `status2` is writable. + assert_eq!(unsafe { libc::waitpid(pid2, &raw mut status2, 0) }, pid2); + assert!( + libc::WIFEXITED(status2) && libc::WEXITSTATUS(status2) == 0, + "sh execve with stale __FSPY_BOOTSTRAP failed with status {status2}" + ); + } + ); + + let accesses = test_utils::spawn_command(cmd).await?; + assert_contains(&accesses, probe_path, fspy::PathAccess::Read); + Ok(()) +} + +#[test(tokio::test)] +async fn posix_spawn_setsigdef_resets_child_sigsys_without_mutating_parent() -> anyhow::Result<()> { + let probe_path = Path::new("/fspy-posix-spawn-sigdef-probe"); + let cmd = vt_subprocess_test::command_for_fn!( + probe_path.to_str().unwrap().to_owned(), + |probe_path: String| { + use std::{ffi::CString, os::unix::ffi::OsStrExt as _}; + + if std::env::var_os("FSPY_TEST_SPAWN_SIGDEF_CHILD").is_some() { + // Child requested `POSIX_SPAWN_SETSIGDEF` with `SIGSYS` + + // `POSIX_SPAWN_SETSIGMASK` with `SIGSYS | SIGUSR1`, so it must + // observe `SIGSYS == SIG_DFL` (not parent's `SIG_IGN`) and both + // signals blocked. + // SAFETY: `libc::sigaction` is a plain C struct valid when zeroed. + let mut old: libc::sigaction = unsafe { std::mem::zeroed() }; + // SAFETY: querying current disposition for `SIGSYS`. + let rc = unsafe { libc::sigaction(libc::SIGSYS, std::ptr::null(), &raw mut old) }; + assert_eq!(rc, 0); + assert_eq!( + old.sa_sigaction, + libc::SIG_DFL, + "posix_spawn POSIX_SPAWN_SETSIGDEF did not reset child SIGSYS to SIG_DFL" + ); + + // SAFETY: `sigset_t` is a plain C struct valid when zeroed. + let mut cur_mask: libc::sigset_t = unsafe { std::mem::zeroed() }; + // SAFETY: querying current thread signal mask. + let mask_rc = unsafe { + libc::sigprocmask(libc::SIG_SETMASK, std::ptr::null(), &raw mut cur_mask) + }; + assert_eq!(mask_rc, 0); + // SAFETY: `cur_mask` was initialized by `sigprocmask`. + let sigsys_blocked = + unsafe { libc::sigismember(&raw const cur_mask, libc::SIGSYS) }; + assert_eq!( + sigsys_blocked, 1, + "posix_spawn POSIX_SPAWN_SETSIGMASK did not block SIGSYS" + ); + // SAFETY: `cur_mask` was initialized by `sigprocmask`. + let sigusr1_blocked = + unsafe { libc::sigismember(&raw const cur_mask, libc::SIGUSR1) }; + assert_eq!( + sigusr1_blocked, 1, + "posix_spawn POSIX_SPAWN_SETSIGMASK did not block SIGUSR1" + ); + + // Syscall tracking must keep working inside the spawned child. + let _ = std::fs::File::open(&probe_path); + return; + } + + // Parent sets `SIGSYS` to `SIG_IGN`. + // SAFETY: `libc::sigaction` is a plain C struct valid when zeroed. + let mut ign: libc::sigaction = unsafe { std::mem::zeroed() }; + ign.sa_sigaction = libc::SIG_IGN; + // SAFETY: installing `SIG_IGN` for `SIGSYS`. + let ign_rc = + unsafe { libc::sigaction(libc::SIGSYS, &raw const ign, std::ptr::null_mut()) }; + assert_eq!(ign_rc, 0); + + let exe = std::fs::read_link("/proc/self/exe").unwrap(); + let prog = CString::new(exe.as_os_str().as_bytes()).unwrap(); + let mut args: Vec = + std::env::args_os().map(|a| CString::new(a.as_bytes()).unwrap()).collect(); + if args.is_empty() { + let cmdline = std::fs::read("/proc/self/cmdline").unwrap(); + let mut parts: Vec<&[u8]> = cmdline.split(|&b| b == 0).collect(); + if parts.last().is_some_and(|s| s.is_empty()) { + parts.pop(); + } + args = parts.into_iter().map(|p| CString::new(p).unwrap()).collect(); + } + let mut argv: Vec<*mut libc::c_char> = + args.iter().map(|s| s.as_ptr().cast_mut()).collect(); + argv.push(std::ptr::null_mut()); + + let mut env_cstrs: Vec = std::env::vars_os() + .map(|(k, v)| { + let mut bytes = k.as_bytes().to_vec(); + bytes.push(b'='); + bytes.extend_from_slice(v.as_bytes()); + CString::new(bytes).unwrap() + }) + .collect(); + env_cstrs.push(CString::new("FSPY_TEST_SPAWN_SIGDEF_CHILD=1").unwrap()); + let mut envp: Vec<*mut libc::c_char> = + env_cstrs.iter().map(|s| s.as_ptr().cast_mut()).collect(); + envp.push(std::ptr::null_mut()); + + // Configure `posix_spawnattr_t` with `POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK`. + // SAFETY: `posix_spawnattr_t` and `sigset_t` are plain C structs valid when zeroed. + let mut attr: libc::posix_spawnattr_t = unsafe { std::mem::zeroed() }; + // SAFETY: `sigset_t` is valid when zeroed. + let mut sigdef_set: libc::sigset_t = unsafe { std::mem::zeroed() }; + // SAFETY: `sigset_t` is valid when zeroed. + let mut sigmask_set: libc::sigset_t = unsafe { std::mem::zeroed() }; + let mut child_pid: libc::pid_t = 0; + let spawn_flags = + libc::c_short::try_from(libc::POSIX_SPAWN_SETSIGDEF | libc::POSIX_SPAWN_SETSIGMASK) + .unwrap(); + // SAFETY: valid stack-local `posix_spawnattr_t`, `sigset_t`, and C arrays. + let spawn_rc = unsafe { + assert_eq!(libc::posix_spawnattr_init(&raw mut attr), 0); + libc::sigemptyset(&raw mut sigdef_set); + libc::sigaddset(&raw mut sigdef_set, libc::SIGSYS); + libc::sigemptyset(&raw mut sigmask_set); + libc::sigaddset(&raw mut sigmask_set, libc::SIGSYS); + libc::sigaddset(&raw mut sigmask_set, libc::SIGUSR1); + assert_eq!(libc::posix_spawnattr_setflags(&raw mut attr, spawn_flags), 0); + assert_eq!( + libc::posix_spawnattr_setsigdefault(&raw mut attr, &raw const sigdef_set), + 0 + ); + assert_eq!( + libc::posix_spawnattr_setsigmask(&raw mut attr, &raw const sigmask_set), + 0 + ); + let rc = libc::posix_spawn( + &raw mut child_pid, + prog.as_ptr(), + std::ptr::null(), + &raw const attr, + argv.as_ptr(), + envp.as_ptr(), + ); + libc::posix_spawnattr_destroy(&raw mut attr); + rc + }; + assert_eq!(spawn_rc, 0, "posix_spawn failed with errno {spawn_rc}"); + + let mut status: libc::c_int = 0; + // SAFETY: `child_pid` is our child and `status` is writable. + let waited = unsafe { libc::waitpid(child_pid, &raw mut status, 0) }; + assert_eq!(waited, child_pid); + assert!( + libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, + "posix_spawn child failed with status {status}" + ); + + // Parent must retain `SIGSYS == SIG_IGN`! + // SAFETY: `libc::sigaction` is a plain C struct valid when zeroed. + let mut parent_old: libc::sigaction = unsafe { std::mem::zeroed() }; + // SAFETY: querying parent's `SIGSYS` disposition. + let parent_rc = + unsafe { libc::sigaction(libc::SIGSYS, std::ptr::null(), &raw mut parent_old) }; + assert_eq!(parent_rc, 0); + assert_eq!( + parent_old.sa_sigaction, + libc::SIG_IGN, + "posix_spawn child clobbered parent's SIGSYS SIG_IGN" + ); + } + ); + + let accesses = test_utils::spawn_command(cmd).await?; + assert_contains(&accesses, probe_path, fspy::PathAccess::Read); + Ok(()) +} + +#[test(tokio::test)] +async fn execve_of_et_exec_overlapping_launcher_region_returns_eexist_cleanly() -> anyhow::Result<()> +{ + #[cfg(target_arch = "x86_64")] + const MACHINE: u16 = elf::abi::EM_X86_64; + #[cfg(target_arch = "aarch64")] + const MACHINE: u16 = elf::abi::EM_AARCH64; + + let survived_probe = Path::new("/fspy-overlap-et-exec-survived-probe"); + let tmp_dir = tempfile::tempdir()?; + let overlap_path = tmp_dir.path().canonicalize()?.join("overlap_et_exec"); + + // Construct a minimal valid native ELF64 `ET_EXEC` whose `PT_LOAD` overlaps + // `fspy_elf_loader::LAUNCHER_REGION`. + // SAFETY: `_SC_PAGESIZE` is a standard `sysconf` query. + let page = usize::try_from(unsafe { libc::sysconf(libc::_SC_PAGESIZE) }).unwrap(); + let vaddr = u64::try_from(fspy_elf_loader::LAUNCHER_REGION.0 + 4 * page).unwrap(); + + let mut bytes = vec![0_u8; 2 * page]; + bytes[0..7].copy_from_slice(b"\x7fELF\x02\x01\x01"); + bytes[16..18].copy_from_slice(&elf::abi::ET_EXEC.to_le_bytes()); + bytes[18..20].copy_from_slice(&MACHINE.to_le_bytes()); + bytes[20..24].copy_from_slice(&1_u32.to_le_bytes()); + bytes[24..32].copy_from_slice(&(vaddr + 0x200).to_le_bytes()); + bytes[32..40].copy_from_slice(&64_u64.to_le_bytes()); // e_phoff + bytes[52..54].copy_from_slice(&64_u16.to_le_bytes()); // e_ehsize + bytes[54..56].copy_from_slice(&56_u16.to_le_bytes()); // e_phentsize + bytes[56..58].copy_from_slice(&1_u16.to_le_bytes()); // e_phnum + + let ph = &mut bytes[64..64 + 56]; + ph[0..4].copy_from_slice(&elf::abi::PT_LOAD.to_le_bytes()); + ph[4..8].copy_from_slice(&(elf::abi::PF_R | elf::abi::PF_X).to_le_bytes()); + ph[8..16].copy_from_slice(&0_u64.to_le_bytes()); // p_offset + ph[16..24].copy_from_slice(&vaddr.to_le_bytes()); // p_vaddr + ph[32..40].copy_from_slice(&u64::try_from(page).unwrap().to_le_bytes()); // p_filesz + ph[40..48].copy_from_slice(&u64::try_from(page).unwrap().to_le_bytes()); // p_memsz + ph[48..56].copy_from_slice(&u64::try_from(page).unwrap().to_le_bytes()); // p_align + + std::fs::write(&overlap_path, &bytes)?; + std::fs::set_permissions(&overlap_path, std::os::unix::fs::PermissionsExt::from_mode(0o755))?; + + let cmd = vt_subprocess_test::command_for_fn!( + (overlap_path.to_str().unwrap().to_owned(), survived_probe.to_str().unwrap().to_owned()), + |(overlap_path, survived_probe): (String, String)| { + use std::ffi::CString; + + let prog = CString::new(overlap_path).unwrap(); + let argv = [prog.as_ptr(), std::ptr::null()]; + let envp = [std::ptr::null::()]; + // SAFETY: valid NUL/NULL-terminated arrays; `execve` must fail with `EEXIST`. + let rc = unsafe { libc::execve(prog.as_ptr(), argv.as_ptr(), envp.as_ptr()) }; + assert_eq!(rc, -1, "overlapping ET_EXEC execve unexpectedly succeeded"); + assert_eq!( + std::io::Error::last_os_error().raw_os_error(), + Some(libc::EEXIST), + "expected EEXIST (not ENOEXEC) for ET_EXEC overlapping LAUNCHER_REGION" + ); + + // Caller survived and syscall tracking remains healthy. + let _ = std::fs::File::open(&survived_probe); + } + ); + + let accesses = test_utils::spawn_command(cmd).await?; + assert_contains(&accesses, survived_probe, fspy::PathAccess::Read); + Ok(()) +} diff --git a/crates/fspy/tests/linux_syscalls.rs b/crates/fspy/tests/linux_syscalls.rs new file mode 100644 index 000000000..862448876 --- /dev/null +++ b/crates/fspy/tests/linux_syscalls.rs @@ -0,0 +1,785 @@ +//! Linux-specific syscall coverage tests for `fspy_preload_linux`: +//! - `execveat` variants (`AT_SYMLINK_NOFOLLOW`, non-CWD `dirfd`, `O_PATH` + +//! `AT_EMPTY_PATH` on both ELF binaries and `#!` scripts, `AT_EMPTY_PATH` on +//! non-`CLOEXEC` and `CLOEXEC` `#!` scripts) +//! - `newfstatat`/`fstatat`, `statx`, and `faccessat2` with valid `fd` + `AT_EMPTY_PATH` +//! - `access`/`faccessat`/`faccessat2` and `mkdirat`/`renameat`/`linkat`/`symlinkat`/`openat2` +//! with non-CWD `dirfd` + relative path +//! - `openat2` invalid `how_ptr` / invalid `size` (`EFAULT` / `EINVAL`) +//! - `openat(O_RDONLY | O_CREAT)` / `openat(O_RDONLY | O_TRUNC)` recording `ReadWrite`, +//! and `renameat2(RENAME_EXCHANGE)` recording both paths +//! - Legacy x86-64 `SYS_open`, `SYS_stat`, and `SYS_lstat` +#![cfg(target_os = "linux")] + +mod test_utils; + +use std::{ + fs::{self, File, Permissions}, + os::unix::fs::{PermissionsExt as _, symlink}, + path::Path, +}; + +use fspy::PathAccess; +use test_log::test; +#[cfg(target_arch = "x86_64")] +use test_utils::assert_includes; +use test_utils::{assert_contains, test_bin_path}; + +/// `STATX_BASIC_STATS`. Not defined in `libc` on every musl target. +const STATX_BASIC_STATS: libc::c_uint = 0x7ff; + +/// `RENAME_EXCHANGE`. Not defined in `libc` on every musl target. +const RENAME_EXCHANGE: libc::c_uint = 2; + +/// Kernel `struct statx` (256 bytes, 8-byte aligned). +#[repr(C, align(8))] +struct StatxBuf([u8; 256]); + +/// Kernel `struct open_how` (24 bytes). +#[repr(C)] +struct OpenHow { + flags: u64, + mode: u64, + resolve: u64, +} + +fn errno() -> libc::c_int { + std::io::Error::last_os_error().raw_os_error().unwrap() +} + +fn write_exec(path: &Path, content: &[u8]) { + fs::write(path, content).unwrap(); + fs::set_permissions(path, Permissions::from_mode(0o755)).unwrap(); +} + +#[test(tokio::test)] +async fn execveat_nofollow_dirfd_o_path_and_empty_path_scripts() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + + // Copy the static test binary into `root` so we can exec it via non-CWD + // `dirfd` + relative path and via `O_PATH` + `AT_EMPTY_PATH`. + let rel_bin = root.join("rel_bin"); + fs::copy(test_bin_path(), &rel_bin)?; + fs::set_permissions(&rel_bin, Permissions::from_mode(0o755))?; + + let bin_symlink = root.join("bin_link"); + symlink(&rel_bin, &bin_symlink)?; + + let probe_rel_bin = Path::new("/fspy-execveat-rel-bin-probe"); + let probe_rel_script = Path::new("/fspy-execveat-rel-script-probe"); + let probe_opath_bin = Path::new("/fspy-execveat-opath-bin-probe"); + let probe_opath_script = Path::new("/fspy-execveat-opath-script-probe"); + let probe_empty_script = Path::new("/fspy-execveat-empty-script-probe"); + + let rel_script = root.join("rel_script.sh"); + write_exec( + &rel_script, + format!("#!/bin/sh\n{} open_read {}\n", rel_bin.display(), probe_rel_script.display()) + .as_bytes(), + ); + + let opath_script = root.join("opath_script.sh"); + write_exec( + &opath_script, + format!("#!/bin/sh\n{} open_read {}\n", rel_bin.display(), probe_opath_script.display()) + .as_bytes(), + ); + + let empty_script = root.join("empty_script.sh"); + write_exec( + &empty_script, + format!("#!/bin/sh\n{} open_read {}\n", rel_bin.display(), probe_empty_script.display()) + .as_bytes(), + ); + + let args = ( + root.to_str().unwrap().to_owned(), + probe_rel_bin.to_str().unwrap().to_owned(), + probe_opath_bin.to_str().unwrap().to_owned(), + ); + + let accesses = + track_fn!(args, |(root_str, probe_rel_bin, probe_opath_bin): (String, String, String)| { + use std::{ffi::CString, os::fd::AsRawFd as _}; + + fn run_execveat_in_child( + dirfd: libc::c_int, + path: &std::ffi::CStr, + argv: &[*const libc::c_char], + flags: libc::c_int, + ) -> libc::c_int { + let envp = [std::ptr::null::()]; + // SAFETY: `fork()` followed by async-signal-safe `execveat` + `_exit`. + let pid = unsafe { libc::fork() }; + assert!(pid >= 0, "fork failed"); + if pid == 0 { + // SAFETY: arguments are valid NUL/NULL-terminated C strings/arrays. + unsafe { + libc::syscall( + libc::SYS_execveat, + dirfd, + path.as_ptr(), + argv.as_ptr(), + envp.as_ptr(), + flags, + ); + libc::_exit(127); + } + } + let mut status: libc::c_int = 0; + // SAFETY: `pid` is our child and `status` is writable. + assert_eq!(unsafe { libc::waitpid(pid, &raw mut status, 0) }, pid); + assert!( + libc::WIFEXITED(status), + "execveat child terminated abnormally: status={status}" + ); + libc::WEXITSTATUS(status) + } + + // Ensure CWD is `/` so relative names MUST resolve against `dirfd`. + std::env::set_current_dir("/").unwrap(); + let dir = File::open(&root_str).unwrap(); + let dirfd = dir.as_raw_fd(); + + // 1. `AT_SYMLINK_NOFOLLOW` on a symlink -> `ELOOP`. + let argv_link = [c"bin_link".as_ptr(), std::ptr::null()]; + let envp_empty = [std::ptr::null::()]; + // SAFETY: valid arguments to `execveat` expected to fail with `ELOOP`. + let rc = unsafe { + libc::syscall( + libc::SYS_execveat, + dirfd, + c"bin_link".as_ptr(), + argv_link.as_ptr(), + envp_empty.as_ptr(), + libc::AT_SYMLINK_NOFOLLOW, + ) + }; + assert_eq!(rc, -1, "execveat AT_SYMLINK_NOFOLLOW on symlink should fail"); + assert_eq!(errno(), libc::ELOOP); + + // 2. Non-CWD `dirfd` + relative ELF executable. + let probe_rel_c = CString::new(probe_rel_bin).unwrap(); + let argv_rel_bin = [ + c"rel_bin".as_ptr(), + c"open_read".as_ptr(), + probe_rel_c.as_ptr(), + std::ptr::null(), + ]; + assert_eq!(run_execveat_in_child(dirfd, c"rel_bin", &argv_rel_bin, 0), 0); + + // 3. Non-CWD `dirfd` + relative `#!` script. + let argv_rel_script = [c"rel_script.sh".as_ptr(), std::ptr::null()]; + assert_eq!(run_execveat_in_child(dirfd, c"rel_script.sh", &argv_rel_script, 0), 0); + + // 4. `O_PATH` + `AT_EMPTY_PATH` on an ELF executable. + // SAFETY: valid path relative to `dirfd`. + let opath_bin_fd = + unsafe { libc::openat(dirfd, c"rel_bin".as_ptr(), libc::O_PATH | libc::O_CLOEXEC) }; + assert!(opath_bin_fd >= 0, "openat O_PATH bin failed: {}", errno()); + let probe_opath_c = CString::new(probe_opath_bin).unwrap(); + let argv_opath_bin = [ + c"opath_bin".as_ptr(), + c"open_read".as_ptr(), + probe_opath_c.as_ptr(), + std::ptr::null(), + ]; + assert_eq!( + run_execveat_in_child(opath_bin_fd, c"", &argv_opath_bin, libc::AT_EMPTY_PATH), + 0 + ); + // SAFETY: closing our owned descriptor. + unsafe { libc::close(opath_bin_fd) }; + + // 5. `O_PATH` (without `O_CLOEXEC`) + `AT_EMPTY_PATH` on a `#!` script. + // SAFETY: valid path relative to `dirfd`. + let opath_script_fd = + unsafe { libc::openat(dirfd, c"opath_script.sh".as_ptr(), libc::O_PATH) }; + assert!(opath_script_fd >= 0, "openat O_PATH script failed: {}", errno()); + let argv_opath_script = [c"opath_script".as_ptr(), std::ptr::null()]; + assert_eq!( + run_execveat_in_child( + opath_script_fd, + c"", + &argv_opath_script, + libc::AT_EMPTY_PATH + ), + 0 + ); + // SAFETY: closing our owned descriptor. + unsafe { libc::close(opath_script_fd) }; + + // 6. `AT_EMPTY_PATH` on `#!` script: non-`CLOEXEC` succeeds, `CLOEXEC` fails `ENOENT`. + // SAFETY: valid path relative to `dirfd`. + let non_cloexec_fd = + unsafe { libc::openat(dirfd, c"empty_script.sh".as_ptr(), libc::O_RDONLY) }; + assert!(non_cloexec_fd >= 0, "openat non-cloexec script failed: {}", errno()); + let argv_empty_script = [c"empty_script".as_ptr(), std::ptr::null()]; + assert_eq!( + run_execveat_in_child(non_cloexec_fd, c"", &argv_empty_script, libc::AT_EMPTY_PATH), + 0 + ); + // SAFETY: closing our owned descriptor. + unsafe { libc::close(non_cloexec_fd) }; + + // `File::open` sets `O_CLOEXEC` -> `execveat(AT_EMPTY_PATH)` on `#!` returns `ENOENT`. + let cloexec_script = File::open(format!("{root_str}/empty_script.sh")).unwrap(); + // SAFETY: valid arguments to `execveat` expected to fail with `ENOENT`. + let rc_cloexec = unsafe { + libc::syscall( + libc::SYS_execveat, + cloexec_script.as_raw_fd(), + c"".as_ptr(), + argv_empty_script.as_ptr(), + envp_empty.as_ptr(), + libc::AT_EMPTY_PATH, + ) + }; + assert_eq!(rc_cloexec, -1, "AT_EMPTY_PATH on CLOEXEC script should fail"); + assert_eq!(errno(), libc::ENOENT); + + // 7. `execveat(AT_FDCWD, "", ..., AT_EMPTY_PATH)` refers to the current + // working directory and must return `EACCES` (matching Linux kernel). + // SAFETY: valid arguments to `execveat` expected to fail with `EACCES`. + let rc_cwd_empty = unsafe { + libc::syscall( + libc::SYS_execveat, + libc::AT_FDCWD, + c"".as_ptr(), + argv_empty_script.as_ptr(), + envp_empty.as_ptr(), + libc::AT_EMPTY_PATH, + ) + }; + assert_eq!(rc_cwd_empty, -1, "execveat(AT_FDCWD, \"\", AT_EMPTY_PATH) should fail"); + assert_eq!(errno(), libc::EACCES); + }) + .await?; + + assert_contains(&accesses, &rel_bin, PathAccess::Read); + assert_contains(&accesses, &rel_script, PathAccess::Read); + assert_contains(&accesses, &opath_script, PathAccess::Read); + assert_contains(&accesses, &empty_script, PathAccess::Read); + assert_contains(&accesses, probe_rel_bin, PathAccess::Read); + assert_contains(&accesses, probe_rel_script, PathAccess::Read); + assert_contains(&accesses, probe_opath_bin, PathAccess::Read); + assert_contains(&accesses, probe_opath_script, PathAccess::Read); + assert_contains(&accesses, probe_empty_script, PathAccess::Read); + Ok(()) +} + +#[test(tokio::test)] +async fn empty_path_fstatat_statx_and_faccessat2_record_fd_path() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + let f_fstatat = root.join("empty_fstatat"); + let f_statx = root.join("empty_statx"); + let f_faccessat2 = root.join("empty_faccessat2"); + fs::write(&f_fstatat, b"a")?; + fs::write(&f_statx, b"b")?; + fs::write(&f_faccessat2, b"c")?; + + let args = ( + f_fstatat.to_str().unwrap().to_owned(), + f_statx.to_str().unwrap().to_owned(), + f_faccessat2.to_str().unwrap().to_owned(), + ); + + let accesses = track_fn!(args, |(p1, p2, p3): (String, String, String)| { + use std::os::fd::AsRawFd as _; + + // Open each file via `O_PATH` before invoking the `AT_EMPTY_PATH` + // syscalls (the `openat` itself also records Read, and we additionally + // verify the kernel calls succeed / behave as expected under seccomp). + let file1 = File::open(&p1).unwrap(); + let mut st = std::mem::MaybeUninit::::uninit(); + // SAFETY: `file1` is open and `st` is writable. + let rc_fstatat = unsafe { + libc::fstatat(file1.as_raw_fd(), c"".as_ptr(), st.as_mut_ptr(), libc::AT_EMPTY_PATH) + }; + assert_eq!(rc_fstatat, 0); + + let file2 = File::open(&p2).unwrap(); + let mut stx = StatxBuf([0; 256]); + // SAFETY: `file2` is open and `stx` is writable. + let rc_statx = unsafe { + libc::syscall( + libc::SYS_statx, + file2.as_raw_fd(), + c"".as_ptr(), + libc::AT_EMPTY_PATH, + STATX_BASIC_STATS, + core::ptr::from_mut(&mut stx), + ) + }; + assert_eq!(rc_statx, 0); + + let file3 = File::open(&p3).unwrap(); + // SAFETY: `file3` is open and `c""` is a valid C string. + // Kernels before 6.13 reject `AT_EMPTY_PATH` in `faccessat2` with + // `EINVAL` (and pre-5.8 return `ENOSYS`), while `fspy_preload_linux` + // still records the descriptor path before replaying. + let rc = unsafe { + libc::syscall( + libc::SYS_faccessat2, + file3.as_raw_fd(), + c"".as_ptr(), + libc::F_OK, + libc::AT_EMPTY_PATH, + ) + }; + assert!( + rc == 0 || matches!(errno(), libc::EINVAL | libc::ENOSYS), + "unexpected faccessat2(AT_EMPTY_PATH) result: rc={rc}, errno={}", + errno() + ); + }) + .await?; + + assert_contains(&accesses, &f_fstatat, PathAccess::Read); + assert_contains(&accesses, &f_statx, PathAccess::Read); + assert_contains(&accesses, &f_faccessat2, PathAccess::Read); + Ok(()) +} + +#[test(tokio::test)] +async fn access_and_dirfd_relative_fs_syscalls_are_tracked() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + + let access_file = root.join("via_access"); + let faccessat_file = root.join("via_faccessat"); + let faccessat2_file = root.join("via_faccessat2"); + let ren_src = root.join("ren_src"); + let ren_dst = root.join("ren_dst"); + let link_src = root.join("link_src"); + let link_dst = root.join("link_dst"); + let sym_dst = root.join("sym_dst"); + let mkdir_dst = root.join("mkdir_dst"); + let openat2_file = root.join("via_openat2"); + + fs::write(&access_file, b"")?; + fs::write(&faccessat_file, b"")?; + fs::write(&faccessat2_file, b"")?; + fs::write(&ren_src, b"")?; + fs::write(&link_src, b"")?; + fs::write(&openat2_file, b"")?; + + let root_str = root.to_str().unwrap().to_owned(); + let accesses = track_fn!(root_str, |root_str: String| { + use std::{ffi::CString, os::fd::AsRawFd as _}; + + // Change CWD to `/` so every relative path below MUST resolve against `dirfd`. + std::env::set_current_dir("/").unwrap(); + let dir = File::open(&root_str).unwrap(); + let dirfd = dir.as_raw_fd(); + + let abs_access = CString::new(format!("{root_str}/via_access")).unwrap(); + // SAFETY: `abs_access` is a valid NUL-terminated path. + assert_eq!(unsafe { libc::access(abs_access.as_ptr(), libc::F_OK) }, 0); + + // SAFETY: `dirfd` is open and names are valid NUL-terminated strings. + unsafe { + assert_eq!(libc::faccessat(dirfd, c"via_faccessat".as_ptr(), libc::F_OK, 0), 0); + + let rc_fa2 = libc::syscall( + libc::SYS_faccessat2, + dirfd, + c"via_faccessat2".as_ptr(), + libc::F_OK, + 0, + ); + assert!( + rc_fa2 == 0 || errno() == libc::ENOSYS, + "faccessat2 failed: rc={rc_fa2}, errno={}", + errno() + ); + + assert_eq!(libc::mkdirat(dirfd, c"mkdir_dst".as_ptr(), 0o755), 0); + assert_eq!(libc::renameat(dirfd, c"ren_src".as_ptr(), dirfd, c"ren_dst".as_ptr()), 0); + assert_eq!( + libc::linkat(dirfd, c"link_src".as_ptr(), dirfd, c"link_dst".as_ptr(), 0), + 0 + ); + assert_eq!(libc::symlinkat(c"target".as_ptr(), dirfd, c"sym_dst".as_ptr()), 0); + + let how = + OpenHow { flags: u64::try_from(libc::O_RDONLY).unwrap(), mode: 0, resolve: 0 }; + let fd = libc::syscall( + libc::SYS_openat2, + dirfd, + c"via_openat2".as_ptr(), + &raw const how, + size_of::(), + ); + assert!(fd >= 0, "openat2 failed: errno={}", errno()); + libc::close(libc::c_int::try_from(fd).unwrap()); + } + }) + .await?; + + assert_contains(&accesses, &access_file, PathAccess::Read); + assert_contains(&accesses, &faccessat_file, PathAccess::Read); + assert_contains(&accesses, &faccessat2_file, PathAccess::Read); + assert_contains(&accesses, &mkdir_dst, PathAccess::Mkdir); + assert_contains(&accesses, &ren_dst, PathAccess::RenameTarget); + assert_contains(&accesses, &link_dst, PathAccess::Write); + assert_contains(&accesses, &sym_dst, PathAccess::Write); + assert_contains(&accesses, &openat2_file, PathAccess::Read); + Ok(()) +} + +#[test(tokio::test)] +async fn openat2_invalid_how_ptr_and_size_return_efault_and_einval() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let file_path = tmp_dir.path().canonicalize()?.join("probe"); + fs::write(&file_path, b"")?; + + let path_str = file_path.to_str().unwrap().to_owned(); + let _accesses = track_fn!(path_str, |path_str: String| { + use std::ffi::CString; + + let c_path = CString::new(path_str).unwrap(); + + // 1. NULL `how_ptr` -> `EFAULT`. + // SAFETY: kernel validates `how_ptr` and returns `-EFAULT`. + let rc_null = unsafe { + libc::syscall( + libc::SYS_openat2, + libc::AT_FDCWD, + c_path.as_ptr(), + 0_usize, + size_of::(), + ) + }; + assert_eq!(rc_null, -1); + assert_eq!(errno(), libc::EFAULT); + + // 2. First-page bad `how_ptr` -> `EFAULT` without crashing `SIGSYS`. + // SAFETY: `fspy_elf_loader` rejects first-page pointers and kernel returns `-EFAULT`. + let rc_low = unsafe { + libc::syscall( + libc::SYS_openat2, + libc::AT_FDCWD, + c_path.as_ptr(), + 0x10_usize, + size_of::(), + ) + }; + assert_eq!(rc_low, -1); + assert_eq!(errno(), libc::EFAULT); + + // 3. Undersized `size` (< `size_of::()`) -> `EINVAL`. + let how = OpenHow { flags: u64::try_from(libc::O_RDONLY).unwrap(), mode: 0, resolve: 0 }; + // SAFETY: valid `how` pointer with intentionally too-small `size`. + let rc_small = unsafe { + libc::syscall( + libc::SYS_openat2, + libc::AT_FDCWD, + c_path.as_ptr(), + &raw const how, + 8_usize, + ) + }; + assert_eq!(rc_small, -1); + assert_eq!(errno(), libc::EINVAL); + }) + .await?; + + Ok(()) +} + +#[test(tokio::test)] +async fn openat_rdonly_creat_trunc_and_renameat2_exchange() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + + let created = root.join("rdonly_creat"); + let truncated = root.join("rdonly_trunc"); + fs::write(&truncated, b"old content")?; + let ex_a = root.join("exchange_a"); + let ex_b = root.join("exchange_b"); + fs::write(&ex_a, b"a")?; + fs::write(&ex_b, b"b")?; + + let root_str = root.to_str().unwrap().to_owned(); + let accesses = track_fn!(root_str, |root_str: String| { + use std::os::fd::AsRawFd as _; + + let dir = File::open(&root_str).unwrap(); + let dirfd = dir.as_raw_fd(); + + // 1. `O_RDONLY | O_CREAT` creates the file and must record `ReadWrite`. + // SAFETY: `dirfd` is open and filename is a valid C string. + let fd_creat = unsafe { + libc::openat(dirfd, c"rdonly_creat".as_ptr(), libc::O_RDONLY | libc::O_CREAT, 0o644) + }; + assert!(fd_creat >= 0, "openat O_RDONLY|O_CREAT failed: {}", errno()); + // SAFETY: closing our owned descriptor. + unsafe { libc::close(fd_creat) }; + + // 2. `O_RDONLY | O_TRUNC` truncates the file and must record `ReadWrite`. + // SAFETY: `dirfd` is open and filename is a valid C string. + let fd_trunc = unsafe { + libc::openat(dirfd, c"rdonly_trunc".as_ptr(), libc::O_RDONLY | libc::O_TRUNC) + }; + assert!(fd_trunc >= 0, "openat O_RDONLY|O_TRUNC failed: {}", errno()); + // SAFETY: closing our owned descriptor. + unsafe { libc::close(fd_trunc) }; + + // 3. `renameat2(..., RENAME_EXCHANGE)` swaps both paths and must record both. + // SAFETY: `dirfd` is open and both filenames are valid C strings. + let rc = unsafe { + libc::syscall( + libc::SYS_renameat2, + dirfd, + c"exchange_a".as_ptr(), + dirfd, + c"exchange_b".as_ptr(), + RENAME_EXCHANGE, + ) + }; + assert_eq!(rc, 0, "renameat2(RENAME_EXCHANGE) failed: {}", errno()); + }) + .await?; + + assert_contains(&accesses, &created, PathAccess::ReadWrite); + assert_contains(&accesses, &truncated, PathAccess::ReadWrite); + assert_contains(&accesses, &ex_a, PathAccess::RenameTarget); + assert_contains(&accesses, &ex_b, PathAccess::RenameTarget); + assert_eq!(fs::read(&ex_a)?, b"b"); + assert_eq!(fs::read(&ex_b)?, b"a"); + Ok(()) +} + +#[cfg(target_arch = "x86_64")] +#[test(tokio::test)] +async fn legacy_x86_64_open_creat_stat_lstat_syscalls_are_tracked() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + + let open_target = root.join("legacy_open"); + let creat_target = root.join("legacy_creat"); + let stat_target = root.join("legacy_stat"); + let lstat_target = root.join("legacy_lstat_link"); + fs::write(&open_target, b"open")?; + fs::write(&stat_target, b"stat")?; + symlink(&stat_target, &lstat_target)?; + + let args = ( + open_target.to_str().unwrap().to_owned(), + creat_target.to_str().unwrap().to_owned(), + stat_target.to_str().unwrap().to_owned(), + lstat_target.to_str().unwrap().to_owned(), + ); + + let accesses = + track_fn!(args, |(p_open, p_creat, p_stat, p_lstat): (String, String, String, String)| { + use std::ffi::CString; + + #[repr(C, align(8))] + struct RawStatBuf([u8; 256]); + + let c_open = CString::new(p_open).unwrap(); + let c_creat = CString::new(p_creat).unwrap(); + let c_stat = CString::new(p_stat).unwrap(); + let c_lstat = CString::new(p_lstat).unwrap(); + + // SAFETY: valid C string; `SYS_open` takes `(path, flags, mode)`. + let fd = unsafe { libc::syscall(libc::SYS_open, c_open.as_ptr(), libc::O_RDONLY, 0) }; + assert!(fd >= 0, "SYS_open failed: {}", errno()); + // SAFETY: closing our owned descriptor. + unsafe { libc::close(libc::c_int::try_from(fd).unwrap()) }; + + // SAFETY: valid C string; `SYS_creat` takes `(path, mode)`. + let creat_fd = unsafe { libc::syscall(libc::SYS_creat, c_creat.as_ptr(), 0o644) }; + assert!(creat_fd >= 0, "SYS_creat failed: {}", errno()); + // SAFETY: closing our owned descriptor. + unsafe { libc::close(libc::c_int::try_from(creat_fd).unwrap()) }; + + let mut stat_buf = RawStatBuf([0; 256]); + // SAFETY: valid C string and 256-byte aligned buffer (>= x86_64 `struct stat`). + let rc_stat = + unsafe { libc::syscall(libc::SYS_stat, c_stat.as_ptr(), &raw mut stat_buf) }; + assert_eq!(rc_stat, 0); + // SAFETY: valid C string and 256-byte aligned buffer (>= x86_64 `struct stat`). + let rc_lstat = + unsafe { libc::syscall(libc::SYS_lstat, c_lstat.as_ptr(), &raw mut stat_buf) }; + assert_eq!(rc_lstat, 0); + }) + .await?; + + assert_includes(&accesses, &open_target, PathAccess::Read); + assert_includes(&accesses, &creat_target, PathAccess::Write); + assert_includes(&accesses, &stat_target, PathAccess::Read); + assert_includes(&accesses, &lstat_target, PathAccess::Read); + Ok(()) +} + +#[test(tokio::test)] +async fn execveat_sets_kernel_matching_at_execfn_while_preserving_proc_self_exe() +-> anyhow::Result<()> { + let cmd = vt_subprocess_test::command_for_fn!((), |()| { + use std::{ + ffi::{CStr, CString}, + os::{fd::AsRawFd as _, unix::ffi::OsStrExt as _}, + }; + + if let Some(expected_execfn) = std::env::var_os("FSPY_TEST_EXPECT_EXECFN") { + let expected_exe = std::env::var_os("FSPY_TEST_EXPECT_EXE").unwrap(); + // SAFETY: `getauxval(AT_EXECFN)` returns a pointer to the NUL-terminated + // `AT_EXECFN` string on the initial stack (or 0 if absent). + let raw = unsafe { libc::getauxval(libc::AT_EXECFN) }; + assert_ne!(raw, 0, "AT_EXECFN missing in execveat child"); + // SAFETY: non-zero `AT_EXECFN` points to a valid NUL-terminated C string. + let actual_execfn = unsafe { CStr::from_ptr(raw as *const libc::c_char) }; + assert_eq!( + actual_execfn.to_bytes(), + expected_execfn.as_bytes(), + "AT_EXECFN did not match Linux execveat format" + ); + let actual_exe = std::fs::read_link("/proc/self/exe").unwrap(); + assert_eq!( + actual_exe.as_os_str().as_bytes(), + expected_exe.as_bytes(), + "/proc/self/exe did not preserve real binary path" + ); + return; + } + + let exe = std::fs::read_link("/proc/self/exe").unwrap(); + let exe_dir = exe.parent().unwrap(); + let exe_name = exe.file_name().unwrap(); + + let mut args: Vec = + std::env::args_os().map(|a| CString::new(a.as_bytes()).unwrap()).collect(); + if args.is_empty() { + let cmdline = std::fs::read("/proc/self/cmdline").unwrap(); + let mut parts: Vec<&[u8]> = cmdline.split(|&b| b == 0).collect(); + if parts.last().is_some_and(|s| s.is_empty()) { + parts.pop(); + } + args = parts.into_iter().map(|p| CString::new(p).unwrap()).collect(); + } + let mut argv: Vec<*const libc::c_char> = args.iter().map(|s| s.as_ptr()).collect(); + argv.push(std::ptr::null()); + + let base_envs: Vec = std::env::vars_os() + .filter(|(k, _)| k != "FSPY_TEST_EXPECT_EXECFN" && k != "FSPY_TEST_EXPECT_EXE") + .map(|(k, v)| { + let mut bytes = k.as_bytes().to_vec(); + bytes.push(b'='); + bytes.extend_from_slice(v.as_bytes()); + CString::new(bytes).unwrap() + }) + .collect(); + + let run_case = |dirfd: libc::c_int, + path: &CStr, + flags: libc::c_int, + expect_execfn: &str, + chdir_root: bool| { + let mut envs = base_envs.clone(); + envs.push(CString::new(format!("FSPY_TEST_EXPECT_EXECFN={expect_execfn}")).unwrap()); + let mut exe_env = b"FSPY_TEST_EXPECT_EXE=".to_vec(); + exe_env.extend_from_slice(exe.as_os_str().as_bytes()); + envs.push(CString::new(exe_env).unwrap()); + let mut envp: Vec<*const libc::c_char> = envs.iter().map(|s| s.as_ptr()).collect(); + envp.push(std::ptr::null()); + + // SAFETY: `fork()` followed by async-signal-safe `chdir`/`execveat`/`_exit`. + let pid = unsafe { libc::fork() }; + assert!(pid >= 0, "fork failed"); + if pid == 0 { + // SAFETY: all pointers are valid NUL/NULL-terminated C strings/arrays. + unsafe { + if chdir_root { + let _ = libc::chdir(c"/".as_ptr()); + } + libc::syscall( + libc::SYS_execveat, + dirfd, + path.as_ptr(), + argv.as_ptr(), + envp.as_ptr(), + flags, + ); + libc::_exit(127); + } + } + let mut status: libc::c_int = 0; + // SAFETY: `pid` is our child and `status` is writable. + assert_eq!(unsafe { libc::waitpid(pid, &raw mut status, 0) }, pid); + assert!( + libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, + "execveat AT_EXECFN check failed for {expect_execfn} with status {status}" + ); + }; + + // 1. `execveat(bin_fd, "", ..., AT_EMPTY_PATH)` -> `/dev/fd/`. + let bin_file = File::open(&exe).unwrap(); + let expect_empty = format!("/dev/fd/{}", bin_file.as_raw_fd()); + run_case(bin_file.as_raw_fd(), c"", libc::AT_EMPTY_PATH, &expect_empty, false); + + // 2. `execveat(dirfd, basename, ..., 0)` -> `/dev/fd//`. + let dir_file = File::open(exe_dir).unwrap(); + let name_c = CString::new(exe_name.as_bytes()).unwrap(); + let expect_rel = format!("/dev/fd/{}/{}", dir_file.as_raw_fd(), exe_name.to_str().unwrap()); + run_case(dir_file.as_raw_fd(), &name_c, 0, &expect_rel, true); + }); + + let _accesses = test_utils::spawn_command(cmd).await?; + Ok(()) +} + +/// Files under `/dev/shm`, an ordinary tmpfs that can hold a workspace, are +/// tracked like any other path. +#[test(tokio::test)] +async fn dev_shm_paths_are_tracked() -> anyhow::Result<()> { + let shm_dir = tempfile::tempdir_in("/dev/shm")?; + let input = shm_dir.path().join("input"); + fs::write(&input, b"shm")?; + + let accesses = track_fn!(input.to_str().unwrap().to_owned(), |input: String| { + assert_eq!(fs::read(input).unwrap(), b"shm"); + }) + .await?; + assert_contains(&accesses, &input, PathAccess::Read); + Ok(()) +} + +/// A path with no NUL within `PATH_MAX`, ending at an unreadable page, fails +/// with `ENAMETOOLONG` as it does natively instead of crashing the tracker. +#[test(tokio::test)] +async fn unterminated_path_fails_with_enametoolong() -> anyhow::Result<()> { + let _accesses = track_fn!((), |()| { + const PAGE: usize = 1 << 16; // at least the page size on every Linux target + // SAFETY: maps two fresh anonymous regions of `PAGE` bytes. + let base = unsafe { + libc::mmap( + std::ptr::null_mut(), + 2 * PAGE, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, + -1, + 0, + ) + }; + assert_ne!(base, libc::MAP_FAILED); + // Fill the bytes right before the guard with non-NUL bytes. + let start = PAGE - 4096; + // SAFETY: `base..base + PAGE` is writable, and the guard region after + // it becomes unreadable. + let rc = unsafe { + std::ptr::write_bytes(base.cast::().add(start), b'a', 4096); + libc::mprotect(base.cast::().add(PAGE).cast(), PAGE, libc::PROT_NONE) + }; + assert_eq!(rc, 0); + // SAFETY: the path's 4096 bytes are readable; the kernel stops there. + let fd = unsafe { libc::open(base.cast::().add(start).cast(), libc::O_RDONLY) }; + assert_eq!((fd, errno()), (-1, libc::ENAMETOOLONG)); + }) + .await?; + Ok(()) +} diff --git a/crates/fspy/tests/macos_preload.rs b/crates/fspy/tests/macos_preload.rs new file mode 100644 index 000000000..d90541642 --- /dev/null +++ b/crates/fspy/tests/macos_preload.rs @@ -0,0 +1,1092 @@ +#![cfg(target_os = "macos")] +mod test_utils; + +use std::{ + ffi::CString, + fs::{self, Permissions}, + os::unix::fs::PermissionsExt as _, + path::Path, + ptr::null, +}; + +use fspy::PathAccess; +use test_log::test; +use test_utils::{assert_contains, assert_not_contains}; + +fn write_executable(path: &Path, content: &str) -> anyhow::Result<()> { + fs::write(path, content)?; + fs::set_permissions(path, Permissions::from_mode(0o755))?; + Ok(()) +} + +/// Runs `f` in a forked child process and asserts it exits cleanly with code 0. +fn run_in_fork(f: impl FnOnce()) { + // SAFETY: `fork()` is followed immediately by `exec*` or `_exit`. + let pid = unsafe { libc::fork() }; + assert!(pid >= 0, "fork failed: {}", std::io::Error::last_os_error()); + if pid == 0 { + f(); + // SAFETY: terminate child immediately without running parent destructors. + unsafe { libc::_exit(127) }; + } + let mut status: libc::c_int = 0; + // SAFETY: `pid` is our child and `status` is valid writable storage. + let waited = unsafe { libc::waitpid(pid, &raw mut status, 0) }; + assert_eq!(waited, pid); + assert!( + libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, + "child failed with raw status {status:#x}" + ); +} + +#[test(tokio::test)] +async fn exec_family_variants_succeed_and_preserve_tracking() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + let bin_dir = root.join("bin"); + fs::create_dir(&bin_dir)?; + + let execve_marker = root.join("marker_execve"); + let execv_marker = root.join("marker_execv"); + let execvp_marker = root.join("marker_execvp"); + let execlp_marker = root.join("marker_execlp"); + let execle_marker = root.join("marker_execle"); + for marker in [&execve_marker, &execv_marker, &execvp_marker, &execlp_marker, &execle_marker] { + fs::write(marker, "ok")?; + } + + let script_execve = root.join("s_execve.sh"); + write_executable( + &script_execve, + &format!( + "#!/bin/sh\n[ \"$CUSTOM_ENV\" = \"from_execve\" ] || exit 2\ncat \"{}\" >/dev/null\n", + execve_marker.display() + ), + )?; + let script_execv = root.join("s_execv.sh"); + write_executable( + &script_execv, + &format!("#!/bin/sh\ncat \"{}\" >/dev/null\n", execv_marker.display()), + )?; + let script_execvp = bin_dir.join("fspy_test_execvp_cmd"); + write_executable( + &script_execvp, + &format!("#!/bin/sh\ncat \"{}\" >/dev/null\n", execvp_marker.display()), + )?; + let script_execlp = bin_dir.join("fspy_test_execlp_cmd"); + write_executable( + &script_execlp, + &format!("#!/bin/sh\ncat \"{}\" >/dev/null\n", execlp_marker.display()), + )?; + let script_execle = root.join("s_execle.sh"); + write_executable( + &script_execle, + &format!( + "#!/bin/sh\n[ \"$CUSTOM_ENV\" = \"from_execle\" ] || exit 2\ncat \"{}\" >/dev/null\n", + execle_marker.display() + ), + )?; + + let args = ( + script_execve.to_str().unwrap().to_owned(), + script_execv.to_str().unwrap().to_owned(), + script_execle.to_str().unwrap().to_owned(), + bin_dir.to_str().unwrap().to_owned(), + ); + + let accesses = track_fn!(args, |(script_execve, script_execv, script_execle, bin_dir): ( + String, + String, + String, + String + )| { + // 1. execve with custom envp (fspy must inject tracking env into it) + run_in_fork(|| { + let prog = CString::new(script_execve.as_str()).unwrap(); + let argv = [prog.as_ptr(), null()]; + let env0 = CString::new("CUSTOM_ENV=from_execve").unwrap(); + let env1 = CString::new("PATH=/bin:/usr/bin").unwrap(); + let envp = [env0.as_ptr(), env1.as_ptr(), null()]; + // SAFETY: all pointers are valid NUL-terminated strings / arrays. + unsafe { libc::execve(prog.as_ptr(), argv.as_ptr(), envp.as_ptr()) }; + }); + + // 2. execv + run_in_fork(|| { + let prog = CString::new(script_execv.as_str()).unwrap(); + let argv = [prog.as_ptr(), null()]; + // SAFETY: `prog` and `argv` are valid. + unsafe { libc::execv(prog.as_ptr(), argv.as_ptr()) }; + }); + + // 3. execvp (searches PATH) + run_in_fork(|| { + let new_path = format!("{bin_dir}:/bin:/usr/bin"); + // SAFETY: running in single-threaded forked child. + unsafe { std::env::set_var("PATH", new_path) }; + let prog = c"fspy_test_execvp_cmd"; + let argv = [prog.as_ptr(), null()]; + // SAFETY: `prog` and `argv` are valid. + unsafe { libc::execvp(prog.as_ptr(), argv.as_ptr()) }; + }); + + // 4. execlp (searches PATH, variadic argv) + run_in_fork(|| { + let new_path = format!("{bin_dir}:/bin:/usr/bin"); + // SAFETY: running in single-threaded forked child. + unsafe { std::env::set_var("PATH", new_path) }; + let prog = c"fspy_test_execlp_cmd"; + // SAFETY: variadic args terminated by NULL. + unsafe { libc::execlp(prog.as_ptr(), prog.as_ptr(), null::()) }; + }); + + // 5. execle (variadic argv + trailing envp) + run_in_fork(|| { + let prog = CString::new(script_execle.as_str()).unwrap(); + let env0 = CString::new("CUSTOM_ENV=from_execle").unwrap(); + let env1 = CString::new("PATH=/bin:/usr/bin").unwrap(); + let envp = [env0.as_ptr(), env1.as_ptr(), null()]; + // SAFETY: variadic args terminated by NULL followed by valid `envp`. + unsafe { + libc::execle(prog.as_ptr(), prog.as_ptr(), null::(), envp.as_ptr()) + }; + }); + }) + .await?; + + for marker in [&execve_marker, &execv_marker, &execvp_marker, &execlp_marker, &execle_marker] { + assert_contains(&accesses, marker, PathAccess::Read); + } + + Ok(()) +} + +#[test(tokio::test)] +async fn which_path_search_handles_unset_empty_and_directory_entries() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + + let dir_with_subdir = root.join("dir_with_subdir"); + let dir_with_real = root.join("dir_with_real"); + let empty_entry_cwd = root.join("empty_entry_cwd"); + fs::create_dir(&dir_with_subdir)?; + fs::create_dir(&dir_with_real)?; + fs::create_dir(&empty_entry_cwd)?; + + // Place a directory named `same_name` in the first PATH entry, and an executable + // script with the same name in the second PATH entry. + fs::create_dir(dir_with_subdir.join("same_name"))?; + let skipped_marker = root.join("marker_dir_skip"); + fs::write(&skipped_marker, "ok")?; + write_executable( + &dir_with_real.join("same_name"), + &format!("#!/bin/sh\ncat \"{}\" >/dev/null\n", skipped_marker.display()), + )?; + + // Place an executable in `empty_entry_cwd` to be found via an empty PATH component. + let empty_marker = root.join("marker_empty_path"); + fs::write(&empty_marker, "ok")?; + write_executable( + &empty_entry_cwd.join("local_cmd"), + &format!("#!/bin/sh\ncat \"{}\" >/dev/null\n", empty_marker.display()), + )?; + + // A `broken_tool` whose interpreter is missing in the first PATH entry, a + // working one in the second, and a script without `#!`, which `execvp` + // (unlike `posix_spawnp`) runs with `/bin/sh`. + let dir_with_broken = root.join("dir_with_broken"); + fs::create_dir(&dir_with_broken)?; + write_executable(&dir_with_broken.join("broken_tool"), "#!/nonexistent/fspy-interpreter\n")?; + let broken_skip_marker = root.join("marker_broken_skip"); + fs::write(&broken_skip_marker, "ok")?; + write_executable( + &dir_with_real.join("broken_tool"), + &format!("#!/bin/sh\ncat \"{}\" >/dev/null\n", broken_skip_marker.display()), + )?; + let no_shebang_marker = root.join("marker_no_shebang"); + fs::write(&no_shebang_marker, "ok")?; + write_executable( + &dir_with_real.join("no_shebang"), + &format!("cat \"{}\" >/dev/null\n", no_shebang_marker.display()), + )?; + + let args = ( + dir_with_subdir.to_str().unwrap().to_owned(), + dir_with_real.to_str().unwrap().to_owned(), + empty_entry_cwd.to_str().unwrap().to_owned(), + dir_with_broken.to_str().unwrap().to_owned(), + ); + + let accesses = track_fn!(args, |( + dir_with_subdir, + dir_with_real, + empty_entry_cwd, + dir_with_broken, + ): (String, String, String, String)| { + // 1. Directory on PATH is skipped in favor of a later regular executable. + run_in_fork(|| { + let path = format!("{dir_with_subdir}:{dir_with_real}:/bin:/usr/bin"); + // SAFETY: single-threaded forked child. + unsafe { std::env::set_var("PATH", path) }; + let prog = c"same_name"; + let argv = [prog.as_ptr(), null()]; + // SAFETY: `prog` and `argv` are valid. + unsafe { libc::execvp(prog.as_ptr(), argv.as_ptr()) }; + }); + + // 2. Directory on PATH with no later match fails with EACCES. + run_in_fork(|| { + // SAFETY: single-threaded forked child. + unsafe { std::env::set_var("PATH", &dir_with_subdir) }; + let prog = c"same_name"; + let argv = [prog.as_ptr(), null()]; + // SAFETY: `prog` and `argv` are valid. + let ret = unsafe { libc::execvp(prog.as_ptr(), argv.as_ptr()) }; + assert_eq!(ret, -1); + assert_eq!( + std::io::Error::last_os_error().raw_os_error(), + Some(libc::EACCES), + "directory-only PATH match must fail with EACCES" + ); + // SAFETY: exit child cleanly after checking errno. + unsafe { libc::_exit(0) }; + }); + + // 3. Unset PATH falls back to default PATH (`/usr/local/bin:/bin:/usr/bin`). + run_in_fork(|| { + // SAFETY: single-threaded forked child. + unsafe { std::env::remove_var("PATH") }; + let prog = c"true"; + let argv = [prog.as_ptr(), null()]; + // SAFETY: `prog` and `argv` are valid. + unsafe { libc::execvp(prog.as_ptr(), argv.as_ptr()) }; + }); + + // 4. Empty PATH component searches the current working directory. + run_in_fork(|| { + std::env::set_current_dir(&empty_entry_cwd).unwrap(); + // Leading colon creates an empty first PATH entry (= CWD). + // SAFETY: single-threaded forked child. + unsafe { std::env::set_var("PATH", ":/bin:/usr/bin") }; + let prog = c"local_cmd"; + let argv = [prog.as_ptr(), null()]; + // SAFETY: `prog` and `argv` are valid. + unsafe { libc::execvp(prog.as_ptr(), argv.as_ptr()) }; + }); + + // 5. A candidate that fails to exec (its interpreter is missing) moves on + // to the next PATH entry, for `execvp` and `posix_spawnp` alike. + let broken_path = format!("{dir_with_broken}:{dir_with_real}:/bin:/usr/bin"); + run_in_fork(|| { + // SAFETY: single-threaded forked child. + unsafe { std::env::set_var("PATH", &broken_path) }; + let prog = c"broken_tool"; + let argv = [prog.as_ptr(), null()]; + // SAFETY: `prog` and `argv` are valid. + unsafe { libc::execvp(prog.as_ptr(), argv.as_ptr()) }; + }); + run_in_fork(|| { + // SAFETY: single-threaded forked child. + unsafe { std::env::set_var("PATH", &broken_path) }; + let prog = c"broken_tool"; + let argv = [prog.as_ptr().cast_mut(), std::ptr::null_mut()]; + let mut pid: libc::pid_t = 0; + // SAFETY: all pointers are valid, and `environ` is this process's environment. + let rc = unsafe { + libc::posix_spawnp( + &raw mut pid, + prog.as_ptr(), + null(), + null(), + argv.as_ptr(), + (*libc::_NSGetEnviron()).cast_const(), + ) + }; + assert_eq!(rc, 0, "posix_spawnp(broken_tool) failed: {rc}"); + let mut status = 0; + // SAFETY: `pid` is our child and `status` is writable. + assert_eq!(unsafe { libc::waitpid(pid, &raw mut status, 0) }, pid); + assert!(libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0); + // SAFETY: exit the forked child cleanly. + unsafe { libc::_exit(0) }; + }); + + // 6. `execvp` runs an executable without a recognized format with `/bin/sh`. + run_in_fork(|| { + // SAFETY: single-threaded forked child. + unsafe { std::env::set_var("PATH", &dir_with_real) }; + let prog = c"no_shebang"; + let argv = [prog.as_ptr(), null()]; + // SAFETY: `prog` and `argv` are valid. + unsafe { libc::execvp(prog.as_ptr(), argv.as_ptr()) }; + }); + }) + .await?; + + assert_contains(&accesses, &skipped_marker, PathAccess::Read); + assert_contains(&accesses, &empty_marker, PathAccess::Read); + assert_contains(&accesses, &broken_skip_marker, PathAccess::Read); + assert_contains(&accesses, &no_shebang_marker, PathAccess::Read); + + Ok(()) +} + +#[test(tokio::test)] +async fn sip_stripping_and_dyld_insert_libraries_merging() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + let sed_input = root.join("input.txt"); + fs::write(&sed_input, "hello world\n")?; + let awk_link = root.join("awk_link"); + std::os::unix::fs::symlink("/usr/bin/awk", &awk_link)?; + + let args = (sed_input.to_str().unwrap().to_owned(), awk_link.to_str().unwrap().to_owned()); + + let accesses = track_fn!(args, |(sed_input, awk_link): (String, String)| { + // 1. Non-injectable SIP binary (`/usr/bin/sed`) executes cleanly. + let out = std::process::Command::new("/usr/bin/sed") + .args(["s/world/fspy/", &sed_input]) + .output() + .unwrap(); + assert!(out.status.success(), "sed failed: {}", String::from_utf8_lossy(&out.stderr)); + assert_eq!(out.stdout, b"hello fspy\n"); + + // 2. Non-injectable SIP binary invoked via symlink strips FSPY_PAYLOAD. + let out = std::process::Command::new(&awk_link) + .arg("BEGIN { printf \"%s\", ENVIRON[\"FSPY_PAYLOAD\"] }") + .output() + .unwrap(); + assert!(out.status.success(), "awk failed: {}", String::from_utf8_lossy(&out.stderr)); + assert!( + out.stdout.is_empty(), + "FSPY_PAYLOAD must be stripped for symlinked SIP binary, got {:?}", + String::from_utf8_lossy(&out.stdout) + ); + + // 3. Pre-existing DYLD_INSERT_LIBRARIES on an injectable binary is preserved + // with fspy's preload appended rather than clobbered. + let user_lib = "/usr/lib/libSystem.B.dylib"; + let out = std::process::Command::new("/bin/sh") + .env("DYLD_INSERT_LIBRARIES", user_lib) + .args(["-c", "printf '%s' \"$DYLD_INSERT_LIBRARIES\""]) + .output() + .unwrap(); + assert!(out.status.success(), "sh failed: {}", String::from_utf8_lossy(&out.stderr)); + let dyld = String::from_utf8(out.stdout).unwrap(); + let parts: Vec<&str> = dyld.split(':').collect(); + assert!( + parts.len() >= 2 + && parts[0] == user_lib + && Path::new(parts.last().unwrap()) + .extension() + .is_some_and(|ext| ext.eq_ignore_ascii_case("dylib")), + "expected user preload preserved before fspy preload, got {dyld:?}" + ); + }) + .await?; + + assert_contains(&accesses, Path::new("/usr/bin/sed"), PathAccess::Read); + assert_contains(&accesses, &awk_link, PathAccess::Read); + + Ok(()) +} + +#[test(tokio::test)] +async fn fopen_and_freopen_plus_modes_record_read_write() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + + let p_r = root.join("mode_r"); + let p_w = root.join("mode_w"); + let p_a = root.join("mode_a"); + let p_rplus = root.join("mode_rplus"); + let p_wplus = root.join("mode_wplus"); + let p_aplus = root.join("mode_aplus"); + let p_freopen = root.join("mode_freopen_rplus"); + fs::write(&p_r, "r")?; + fs::write(&p_rplus, "r+")?; + fs::write(&p_freopen, "freopen")?; + + let root_str = root.to_str().unwrap().to_owned(); + let accesses = track_fn!(root_str, |root_str: String| { + let open_and_close = |name: &str, mode: &core::ffi::CStr| { + let p = CString::new(format!("{root_str}/{name}")).unwrap(); + // SAFETY: `p` and `mode` are valid NUL-terminated C strings. + let fp = unsafe { libc::fopen(p.as_ptr(), mode.as_ptr()) }; + assert!(!fp.is_null(), "fopen({name}, {mode:?}) failed"); + // SAFETY: `fp` was returned by `fopen` above. + unsafe { libc::fclose(fp) }; + }; + + open_and_close("mode_r", c"r"); + open_and_close("mode_w", c"w"); + open_and_close("mode_a", c"a"); + open_and_close("mode_rplus", c"r+"); + open_and_close("mode_wplus", c"w+"); + open_and_close("mode_aplus", c"a+"); + + let p_tmp = CString::new(format!("{root_str}/mode_r")).unwrap(); + let p_re = CString::new(format!("{root_str}/mode_freopen_rplus")).unwrap(); + // SAFETY: valid C strings and FILE stream from `fopen`. + unsafe { + let fp = libc::fopen(p_tmp.as_ptr(), c"r".as_ptr()); + assert!(!fp.is_null()); + let fp2 = libc::freopen(p_re.as_ptr(), c"r+".as_ptr(), fp); + assert!(!fp2.is_null()); + libc::fclose(fp2); + } + }) + .await?; + + assert_contains(&accesses, &p_r, PathAccess::Read); + assert_contains(&accesses, &p_w, PathAccess::Write); + assert_contains(&accesses, &p_a, PathAccess::Write); + assert_contains(&accesses, &p_rplus, PathAccess::ReadWrite); + assert_contains(&accesses, &p_wplus, PathAccess::ReadWrite); + assert_contains(&accesses, &p_aplus, PathAccess::ReadWrite); + assert_contains(&accesses, &p_freopen, PathAccess::ReadWrite); + + Ok(()) +} + +#[test(tokio::test)] +async fn empty_path_calls_do_not_record_cwd_or_dirfd() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + let sub_dir = root.join("sub"); + fs::create_dir(&sub_dir)?; + + let args = (root.to_str().unwrap().to_owned(), sub_dir.to_str().unwrap().to_owned()); + let accesses = track_fn!(args, |(root_str, sub_str): (String, String)| { + std::env::set_current_dir(&root_str).unwrap(); + let sub_c = CString::new(sub_str).unwrap(); + // SAFETY: `sub_c` and `c""` are valid NUL-terminated C strings. + unsafe { + assert_eq!(libc::open(c"".as_ptr(), libc::O_RDONLY), -1); + let mut st = std::mem::MaybeUninit::::zeroed(); + assert_eq!(libc::stat(c"".as_ptr(), st.as_mut_ptr()), -1); + assert_eq!(libc::lstat(c"".as_ptr(), st.as_mut_ptr()), -1); + assert_eq!(libc::access(c"".as_ptr(), libc::F_OK), -1); + + let dirfd = libc::open(sub_c.as_ptr(), libc::O_RDONLY | libc::O_DIRECTORY); + assert!(dirfd >= 0); + assert_eq!(libc::openat(dirfd, c"".as_ptr(), libc::O_RDONLY), -1); + assert_eq!(libc::fstatat(dirfd, c"".as_ptr(), st.as_mut_ptr(), 0), -1); + libc::close(dirfd); + } + }) + .await?; + + assert_not_contains(&accesses, &root); + // `sub_dir` itself was opened with `O_RDONLY`, not written or re-recorded via `openat("", ...)`. + assert_contains(&accesses, &sub_dir, PathAccess::Read); + + Ok(()) +} + +#[test(tokio::test)] +async fn open_rdonly_with_creat_or_trunc_and_rename_swap() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + + let p_creat = root.join("rdonly_creat"); + let p_trunc = root.join("rdonly_trunc"); + fs::write(&p_trunc, "content")?; + let swap_a = root.join("swap_a"); + let swap_b = root.join("swap_b"); + fs::write(&swap_a, "aaa")?; + fs::write(&swap_b, "bbb")?; + + let root_str = root.to_str().unwrap().to_owned(); + let accesses = track_fn!(root_str, |root_str: String| { + let c_creat = CString::new(format!("{root_str}/rdonly_creat")).unwrap(); + let c_trunc = CString::new(format!("{root_str}/rdonly_trunc")).unwrap(); + let c_a = CString::new(format!("{root_str}/swap_a")).unwrap(); + let c_b = CString::new(format!("{root_str}/swap_b")).unwrap(); + // SAFETY: all paths are valid NUL-terminated C strings. + unsafe { + let fd = libc::open(c_creat.as_ptr(), libc::O_RDONLY | libc::O_CREAT, 0o644); + assert!(fd >= 0, "open(O_RDONLY|O_CREAT) failed: {}", std::io::Error::last_os_error()); + libc::close(fd); + + let fd = libc::open(c_trunc.as_ptr(), libc::O_RDONLY | libc::O_TRUNC); + if fd >= 0 { + libc::close(fd); + } + + assert_eq!( + libc::renamex_np(c_a.as_ptr(), c_b.as_ptr(), libc::RENAME_SWAP), + 0, + "renamex_np(RENAME_SWAP) failed: {}", + std::io::Error::last_os_error() + ); + } + }) + .await?; + + assert_contains(&accesses, &p_creat, PathAccess::ReadWrite); + assert_contains(&accesses, &p_trunc, PathAccess::ReadWrite); + assert_contains(&accesses, &swap_a, PathAccess::RenameTarget); + assert_contains(&accesses, &swap_b, PathAccess::RenameTarget); + + Ok(()) +} + +#[test(tokio::test)] +async fn posix_spawn_addchdir_np_resolves_relative_program() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + let sub = root.join("child_cwd"); + fs::create_dir(&sub)?; + let marker = sub.join("marker_chdir"); + fs::write(&marker, "ok")?; + let script = sub.join("run.sh"); + write_executable(&script, "#!/bin/sh\ncat marker_chdir >/dev/null\n")?; + + let sub_str = sub.to_str().unwrap().to_owned(); + let accesses = track_fn!(sub_str, |sub_str: String| { + // `std::process::Command::current_dir` uses `posix_spawn_file_actions_addchdir_np` + // on macOS. + let status = std::process::Command::new("./run.sh") + .current_dir(&sub_str) + .status() + .expect("posix_spawn with addchdir_np failed"); + assert!(status.success()); + }) + .await?; + + assert_contains(&accesses, &script, PathAccess::Read); + assert_contains(&accesses, &marker, PathAccess::Read); + + Ok(()) +} + +#[test(tokio::test)] +async fn posix_spawn_addchdir_np_is_fork_safe_under_concurrent_churn() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + let sub = root.join("fork_child_cwd"); + fs::create_dir(&sub)?; + let marker = sub.join("marker_fork_chdir"); + fs::write(&marker, "ok")?; + let script = sub.join("run.sh"); + write_executable(&script, "#!/bin/sh\ncat marker_fork_chdir >/dev/null\n")?; + + let sub_str = sub.to_str().unwrap().to_owned(); + let accesses = track_fn!(sub_str, |sub_str: String| { + use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }; + + unsafe extern "C" { + fn posix_spawn_file_actions_addchdir_np( + file_actions: *mut libc::posix_spawn_file_actions_t, + path: *const libc::c_char, + ) -> libc::c_int; + } + + let stop = Arc::new(AtomicBool::new(false)); + let sub_c = CString::new(sub_str).unwrap(); + + // Spawn background threads hammering `addchdir_np` + `destroy` while the + // main thread repeatedly calls `fork()` and uses `addchdir_np` + + // `posix_spawn` in the forked child. + let mut workers = Vec::new(); + for _ in 0..2 { + let stop_flag = Arc::clone(&stop); + let dir_c = sub_c.clone(); + workers.push(std::thread::spawn(move || { + while !stop_flag.load(Ordering::Relaxed) { + let mut actions: libc::posix_spawn_file_actions_t = std::ptr::null_mut(); + // SAFETY: valid uninitialized handle and NUL-terminated path. + unsafe { + if libc::posix_spawn_file_actions_init(&raw mut actions) == 0 { + let _ = posix_spawn_file_actions_addchdir_np( + &raw mut actions, + dir_c.as_ptr(), + ); + let _ = libc::posix_spawn_file_actions_destroy(&raw mut actions); + } + } + } + })); + } + + let prog = c"./run.sh"; + let argv = [prog.as_ptr().cast_mut(), std::ptr::null_mut()]; + let path_env = c"PATH=/bin:/usr/bin"; + let envp = [path_env.as_ptr().cast_mut(), std::ptr::null_mut()]; + + for _ in 0..16 { + // SAFETY: child executes only raw libc / `posix_spawn` + `_exit`. + let pid = unsafe { libc::fork() }; + assert!(pid >= 0, "fork failed: {}", std::io::Error::last_os_error()); + if pid == 0 { + let mut actions: libc::posix_spawn_file_actions_t = std::ptr::null_mut(); + // SAFETY: all pointers are pre-allocated valid C strings / arrays. + unsafe { + if libc::posix_spawn_file_actions_init(&raw mut actions) != 0 { + libc::_exit(10); + } + if posix_spawn_file_actions_addchdir_np(&raw mut actions, sub_c.as_ptr()) != 0 { + libc::_exit(11); + } + let mut grandchild: libc::pid_t = 0; + let rc = libc::posix_spawn( + &raw mut grandchild, + prog.as_ptr(), + &raw const actions, + std::ptr::null(), + argv.as_ptr(), + envp.as_ptr(), + ); + let _ = libc::posix_spawn_file_actions_destroy(&raw mut actions); + if rc != 0 { + libc::_exit(12); + } + let mut gc_status: libc::c_int = 0; + if libc::waitpid(grandchild, &raw mut gc_status, 0) != grandchild + || !libc::WIFEXITED(gc_status) + || libc::WEXITSTATUS(gc_status) != 0 + { + libc::_exit(13); + } + libc::_exit(0); + } + } + let mut status: libc::c_int = 0; + // SAFETY: `pid` is our child and `status` is writable. + let waited = unsafe { libc::waitpid(pid, &raw mut status, 0) }; + assert_eq!(waited, pid); + assert!( + libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, + "forked child failed with status {status:#x}" + ); + } + + stop.store(true, Ordering::Relaxed); + for worker in workers { + worker.join().unwrap(); + } + }) + .await?; + + assert_contains(&accesses, &script, PathAccess::Read); + assert_contains(&accesses, &marker, PathAccess::Read); + + Ok(()) +} + +#[test(tokio::test)] +async fn posix_spawn_defers_relative_addchdir_and_addfchdir_resolution_to_spawn_time() +-> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + + let dir_a = root.join("dir_a"); + let dir_b = root.join("dir_b"); + let sub_a = dir_a.join("sub"); + let sub_b = dir_b.join("sub"); + fs::create_dir_all(&sub_a)?; + fs::create_dir_all(&sub_b)?; + + let marker_rel_a = sub_a.join("marker_rel_a"); + let marker_rel_b = sub_b.join("marker_rel_b"); + let marker_fd_a = dir_a.join("marker_fd_a"); + let marker_fd_b = dir_b.join("marker_fd_b"); + for m in [&marker_rel_a, &marker_rel_b, &marker_fd_a, &marker_fd_b] { + fs::write(m, "ok")?; + } + + let script_rel_a = sub_a.join("run.sh"); + let script_rel_b = sub_b.join("run.sh"); + let script_fd_a = dir_a.join("run_fd.sh"); + let script_fd_b = dir_b.join("run_fd.sh"); + write_executable(&script_rel_a, "#!/bin/sh\ncat marker_rel_a >/dev/null\n")?; + write_executable(&script_rel_b, "#!/bin/sh\ncat marker_rel_b >/dev/null\n")?; + write_executable(&script_fd_a, "#!/bin/sh\ncat marker_fd_a >/dev/null\n")?; + write_executable(&script_fd_b, "#!/bin/sh\ncat marker_fd_b >/dev/null\n")?; + + let args = (dir_a.to_str().unwrap().to_owned(), dir_b.to_str().unwrap().to_owned()); + let accesses = track_fn!(args, |(dir_a, dir_b): (String, String)| { + unsafe extern "C" { + fn posix_spawn_file_actions_addchdir_np( + file_actions: *mut libc::posix_spawn_file_actions_t, + path: *const libc::c_char, + ) -> libc::c_int; + fn posix_spawn_file_actions_addfchdir_np( + file_actions: *mut libc::posix_spawn_file_actions_t, + fd: libc::c_int, + ) -> libc::c_int; + } + + let spawn_and_wait = |prog: &std::ffi::CStr, actions: &libc::posix_spawn_file_actions_t| { + let argv = [prog.as_ptr().cast_mut(), std::ptr::null_mut()]; + let path_env = c"PATH=/bin:/usr/bin"; + let envp = [path_env.as_ptr().cast_mut(), std::ptr::null_mut()]; + let mut child: libc::pid_t = 0; + // SAFETY: all pointers are valid C strings/arrays and `actions` is initialized. + let rc = unsafe { + libc::posix_spawn( + &raw mut child, + prog.as_ptr(), + std::ptr::from_ref(actions), + std::ptr::null(), + argv.as_ptr(), + envp.as_ptr(), + ) + }; + assert_eq!(rc, 0, "posix_spawn({prog:?}) failed with errno {rc}"); + let mut status: libc::c_int = 0; + // SAFETY: `child` is our child and `status` is writable. + assert_eq!(unsafe { libc::waitpid(child, &raw mut status, 0) }, child); + assert!( + libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, + "child for {prog:?} failed with raw status {status:#x}" + ); + }; + + // 1. Single `file_actions` with relative `addchdir_np("sub")` reused across `chdir`. + std::env::set_current_dir(&dir_a).unwrap(); + let mut rel_actions: libc::posix_spawn_file_actions_t = std::ptr::null_mut(); + // SAFETY: valid uninitialized handle and NUL-terminated relative path. + unsafe { + assert_eq!(libc::posix_spawn_file_actions_init(&raw mut rel_actions), 0); + assert_eq!( + posix_spawn_file_actions_addchdir_np(&raw mut rel_actions, c"sub".as_ptr()), + 0 + ); + } + spawn_and_wait(c"./run.sh", &rel_actions); + + std::env::set_current_dir(&dir_b).unwrap(); + spawn_and_wait(c"./run.sh", &rel_actions); + // SAFETY: destroying initialized `rel_actions`. + unsafe { assert_eq!(libc::posix_spawn_file_actions_destroy(&raw mut rel_actions), 0) }; + + // 2. Single `file_actions` with `addfchdir_np(fd)` where `dup2` retargets `fd` + // from `dir_a` to `dir_b` before the second spawn. + let dir_a_c = CString::new(dir_a.as_str()).unwrap(); + let dir_b_c = CString::new(dir_b.as_str()).unwrap(); + // SAFETY: valid C path strings for opening directory fds. + let fd_a = unsafe { libc::open(dir_a_c.as_ptr(), libc::O_RDONLY | libc::O_DIRECTORY) }; + assert!(fd_a >= 0, "open(dir_a) failed: {}", std::io::Error::last_os_error()); + // SAFETY: valid C path string. + let fd_b = unsafe { libc::open(dir_b_c.as_ptr(), libc::O_RDONLY | libc::O_DIRECTORY) }; + assert!(fd_b >= 0, "open(dir_b) failed: {}", std::io::Error::last_os_error()); + + let mut fd_actions: libc::posix_spawn_file_actions_t = std::ptr::null_mut(); + // SAFETY: valid uninitialized handle and open directory descriptor `fd_a`. + unsafe { + assert_eq!(libc::posix_spawn_file_actions_init(&raw mut fd_actions), 0); + assert_eq!(posix_spawn_file_actions_addfchdir_np(&raw mut fd_actions, fd_a), 0); + } + spawn_and_wait(c"./run_fd.sh", &fd_actions); + + // Retarget `fd_a` to point at `dir_b` and spawn again with the same `fd_actions`. + // SAFETY: `fd_b` and `fd_a` are valid open descriptors. + assert_eq!(unsafe { libc::dup2(fd_b, fd_a) }, fd_a); + spawn_and_wait(c"./run_fd.sh", &fd_actions); + + // SAFETY: destroying initialized handle and closing owned descriptors. + unsafe { + assert_eq!(libc::posix_spawn_file_actions_destroy(&raw mut fd_actions), 0); + libc::close(fd_a); + libc::close(fd_b); + } + }) + .await?; + + assert_contains(&accesses, &script_rel_a, PathAccess::Read); + assert_contains(&accesses, &marker_rel_a, PathAccess::Read); + assert_contains(&accesses, &script_rel_b, PathAccess::Read); + assert_contains(&accesses, &marker_rel_b, PathAccess::Read); + assert_contains(&accesses, &script_fd_a, PathAccess::Read); + assert_contains(&accesses, &marker_fd_a, PathAccess::Read); + assert_contains(&accesses, &script_fd_b, PathAccess::Read); + assert_contains(&accesses, &marker_fd_b, PathAccess::Read); + + Ok(()) +} + +#[test(tokio::test)] +async fn posix_spawn_addfchdir_np_child_only_fd_and_realloc_actions() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + let sub = root.join("child_only_fd_dir"); + fs::create_dir(&sub)?; + + let marker = sub.join("marker_child_only_fd"); + fs::write(&marker, "ok")?; + + // Build a non-SIP relative `./helper` executable in `sub` by symlinking the + // test binary and passing `command_for_fn!`'s dispatch args. + let helper_cmd = + test_utils::command_for_fn!(marker.to_str().unwrap().to_owned(), |marker_path: String| { + assert_eq!(std::env::var("CUSTOM_ONLY").as_deref(), Ok("1")); + assert_eq!(fs::read(&marker_path).unwrap(), b"ok"); + }); + let helper_link = sub.join("helper"); + std::os::unix::fs::symlink(&helper_cmd.program, &helper_link)?; + let helper_args: Vec = + helper_cmd.args.into_iter().map(|s| s.into_string().unwrap()).collect(); + + // Place a decoy `./helper` in `root` (the parent's CWD) that fails if run, + // so we prove `ResolvedChdir::Unresolvable` never falls back to parent CWD. + write_executable(&root.join("helper"), "#!/bin/sh\nexit 99\n")?; + + let args = (root.to_str().unwrap().to_owned(), sub.to_str().unwrap().to_owned(), helper_args); + let accesses = + track_fn!(args, |(root_dir, sub_dir, helper_args): (String, String, Vec)| { + unsafe extern "C" { + fn posix_spawn_file_actions_addchdir_np( + file_actions: *mut libc::posix_spawn_file_actions_t, + path: *const libc::c_char, + ) -> libc::c_int; + fn posix_spawn_file_actions_addfchdir_np( + file_actions: *mut libc::posix_spawn_file_actions_t, + fd: libc::c_int, + ) -> libc::c_int; + } + + std::env::set_current_dir(&root_dir).unwrap(); + + // Pick an fd number that is not open in the parent so `addopen` + // creates it exclusively in the spawned child. + let child_fd = (40..200) + // SAFETY: `F_GETFD` on a candidate fd only queries descriptor state. + .find(|&fd| unsafe { libc::fcntl(fd, libc::F_GETFD) } == -1) + .expect("no unused fd in 40..200"); + + let sub_c = CString::new(sub_dir.as_str()).unwrap(); + let prog = c"./helper"; + let c_args: Vec = + helper_args.iter().map(|s| CString::new(s.as_str()).unwrap()).collect(); + let mut argv: Vec<*mut libc::c_char> = Vec::with_capacity(c_args.len() + 2); + argv.push(prog.as_ptr().cast_mut()); + for arg in &c_args { + argv.push(arg.as_ptr().cast_mut()); + } + argv.push(std::ptr::null_mut()); + + // Explicit custom `envp` without inheriting `environ` (no `DYLD_INSERT_LIBRARIES` + // or `FSPY_PAYLOAD`); `fspy_preload_macos` must inject both into it. + let custom_env = c"CUSTOM_ONLY=1"; + let envp = [custom_env.as_ptr().cast_mut(), std::ptr::null_mut()]; + + // 1. `addopen(child_fd, sub)` + `addfchdir_np(child_fd)` + `addclose(child_fd)`. + // On current XNU, `PSFA_FCHDIR` checks the parent's fd table before + // `addopen` runs and returns `EBADF`; on a POSIX.1-2024 sequential + // kernel it succeeds in `sub`. Either way, fspy must not fail with + // spurious `ENOENT` or execute the decoy `./helper` in `root_dir`. + let mut actions: libc::posix_spawn_file_actions_t = std::ptr::null_mut(); + // SAFETY: valid uninitialized handle and NUL-terminated directory path. + unsafe { + assert_eq!(libc::posix_spawn_file_actions_init(&raw mut actions), 0); + assert_eq!( + libc::posix_spawn_file_actions_addopen( + &raw mut actions, + child_fd, + sub_c.as_ptr(), + libc::O_RDONLY | libc::O_DIRECTORY, + 0, + ), + 0 + ); + assert_eq!(posix_spawn_file_actions_addfchdir_np(&raw mut actions, child_fd), 0); + assert_eq!(libc::posix_spawn_file_actions_addclose(&raw mut actions, child_fd), 0); + } + + let mut child: libc::pid_t = 0; + // SAFETY: all pointers are valid C strings/arrays and `actions` is initialized. + let rc = unsafe { + libc::posix_spawn( + &raw mut child, + prog.as_ptr(), + &raw const actions, + std::ptr::null(), + argv.as_ptr(), + envp.as_ptr(), + ) + }; + // SAFETY: destroying initialized `actions`. + unsafe { assert_eq!(libc::posix_spawn_file_actions_destroy(&raw mut actions), 0) }; + if rc == 0 { + let mut status: libc::c_int = 0; + // SAFETY: `child` is our child and `status` is writable. + assert_eq!(unsafe { libc::waitpid(child, &raw mut status, 0) }, child); + assert!( + libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, + "child failed with raw status {status:#x}" + ); + } else { + assert_eq!( + rc, + libc::EBADF, + "expected EBADF from XNU (or 0 on sequential kernels), not spurious errno {rc}" + ); + } + + // 2. `addchdir_np(sub)` followed by multiple file actions that force + // libsystem to `realloc` `*file_actions`, with explicit custom `envp`: + // verifies rekeying survives reallocation and child access is tracked. + let mut realloc_actions: libc::posix_spawn_file_actions_t = std::ptr::null_mut(); + // SAFETY: valid uninitialized handle and NUL-terminated paths. + unsafe { + assert_eq!(libc::posix_spawn_file_actions_init(&raw mut realloc_actions), 0); + assert_eq!( + posix_spawn_file_actions_addchdir_np(&raw mut realloc_actions, sub_c.as_ptr()), + 0 + ); + assert_eq!( + libc::posix_spawn_file_actions_addopen( + &raw mut realloc_actions, + child_fd, + c"/dev/null".as_ptr(), + libc::O_RDONLY, + 0, + ), + 0 + ); + assert_eq!( + libc::posix_spawn_file_actions_adddup2( + &raw mut realloc_actions, + child_fd, + child_fd + 1, + ), + 0 + ); + assert_eq!( + libc::posix_spawn_file_actions_addclose(&raw mut realloc_actions, child_fd), + 0 + ); + assert_eq!( + libc::posix_spawn_file_actions_addclose(&raw mut realloc_actions, child_fd + 1), + 0 + ); + } + let mut child2: libc::pid_t = 0; + // SAFETY: all pointers are valid C strings/arrays and `realloc_actions` is initialized. + let rc2 = unsafe { + libc::posix_spawn( + &raw mut child2, + prog.as_ptr(), + &raw const realloc_actions, + std::ptr::null(), + argv.as_ptr(), + envp.as_ptr(), + ) + }; + // SAFETY: destroying initialized `realloc_actions`. + unsafe { + assert_eq!(libc::posix_spawn_file_actions_destroy(&raw mut realloc_actions), 0); + } + assert_eq!(rc2, 0, "posix_spawn(./helper) after file_actions realloc failed: {rc2}"); + + let mut status2: libc::c_int = 0; + // SAFETY: `child2` is our child and `status2` is writable. + assert_eq!(unsafe { libc::waitpid(child2, &raw mut status2, 0) }, child2); + assert!( + libc::WIFEXITED(status2) && libc::WEXITSTATUS(status2) == 0, + "child2 failed with raw status {status2:#x}" + ); + + // 3. A failing add can still grow (and move) the list: libsystem grows + // a full list before rejecting an overlong chdir path with + // `ENAMETOOLONG`. `addchdir_np(sub)` + `addopen` fill the initial + // two slots, so the chdir must follow the list through that call. + let overlong = + CString::new(vec![b'a'; usize::try_from(libc::PATH_MAX).unwrap()]).unwrap(); + let mut grown_actions: libc::posix_spawn_file_actions_t = std::ptr::null_mut(); + // SAFETY: valid uninitialized handle and NUL-terminated paths. + unsafe { + assert_eq!(libc::posix_spawn_file_actions_init(&raw mut grown_actions), 0); + assert_eq!( + posix_spawn_file_actions_addchdir_np(&raw mut grown_actions, sub_c.as_ptr()), + 0 + ); + assert_eq!( + libc::posix_spawn_file_actions_addopen( + &raw mut grown_actions, + child_fd, + c"/dev/null".as_ptr(), + libc::O_RDONLY, + 0, + ), + 0 + ); + assert_eq!( + posix_spawn_file_actions_addchdir_np(&raw mut grown_actions, overlong.as_ptr()), + libc::ENAMETOOLONG + ); + } + let mut child3: libc::pid_t = 0; + // SAFETY: all pointers are valid C strings/arrays and `grown_actions` is initialized. + let rc3 = unsafe { + libc::posix_spawn( + &raw mut child3, + prog.as_ptr(), + &raw const grown_actions, + std::ptr::null(), + argv.as_ptr(), + envp.as_ptr(), + ) + }; + // SAFETY: destroying initialized `grown_actions`. + unsafe { + assert_eq!(libc::posix_spawn_file_actions_destroy(&raw mut grown_actions), 0); + } + assert_eq!(rc3, 0, "posix_spawn(./helper) after a failed growing add failed: {rc3}"); + let mut status3: libc::c_int = 0; + // SAFETY: `child3` is our child and `status3` is writable. + assert_eq!(unsafe { libc::waitpid(child3, &raw mut status3, 0) }, child3); + assert!( + libc::WIFEXITED(status3) && libc::WEXITSTATUS(status3) == 0, + "child3 failed with raw status {status3:#x}" + ); + }) + .await?; + + assert_contains(&accesses, &marker, PathAccess::Read); + + Ok(()) +} + +/// When resolving a relative path fails (here opening `.` hits `EMFILE`) +/// while the call itself still succeeds, the trace is reported incomplete +/// instead of complete without the access. +#[test(tokio::test)] +async fn unresolvable_relative_path_reports_tracking_incomplete() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + fs::write(root.join("input"), "data")?; + + let cmd = test_utils::command_for_fn!(root.to_str().unwrap().to_owned(), |root: String| { + std::env::set_current_dir(root).unwrap(); + // Fill the descriptor table, so the tracker can't open `.`. + let mut fds = Vec::new(); + loop { + // SAFETY: opening `/dev/null` read-only has no preconditions. + let fd = unsafe { libc::open(c"/dev/null".as_ptr(), libc::O_RDONLY) }; + if fd < 0 { + break; + } + fds.push(fd); + } + let mut st = std::mem::MaybeUninit::::uninit(); + // SAFETY: valid NUL-terminated relative path and writable `stat` storage. + let rc = unsafe { libc::stat(c"input".as_ptr(), st.as_mut_ptr()) }; + for fd in fds { + // SAFETY: closing descriptors this closure opened. + unsafe { libc::close(fd) }; + } + assert_eq!(rc, 0, "stat(input) failed"); + }); + let tracked = + fspy::Command::from(cmd).spawn(tokio_util::sync::CancellationToken::new()).await?; + let termination = tracked.wait_handle.await?; + assert!(termination.status.success(), "the child failed: {:?}", termination.status); + assert!(matches!(termination.path_accesses, Err(fspy::TrackingIncomplete))); + Ok(()) +} diff --git a/crates/fspy/tests/node_fs.rs b/crates/fspy/tests/node_fs.rs index 7430bd6a5..b9fec2527 100644 --- a/crates/fspy/tests/node_fs.rs +++ b/crates/fspy/tests/node_fs.rs @@ -53,13 +53,12 @@ fn track_script( }) } -// Bun's Linux runtime uses direct syscalls, which require universal seccomp -// tracing instead of preload interception. Deno does not distribute a musl -// runtime. Node remains covered on every target. +// Deno does not distribute a musl runtime. Node and Bun are covered on every +// target (Bun's direct syscalls on Linux are traced via `fspy_preload_linux`). #[test_case("node")] #[ignore = "requires node"] -#[cfg_attr(not(target_os = "linux"), test_case("bun"))] -#[cfg_attr(not(target_os = "linux"), ignore = "requires node")] +#[test_case("bun")] +#[ignore = "requires node"] #[cfg_attr(not(target_env = "musl"), test_case("deno"))] #[cfg_attr(not(target_env = "musl"), ignore = "requires node")] fn read_sync(runtime: &str) -> anyhow::Result<()> { @@ -70,8 +69,8 @@ fn read_sync(runtime: &str) -> anyhow::Result<()> { #[test_case("node")] #[ignore = "requires node"] -#[cfg_attr(not(target_os = "linux"), test_case("bun"))] -#[cfg_attr(not(target_os = "linux"), ignore = "requires node")] +#[test_case("bun")] +#[ignore = "requires node"] #[cfg_attr(not(target_env = "musl"), test_case("deno"))] #[cfg_attr(not(target_env = "musl"), ignore = "requires node")] fn exist_sync(runtime: &str) -> anyhow::Result<()> { @@ -82,8 +81,8 @@ fn exist_sync(runtime: &str) -> anyhow::Result<()> { #[test_case("node")] #[ignore = "requires node"] -#[cfg_attr(not(target_os = "linux"), test_case("bun"))] -#[cfg_attr(not(target_os = "linux"), ignore = "requires node")] +#[test_case("bun")] +#[ignore = "requires node"] #[cfg_attr(not(target_env = "musl"), test_case("deno"))] #[cfg_attr(not(target_env = "musl"), ignore = "requires node")] fn stat_sync(runtime: &str) -> anyhow::Result<()> { @@ -94,8 +93,8 @@ fn stat_sync(runtime: &str) -> anyhow::Result<()> { #[test_case("node")] #[ignore = "requires node"] -#[cfg_attr(not(target_os = "linux"), test_case("bun"))] -#[cfg_attr(not(target_os = "linux"), ignore = "requires node")] +#[test_case("bun")] +#[ignore = "requires node"] #[cfg_attr(not(target_env = "musl"), test_case("deno"))] #[cfg_attr(not(target_env = "musl"), ignore = "requires node")] fn create_read_stream(runtime: &str) -> anyhow::Result<()> { @@ -110,8 +109,8 @@ fn create_read_stream(runtime: &str) -> anyhow::Result<()> { #[test_case("node")] #[ignore = "requires node"] -#[cfg_attr(not(target_os = "linux"), test_case("bun"))] -#[cfg_attr(not(target_os = "linux"), ignore = "requires node")] +#[test_case("bun")] +#[ignore = "requires node"] #[cfg_attr(not(target_env = "musl"), test_case("deno"))] #[cfg_attr(not(target_env = "musl"), ignore = "requires node")] fn create_write_stream(runtime: &str) -> anyhow::Result<()> { @@ -128,8 +127,8 @@ fn create_write_stream(runtime: &str) -> anyhow::Result<()> { #[test_case("node")] #[ignore = "requires node"] -#[cfg_attr(not(target_os = "linux"), test_case("bun"))] -#[cfg_attr(not(target_os = "linux"), ignore = "requires node")] +#[test_case("bun")] +#[ignore = "requires node"] #[cfg_attr(not(target_env = "musl"), test_case("deno"))] #[cfg_attr(not(target_env = "musl"), ignore = "requires node")] fn write_sync(runtime: &str) -> anyhow::Result<()> { @@ -146,8 +145,8 @@ fn write_sync(runtime: &str) -> anyhow::Result<()> { #[test_case("node")] #[ignore = "requires node"] -#[cfg_attr(not(target_os = "linux"), test_case("bun"))] -#[cfg_attr(not(target_os = "linux"), ignore = "requires node")] +#[test_case("bun")] +#[ignore = "requires node"] #[cfg_attr(not(target_env = "musl"), test_case("deno"))] #[cfg_attr(not(target_env = "musl"), ignore = "requires node")] fn symlink_junction_sync(runtime: &str) -> anyhow::Result<()> { @@ -174,8 +173,8 @@ fn symlink_junction_sync(runtime: &str) -> anyhow::Result<()> { #[test_case("node")] #[ignore = "requires node"] -#[cfg_attr(not(target_os = "linux"), test_case("bun"))] -#[cfg_attr(not(target_os = "linux"), ignore = "requires node")] +#[test_case("bun")] +#[ignore = "requires node"] #[cfg_attr(not(target_env = "musl"), test_case("deno"))] #[cfg_attr(not(target_env = "musl"), ignore = "requires node")] fn read_dir_sync(runtime: &str) -> anyhow::Result<()> { @@ -186,8 +185,8 @@ fn read_dir_sync(runtime: &str) -> anyhow::Result<()> { #[test_case("node")] #[ignore = "requires node"] -#[cfg_attr(not(target_os = "linux"), test_case("bun"))] -#[cfg_attr(not(target_os = "linux"), ignore = "requires node")] +#[test_case("bun")] +#[ignore = "requires node"] #[cfg_attr(not(target_env = "musl"), test_case("deno"))] #[cfg_attr(not(target_env = "musl"), ignore = "requires node")] fn subprocess(runtime: &str) -> anyhow::Result<()> { @@ -204,3 +203,69 @@ fn subprocess(runtime: &str) -> anyhow::Result<()> { assert_contains(&accesses, current_dir().unwrap().join("hello").as_path(), PathAccess::Read); Ok(()) } + +#[test_case("node")] +#[ignore = "requires node"] +#[test_case("bun")] +#[ignore = "requires node"] +#[cfg_attr(not(target_env = "musl"), test_case("deno"))] +#[cfg_attr(not(target_env = "musl"), ignore = "requires node")] +fn fork_ipc(runtime: &str) -> anyhow::Result<()> { + let tmpdir = tempfile::tempdir()?; + let tmp_path = std::fs::canonicalize(tmpdir.path())?; + let data_path = tmp_path.join("data.txt"); + std::fs::write(&data_path, "hello-ipc")?; + let child_path = tmp_path.join("child.cjs"); + std::fs::write( + &child_path, + "const fs = require('node:fs');\n\ + const content = fs.readFileSync(process.argv.at(-1), 'utf8');\n\ + process.send(content, () => { process.disconnect(); });\n", + )?; + let accesses = track_script( + runtime, + "const child = child_process.fork(process.argv.at(-2), [process.argv.at(-1)]); \ + let received = null; \ + child.on('message', (msg) => { received = msg; }); \ + child.on('exit', (code) => { \ + if (code !== 0 || received !== 'hello-ipc') process.exit(1); \ + });", + &[child_path.as_os_str(), data_path.as_os_str()], + )?; + assert_contains(&accesses, &data_path, PathAccess::Read); + Ok(()) +} + +/// `process.title` overwrites the argv strings. The tracked program keeps the +/// kernel's argument strings, so `/proc/self/cmdline` shows the new title, both +/// when spawned directly and after a nested `exec`. +#[cfg(target_os = "linux")] +#[test] +#[ignore = "requires node"] +fn process_title_shows_in_proc_cmdline() -> anyhow::Result<()> { + let (node, path) = resolve_runtime("node")?; + let script = "process.title = 'fspy-title-probe'; \ + const cmdline = require('node:fs').readFileSync('/proc/self/cmdline', 'latin1'); \ + if (!cmdline.startsWith('fspy-title-probe\\0')) { \ + console.error(JSON.stringify(cmdline)); process.exit(1); \ + }"; + for nested in [false, true] { + let mut command = if nested { + let mut command = fspy::Command::new("/bin/sh"); + command.args(["-c", "exec \"$0\" -e \"$1\""]).arg(&node).arg(script); + command + } else { + let mut command = fspy::Command::new(&node); + command.arg("-e").arg(script); + command + }; + command.envs(vars_os()).env("PATH", &path); + tokio::runtime::Runtime::new()?.block_on(async { + let child = command.spawn(tokio_util::sync::CancellationToken::new()).await?; + let termination = child.wait_handle.await?; + assert!(termination.status.success(), "nested={nested}: {:?}", termination.status); + anyhow::Ok(()) + })?; + } + Ok(()) +} diff --git a/crates/fspy/tests/rust_std.rs b/crates/fspy/tests/rust_std.rs index 9bbbc37b4..59adf7b4d 100644 --- a/crates/fspy/tests/rust_std.rs +++ b/crates/fspy/tests/rust_std.rs @@ -217,24 +217,31 @@ async fn syscall_during_dlopen() { // The interposer used to resolve libc's syscall with dlsym, which waits for dlopen, // so a second thread calling syscall waited for the first through futex, re-entering // the interposer until its stack overflowed. - fn call_syscall_during_dlopen(fifo_path: &str) { - // This waits for dlopen to open the FIFO, which it reads until writers close. + // Hold each FIFO writer open across a barrier so `dlopen` cannot read EOF and close + // the FIFO before the other writer calls `open` (which would block forever). + fn call_syscall_during_dlopen(fifo_path: &str, barrier: &std::sync::Barrier) { + // This waits for dlopen to open the FIFO, which it reads until all writers close. let _writer = OpenOptions::new().write(true).open(fifo_path).unwrap(); // SAFETY: getpid takes no arguments. unsafe { libc::syscall(libc::SYS_getpid) }; + barrier.wait(); } // Opening files and spawning threads can also wait for dlopen, so do both first. File::open("/").unwrap(); + let barrier = std::sync::Arc::new(std::sync::Barrier::new(2)); let path = fifo_path.clone(); - std::thread::spawn(move || { + let barrier_clone = std::sync::Arc::clone(&barrier); + let worker = std::thread::spawn(move || { let c = std::ffi::CString::new(path.as_str()).unwrap(); // SAFETY: dlopen fails on the FIFO's empty contents. - std::thread::spawn(move || unsafe { + let loader = std::thread::spawn(move || unsafe { libc::dlopen(c.as_ptr(), libc::RTLD_NOW); }); - call_syscall_during_dlopen(&path); + call_syscall_during_dlopen(&path, &barrier_clone); + loader.join().unwrap(); }); - call_syscall_during_dlopen(&fifo_path); + call_syscall_during_dlopen(&fifo_path, &barrier); + worker.join().unwrap(); }) .await .unwrap(); diff --git a/crates/fspy/tests/shebang.rs b/crates/fspy/tests/shebang.rs index def96b7a1..c0204b694 100644 --- a/crates/fspy/tests/shebang.rs +++ b/crates/fspy/tests/shebang.rs @@ -12,6 +12,21 @@ use test_log::test; use test_utils::assert_contains; use tokio::fs; +/// Coordinates script creation (`O_WRONLY`) against concurrent `fork`/`vfork` +/// spawns across tests in this binary so no sibling spawn briefly inherits a +/// writable script descriptor and triggers a transient Linux `ETXTBSY`. +static SCRIPT_EXEC_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(()); + +async fn write_executable_script( + path: impl AsRef, + content: impl AsRef<[u8]>, +) -> anyhow::Result<()> { + let _write_guard = SCRIPT_EXEC_LOCK.write().await; + fs::write(path.as_ref(), content).await?; + fs::set_permissions(path.as_ref(), std::fs::Permissions::from_mode(0o755)).await?; + Ok(()) +} + #[test(tokio::test)] async fn spawn_sh_shebang() -> anyhow::Result<()> { let tmp_dir = tempfile::TempDir::new()?; @@ -19,12 +34,9 @@ async fn spawn_sh_shebang() -> anyhow::Result<()> { let shebang_script_path = tmp_dir.path().join("fspy_test_shebang_script.sh"); let shebang_script_path = shebang_script_path.into_os_string().into_string().unwrap(); - fs::write(&shebang_script_path, "#!/bin/sh\ncat hello\n").await?; - - let mut perms = fs::metadata(&shebang_script_path).await?.permissions(); - perms.set_mode(0o755); - fs::set_permissions(&shebang_script_path, perms).await?; + write_executable_script(&shebang_script_path, "#!/bin/sh\ncat hello\n").await?; + let _exec_guard = SCRIPT_EXEC_LOCK.read().await; let accesses = track_fn!(shebang_script_path.clone(), |shebang_script_path: String| { let _ignored = Command::new(&shebang_script_path) .current_dir("/") @@ -42,29 +54,30 @@ async fn spawn_sh_shebang() -> anyhow::Result<()> { Ok(()) } -// Skipped on musl: fspy tracks only through seccomp there, which doesn't -// record the interpreter, because the kernel opens it without a syscall. -#[cfg(not(target_env = "musl"))] #[test(tokio::test)] async fn spawn_shebang_with_long_interpreter_path() -> anyhow::Result<()> { let tmp_dir = tempfile::TempDir::new()?; // Kernels read 256 (Linux) or 512 (macOS) bytes of the shebang line, so a - // 200-byte interpreter path must be kept whole. - let mut interpreter = tmp_dir.path().to_path_buf(); - while interpreter.as_os_str().len() < 150 { - interpreter.push("d".repeat(40)); + // 200-byte interpreter path must be kept whole. Keep the symlink basename + // `sh` so multi-call binaries like Alpine's BusyBox `/bin/sh` dispatch to + // the `sh` applet. + let mut dir = tmp_dir.path().to_path_buf(); + while dir.as_os_str().len() < 150 { + dir.push("d".repeat(40)); } - fs::create_dir_all(&interpreter).await?; - interpreter.push("x".repeat(200 - interpreter.as_os_str().len() - 1)); + dir.push("d".repeat(200 - "/sh".len() - dir.as_os_str().len() - 1)); + fs::create_dir_all(&dir).await?; + let interpreter = dir.join("sh"); assert_eq!(interpreter.as_os_str().len(), 200); fs::symlink("/bin/sh", &interpreter).await?; let script_path = tmp_dir.path().join("long_shebang.sh"); - fs::write(&script_path, format!("#!{}\necho ok\n", interpreter.display())).await?; - fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o755)).await?; + write_executable_script(&script_path, format!("#!{}\necho ok\n", interpreter.display())) + .await?; let script_path = script_path.into_os_string().into_string().unwrap(); + let _exec_guard = SCRIPT_EXEC_LOCK.read().await; let accesses = track_fn!(script_path, |script_path: String| { let output = Command::new(&script_path).stdin(Stdio::null()).output(); // On macOS, fspy only swaps the arm64e `/bin/sh` for its own shell when @@ -87,3 +100,164 @@ async fn spawn_shebang_with_long_interpreter_path() -> anyhow::Result<()> { Ok(()) } + +/// macOS splits shebang arguments on whitespace; Linux passes everything after +/// the interpreter as a single argument. +#[test(tokio::test)] +async fn shebang_argument_splitting_matches_platform() -> anyhow::Result<()> { + let tmp_dir = tempfile::TempDir::new()?; + let script_path = tmp_dir.path().canonicalize()?.join("split_args.sh"); + write_executable_script(&script_path, "#!/bin/echo foo bar\n").await?; + let script_str = script_path.to_str().unwrap().to_owned(); + + let expected = if cfg!(target_os = "macos") { + format!("foo bar {script_str}\n") + } else { + format!("foo bar {script_str}\n") + }; + let _exec_guard = SCRIPT_EXEC_LOCK.read().await; + let untraced = Command::new(&script_str).stdin(Stdio::null()).output()?; + assert!(untraced.status.success()); + assert_eq!(String::from_utf8_lossy(&untraced.stdout), expected); + + let args = (script_str, expected); + let accesses = track_fn!(args, |(script_str, expected): (String, String)| { + let output = Command::new(&script_str) + .stdin(Stdio::null()) + .output() + .expect("Failed to execute shebang script"); + assert!(output.status.success()); + assert_eq!(String::from_utf8_lossy(&output.stdout), expected); + }) + .await?; + + assert_contains(&accesses, &script_path, PathAccess::Read); + + Ok(()) +} + +/// Chained shebang depth limits: Linux allows 5 hops and rejects the 6th with +/// `ELOOP`; macOS allows 1 hop and rejects the 2nd with `ENOEXEC`. +#[test(tokio::test)] +async fn chained_shebang_depth_matches_platform() -> anyhow::Result<()> { + let tmp_dir = tempfile::TempDir::new()?; + let root = tmp_dir.path().canonicalize()?; + + let mut scripts = Vec::new(); + let base = root.join("hop1.sh"); + write_executable_script(&base, "#!/bin/sh\necho chained-ok\n").await?; + scripts.push(base); + + let max_hops = if cfg!(target_os = "macos") { 2 } else { 6 }; + for i in 2..=max_hops { + let prev = scripts.last().unwrap(); + let next = root.join(format!("hop{i}.sh")); + write_executable_script(&next, format!("#!{}\n", prev.display())).await?; + scripts.push(next); + } + + let max_ok = scripts[scripts.len() - 2].to_str().unwrap().to_owned(); + let too_deep = scripts[scripts.len() - 1].to_str().unwrap().to_owned(); + let expected_errno = if cfg!(target_os = "macos") { libc::ENOEXEC } else { libc::ELOOP }; + + let args = (max_ok, too_deep, expected_errno); + let _exec_guard = SCRIPT_EXEC_LOCK.read().await; + let accesses = + track_fn!(args, |(max_ok, too_deep, expected_errno): (String, String, libc::c_int)| { + let output = Command::new(&max_ok) + .stdin(Stdio::null()) + .output() + .expect("max allowed shebang depth should succeed"); + assert!(output.status.success()); + assert_eq!(output.stdout, b"chained-ok\n"); + + let err = Command::new(&too_deep) + .stdin(Stdio::null()) + .status() + .expect_err("exceeding shebang recursion depth should fail"); + assert_eq!(err.raw_os_error(), Some(expected_errno)); + }) + .await?; + + for script in &scripts { + assert_contains(&accesses, script, PathAccess::Read); + } + + Ok(()) +} + +/// A shebang line exceeding the kernel's buffer limit must fail with `ENOEXEC`. +#[test(tokio::test)] +async fn overlong_shebang_is_rejected_with_enoexec() -> anyhow::Result<()> { + fn posix_spawn_errno(path: &std::ffi::CStr) -> libc::c_int { + let argv = [path.as_ptr().cast_mut(), std::ptr::null_mut()]; + let envp = [std::ptr::null_mut::()]; + let mut pid: libc::pid_t = 0; + // SAFETY: `path`, `argv`, and `envp` are valid NUL/NULL-terminated. + let rc = unsafe { + libc::posix_spawn( + &raw mut pid, + path.as_ptr(), + std::ptr::null(), + std::ptr::null(), + argv.as_ptr(), + envp.as_ptr(), + ) + }; + if rc == 0 { + let mut status = 0; + // SAFETY: reap unexpected child. + unsafe { libc::waitpid(pid, &raw mut status, 0) }; + } + rc + } + + let tmp_dir = tempfile::TempDir::new()?; + let script_path = tmp_dir.path().canonicalize()?.join("overlong.sh"); + // Longer than both Linux's 256-byte and macOS's 512-byte kernel buffers. + let content = format!("#!/{}\n", "a".repeat(520)); + write_executable_script(&script_path, content).await?; + let script_str = script_path.to_str().unwrap().to_owned(); + + // Use `posix_spawn` directly: `posix_spawnp` (used by `std::process::Command`) + // falls back to `/bin/sh` on `ENOEXEC` on macOS. + let c_script = std::ffi::CString::new(script_str.as_str())?; + let _exec_guard = SCRIPT_EXEC_LOCK.read().await; + assert_eq!(posix_spawn_errno(&c_script), libc::ENOEXEC); + + let accesses = track_fn!(script_str, |script_str: String| { + let c_script = std::ffi::CString::new(script_str.as_str()).unwrap(); + assert_eq!(posix_spawn_errno(&c_script), libc::ENOEXEC); + }) + .await?; + + assert_contains(&accesses, &script_path, PathAccess::Read); + + Ok(()) +} + +/// Executing a FIFO must not block (opened with `O_NONBLOCK`) and must fail +/// with `EACCES`, matching the kernel's `execve`. +#[test(tokio::test)] +async fn exec_fifo_does_not_block_and_returns_eacces() -> anyhow::Result<()> { + let tmp_dir = tempfile::TempDir::new()?; + let fifo_path = tmp_dir.path().canonicalize()?.join("exec_fifo"); + let fifo_cstr = std::ffi::CString::new(fifo_path.to_str().unwrap())?; + // SAFETY: `fifo_cstr` is a valid NUL-terminated path. + assert_eq!(unsafe { libc::mkfifo(fifo_cstr.as_ptr(), 0o755) }, 0); + let fifo_str = fifo_path.to_str().unwrap().to_owned(); + + let _exec_guard = SCRIPT_EXEC_LOCK.read().await; + let untraced_err = Command::new(&fifo_str).stdin(Stdio::null()).status().unwrap_err(); + assert_eq!(untraced_err.raw_os_error(), Some(libc::EACCES)); + + let accesses = track_fn!(fifo_str, |fifo_str: String| { + let err = Command::new(&fifo_str).stdin(Stdio::null()).status().unwrap_err(); + assert_eq!(err.raw_os_error(), Some(libc::EACCES)); + }) + .await?; + + assert_contains(&accesses, &fifo_path, PathAccess::Read); + + Ok(()) +} diff --git a/crates/fspy/tests/spawn_errors.rs b/crates/fspy/tests/spawn_errors.rs new file mode 100644 index 000000000..79aaf2c2d --- /dev/null +++ b/crates/fspy/tests/spawn_errors.rs @@ -0,0 +1,106 @@ +//! Top-level spawn error handling across Unix platforms (Linux `Target::Unresolved` +//! and macOS `EncodedPayload::prepare_exec`). +#![cfg(unix)] + +use std::{fs, os::unix::fs::PermissionsExt as _}; + +use fspy::error::SpawnError; +use test_log::test; +use tokio_util::sync::CancellationToken; + +fn assert_os_spawn_errno(result: Result, expected_errno: i32) { + match result { + Err(SpawnError::OsSpawn(err)) => { + assert_eq!( + err.raw_os_error(), + Some(expected_errno), + "expected errno {expected_errno}, got {err:?}" + ); + } + Err(other) => panic!("expected SpawnError::OsSpawn({expected_errno}), got {other:?}"), + Ok(_) => panic!("expected SpawnError::OsSpawn({expected_errno}), but spawn succeeded"), + } +} + +#[test(tokio::test)] +async fn top_level_spawn_exec_errors_return_os_spawn_with_expected_errno() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + + // 1a. Malformed/empty shebang and overlong shebang -> ENOEXEC (rejected during + // exec preparation on both Linux and macOS). + let malformed_shebang = root.join("malformed_shebang.sh"); + fs::write(&malformed_shebang, "#!\n")?; + fs::set_permissions(&malformed_shebang, fs::Permissions::from_mode(0o755))?; + assert_os_spawn_errno( + fspy::Command::new(&malformed_shebang).spawn(CancellationToken::new()).await, + libc::ENOEXEC, + ); + + let overlong_shebang = root.join("overlong_shebang.sh"); + fs::write(&overlong_shebang, format!("#!/{}\n", "a".repeat(520)))?; + fs::set_permissions(&overlong_shebang, fs::Permissions::from_mode(0o755))?; + assert_os_spawn_errno( + fspy::Command::new(&overlong_shebang).spawn(CancellationToken::new()).await, + libc::ENOEXEC, + ); + + // 1b. Shebang-less executable -> ENOEXEC on Linux (`fspy_preload_linux` uses + // raw `execve`, which does not fall back to `/bin/sh`, unlike macOS + // `posix_spawnp` / `execvp` used by `tokio::process::Command`). + #[cfg(target_os = "linux")] + { + let shebangless = root.join("shebangless"); + fs::write(&shebangless, "not a binary or shebang script\n")?; + fs::set_permissions(&shebangless, fs::Permissions::from_mode(0o755))?; + assert_os_spawn_errno( + fspy::Command::new(&shebangless).spawn(CancellationToken::new()).await, + libc::ENOEXEC, + ); + } + + // 2. Script with missing interpreter -> ENOENT + let missing_interp = root.join("missing_interp.sh"); + fs::write(&missing_interp, "#!/nonexistent/fspy_missing_interpreter\n")?; + fs::set_permissions(&missing_interp, fs::Permissions::from_mode(0o755))?; + assert_os_spawn_errno( + fspy::Command::new(&missing_interp).spawn(CancellationToken::new()).await, + libc::ENOENT, + ); + + // 3. Non-executable (0o644) file as shebang interpreter -> EACCES + let non_exec = root.join("non_exec_file"); + fs::write(&non_exec, "plain file\n")?; + fs::set_permissions(&non_exec, fs::Permissions::from_mode(0o644))?; + let script_non_exec = root.join("via_non_exec.sh"); + fs::write(&script_non_exec, format!("#!{}\n", non_exec.display()))?; + fs::set_permissions(&script_non_exec, fs::Permissions::from_mode(0o755))?; + assert_os_spawn_errno( + fspy::Command::new(&script_non_exec).spawn(CancellationToken::new()).await, + libc::EACCES, + ); + + // 4. Directory as shebang interpreter -> EACCES + let dir_target = root.join("a_directory"); + fs::create_dir(&dir_target)?; + let script_dir = root.join("via_dir.sh"); + fs::write(&script_dir, format!("#!{}\n", dir_target.display()))?; + fs::set_permissions(&script_dir, fs::Permissions::from_mode(0o755))?; + assert_os_spawn_errno( + fspy::Command::new(&script_dir).spawn(CancellationToken::new()).await, + libc::EACCES, + ); + + // Direct top-level spawns of a non-executable 0o644 file or a directory are + // rejected during `resolve_program()` with `SpawnError::Which`. + assert!(matches!( + fspy::Command::new(&non_exec).spawn(CancellationToken::new()).await, + Err(SpawnError::Which { .. }) + )); + assert!(matches!( + fspy::Command::new(&dir_target).spawn(CancellationToken::new()).await, + Err(SpawnError::Which { .. }) + )); + + Ok(()) +} diff --git a/crates/fspy/tests/static_executable.rs b/crates/fspy/tests/static_executable.rs index 9de887a03..330a26bbe 100644 --- a/crates/fspy/tests/static_executable.rs +++ b/crates/fspy/tests/static_executable.rs @@ -1,8 +1,5 @@ -//! Tests for fspy tracing of statically-linked executables (seccomp path). -//! Skipped on musl: the test binary is an artifact dep targeting musl, and when -//! the CI builds with `-crt-static` the binary becomes dynamically linked, -//! defeating the purpose of these tests. -#![cfg(all(target_os = "linux", not(target_env = "musl")))] +//! Tests for fspy tracing of statically-linked executables on Linux. +#![cfg(target_os = "linux")] use std::path::Path; use fspy::PathAccessIterable; diff --git a/crates/fspy/tests/test_utils/mod.rs b/crates/fspy/tests/test_utils/mod.rs index e8ded0561..2b26be639 100644 --- a/crates/fspy/tests/test_utils/mod.rs +++ b/crates/fspy/tests/test_utils/mod.rs @@ -162,8 +162,8 @@ pub async fn spawn_command(cmd: vt_subprocess_test::Command) -> anyhow::Result

&'static Path { sync::LazyLock, }; - use fspy_shared_unix::is_dynamically_linked_to_libc; - const TEST_BIN_CONTENT: &[u8] = include_bytes!(env!("CARGO_BIN_FILE_FSPY_TEST_BIN")); static TEST_BIN_PATH: LazyLock = LazyLock::new(|| { - assert_eq!( - is_dynamically_linked_to_libc(TEST_BIN_CONTENT), - Ok(false), - "Test binary is not a static executable" - ); - - let test_bin_path = PathBuf::from(env!("CARGO_TARGET_TMPDIR")) - .join(concat!("fspy-test-bin-", env!("CARGO_CRATE_NAME"))); - fs::write(&test_bin_path, TEST_BIN_CONTENT).expect("failed to write test binary"); - fs::set_permissions(&test_bin_path, Permissions::from_mode(0o755)) + let dir = + std::env::var_os("CARGO_TARGET_TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from); + let test_bin_path = dir.join(concat!("fspy-test-bin-", env!("CARGO_CRATE_NAME"))); + let tmp_path = dir.join(format!( + "fspy-test-bin-{}-{}.tmp", + env!("CARGO_CRATE_NAME"), + std::process::id() + )); + fs::write(&tmp_path, TEST_BIN_CONTENT).expect("failed to write test binary"); + fs::set_permissions(&tmp_path, Permissions::from_mode(0o755)) .expect("failed to set permissions on test binary"); + fs::rename(&tmp_path, &test_bin_path).expect("failed to install test binary"); test_bin_path }); diff --git a/crates/fspy/tests/untracked_fallback.rs b/crates/fspy/tests/untracked_fallback.rs index c3e95b94b..8cdc19e53 100644 --- a/crates/fspy/tests/untracked_fallback.rs +++ b/crates/fspy/tests/untracked_fallback.rs @@ -1,128 +1,323 @@ -//! Tests for the untracked-exec fallback: when the preload cannot install -//! the seccomp filter, the exec must proceed untracked and the run must be -//! reported as incompletely tracked (so it is not cached), rather than -//! every spawn failing. Skipped on musl: no preload library exists there. -#![cfg(all(target_os = "linux", not(target_env = "musl")))] +//! Tests for Linux untracked fallback and authentic exec errors: +//! - When `seccomp` is blocked by an outer sandbox, `fspy` runs commands +//! untracked and reports `Err(TrackingIncomplete)` rather than failing every +//! spawn. +//! - Authentic exec errors (such as `ENOEXEC` on a script without a `#!` line) +//! propagate normally and keep the trace complete. +#![cfg(target_os = "linux")] use std::{ - ffi::OsStr, fs::{self, Permissions}, - os::unix::{ffi::OsStrExt as _, fs::PermissionsExt as _}, - path::{Path, PathBuf}, - process::Command, + mem::offset_of, + os::unix::fs::PermissionsExt as _, + process::Stdio, }; -use allocator_api2::alloc::Global; -use fspy_seccomp_unotify::payload::SeccompPayload; -use fspy_shared::ipc::{ - IpcStr, - channel::{Receiver, RecordsLost, channel}, +use fspy::TrackingIncomplete; +use linux_raw_sys::{ + errno::{EIO, EPERM}, + prctl::PR_SET_NO_NEW_PRIVS, + ptrace::{ + BPF_ABS, BPF_JEQ, BPF_JMP, BPF_K, BPF_LD, BPF_RET, BPF_W, SECCOMP_RET_ALLOW, + SECCOMP_RET_DATA, SECCOMP_RET_ERRNO, SECCOMP_SET_MODE_FILTER, seccomp_data, sock_filter, + sock_fprog, + }, }; -use fspy_shared_unix::payload::{Payload, encode_payload}; - -use crate::test_utils::test_bin_path; - -mod test_utils; - -/// The preload cdylib, built as a dependency of this crate. -const PRELOAD_CDYLIB: &str = env!("CARGO_CDYLIB_FILE_FSPY_PRELOAD_UNIX"); - -/// Clears `command`'s environment and preloads fspy into it with a seccomp -/// payload whose install always fails. Returns the channel the preload -/// reports to. -fn preload_with_failing_seccomp(command: &mut Command) -> Receiver { - let receiver = channel(1 << 30, Global).unwrap(); - { - let preload_path: &IpcStr = Path::new(PRELOAD_CDYLIB).into(); - let payload = Payload { - ipc_channel_conf: receiver.conf(), - preload_path, - seccomp_payload: SeccompPayload::unreachable( - b"/nonexistent/fspy-unreachable-supervisor".to_vec(), - ), - }; - let bump = bumpalo::Bump::new(); - let encoded = encode_payload(payload, &bump); - command - .env_clear() - .env("LD_PRELOAD", PRELOAD_CDYLIB) - .env("FSPY_PAYLOAD", OsStr::from_bytes(encoded.encoded_string.as_ref())); - } - receiver -} +use syscalls::Sysno; +use test_log::test; +use tokio::io::AsyncReadExt as _; +use tokio_util::sync::CancellationToken; +use vt_subprocess_test::command_for_fn; -/// A static binary exec'd from a traced process needs the preload's inline -/// seccomp install. When that install fails (here: the payload's empty -/// filter, which the kernel refuses), the binary must still run — untracked -/// — and the channel must report the loss. -#[test] -fn static_binary_runs_untracked_when_injection_fails() { - let mut command = Command::new("/bin/sh"); - let receiver = preload_with_failing_seccomp(&mut command); - let output = command - .arg("-c") - .arg(format!("exec {} stat /hello", test_bin_path().display())) - .output() - .expect("failed to spawn the shell"); +/// An authentic exec error (`ENOEXEC` for a script without a `#!` line) keeps +/// its errno and leaves the trace complete so `/bin/sh` runs the script itself, +/// as it does without tracking. +#[test(tokio::test)] +async fn exec_errors_are_not_reported_as_lost() { + let dir = tempfile::tempdir().expect("failed to create temp dir"); + let script = dir.path().join("fspy-script-without-shebang"); + fs::write(&script, "exit 0\n").expect("failed to write the script"); + fs::set_permissions(&script, Permissions::from_mode(0o755)) + .expect("failed to set permissions on the script"); + + let mut command = fspy::Command::new("/bin/sh"); + command.arg("-c").arg(script.as_os_str()).stdin(Stdio::null()); + let tracked = command.spawn(CancellationToken::new()).await.expect("failed to spawn /bin/sh"); + let termination = tracked.wait_handle.await.expect("failed to wait for /bin/sh"); + assert!(termination.status.success(), "the script without a shebang did not run"); assert!( - output.status.success(), - "the static binary did not run: {}", - String::from_utf8_lossy(&output.stderr) + termination.path_accesses.is_ok(), + "an authentic exec error was reported as an untracked exec" ); - - let Err(RecordsLost) = receiver.close() else { - panic!("the channel did not report the untracked exec"); - }; } -/// The untracked fallback must replay the interposed call as it was made, -/// not as `execve`. GNU `env` runs its command through `execvp`, so a bare -/// program name found only on `PATH` still runs when injection fails; -/// forwarding it to `execve` would fail with `ENOENT` instead. +/// When an outer sandbox blocks `SYS_seccomp` with `EPERM`, `fspy` detects +/// this during initialization, runs spawned commands untracked, and reports +/// `Err(TrackingIncomplete)` so callers do not cache partial traces. #[test] -fn execvp_fallback_keeps_path_search() { - let test_bin = test_bin_path(); - let mut command = Command::new("/usr/bin/env"); - let receiver = preload_with_failing_seccomp(&mut command); - let output = command - .arg(test_bin.file_name().unwrap()) - .arg("stat") - .arg("/hello") - .env("PATH", test_bin.parent().unwrap()) - .current_dir("/") - .output() - .expect("failed to spawn env"); +fn seccomp_blocked_sandbox_falls_back_to_untracked() { + let cmd = command_for_fn!((), |()| { + #[expect( + clippy::cast_possible_truncation, + reason = "cBPF opcodes and offsets fit in u16/u32" + )] + let filter = [ + sock_filter { + code: (BPF_LD | BPF_W | BPF_ABS) as u16, + jt: 0, + jf: 0, + k: offset_of!(seccomp_data, nr) as u32, + }, + sock_filter { + code: (BPF_JMP | BPF_JEQ | BPF_K) as u16, + jt: 0, + jf: 1, + k: Sysno::seccomp as u32, + }, + sock_filter { + code: (BPF_RET | BPF_K) as u16, + jt: 0, + jf: 0, + k: SECCOMP_RET_ERRNO | (EPERM & SECCOMP_RET_DATA), + }, + sock_filter { code: (BPF_RET | BPF_K) as u16, jt: 0, jf: 0, k: SECCOMP_RET_ALLOW }, + ]; + let prog = sock_fprog { len: 4, filter: filter.as_ptr().cast_mut() }; + // SAFETY: installs a valid 4-instruction seccomp filter on this test subprocess. + unsafe { + syscalls::syscall!(Sysno::prctl, PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0).unwrap(); + syscalls::syscall!(Sysno::seccomp, SECCOMP_SET_MODE_FILTER, 0, &raw const prog) + .unwrap(); + } + + let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); + rt.block_on(async { + let mut command = fspy::Command::new("/bin/echo"); + command.arg("sandbox-ok").stdout(Stdio::piped()).stdin(Stdio::null()); + let mut tracked = command + .spawn(CancellationToken::new()) + .await + .expect("sandboxed spawn should fall back untracked"); + let mut stdout = Vec::new(); + tracked.stdout.take().unwrap().read_to_end(&mut stdout).await.unwrap(); + let termination = tracked.wait_handle.await.unwrap(); + assert!(termination.status.success()); + assert_eq!(stdout, b"sandbox-ok\n"); + assert!(matches!(termination.path_accesses, Err(TrackingIncomplete))); + }); + }); + + let output = std::process::Command::from(cmd).output().expect("failed to run sandbox test"); assert!( output.status.success(), - "the execvp fallback lost its PATH search: {}", - String::from_utf8_lossy(&output.stderr) + "sandboxed subprocess failed: stdout={}, stderr={}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), ); +} + +/// When a descriptor-relative path can't be resolved (here because the program +/// fails `readlinkat`, which resolving its directory descriptor needs, with +/// `EIO`), the access still happens, so the trace is reported incomplete +/// instead of complete without it. +#[test(tokio::test)] +async fn unresolvable_relative_path_reports_tracking_incomplete() { + let dir = tempfile::tempdir().expect("failed to create temp dir"); + fs::write(dir.path().join("input"), "data").expect("failed to write input"); + let cmd = command_for_fn!(dir.path().to_str().unwrap().to_owned(), |dir: String| { + use std::os::fd::AsRawFd as _; + + let dir = fs::File::open(dir).unwrap(); + deny_syscalls(&[(Sysno::readlinkat, EIO)]); + // SAFETY: valid directory descriptor and NUL-terminated relative path. + let fd = unsafe { libc::openat(dir.as_raw_fd(), c"input".as_ptr(), libc::O_RDONLY) }; + assert!(fd >= 0, "openat(dirfd, input) failed"); + }); + let tracked = fspy::Command::from(cmd) + .spawn(CancellationToken::new()) + .await + .expect("failed to spawn the child"); + let termination = tracked.wait_handle.await.expect("failed to wait for the child"); + assert!(termination.status.success(), "the child failed: {:?}", termination.status); + assert!(matches!(termination.path_accesses, Err(TrackingIncomplete))); +} - let Err(RecordsLost) = receiver.close() else { - panic!("the channel did not report the untracked exec"); +/// A sandbox that answers filesystem syscalls with `EPERM`, as Chromium's +/// renderer policy does, also denies the lookups that resolve relative paths +/// and descriptors. The program's own path lookups fail the same way, so the +/// trace stays complete instead of reporting a loss. +#[test(tokio::test)] +async fn sandbox_denied_lookups_keep_the_trace_complete() { + let dir = tempfile::tempdir().expect("failed to create temp dir"); + fs::write(dir.path().join("input"), "data").expect("failed to write input"); + let cmd = command_for_fn!(dir.path().to_str().unwrap().to_owned(), |dir: String| { + use std::os::fd::AsRawFd as _; + + std::env::set_current_dir(dir).unwrap(); + let file = fs::File::open("input").unwrap(); + deny_syscalls(&[ + (Sysno::getcwd, EPERM), + (Sysno::openat, EPERM), + (Sysno::readlinkat, EPERM), + ]); + // SAFETY: NUL-terminated relative path. + let fd = unsafe { libc::openat(libc::AT_FDCWD, c"input".as_ptr(), libc::O_RDONLY) }; + let err = std::io::Error::last_os_error(); + assert!(fd < 0 && err.raw_os_error() == Some(EPERM.cast_signed()), "{err}"); + let mut stat = std::mem::MaybeUninit::::uninit(); + // SAFETY: open descriptor, empty NUL-terminated path, writable `stat`. + let rc = unsafe { + libc::fstatat(file.as_raw_fd(), c"".as_ptr(), stat.as_mut_ptr(), libc::AT_EMPTY_PATH) + }; + assert_eq!(rc, 0, "{}", std::io::Error::last_os_error()); + }); + let tracked = fspy::Command::from(cmd) + .spawn(CancellationToken::new()) + .await + .expect("failed to spawn the child"); + let termination = tracked.wait_handle.await.expect("failed to wait for the child"); + assert!(termination.status.success(), "the child failed: {:?}", termination.status); + assert!(termination.path_accesses.is_ok(), "sandbox-denied lookups were reported as a loss"); +} + +/// Installs a seccomp filter that fails each listed syscall with its errno +/// and allows every other one. +#[expect(clippy::cast_possible_truncation, reason = "cBPF opcodes and offsets fit in u16/u32")] +fn deny_syscalls(denied: &[(Sysno, u32)]) { + let load_nr = sock_filter { + code: (BPF_LD | BPF_W | BPF_ABS) as u16, + jt: 0, + jf: 0, + k: offset_of!(seccomp_data, nr) as u32, }; + let mut filter = vec![load_nr]; + for &(sysno, errno) in denied { + filter.push(sock_filter { + code: (BPF_JMP | BPF_JEQ | BPF_K) as u16, + jt: 0, + jf: 1, + k: sysno as u32, + }); + filter.push(sock_filter { + code: (BPF_RET | BPF_K) as u16, + jt: 0, + jf: 0, + k: SECCOMP_RET_ERRNO | (errno & SECCOMP_RET_DATA), + }); + } + filter.push(sock_filter { code: (BPF_RET | BPF_K) as u16, jt: 0, jf: 0, k: SECCOMP_RET_ALLOW }); + let prog = + sock_fprog { len: u16::try_from(filter.len()).unwrap(), filter: filter.as_mut_ptr() }; + // SAFETY: installs a valid seccomp filter on this tracked process, which + // already runs with `no_new_privs`. + unsafe { + syscalls::syscall!(Sysno::prctl, PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0).unwrap(); + syscalls::syscall!(Sysno::seccomp, SECCOMP_SET_MODE_FILTER, 0, &raw const prog).unwrap(); + } +} + +/// An exec whose relative path can't be resolved (here under a working +/// directory longer than `PATH_MAX`) still runs, and the trace is reported +/// incomplete instead of complete without the executable. +#[test(tokio::test)] +async fn unresolvable_exec_path_reports_tracking_incomplete() { + const DEPTH: usize = 30; // 30 nested 200-byte components exceed `PATH_MAX`. + let component = "d".repeat(200); + let dir = tempfile::tempdir().expect("failed to create temp dir"); + // Build the tree untracked; tracked `mkdir`s there would report a loss too. + let args = (dir.path().to_str().unwrap().to_owned(), component); + let build = command_for_fn!(args.clone(), |(dir, component): (String, String)| { + std::env::set_current_dir(dir).unwrap(); + for _ in 0..DEPTH { + fs::create_dir(&component).unwrap(); + std::env::set_current_dir(&component).unwrap(); + } + std::os::unix::fs::symlink("/bin/true", "child").unwrap(); + }); + let status = std::process::Command::from(build).status().expect("failed to build the tree"); + assert!(status.success()); + + let cmd = command_for_fn!(args, |(dir, component): (String, String)| { + // `chdir` isn't tracked, so only the exec below meets the deep cwd. + std::env::set_current_dir(dir).unwrap(); + for _ in 0..DEPTH { + std::env::set_current_dir(&component).unwrap(); + } + // SAFETY: `fork` is followed by `execv` or `_exit` in the child. + let pid = unsafe { libc::fork() }; + if pid == 0 { + // busybox `true` (Alpine) picks its applet from `argv[0]`. + let argv = [c"true".as_ptr(), std::ptr::null()]; + // SAFETY: valid NUL-terminated path and NULL-terminated argv. + unsafe { libc::execv(c"./child".as_ptr(), argv.as_ptr()) }; + // SAFETY: the exec failed; end the forked child. + unsafe { libc::_exit(127) }; + } + let mut status = 0; + // SAFETY: `pid` is our child and `status` is writable. + assert_eq!(unsafe { libc::waitpid(pid, &raw mut status, 0) }, pid); + assert!(libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, "{status:#x}"); + }); + let tracked = fspy::Command::from(cmd) + .spawn(CancellationToken::new()) + .await + .expect("failed to spawn the deep-cwd child"); + let termination = tracked.wait_handle.await.expect("failed to wait for the deep-cwd child"); + assert!(termination.status.success(), "the deep-cwd child failed: {:?}", termination.status); + assert!(matches!(termination.path_accesses, Err(TrackingIncomplete))); +} + +/// After the working directory is unlinked, a relative access through `..` +/// still succeeds while its path can't be resolved, so the trace is reported +/// incomplete. +#[test(tokio::test)] +async fn access_from_deleted_cwd_reports_tracking_incomplete() { + let dir = tempfile::tempdir().expect("failed to create temp dir"); + fs::write(dir.path().join("input"), "data").expect("failed to write input"); + let cmd = command_for_fn!(dir.path().to_str().unwrap().to_owned(), |dir: String| { + std::env::set_current_dir(dir).unwrap(); + fs::create_dir("gone").unwrap(); + std::env::set_current_dir("gone").unwrap(); + fs::remove_dir("../gone").unwrap(); + assert_eq!(fs::read("../input").unwrap(), b"data"); + }); + let tracked = fspy::Command::from(cmd) + .spawn(CancellationToken::new()) + .await + .expect("failed to spawn the child"); + let termination = tracked.wait_handle.await.expect("failed to wait for the child"); + assert!(termination.status.success(), "the child failed: {:?}", termination.status); + assert!(matches!(termination.path_accesses, Err(TrackingIncomplete))); } -/// Only a failed seccomp install takes the untracked path. An exec that -/// fails the way the real exec would, here `ENOEXEC` for a script without a -/// `#!` line, keeps its errno and leaves the trace complete. `sh` then runs -/// the script itself, as it does without tracking. +/// A relative `TMPDIR` names the launcher relative to the parent's directory, +/// so tracked processes that change directory keep executing commands. #[test] -fn exec_errors_are_not_reported_as_lost() { - let script = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("fspy-script-without-shebang"); - fs::write(&script, "exit 0\n").expect("failed to write the script"); - fs::set_permissions(&script, Permissions::from_mode(0o755)) - .expect("failed to set permissions on the script"); +fn relative_temp_dir_survives_cd_in_tracked_process() { + let tmp_dir = tempfile::tempdir().expect("failed to create temp dir"); + let cmd = command_for_fn!(tmp_dir.path().to_str().unwrap().to_owned(), |dir: String| { + std::env::set_current_dir(&dir).unwrap(); + fs::create_dir("relativetmp").unwrap(); + fs::create_dir("child").unwrap(); + // SAFETY: this test subprocess is still single-threaded, and `fspy` + // reads `TMPDIR` only on first spawn. + unsafe { std::env::set_var("TMPDIR", "relativetmp") }; - let mut command = Command::new("/bin/sh"); - let receiver = preload_with_failing_seccomp(&mut command); - let output = - command.arg("-c").arg(script.as_os_str()).output().expect("failed to spawn the shell"); + let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); + rt.block_on(async { + let mut command = fspy::Command::new("/bin/sh"); + command.args(["-c", "cd child && /bin/true"]).stdin(Stdio::null()); + let tracked = command.spawn(CancellationToken::new()).await.unwrap(); + let termination = tracked.wait_handle.await.unwrap(); + assert!(termination.status.success(), "{:?}", termination.status); + }); + }); + + let output = std::process::Command::from(cmd).output().expect("failed to run TMPDIR test"); assert!( output.status.success(), - "the script without a shebang did not run: {}", - String::from_utf8_lossy(&output.stderr) + "relative TMPDIR subprocess failed: stdout={}, stderr={}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), ); - - assert!(receiver.close().is_ok(), "an authentic exec error was reported as an untracked exec"); } diff --git a/crates/fspy_benchmark/README.md b/crates/fspy_benchmark/README.md index 7d722b214..61183a9bf 100644 --- a/crates/fspy_benchmark/README.md +++ b/crates/fspy_benchmark/README.md @@ -5,7 +5,7 @@ Measures what fspy costs a process it tracks, and whether a change to fspy moved - `launch`: the wall clock of a tracked launch that opens nothing. This is the cost of starting a process under tracking: injection, session setup, and teardown. - `access`: how long a batch of opens takes, timed by two threads that each open their own path. This is the cost of interception itself, under the concurrency a tracked process normally has. -Linux measures a dynamically linked target (`LD_PRELOAD`) and a `x86_64-unknown-linux-musl` target (seccomp user notification). macOS measures `DYLD_INSERT_LIBRARIES`. Windows measures Detours injection. +Linux measures both a dynamically linked target and a static `x86_64-unknown-linux-musl` target through the freestanding ELF/`SIGSYS` tracker. macOS measures `DYLD_INSERT_LIBRARIES`. Windows measures Detours injection. Run the overhead report locally with: diff --git a/crates/fspy_client_unix/Cargo.toml b/crates/fspy_client_unix/Cargo.toml deleted file mode 100644 index c0b9da26a..000000000 --- a/crates/fspy_client_unix/Cargo.toml +++ /dev/null @@ -1,26 +0,0 @@ -[package] -name = "fspy_client_unix" -edition = "2024" -license.workspace = true -publish = false - -[target.'cfg(all(unix, not(target_env = "musl")))'.dependencies] -allocator-api2 = { workspace = true, features = ["alloc"] } -anyhow = { workspace = true } -bstr = { workspace = true, features = ["alloc", "std"] } -fspy_shared = { workspace = true } -fspy_shared_unix = { workspace = true } -libc = { workspace = true } -nix = { workspace = true, features = ["fs"] } -fspy_nostd = { workspace = true } -fspy_nostd_alloc = { workspace = true } - -[target.'cfg(all(target_os = "linux", not(target_env = "musl")))'.dependencies] -itoa = { workspace = true } - -[lints] -workspace = true - -[lib] -doctest = false -test = false diff --git a/crates/fspy_client_unix/README.md b/crates/fspy_client_unix/README.md deleted file mode 100644 index 6839cc9f2..000000000 --- a/crates/fspy_client_unix/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# fspy_client_unix - -The Unix client that resolves and reports file accesses to the fspy supervisor. - -The preload library owns interception-specific initialization and re-entry -guards. This crate owns the reusable client, path conversion, and exec -transformation so another Unix injection mechanism can provide its own runtime -integration around the same client. diff --git a/crates/fspy_client_unix/src/convert.rs b/crates/fspy_client_unix/src/convert.rs deleted file mode 100644 index 6b3e72c93..000000000 --- a/crates/fspy_client_unix/src/convert.rs +++ /dev/null @@ -1,239 +0,0 @@ -use std::ffi::CStr; - -use allocator_api2::{alloc::Allocator, vec::Vec}; -use bstr::ByteSlice; -use fspy_nostd::{BorrowedFd, CWD}; -use fspy_shared::ipc::AccessMode; -use libc::{c_char, c_int}; - -#[cfg(target_os = "linux")] -fn get_fd_path(allocator: A, fd: BorrowedFd<'_>) -> nix::Result>> { - if fd.as_raw_fd() == CWD.as_raw_fd() { - let path = fspy_nostd_alloc::fs::getcwd(allocator) - .map_err(|errno| nix::errno::Errno::from_raw(errno.raw_os_error()))? - .into_units(); - return Ok(Some(path)); - } - let mut path = [0; PROC_FD_PATH_CAPACITY]; - let path = proc_fd_path(fd.as_raw_fd(), &mut path); - match fspy_nostd_alloc::fs::readlinkat(allocator, CWD, path) { - Ok(path) => Ok(Some(path)), - Err(fspy_nostd::Error::BADF | fspy_nostd::Error::NOENT) => Ok(None), - Err(errno) => Err(nix::errno::Errno::from_raw(errno.raw_os_error())), - } -} - -#[cfg(target_os = "linux")] -pub const PROC_FD_PATH_CAPACITY: usize = - b"/proc/self/fd/".len() + ::MAX_STR_LEN + 1; - -/// Formats `/proc/self/fd/{fd}` into `buf`, without allocating. -#[cfg(target_os = "linux")] -pub fn proc_fd_path( - fd: c_int, - buf: &mut [u8; PROC_FD_PATH_CAPACITY], -) -> fspy_nostd::CStr<'_, fspy_nostd::Thin> { - const PREFIX: &[u8] = b"/proc/self/fd/"; - - let mut formatted = itoa::Buffer::new(); - let fd = formatted.format(fd).as_bytes(); - - buf[..PREFIX.len()].copy_from_slice(PREFIX); - let end = PREFIX.len() + fd.len(); - buf[PREFIX.len()..end].copy_from_slice(fd); - buf[end] = 0; - - // SAFETY: the initialized prefix ends in NUL and lives as long as `buf`. - unsafe { fspy_nostd::CStr::from_ptr(buf.as_ptr().cast()) } -} - -#[cfg(target_os = "macos")] -fn get_fd_path(allocator: A, fd: BorrowedFd<'_>) -> nix::Result>> { - if fd.as_raw_fd() == CWD.as_raw_fd() { - let path = fspy_nostd_alloc::fs::getcwd(allocator) - .map_err(|errno| nix::errno::Errno::from_raw(errno.raw_os_error()))? - .into_units(); - return Ok(Some(path)); - } - - match fspy_nostd_alloc::fs::fcntl_getpath(allocator, fd) { - Ok(path) => { - // `F_GETPATH` does not return a length. Count at this caller before - // converting its allocation into the returned path. - Ok(Some(path.count().into_units())) - } - Err(fspy_nostd::Error::BADF | fspy_nostd::Error::NOENT) => Ok(None), - Err(errno) => Err(nix::errno::Errno::from_raw(errno.raw_os_error())), - } -} - -pub trait ToAbsolutePath { - /// Resolves this argument to an absolute path allocated in `allocator`, - /// or borrowed from the argument itself when it is already absolute. - /// - /// The result is a C string so that callers forwarding it to an exec — - /// which needs a terminator — cannot be handed unterminated bytes; - /// [`as_units`] gives the path without the NUL. - /// - /// [`as_units`]: fspy_nostd::CStr::as_units - /// - /// # Errors - /// - /// Returns the error reported while resolving a descriptor or the current - /// working directory. - fn to_absolute_path<'a, A: Allocator>( - self, - allocator: &'a A, - ) -> nix::Result>> - where - Self: 'a; -} - -impl ToAbsolutePath for BorrowedFd<'_> { - fn to_absolute_path<'a, A: Allocator>( - self, - allocator: &'a A, - ) -> nix::Result>> - where - Self: 'a, - { - let Some(mut path) = get_fd_path(allocator, self)? else { - return Ok(None); - }; - path.push(0); - // SAFETY: a resolved descriptor path carries no interior NUL, and - // exactly one was appended above. The storage stays in `allocator` - // until it is dropped, which for a per-call arena ends the call. - Ok(Some(unsafe { fspy_nostd::CStr::from_units_with_nul_unchecked(path.leak()) })) - } -} - -impl ToAbsolutePath for Option { - fn to_absolute_path<'a, A: Allocator>( - self, - allocator: &'a A, - ) -> nix::Result>> - where - Self: 'a, - { - self.map_or(Ok(None), |path| path.to_absolute_path(allocator)) - } -} - -/// A pathname resolved against a directory descriptor, as in `openat`. -/// -/// The descriptor is `None` when the caller passed `-1`. The kernel ignores -/// it for an absolute pathname and fails a relative one with `EBADF`. -pub struct PathAt<'fd, 'path>( - pub Option>, - pub fspy_nostd::CStr<'path, fspy_nostd::Thin>, -); - -impl PathAt<'_, '_> { - /// Borrows raw directory-descriptor and pathname arguments. - /// - /// # Safety - /// - /// `fd` must be `-1` or remain valid while the returned value is used, - /// and `path` must point to a valid NUL-terminated string. - #[must_use] - pub const unsafe fn borrow_raw(fd: c_int, path: *const c_char) -> Self { - // SAFETY: both invariants are upheld by the caller. - Self(unsafe { BorrowedFd::try_borrow_raw(fd) }, unsafe { - fspy_nostd::CStr::from_ptr(path.cast()) - }) - } -} - -impl ToAbsolutePath for PathAt<'_, '_> { - fn to_absolute_path<'a, A: Allocator>( - self, - allocator: &'a A, - ) -> nix::Result>> - where - Self: 'a, - { - let counted = self.1.count(); - let pathname = counted.as_units(); - - if pathname.starts_with(b"/") { - // Already absolute, and already NUL-terminated by the caller. - Ok(Some(counted)) - } else { - // A relative pathname at `-1` accesses nothing: the call fails. - let Some(dirfd) = self.0 else { - return Ok(None); - }; - let Some(mut base) = get_fd_path(allocator, dirfd)? else { - return Ok(None); - }; - if !pathname.is_empty() { - if !base.ends_with(b"/") { - base.push(b'/'); - } - base.extend_from_slice(pathname); - } - base.push(0); - // SAFETY: neither the directory nor the pathname carries an - // interior NUL — both come from C strings or the kernel — and - // exactly one was appended above. The storage stays in - // `allocator` until it is dropped. - Ok(Some(unsafe { fspy_nostd::CStr::from_units_with_nul_unchecked(base.leak()) })) - } - } -} - -impl ToAbsolutePath for fspy_nostd::CStr<'_, fspy_nostd::Thin> { - fn to_absolute_path<'a, A: Allocator>( - self, - allocator: &'a A, - ) -> nix::Result>> - where - Self: 'a, - { - PathAt(Some(CWD), self).to_absolute_path(allocator) - } -} - -pub trait ToAccessMode { - /// Converts the intercepted operation's mode into an access mode. - /// - /// # Safety - /// - /// Implementations backed by raw process pointers require those pointers - /// to remain valid for the conversion. - unsafe fn to_access_mode(self) -> AccessMode; -} - -impl ToAccessMode for AccessMode { - unsafe fn to_access_mode(self) -> AccessMode { - self - } -} - -pub struct OpenFlags(pub c_int); -impl ToAccessMode for OpenFlags { - unsafe fn to_access_mode(self) -> AccessMode { - match self.0 & libc::O_ACCMODE { - libc::O_RDWR => AccessMode::ReadWrite, - libc::O_WRONLY => AccessMode::Write, - _ => AccessMode::Read, - } - } -} - -pub struct ModeStr(pub *const c_char); -impl ToAccessMode for ModeStr { - unsafe fn to_access_mode(self) -> AccessMode { - // SAFETY: self.0 is a non-null pointer to a valid null-terminated C - // string, as guaranteed by the libc calling convention. - let mode_str = unsafe { CStr::from_ptr(self.0) }.to_bytes().as_bstr(); - let has_read = mode_str.contains(&b'r'); - let has_write = mode_str.contains(&b'w') || mode_str.contains(&b'a'); - match (has_read, has_write) { - (false, true) => AccessMode::Write, - (true, true) => AccessMode::ReadWrite, - _ => AccessMode::Read, - } - } -} diff --git a/crates/fspy_client_unix/src/lib.rs b/crates/fspy_client_unix/src/lib.rs deleted file mode 100644 index d51c90f10..000000000 --- a/crates/fspy_client_unix/src/lib.rs +++ /dev/null @@ -1,153 +0,0 @@ -//! Reusable Unix client for reporting file accesses to the fspy supervisor. - -// Compile as an empty crate on non-Unix targets and on musl, matching the -// current preload client. Musl support will be enabled as its dependencies are -// made usable before libc initialization. -#![cfg(all(unix, not(target_env = "musl")))] - -pub mod convert; -pub mod raw_exec; - -use std::{ffi::OsStr, fmt::Debug, os::unix::ffi::OsStrExt as _, path::Path}; - -use allocator_api2::alloc::Allocator; -use convert::{ToAbsolutePath, ToAccessMode}; -use fspy_shared::ipc::{AccessMode, channel::Sender}; -use fspy_shared_unix::{ - exec::ExecResolveConfig, - payload::{EncodedPayload, decode_payload_from_env}, - spawn::{PreExec, handle_exec}, -}; -use raw_exec::RawExec; - -pub struct Client<'a> { - encoded_payload: EncodedPayload<'a>, - ipc_sender: Option, -} - -// Seals the view-only design: the client holds views of leaked memory and -// the sender, never an allocator. A retained allocator handle is -// interior-mutable and would fail this assertion. (`Sender`'s own manual -// `Send`/`Sync` impls are the one audited exception the check trusts.) -const _: () = { - const fn assert_send_sync() {} - assert_send_sync::>(); -}; - -impl Debug for Client<'_> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Client").finish() - } -} - -impl<'a> Client<'a> { - /// Constructs a client from the encoded payload in the process - /// environment, leaking the payload's storage into `allocator`. - /// - /// The sender's temporary path decode also comes from `allocator` and - /// drops before this returns; a bump allocator gets that space back, - /// since the block is its most recent allocation. `A: 'a` bounds the - /// client's lifetime — a `'static` allocator yields a `Client<'static>` - /// with no further ceremony — and the client never retains the - /// allocator itself (see the `Send + Sync` assertion above). - /// - /// # Panics - /// - /// Panics when the payload is missing, malformed, or cannot be decoded, - /// and when the channel is there but cannot be attached to (see - /// [`ChannelConf::sender`](fspy_shared::ipc::channel::ChannelConf::sender)). - pub fn from_env( - envs: impl Iterator, - allocator: impl Allocator + Clone + 'a, - ) -> Self { - let encoded_payload = decode_payload_from_env(envs, allocator.clone()).unwrap(); - - // `None` when the channel is already over, which happens when this - // process starts after the root target exited. Nothing is said - // about it: a preload library writing to the traced process's - // stderr corrupts whatever that process is printing. - let ipc_sender = encoded_payload.payload.ipc_channel_conf.sender(allocator); - - Self { encoded_payload, ipc_sender } - } - - fn send(&self, mode: AccessMode, path: &Path) { - let Some(ipc_sender) = &self.ipc_sender else { - return; - }; - let path_bytes = path.as_os_str().as_bytes(); - if path_bytes.starts_with(b"/dev/") - || (cfg!(target_os = "linux") - && (path_bytes.starts_with(b"/proc/") || path_bytes.starts_with(b"/sys/"))) - { - return; - } - // The interception proceeds whether or not the record could be - // sent — a preload library can never panic its host process. - ipc_sender.send(&mode.with_path(path.into())); - } - - /// Marks the run's trace incomplete, so the receiver treats it as - /// untracked and the runner does not cache it. Call it before the - /// process does something that tracking cannot record, such as an exec - /// that continues untracked because [`PreExec::run`] failed. It does - /// nothing when this client has no channel sender. - pub fn report_loss(&self) { - if let Some(ipc_sender) = &self.ipc_sender { - ipc_sender.report_loss(); - } - } - - /// Resolves and reports an exec, returning the transformed arguments to - /// forward and what to run before forwarding them. - /// - /// # Safety - /// - /// `raw_exec` must contain the valid C strings and pointer arrays required - /// by [`RawExec::to_exec`]. The returned `RawExec` points into - /// `allocator`, and must not be used after `allocator` is dropped. - /// - /// # Errors - /// - /// Returns errors from exec resolution or platform preparation. - pub unsafe fn handle_exec( - &self, - config: ExecResolveConfig, - raw_exec: RawExec, - allocator: &A, - ) -> nix::Result<(RawExec, Option)> { - // SAFETY: raw_exec contains valid pointers to C strings and - // null-terminated arrays, as provided by the caller. - let mut exec = unsafe { raw_exec.to_exec(allocator) }; - let pre_exec = handle_exec(&mut exec, config, &self.encoded_payload, |path| { - self.send(AccessMode::Read, path); - })?; - Ok((RawExec::from_exec(exec), pre_exec)) - } - - /// Resolves and reports one intercepted file access. - /// - /// # Safety - /// - /// `path` and `mode` must satisfy their implementation-specific raw - /// pointer and descriptor contracts for the duration of this call. - /// - /// # Errors - /// - /// Returns errors from path resolution or shared-memory serialization. - pub unsafe fn try_handle_open( - &self, - path: impl ToAbsolutePath, - mode: impl ToAccessMode, - allocator: impl Allocator, - ) -> anyhow::Result<()> { - // SAFETY: mode contains a valid pointer (if ModeStr) or a plain value, - // as provided by the caller. - let mode = unsafe { mode.to_access_mode() }; - let Some(abs_path) = path.to_absolute_path(&allocator)? else { - return Ok(()); - }; - self.send(mode, Path::new(OsStr::from_bytes(abs_path.as_units()))); - Ok(()) - } -} diff --git a/crates/fspy_client_unix/src/raw_exec.rs b/crates/fspy_client_unix/src/raw_exec.rs deleted file mode 100644 index d7397c6f0..000000000 --- a/crates/fspy_client_unix/src/raw_exec.rs +++ /dev/null @@ -1,122 +0,0 @@ -use std::{ffi::CStr, ptr::null}; - -use allocator_api2::{alloc::Allocator, vec::Vec}; -use fspy_shared_unix::exec::{Exec, to_vec_in}; - -#[derive(Clone, Copy)] -pub struct RawExec { - pub prog: *const libc::c_char, - pub argv: *const *const libc::c_char, - pub envp: *const *const libc::c_char, -} - -impl RawExec { - unsafe fn collect_c_str_array( - strs: *const *const libc::c_char, - allocator: A, - mut map_fn: impl FnMut(&[u8]) -> T, - ) -> Vec { - let mut count = 0usize; - let mut cur_str = strs; - // SAFETY: cur_str points into a valid null-terminated array of C - // string pointers (argv/envp convention). - while !(unsafe { *cur_str }).is_null() { - count += 1; - // SAFETY: advancing within the bounds of the null-terminated - // pointer array. - cur_str = unsafe { cur_str.add(1) }; - } - - let mut str_vec = Vec::with_capacity_in(count, allocator); - for i in 0..count { - // SAFETY: i < count, so strs.add(i) is within the bounds of the - // pointer array. - let cur_str = unsafe { strs.add(i) }; - // SAFETY: *cur_str is a non-null pointer to a valid - // null-terminated C string, verified by the counting loop above. - str_vec.push(map_fn(unsafe { CStr::from_ptr(*cur_str) }.to_bytes())); - } - str_vec - } - - /// NUL-terminates `s` and leaks it into its allocator. - fn into_c_str(mut s: Vec) -> *const libc::c_char { - s.push(0); - s.leak().as_ptr().cast() - } - - /// Builds a NULL-terminated array of C strings, leaked into the strings' - /// allocator. - fn into_c_str_array( - strs: Vec, A>, - ) -> *const *const libc::c_char { - let mut ptrs = Vec::with_capacity_in(strs.len() + 1, strs.allocator().clone()); - ptrs.extend(strs.into_iter().map(Self::into_c_str)); - ptrs.push(null()); - ptrs.leak().as_ptr() - } - - /// Copies the raw exec arguments into `allocator`. - /// - /// # Safety - /// - /// `prog` must point to a valid C string. `argv` and `envp` must each - /// point to a readable, null-terminated array of valid C string pointers. - pub unsafe fn to_exec(self, allocator: A) -> Exec { - // SAFETY: self.prog is a non-null pointer to a valid null-terminated C - // string, as guaranteed by the libc exec calling convention. - let program = to_vec_in(unsafe { CStr::from_ptr(self.prog) }.to_bytes(), allocator.clone()); - - // SAFETY: self.argv is a valid null-terminated array of C string - // pointers, as guaranteed by the libc exec calling convention. - let args = unsafe { - Self::collect_c_str_array(self.argv, allocator.clone(), |arg| { - to_vec_in(arg, allocator.clone()) - }) - }; - - // SAFETY: self.envp is a valid null-terminated array of C string - // pointers, as guaranteed by the libc exec calling convention. - let envs = unsafe { - Self::collect_c_str_array(self.envp, allocator.clone(), |env| { - env.iter().position(|b| *b == b'=').map_or_else( - || (to_vec_in(env, allocator.clone()), None), - |eq_pos| { - ( - to_vec_in(&env[..eq_pos], allocator.clone()), - Some(to_vec_in(&env[(eq_pos + 1)..], allocator.clone())), - ) - }, - ) - }) - }; - - Exec { program, args, envs } - } - - /// Builds the C strings and pointer arrays for `cmd` in its allocator. - /// - /// They are leaked there rather than freed, so the pointers stay valid - /// until the allocator itself goes away. In the preload that is the - /// interception's per-call bump: exec runs in the child of `fork()` in - /// multithreaded programs, where libc malloc's lock may be held by a - /// thread that no longer exists, and the bump hands everything back - /// when the call ends. - pub fn from_exec(cmd: Exec) -> Self { - let mut envs = Vec::with_capacity_in(cmd.envs.len(), cmd.allocator().clone()); - for (name, value) in cmd.envs { - let mut env = name; - if let Some(value) = value { - env.push(b'='); - env.extend_from_slice(&value); - } - envs.push(env); - } - - Self { - prog: Self::into_c_str(cmd.program), - argv: Self::into_c_str_array(cmd.args), - envp: Self::into_c_str_array(envs), - } - } -} diff --git a/crates/fspy_elf_loader/README.md b/crates/fspy_elf_loader/README.md index 667c87b78..89e5e12c1 100644 --- a/crates/fspy_elf_loader/README.md +++ b/crates/fspy_elf_loader/README.md @@ -68,15 +68,128 @@ Do not try to close these in this crate unless a real target requires it: still works via mmap; leave brk alone. - **External `/proc` views.** `/proc/self/exe` and `/proc//exe` are virtualized inside the tracked process, while external `/proc//exe` - observers still see the launcher binary. + observers still see the launcher binary. `/proc/self/auxv` still holds the + kernel's vector for the launcher, so its `AT_PHDR`, `AT_PHNUM`, `AT_ENTRY`, + and `AT_BASE` differ from what `getauxval` and the startup stack report, and + inspecting program headers through it finds the launcher's. - **Privileged / unsupported binaries.** `PR_SET_NO_NEW_PRIVS` is enabled for seccomp (so setuid/setgid and file-capability escalations do not apply), and ELF32 and `binfmt_misc` binaries are rejected with `ENOEXEC`. +- **Execute-only (`0111`) binaries.** Userland ELF mapping opens the executable + with `O_RDONLY` to validate headers and `mmap` segments, so execute-only + (`chmod 0111`) binaries cannot be mapped and fail with `EACCES`. The macOS + tracker's exec preparation reads the executable too, to resolve `#!`, so + they fail there as well. +- **Real-credential permission checks.** The executable's `X_OK` check uses + `faccessat` with the real user and group IDs, so it does not match kernel + exec permission when real and effective IDs differ, including IDs inherited + from the parent. +- **No executable write protection.** The target is mapped from an ordinary + read-only descriptor rather than kernel-execed, so Linux's `ETXTBSY` write + exclusion does not apply. Opening a running target for writing succeeds, and + truncating or overwriting it can crash the process with `SIGBUS` or corrupt + its code. Executing a file that is still open for writing also succeeds. +- **Deleted or replaced `/proc/self/exe` targets.** Virtualized `/proc/self/exe` + stores the target's path at load time rather than keeping an extra target fd + open (which would break clean FD-table invariants): + - When the target was a `memfd` or already unlinked at load time, `readlink` + still reports the `" (deleted)"` path, while path-following `open`/`stat`/ + `execve` on `/proc/self/exe` reach the launcher instead. + - When a target binary is replaced in place after load (e.g. via `rename`), + path-following calls on `/proc/self/exe` follow the saved path to the new + file rather than the original unlinked inode. + - Only spellings of the link itself (`/proc/self/exe`, `/proc//exe`, + and their task forms) are virtualized. A symlink to it, or a path such as + `/proc/self/root/proc/self/exe`, reaches the launcher, including when a + program re-execs itself through one. - **Launcher path visibility across mount changes.** Every tracked `execve` re-enters the materialized freestanding launcher binary on disk. If a tracked process tree changes its mount namespace or root (`chroot`, `pivot_root`, or a private `/tmp` mount hiding the materialized launcher path), subsequent child `execve` calls fail with `ENOENT`. +- **Signals during blocking trapped calls.** Trapped calls other than opens + that may block and execs (`stat`, `getdents64`, `rename`, and so on, and + `O_NONBLOCK`/`O_PATH` opens) are replayed with maskable signals blocked, + which saves two `rt_sigprocmask` calls (about a quarter of a trapped call's + cost). If one blocks, for example on FUSE or a soft NFS mount, `SIGINT`, + `SIGTERM`, timers, and other handled signals wait until it returns, + indefinitely if it never does. Masking can't defer `SIGKILL`, which + `vp run` uses to cancel tasks. +- **Descriptor-relative scripts.** `execveat(dirfd, "script")` hands the + script to its interpreter by absolute path rather than as + `/dev/fd//script`, so `$0` differs and the path no longer follows the + directory if it is renamed. +- **Process-relative top-level programs.** The top-level program is resolved + after the launcher is exec'd, so `/proc/self/exe` names the launcher (and + fails with `EEXIST`), and a program named through an `FD_CLOEXEC` descriptor + (`/proc/self/fd/` or `/dev/fd/`) fails with `ENOENT`. Execs inside + tracked processes resolve such paths before exec'ing the launcher. +- **Copied argv after shebang expansion.** The target keeps the launcher's + kernel argument strings, so writes to its `argv` (a process title, a + scrubbed secret) show in `/proc//cmdline`. When userland shebang + expansion changes a top-level task's argv, the target gets copies instead, + and `/proc//cmdline` keeps the original arguments for its lifetime. +- **Shared descriptor tables.** In a child that shares its parent's descriptor + table (`CLONE_FILES` without `CLONE_THREAD`, with or without `CLONE_VM`), the + descriptors a tracked `execve` opens stay open in the processes still sharing + the table after the exec, so repeated execs from such children can exhaust + descriptors (`EMFILE`). +- **Free descriptor slots.** A tracked `execve` opens the target (and its + interpreter) and duplicates a handoff descriptor before the kernel closes + `FD_CLOEXEC` descriptors, so an exec from a full descriptor table fails with + `EMFILE` where native exec, which needs no free slot, succeeds. +- **`kcmp`-denied environments.** Where `kcmp` is denied, a shared-VM child + created with `CLONE_CHILD_CLEARTID` that execs does not have its + `clear_child_tid` word cleared and woken, so a parent waiting on that futex + can hang. +- **Signal stacks.** A trapped syscall delivers `SIGSYS` on the current stack + before switching to a private one, so a handler that makes a trapped syscall + on a `sigaltstack` needs room for one more kernel signal frame (about + `AT_MINSIGSTKSZ`) plus trampoline headroom, or it overflows. The dispatcher + always uses `SA_ONSTACK`, so a forwarded target `SIGSYS` handler (including + `SIGSYS` from the target's own seccomp filter) runs on the alternate stack + even when installed without `SA_ONSTACK`. +- **Thread cancellation.** Trapped syscalls are replayed from launcher code, + outside glibc's PC-checked cancellation region, so `pthread_cancel` of a + thread blocked in a trapped syscall (such as an `open` waiting on a FIFO or + device) can hang instead of cancelling. +- **Virtualized `SIGSYS` state.** Only `rt_sigaction`, `rt_sigprocmask`, + `rt_sigpending`, and masked waits see the target's virtual `SIGSYS` blocked + and pending state: + - The `sigwait` family and `signalfd` cannot consume a virtually pending + `SIGSYS`. + - Another handler's `sa_mask` (including `sigfillset`) does not defer + `SIGSYS` while that handler runs. + - Shared-VM children (`vfork`, raw `clone(CLONE_VM)`) do not inherit the + virtual blocked bit, so `vfork` followed by `exec` starts with `SIGSYS` + unblocked (glibc `pthread_create` threads re-apply their mask). A custom + `SIGSYS` handler installed in a raw `CLONE_VM` child is replaced by the + fatal default. + - A virtually pending `SIGSYS` is lost across `exec`. + - A successful raw `rt_sigpending` with a `sigsetsize` shorter than 8 + bytes omits a virtually pending `SIGSYS` (libc always passes 8). + - A handler that blocks `SIGSYS` by editing its `ucontext`'s `uc_sigmask` + (including with `sigfillset`) leaves the real `SIGSYS` blocked after it + returns, so the next trapped syscall terminates the process. + - An asynchronous, non-seccomp `SIGSYS` (from `kill`, `tgkill`, or a timer) + interrupts otherwise untrapped blocking syscalls with `EINTR` when it is + virtually blocked, when `SIGSYS` is ignored, and when the target's handler + was installed with `SA_RESTART`. A process-directed one can stay pending + indefinitely on a thread that virtually blocks it, even while another + thread has it unblocked. + - A masked wait (`ppoll`, `pselect6`, `epoll_pwait`) whose mask blocks + `SIGSYS` retries after `EINTR` whenever a `SIGSYS` was deferred meanwhile, + even if another signal's handler also interrupted it (for example one + that raised `SIGSYS`), so it can swallow that `EINTR`: it returns at its + timeout, or keeps waiting without one. + - The virtual state lives in fixed tables: 2048 threads with virtual + `SIGSYS` state at once, and 64 concurrently pending virtual `SIGSYS` + signals. Past 2048 threads, an `rt_sigprocmask` change that needs a new + slot fails with `ENOMEM`, and implicit updates (deferring `SIGSYS` around + handlers and masked waits, marking it pending) are dropped, so deferral and + delivery can go wrong. Past 64 pending signals, a further one is delivered + with a synthetic `SI_TKILL` `siginfo` instead of its own, losing its + sender, `si_code`, and value. - GNU properties, other arches, growable stack (fixed 8–64 MiB from `RLIMIT_STACK` + guard), and personality cleanup. diff --git a/crates/fspy_elf_loader/src/lib.rs b/crates/fspy_elf_loader/src/lib.rs index 5f68eb1e6..b878eccd3 100644 --- a/crates/fspy_elf_loader/src/lib.rs +++ b/crates/fspy_elf_loader/src/lib.rs @@ -168,24 +168,26 @@ pub struct SyscallInterceptor { pub on_vfork_return: Option, } -/// Borrows a NUL-terminated C string directly from a trapped syscall's user -/// pointer. +/// Borrows a trapped syscall's path argument from its user pointer, scanning +/// at most `PATH_MAX` bytes for the NUL as the kernel does. /// /// # Errors /// /// Returns [`fspy_nostd::Error::FAULT`] if `addr` is in the first page (such as -/// `NULL`). +/// `NULL`), and [`fspy_nostd::Error::NAMETOOLONG`] if no NUL appears within +/// `PATH_MAX` bytes. /// /// # Safety /// -/// Any other `addr` must point to a readable NUL-terminated string valid for -/// `'a`. Like the macOS and Windows preloads, the runtime assumes the pointers -/// programs pass to syscalls are valid; a bad one crashes the process instead -/// of failing with `EFAULT`. +/// Any other `addr` must be readable up to its NUL or `PATH_MAX` bytes, +/// whichever comes first, and stay unchanged for `'a`. Like the macOS and +/// Windows preloads, the runtime assumes the pointers programs pass to +/// syscalls are valid; a pointer into an unmapped page crashes the process +/// instead of failing with `EFAULT`. #[cfg(any(target_os = "linux", target_os = "none"))] -pub unsafe fn user_cstr<'a>(addr: usize) -> Result> { +pub unsafe fn user_path<'a>(addr: usize) -> Result> { // SAFETY: forwarded from caller contract. - unsafe { sigsys::user_cstr(addr) } + unsafe { sigsys::user_path(addr) } } /// Copies a `Copy` value from a trapped syscall's user pointer. @@ -198,7 +200,7 @@ pub unsafe fn user_cstr<'a>(addr: usize) -> Result> { /// # Safety /// /// `T` must be valid for any bit pattern, and any other `addr` must be -/// readable for `size_of::()` bytes (see [`user_cstr`]). +/// readable for `size_of::()` bytes (see [`user_path`]). #[cfg(any(target_os = "linux", target_os = "none"))] pub unsafe fn copy_user_value(addr: usize) -> Result { // SAFETY: forwarded from caller contract. diff --git a/crates/fspy_elf_loader/src/sigsys/mod.rs b/crates/fspy_elf_loader/src/sigsys/mod.rs index 20bb4fbd4..dd533eb1e 100644 --- a/crates/fspy_elf_loader/src/sigsys/mod.rs +++ b/crates/fspy_elf_loader/src/sigsys/mod.rs @@ -50,14 +50,17 @@ pub fn handler_addr() -> usize { (sigsys_trampoline as *const ()).addr() } -/// Borrows a user C string directly from `addr`. +/// Borrows a user path from `addr`, scanning at most `PATH_MAX` bytes as the +/// kernel does. /// /// # Safety /// -/// See [`usermem::user_cstr`]. -pub unsafe fn user_cstr<'a>(addr: usize) -> Result> { +/// See [`usermem::user_cstr_bounded`]. +pub unsafe fn user_path<'a>(addr: usize) -> Result> { // SAFETY: forwarded from caller contract. - unsafe { usermem::user_cstr(addr) } + let path = unsafe { usermem::user_cstr_bounded(addr, fspy_nostd::fs::PATH_MAX) }?; + // SAFETY: `path` is followed by its NUL terminator and valid for `'a`. + Ok(unsafe { CStr::::from_ptr(path.as_ptr()) }) } /// Copies a user `Copy` value. diff --git a/crates/fspy_elf_loader/src/sigsys/usermem.rs b/crates/fspy_elf_loader/src/sigsys/usermem.rs index ee18ef3e4..c87da3a2b 100644 --- a/crates/fspy_elf_loader/src/sigsys/usermem.rs +++ b/crates/fspy_elf_loader/src/sigsys/usermem.rs @@ -16,7 +16,7 @@ use core::{mem::size_of, ptr, slice}; -use fspy_nostd::{CStr, Error, Result, Thin}; +use fspy_nostd::{Error, Result}; /// Minimum valid user-space address (page 0 is never mapped on Linux). const MIN_USER_ADDR: usize = 4096; @@ -78,25 +78,6 @@ pub unsafe fn write_user_bytes(addr: usize, src: &[u8]) -> Result<()> { Ok(()) } -/// Borrows a NUL-terminated C string directly from user address `addr`, -/// returning [`Error::FAULT`] if `addr` is in the first page (such as `NULL`). -/// -/// Prefer [`user_cstr_bounded`] for pathname inspection so malformed or -/// unterminated strings cannot scan arbitrarily far past `PATH_MAX`. -/// -/// # Safety -/// -/// Any other `addr` must point to a readable NUL-terminated C string that -/// remains valid and unmodified for `'a`. -pub unsafe fn user_cstr<'a>(addr: usize) -> Result> { - if addr < MIN_USER_ADDR { - return Err(Error::FAULT); - } - // SAFETY: caller guarantees `addr` points to a readable NUL-terminated C - // string valid for `'a`. - Ok(unsafe { CStr::::from_ptr(ptr::with_exposed_provenance(addr)) }) -} - /// Scans at most `max_len` bytes starting at user address `addr` for a NUL /// terminator and returns the byte slice preceding the NUL. /// diff --git a/crates/fspy_elf_loader_test_launcher/Cargo.toml b/crates/fspy_elf_loader_test_launcher/Cargo.toml index 3c74becc8..0d1ae700f 100644 --- a/crates/fspy_elf_loader_test_launcher/Cargo.toml +++ b/crates/fspy_elf_loader_test_launcher/Cargo.toml @@ -8,7 +8,7 @@ publish.workspace = true rust-version.workspace = true [target.'cfg(target_os = "none")'.dependencies] -fspy_elf_loader = { path = "../fspy_elf_loader" } +fspy_elf_loader = { workspace = true } fspy_nostd = { workspace = true } syscalls = { workspace = true } diff --git a/crates/fspy_elf_loader_test_launcher/src/main.rs b/crates/fspy_elf_loader_test_launcher/src/main.rs index 61fcd71b5..094ae2f2c 100644 --- a/crates/fspy_elf_loader_test_launcher/src/main.rs +++ b/crates/fspy_elf_loader_test_launcher/src/main.rs @@ -58,7 +58,7 @@ mod freestanding { unsafe fn test_handle(call: &Syscall) -> Result { let check_rewritten_path = |path_ptr: usize| -> Result { // SAFETY: `path_ptr` is the trapped syscall's path argument. - let Ok(cstr) = (unsafe { fspy_elf_loader::user_cstr(path_ptr) }) else { + let Ok(cstr) = (unsafe { fspy_elf_loader::user_path(path_ptr) }) else { return Err(Error::NOENT); }; let path = cstr.count().as_units(); @@ -107,13 +107,13 @@ mod freestanding { } if call.args[1] == INTERCEPTOR_VALIDATE_EXEC_ARGV { // SAFETY: `call.args[0]` is the trapped `execve` pathname pointer. - let cstr = unsafe { fspy_elf_loader::user_cstr(call.args[0]) }?; + let cstr = unsafe { fspy_elf_loader::user_path(call.args[0]) }?; let fd = openat(CWD, cstr, OFlags::RDONLY | OFlags::CLOEXEC, Mode::empty())?; fspy_elf_loader::validate_exec(fd.as_fd())?; return Err(Error::NOENT); } // SAFETY: `call.args[0]` is the trapped `execve` pathname pointer. - if let Ok(cstr) = unsafe { fspy_elf_loader::user_cstr(call.args[0]) } + if let Ok(cstr) = unsafe { fspy_elf_loader::user_path(call.args[0]) } && cstr.count().as_units() == SIGSYS_IGNORED_PROBE_PATH { return Err(if call.sigsys_ignored() { Error::LOOP } else { Error::NOENT }); diff --git a/crates/fspy_nostd/src/error.rs b/crates/fspy_nostd/src/error.rs index b53c9eb8d..c03629cab 100644 --- a/crates/fspy_nostd/src/error.rs +++ b/crates/fspy_nostd/src/error.rs @@ -29,6 +29,7 @@ impl Error { pub const NOMEM: Self = Self(errno::NOMEM); pub const NOTDIR: Self = Self(errno::NOTDIR); pub const OVERFLOW: Self = Self(errno::OVERFLOW); + pub const PERM: Self = Self(errno::PERM); pub const RANGE: Self = Self(errno::RANGE); /// Creates an error from a raw errno value. @@ -105,6 +106,7 @@ mod errno { pub const NOMEM: i32 = linux_raw_sys::errno::ENOMEM.cast_signed(); pub const NOTDIR: i32 = linux_raw_sys::errno::ENOTDIR.cast_signed(); pub const OVERFLOW: i32 = linux_raw_sys::errno::EOVERFLOW.cast_signed(); + pub const PERM: i32 = linux_raw_sys::errno::EPERM.cast_signed(); pub const RANGE: i32 = linux_raw_sys::errno::ERANGE.cast_signed(); } @@ -122,6 +124,7 @@ mod errno { pub const NOMEM: i32 = libc::ENOMEM; pub const NOTDIR: i32 = libc::ENOTDIR; pub const OVERFLOW: i32 = libc::EOVERFLOW; + pub const PERM: i32 = libc::EPERM; pub const RANGE: i32 = libc::ERANGE; } diff --git a/crates/fspy_preload_linux/Cargo.toml b/crates/fspy_preload_linux/Cargo.toml new file mode 100644 index 000000000..877360eb0 --- /dev/null +++ b/crates/fspy_preload_linux/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "fspy_preload_linux" +version = "0.0.0" +authors.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true +rust-version.workspace = true + +[target.'cfg(target_os = "none")'.dependencies] +allocator-api2 = { workspace = true, features = ["alloc"] } +bstr = { workspace = true } +fspy_elf_loader = { workspace = true } +fspy_nostd = { workspace = true } +fspy_nostd_alloc = { workspace = true } +fspy_shared = { workspace = true } +fspy_shared_unix = { workspace = true } +linux-raw-sys = { workspace = true, features = ["general", "no_std"] } +syscalls = { workspace = true } + +[[bin]] +name = "fspy_preload_linux" +path = "src/main.rs" +test = false +bench = false + +[lints] +workspace = true diff --git a/crates/fspy_preload_linux/README.md b/crates/fspy_preload_linux/README.md new file mode 100644 index 000000000..dad416613 --- /dev/null +++ b/crates/fspy_preload_linux/README.md @@ -0,0 +1,25 @@ +# `fspy_preload_linux` + +Freestanding Linux ELF loader and `SIGSYS` syscall-tracking runtime for `fspy`. + +## Overview + +`fspy_preload_linux` is built as a fixed-address, `no_std`, `no_main` ELF64 +executable targeting `x86_64-unknown-none` and `aarch64-unknown-none-softfloat`. +Instead of injecting a libc-bound `LD_PRELOAD` shared library or relying on +`seccomp_unotify`, `fspy` spawns `fspy_preload_linux`, which: + +1. Decodes `__FSPY_BOOTSTRAP` from the initial Linux stack environment and + attaches to the shared-memory IPC channel. +2. Resolves (when invoked as `Target::Unresolved`) or opens the target ELF64 + executable, strips `__FSPY_BOOTSTRAP`, and enters the target via + `fspy_elf_loader::exec_elf` with its `SIGSYS` syscall interceptor installed. +3. Intercepts tracked filesystem syscalls and `execve`/`execveat` in-process + inside the `SIGSYS` handler, reporting accessed paths to the IPC channel and + chaining child `execve`/`execveat` calls through `fspy_preload_linux` while + reusing the existing seccomp-BPF filter. + +Because the runtime is completely freestanding and intercepts syscalls directly +via seccomp `SECCOMP_RET_TRAP`, it tracks dynamic glibc binaries, musl binaries, +static binaries, and custom-runtime binaries (such as Go, Bun, and Deno) +uniformly without `LD_PRELOAD`. diff --git a/crates/fspy_preload_linux/build.rs b/crates/fspy_preload_linux/build.rs new file mode 100644 index 000000000..fb91f8fc8 --- /dev/null +++ b/crates/fspy_preload_linux/build.rs @@ -0,0 +1,8 @@ +fn main() { + println!("cargo::rerun-if-changed=build.rs"); + if let Ok(link_args) = std::env::var("DEP_FSPY_ELF_LOADER_LINK_ARGS") { + for argument in link_args.split_whitespace() { + println!("cargo::rustc-link-arg={argument}"); + } + } +} diff --git a/crates/fspy_preload_linux/src/main.rs b/crates/fspy_preload_linux/src/main.rs new file mode 100644 index 000000000..23304e090 --- /dev/null +++ b/crates/fspy_preload_linux/src/main.rs @@ -0,0 +1,1083 @@ +#![cfg_attr(target_os = "none", no_std)] +#![cfg_attr(target_os = "none", no_main)] + +#[cfg(not(target_os = "none"))] +const fn main() {} + +#[cfg(target_os = "none")] +mod runtime { + use core::{ + alloc::Layout, + cell::UnsafeCell, + ffi::c_void, + mem::size_of, + ptr::{self, NonNull}, + sync::atomic::{AtomicBool, AtomicI32, AtomicPtr, Ordering}, + }; + + use allocator_api2::{alloc::Allocator, vec::Vec}; + use bstr::BStr; + use fspy_elf_loader::{Syscall, SyscallAction, SyscallInterceptor}; + use fspy_nostd::{ + BorrowedFd, CStr, CWD, Error, OwnedFd, RawFd, Result, Thin, env::InitialStack, + fs::fcntl_dupfd, + }; + use fspy_nostd_alloc::{ + PageAllocator, PageBump, + fs::{fd_path, resolve_path_at}, + page_bump, pooled_bump, + }; + use fspy_shared::ipc::{ + AccessMode, IpcPath, IpcStr, + channel::{ChannelConf, Sender}, + }; + use fspy_shared_unix::{ + Exec, RawExec, + linux::{ + BOOTSTRAP_ENV_NAME, Bootstrap, ExecAtFlags, Target, encode_bootstrap, + ensure_bootstrap_env, resolve_exec, + }, + }; + use linux_raw_sys::general::{ + AT_EMPTY_PATH, O_ACCMODE, O_CREAT, O_RDONLY, O_RDWR, O_TRUNC, O_WRONLY, RENAME_EXCHANGE, + SIG_SETMASK, STATX_INO, open_how, statx, + }; + use syscalls::Sysno; + + fspy_nostd::main!(run); + fspy_nostd::no_global_alloc!(); + + /// Linux 6.14+ `execveat(2)` flag that checks executability without replacing + /// the process image. + const AT_EXECVE_CHECK: u32 = 0x10000; + + /// Linux `kcmp(2)` operation comparing two processes' `mm_struct`s + /// (`enum kcmp_type::KCMP_VM`). + const KCMP_VM: usize = 1; + + struct SyncCell(UnsafeCell); + + // SAFETY: `STARTUP_BUMP` and `RUNTIME` are initialized once in the fresh, + // single-threaded launcher process before `try_exec_elf` arms seccomp and + // enters the target; after that `RUNTIME` is strictly read-only. + unsafe impl Sync for SyncCell {} + + struct Runtime { + ipc_channel_conf: ChannelConf<'static>, + preload_path: &'static IpcStr, + sender: Option, + /// The root directory when this image started (see [`report_unresolved`]). + start_root: Option, + } + + /// Scratch memory for one `execve` re-routed through the launcher: the + /// arena holding the rewritten `argv`/`envp`, and any descriptors kept open + /// for the new image. + /// + /// A successful exec in a `CLONE_VM` child (`vfork` / `posix_spawn`) + /// leaves the node in its parent's memory, so such nodes are pushed onto + /// [`PARKED_EXEC_SCRATCH`]: + /// - Trapped `posix_spawn` / separate-stack `vfork` children are reclaimed + /// immediately when the parent's `clone` returns via + /// [`reclaim_vfork_child`]. + /// - Untrapped shared-stack `vfork` children are reclaimed on a subsequent + /// exec via `kcmp(my_pid, owner_pid, KCMP_VM, 0, 0) != 0` when + /// [`KCMP_VM_AVAILABLE`] is true, falling back to `set_tid_address` + /// only in restricted containers where `kcmp` is blocked. + struct ExecScratch { + next: AtomicPtr, + active_tid: AtomicI32, + owner_pid: i32, + parked: bool, + used_set_tid_address: bool, + arena: UnsafeCell>, + duped_fd: UnsafeCell, + } + + // SAFETY: `arena` and `duped_fd` are mutated only by the + // exec'ing thread before it leaves the VM or sets `active_tid` to `0` + // (`Release`), and dropped by a reclaimer only after confirming the child + // is gone (via `on_vfork_return`, `kcmp(KCMP_VM) != 0`, or `active_tid == 0` + // with `Acquire` ordering) on a node it detached from `PARKED_EXEC_SCRATCH`. + unsafe impl Sync for ExecScratch {} + + static STARTUP_BUMP: SyncCell = SyncCell(UnsafeCell::new(page_bump())); + static RUNTIME: SyncCell> = SyncCell(UnsafeCell::new(None)); + static PARKED_EXEC_SCRATCH: AtomicPtr = AtomicPtr::new(ptr::null_mut()); + static KCMP_VM_AVAILABLE: AtomicBool = AtomicBool::new(false); + + #[cfg(target_arch = "x86_64")] + const TRACKED_SYSCALLS: &[Sysno] = &[ + Sysno::open, + Sysno::openat, + Sysno::openat2, + Sysno::creat, + Sysno::getdents, + Sysno::getdents64, + Sysno::stat, + Sysno::lstat, + Sysno::newfstatat, + Sysno::statx, + Sysno::access, + Sysno::faccessat, + Sysno::faccessat2, + Sysno::mkdir, + Sysno::mkdirat, + Sysno::rename, + Sysno::renameat, + Sysno::renameat2, + Sysno::link, + Sysno::linkat, + Sysno::symlink, + Sysno::symlinkat, + Sysno::execve, + Sysno::execveat, + ]; + + #[cfg(target_arch = "aarch64")] + const TRACKED_SYSCALLS: &[Sysno] = &[ + Sysno::openat, + Sysno::openat2, + Sysno::getdents64, + Sysno::fstatat, + Sysno::statx, + Sysno::faccessat, + Sysno::faccessat2, + Sysno::mkdirat, + Sysno::renameat, + Sysno::renameat2, + Sysno::linkat, + Sysno::symlinkat, + Sysno::execve, + Sysno::execveat, + ]; + + static INTERCEPTOR: SyscallInterceptor = SyscallInterceptor { + syscalls: TRACKED_SYSCALLS, + handle: handle_syscall, + on_vfork_return: Some(reclaim_vfork_child), + }; + + #[inline] + fn runtime() -> &'static Runtime { + // SAFETY: `RUNTIME` is initialized once during single-threaded startup + // before any `SIGSYS` handler or helper calls `runtime()`. + unsafe { (*RUNTIME.0.get()).as_ref() }.expect("runtime not initialized") + } + + #[expect(clippy::needless_pass_by_value, reason = "signature required by fspy_nostd::main!")] + #[expect(clippy::too_many_lines, reason = "bootstrap decoding plus both target entry paths")] + fn run(stack: InitialStack<'_>) -> ! { + // SAFETY: `run` executes once in a fresh single-threaded process. + let bump: &'static PageBump = unsafe { &*STARTUP_BUMP.0.get() }; + let pid = current_pid(); + KCMP_VM_AVAILABLE.store(pid > 0 && kcmp_vm(pid, pid) == Ok(0), Ordering::Relaxed); + + let bootstrap = Bootstrap::from_env(stack.envs(), bump); + let sender = bootstrap.ipc_channel_conf.sender(bump); + let start_root = root_identity().ok(); + + // SAFETY: single-threaded startup before arming seccomp. + unsafe { + *RUNTIME.0.get() = Some(Runtime { + ipc_channel_conf: bootstrap.ipc_channel_conf, + preload_path: bootstrap.preload_path, + sender, + start_root, + }); + } + + // Capture the raw `(ptr, len)` of any `__FSPY_BOOTSTRAP=...` entries on + // the launcher's initial kernel stack so `on_ready` can zero them in + // place right before entering the target, scrubbing them from + // `/proc/self/environ`. + let mut bootstrap_entries: Vec<(*mut u8, usize), _> = Vec::new_in(bump); + for &entry in stack.envs() { + if is_bootstrap_env(entry) { + let fat = entry.count(); + bootstrap_entries.push((fat.as_ptr().cast_mut(), fat.as_units().len())); + } + } + + let filtered_envs = stack.envs().iter().copied().filter(|&entry| !is_bootstrap_env(entry)); + + match bootstrap.target { + Target::Unresolved { path, error_pipe_fd } => { + let mut exec_args = Vec::with_capacity_in(stack.args().len(), bump); + for arg in stack.args() { + exec_args.push(copy_bytes(arg.count().as_units(), bump)); + } + let mut exec = Exec { + program: copy_bytes(path.as_bytes(), bump), + args: exec_args, + envs: Vec::new_in(bump), + }; + + let resolved = match resolve_exec(&mut exec, Some(CWD), ExecAtFlags::empty(), |p| { + report_exec_read(p); + }) { + Ok(resolved) => resolved, + Err(err) => { + write_error_pipe(error_pipe_fd, err.raw_os_error()); + exit_group(127); + } + }; + + let execfn = leak_cstr(&resolved.execfn, bump); + let argv_in_place = args_match_kernel(&exec.args, stack.args()); + let mut argv = Vec::with_capacity_in(exec.args.len(), bump); + if argv_in_place { + argv.extend(stack.args().iter().copied()); + } else { + for arg in &exec.args { + argv.push(leak_cstr(arg, bump)); + } + } + + let on_ready = || { + scrub_bootstrap_env(&bootstrap_entries); + write_error_pipe(error_pipe_fd, 0); + // Close the error pipe before entering the target so it + // never leaks an open descriptor into the child process. + if error_pipe_fd >= 0 { + // SAFETY: the parent opened `error_pipe_fd` exclusively + // for this startup handshake and transferred ownership + // to us. + drop(unsafe { OwnedFd::from_raw_fd(error_pipe_fd) }); + } + }; + + // SAFETY: fresh single-threaded freestanding launcher; + // `try_exec_elf` copies strings onto the new stack before + // invoking `on_ready` and abandoning ours. + match unsafe { + fspy_elf_loader::try_exec_elf( + resolved.file, + execfn, + argv.into_iter(), + argv_in_place, + filtered_envs, + stack.auxv(), + Some(INTERCEPTOR), + on_ready, + ) + } { + Ok(never) => match never {}, + Err(err) => { + write_error_pipe(error_pipe_fd, err.raw_os_error()); + exit_group(127); + } + } + } + Target::ResolvedFd { fd, execfn, sigmask, sigsys_ignored } => { + let execfn_cstr = + execfn.to_os_c_string_in(bump).expect("resolved execfn contains NUL"); + // SAFETY: parent duped `fd` specifically for this handoff. + let file = unsafe { OwnedFd::from_raw_fd(fd) }; + + restore_sigsys_ignored(sigsys_ignored); + restore_sigmask(sigmask); + + // SAFETY: fresh single-threaded freestanding launcher; + // `try_exec_elf` copies strings onto the new stack before + // invoking `on_ready` and abandoning ours. + match unsafe { + fspy_elf_loader::try_exec_elf( + file, + execfn_cstr.as_c_str().as_thin(), + // The interceptor exec'd us with the target's final argv. + stack.args().iter().copied(), + true, + filtered_envs, + stack.auxv(), + Some(INTERCEPTOR), + || scrub_bootstrap_env(&bootstrap_entries), + ) + } { + Ok(never) => match never {}, + Err(err) => { + write_exec_error_stderr(err); + exit_group(127); + } + } + } + } + } + + /// Returns whether resolved `args` byte-match the kernel's argument strings + /// (no userland shebang expansion), so the target can keep using those and + /// writes to its argv show in `/proc//cmdline` as they do natively. + fn args_match_kernel>( + args: &[T], + kernel: &[CStr<'_, Thin>], + ) -> bool { + args.len() == kernel.len() + && args.iter().zip(kernel).all(|(arg, kernel)| **arg == *kernel.count().as_units()) + } + + fn scrub_bootstrap_env(entries: &[(*mut u8, usize)]) { + for &(ptr, len) in entries { + for i in 0..len { + // SAFETY: `ptr..ptr+len` is a `__FSPY_BOOTSTRAP=...` string on + // our writable initial kernel stack. `try_exec_elf` has already + // finished reading `filtered_envs` and built the target stack, + // so nothing aliases these bytes. Volatile writes prevent + // dead-store elimination before entering the target, keeping + // the bootstrap payload out of `/proc/self/environ`. + unsafe { ptr.add(i).write_volatile(0) }; + } + } + } + + fn is_bootstrap_env(entry: CStr<'_, Thin>) -> bool { + let bytes = entry.count().as_units(); + bytes + .strip_prefix(BOOTSTRAP_ENV_NAME.as_bytes()) + .is_some_and(|rest| rest.is_empty() || rest.starts_with(b"=")) + } + + fn copy_bytes(bytes: &[u8], allocator: A) -> Vec { + let mut out = Vec::with_capacity_in(bytes.len(), allocator); + out.extend_from_slice(bytes); + out + } + + fn leak_cstr<'a, A: Allocator + 'a>(bytes: &[u8], allocator: A) -> CStr<'a, Thin> { + let mut owned = Vec::with_capacity_in(bytes.len() + 1, allocator); + owned.extend_from_slice(bytes); + owned.push(0); + let leaked: &'a [u8] = owned.leak(); + // SAFETY: `leaked` ends with a NUL byte and lives for `'a`. + unsafe { CStr::::from_ptr(leaked.as_ptr()) } + } + + fn write_error_pipe(fd: RawFd, code: i32) { + if fd < 0 { + return; + } + // SAFETY: `fd` is the parent-provided non-negative pipe descriptor. + let borrowed = unsafe { BorrowedFd::borrow_raw(fd) }; + let bytes = code.to_ne_bytes(); + let mut written = 0usize; + while written < bytes.len() { + match fspy_nostd::io::write(borrowed, &bytes[written..]) { + Ok(0) => break, + Ok(n) => written += n, + Err(Error::INTR) => {} + Err(_) => break, + } + } + } + + fn restore_sigsys_ignored(sigsys_ignored: bool) { + #[repr(C)] + struct KernelSigaction { + handler: usize, + flags: usize, + restorer: usize, + mask: u64, + } + if !sigsys_ignored { + return; + } + let ign = KernelSigaction { handler: 1, flags: 0, restorer: 0, mask: 0 }; + // SAFETY: `ign` is a valid stack-local kernel `sigaction` with `SIG_IGN` + // (`1`). Executing from inside the launcher's `PF_X` allowlist bypasses + // the inherited seccomp filter, and `try_exec_elf`'s `sigsys::install` + // will record `SIG_IGN` in the virtualized table before installing our + // handler. + let _ = unsafe { + syscalls::syscall!( + Sysno::rt_sigaction, + linux_raw_sys::general::SIGSYS, + &raw const ign, + 0usize, + size_of::() + ) + }; + } + + fn restore_sigmask(sigmask: u64) { + // SAFETY: `sigmask` is a valid stack-local 64-bit Linux `sigset_t`. + // Executing from inside the launcher's `PF_X` allowlist bypasses the + // inherited seccomp filter, and `exec_elf`'s `sigsys::install` will + // subsequently record and unblock `SIGSYS` if it was set in `sigmask`. + let _ = unsafe { + syscalls::syscall!( + Sysno::rt_sigprocmask, + SIG_SETMASK, + &raw const sigmask, + 0usize, + size_of::() + ) + }; + } + + fn write_exec_error_stderr(err: Error) { + const PREFIX: &[u8] = b"fspy_preload_linux: exec_elf failed (errno="; + const SUFFIX: &[u8] = b")\n"; + let mut buf = [0_u8; 64]; + let mut len = PREFIX.len(); + buf[..len].copy_from_slice(PREFIX); + let code = err.raw_os_error(); + let abs = code.unsigned_abs(); + if code < 0 { + buf[len] = b'-'; + len += 1; + } + let mut digits = [0_u8; 10]; + let mut n = 0; + let mut rem = abs; + loop { + digits[n] = b'0' + (rem % 10) as u8; + n += 1; + rem /= 10; + if rem == 0 { + break; + } + } + for i in (0..n).rev() { + buf[len] = digits[i]; + len += 1; + } + buf[len..len + SUFFIX.len()].copy_from_slice(SUFFIX); + len += SUFFIX.len(); + + // SAFETY: fd 2 is standard error; errors on closed/unwritable stderr are ignored. + let stderr = unsafe { BorrowedFd::borrow_raw(2) }; + let mut written = 0; + while written < len { + match fspy_nostd::io::write(stderr, &buf[written..len]) { + Ok(0) => break, + Ok(k) => written += k, + Err(Error::INTR) => {} + Err(_) => break, + } + } + } + + fn exit_group(code: i32) -> ! { + // SAFETY: `exit_group` terminates the process immediately and never returns. + let _ = unsafe { syscalls::syscall!(Sysno::exit_group, code) }; + loop { + core::hint::spin_loop(); + } + } + + fn send_path(mode: AccessMode, path: &BStr) { + let bytes: &[u8] = path.as_ref(); + // `/dev/shm` is an ordinary tmpfs that can hold a workspace. + let dev_shm = bytes == b"/dev/shm" || bytes.starts_with(b"/dev/shm/"); + if (bytes.starts_with(b"/dev/") && !dev_shm) + || bytes.starts_with(b"/proc/") + || bytes.starts_with(b"/sys/") + { + return; + } + if let Some(sender) = runtime().sender.as_ref() { + sender.send(&mode.with_path(IpcPath::from_bytes(bytes))); + } + } + + #[expect( + clippy::cast_possible_truncation, + clippy::cast_possible_wrap, + reason = "Linux file descriptors are 32-bit signed integers" + )] + const fn arg_i32(raw: usize) -> i32 { + raw as i32 + } + + #[expect(clippy::cast_possible_truncation, reason = "Linux flags live in low 32 bits")] + const fn arg_u32(raw: usize) -> u32 { + raw as u32 + } + + const fn open_mode(flags: u32) -> AccessMode { + match flags & O_ACCMODE { + O_RDWR => AccessMode::ReadWrite, + O_WRONLY => AccessMode::Write, + O_RDONLY if (flags & (O_CREAT | O_TRUNC)) != 0 => AccessMode::ReadWrite, + _ => AccessMode::Read, + } + } + + /// Reports a path-based syscall to the IPC channel. `path_ptr` is the + /// trapped syscall's own argument, which `fspy_elf_loader` assumes valid. + /// + /// A path that can't be resolved marks the trace incomplete (see + /// [`report_unresolved`]), except when the program's own seccomp policy + /// denies the lookup (`getcwd` or `readlinkat`) with `EPERM`. Sandboxes + /// such as Chromium's renderer deny every filesystem syscall that way and + /// reach files only through descriptors and brokers whose opens are + /// tracked where they happen. + fn report_path_at( + dirfd: Option>, + path_ptr: usize, + mode: AccessMode, + allow_empty_path: bool, + ) { + if path_ptr == 0 { + if allow_empty_path && let Some(fd) = dirfd { + report_fd(fd, mode); + } + return; + } + // A path with no NUL within `PATH_MAX` fails with `ENAMETOOLONG`, so + // the syscall accesses nothing. + // SAFETY: `path_ptr` is the trapped syscall's path argument. + let Ok(c_path) = (unsafe { fspy_elf_loader::user_path(path_ptr) }) else { + return; + }; + let raw = c_path.count().as_units(); + if raw.is_empty() { + if allow_empty_path && let Some(fd) = dirfd { + report_fd(fd, mode); + } + return; + } + if raw.starts_with(b"/") { + send_path(mode, BStr::new(raw)); + return; + } + let arena = pooled_bump(); + match resolve_path_at(&arena, dirfd, c_path) { + Ok(Some(resolved)) => send_path(mode, BStr::new(resolved.as_units())), + // The syscall fails with `EBADF` and accesses nothing. + Ok(None) if dirfd.is_none_or(|fd| !is_open_fd(fd)) => {} + Err(Error::PERM) => {} + // The access happens, but its path is unknown (for example a cwd + // longer than `PATH_MAX`), so the trace is incomplete. + Ok(None) | Err(_) => report_unresolved(), + } + } + + fn report_fd(fd: BorrowedFd<'_>, mode: AccessMode) { + let arena = pooled_bump(); + match fd_path(&arena, fd) { + Ok(Some(resolved)) => send_path(mode, BStr::new(resolved.as_units())), + Ok(None) if !is_open_fd(fd) => {} + Err(Error::PERM) => {} + Ok(None) | Err(_) => report_unresolved(), + } + } + + /// Records a file exec resolution read, or a loss when it was read but its + /// path is unknown. + fn report_exec_read(path: Option<&BStr>) { + match path { + Some(path) => send_path(AccessMode::Read, path), + None => report_unresolved(), + } + } + + /// Returns whether `fd` is an open descriptor, counting `AT_FDCWD`: the + /// working directory stays usable for relative paths even once unlinked. + fn is_open_fd(fd: BorrowedFd<'_>) -> bool { + fd.as_raw_fd() == CWD.as_raw_fd() || fspy_nostd::fs::fcntl_is_cloexec(fd).is_ok() + } + + /// Identity of a root directory: its device major and minor, and inode. + type RootId = (u32, u32, u64); + + /// Returns the identity of the process's current root directory. + fn root_identity() -> Result { + let mut stx = core::mem::MaybeUninit::::zeroed(); + // SAFETY: `statx` writes at most `size_of::()` bytes to `stx`, + // and the path is a static NUL-terminated string. + unsafe { + syscalls::syscall!( + Sysno::statx, + CWD.as_raw_fd().cast_unsigned(), + c"/".as_ptr(), + 0, + STATX_INO, + stx.as_mut_ptr() + ) + }?; + // SAFETY: zero-initialized, and `statx` filled the fields read below. + let stx = unsafe { stx.assume_init() }; + Ok((stx.stx_dev_major, stx.stx_dev_minor, stx.stx_ino)) + } + + /// Marks the trace incomplete for an access whose path can't be resolved, + /// unless the process changed its root directory since this image + /// started. Paths inside such a `chroot` can't name files of the tracked + /// filesystem anyway. Chromium's sandbox confines its zygote and + /// renderers to an empty, deleted directory without `/proc`, where every + /// lookup fails, and reaches files only through descriptors opened before. + fn report_unresolved() { + match root_identity() { + Ok(now) if runtime().start_root.is_some_and(|start| start != now) => {} + Err(Error::PERM) => {} + _ => report_loss(), + } + } + + /// Marks the trace incomplete, so the run is reported as untracked + /// instead of cached with a missing access. + fn report_loss() { + if let Some(sender) = runtime().sender.as_ref() { + sender.report_loss(); + } + } + + /// `SIGSYS` interceptor callback invoked by `fspy_elf_loader`. + /// + /// # Safety + /// + /// `call` holds the live (and `/proc/*/exe`-rewritten) arguments of a + /// trapped syscall listed in [`TRACKED_SYSCALLS`]. + unsafe fn handle_syscall(call: &Syscall) -> Result { + // SAFETY: `dirfd` arguments come directly from the trapped syscall; `-1` + // maps to `None` and invalid fds return `Ok(None)` from `fd_path`. + let borrow_dirfd = |raw: usize| unsafe { BorrowedFd::try_borrow_raw(arg_i32(raw)) }; + + match call.sysno { + Sysno::execve => handle_exec( + Some(CWD), + call.args[0], + call.args[1], + call.args[2], + ExecAtFlags::empty(), + call.sigmask(), + call.sigsys_ignored(), + call.is_shared_vm_child(), + ), + Sysno::execveat => { + let raw_flags = arg_u32(call.args[4]); + // Linux 6.14+ `AT_EXECVE_CHECK` validates executability without + // replacing the process image; record the path lookup like + // `faccessat2` and let the kernel answer directly. + if (raw_flags & AT_EXECVE_CHECK) != 0 { + let empty_ok = (raw_flags & AT_EMPTY_PATH) != 0; + report_path_at( + borrow_dirfd(call.args[0]), + call.args[1], + AccessMode::Read, + empty_ok, + ); + return Ok(SyscallAction::Replay); + } + let Some(flags) = ExecAtFlags::from_bits(raw_flags) else { + return Err(Error::INVAL); + }; + handle_exec( + borrow_dirfd(call.args[0]), + call.args[1], + call.args[2], + call.args[3], + flags, + call.sigmask(), + call.sigsys_ignored(), + call.is_shared_vm_child(), + ) + } + _ => { + handle_fs_syscall(call); + Ok(SyscallAction::Replay) + } + } + } + + /// Reports a tracked filesystem syscall to the IPC channel. + fn handle_fs_syscall(call: &Syscall) { + // SAFETY: `dirfd` arguments come directly from the trapped syscall; `-1` + // maps to `None` and invalid fds return `Ok(None)` from `fd_path`. + let dirfd = |idx: usize| unsafe { BorrowedFd::try_borrow_raw(arg_i32(call.args[idx])) }; + let a = call.args; + + match call.sysno { + #[cfg(target_arch = "x86_64")] + Sysno::open => report_path_at(Some(CWD), a[0], open_mode(arg_u32(a[1])), false), + Sysno::openat => report_path_at(dirfd(0), a[1], open_mode(arg_u32(a[2])), false), + Sysno::openat2 => report_openat2(dirfd(0), a[1], a[2], a[3]), + #[cfg(target_arch = "x86_64")] + Sysno::creat => report_path_at(Some(CWD), a[0], AccessMode::Write, false), + #[cfg(target_arch = "x86_64")] + Sysno::getdents => { + if let Some(fd) = dirfd(0) { + report_fd(fd, AccessMode::ReadDir); + } + } + Sysno::getdents64 => { + if let Some(fd) = dirfd(0) { + report_fd(fd, AccessMode::ReadDir); + } + } + #[cfg(target_arch = "x86_64")] + Sysno::stat | Sysno::lstat | Sysno::access => { + report_path_at(Some(CWD), a[0], AccessMode::Read, false); + } + #[cfg(target_arch = "x86_64")] + Sysno::newfstatat => { + let empty_ok = (arg_u32(a[3]) & AT_EMPTY_PATH) != 0; + report_path_at(dirfd(0), a[1], AccessMode::Read, empty_ok); + } + #[cfg(target_arch = "aarch64")] + Sysno::fstatat => { + let empty_ok = (arg_u32(a[3]) & AT_EMPTY_PATH) != 0; + report_path_at(dirfd(0), a[1], AccessMode::Read, empty_ok); + } + Sysno::statx => { + let empty_ok = (arg_u32(a[2]) & AT_EMPTY_PATH) != 0; + report_path_at(dirfd(0), a[1], AccessMode::Read, empty_ok); + } + Sysno::faccessat => { + report_path_at(dirfd(0), a[1], AccessMode::Read, false); + } + Sysno::faccessat2 => { + let empty_ok = (arg_u32(a[3]) & AT_EMPTY_PATH) != 0; + report_path_at(dirfd(0), a[1], AccessMode::Read, empty_ok); + } + #[cfg(target_arch = "x86_64")] + Sysno::mkdir => report_path_at(Some(CWD), a[0], AccessMode::Mkdir, false), + Sysno::mkdirat => report_path_at(dirfd(0), a[1], AccessMode::Mkdir, false), + #[cfg(target_arch = "x86_64")] + Sysno::rename => report_path_at(Some(CWD), a[1], AccessMode::RenameTarget, false), + Sysno::renameat => { + report_path_at(dirfd(2), a[3], AccessMode::RenameTarget, false); + } + Sysno::renameat2 => { + if (arg_u32(a[4]) & RENAME_EXCHANGE) != 0 { + report_path_at(dirfd(0), a[1], AccessMode::RenameTarget, false); + } + report_path_at(dirfd(2), a[3], AccessMode::RenameTarget, false); + } + #[cfg(target_arch = "x86_64")] + Sysno::link | Sysno::symlink => { + report_path_at(Some(CWD), a[1], AccessMode::Write, false); + } + Sysno::linkat => report_path_at(dirfd(2), a[3], AccessMode::Write, false), + Sysno::symlinkat => report_path_at(dirfd(1), a[2], AccessMode::Write, false), + _ => {} + } + } + + fn report_openat2(dirfd: Option>, path_ptr: usize, how_ptr: usize, size: usize) { + if how_ptr == 0 || size < size_of::() { + return; + } + // SAFETY: `open_how` is a `#[repr(C)]` struct of `u64` fields valid for + // any bit pattern, and `how_ptr` is the trapped syscall's argument. + let Ok(how) = (unsafe { fspy_elf_loader::copy_user_value::(how_ptr) }) else { + return; + }; + #[expect( + clippy::cast_possible_truncation, + reason = "O_ACCMODE bits live in low 32 bits of open_how.flags" + )] + let mode = open_mode(how.flags as u32); + report_path_at(dirfd, path_ptr, mode, false); + } + + #[expect( + clippy::cast_possible_truncation, + clippy::cast_possible_wrap, + reason = "Linux pid_t is a positive 32-bit signed integer" + )] + #[inline] + fn current_pid() -> i32 { + // SAFETY: `getpid` takes no arguments and always succeeds. + unsafe { syscalls::raw::syscall0(Sysno::getpid as usize) as i32 } + } + + #[inline] + fn kcmp_vm(pid1: i32, pid2: i32) -> core::result::Result { + // SAFETY: `kcmp(pid1, pid2, KCMP_VM, 0, 0)` takes integer arguments + // only and returns `0` iff both processes share the same `mm_struct`, + // `1..=3` for distinct `mm_struct`s, or `-errno` on failure. + unsafe { + syscalls::syscall!( + Sysno::kcmp, + pid1.cast_unsigned(), + pid2.cast_unsigned(), + KCMP_VM, + 0, + 0 + ) + } + } + + #[inline] + fn shares_vm_with(my_pid: i32, other_pid: i32) -> bool { + if my_pid <= 0 || other_pid <= 0 { + return false; + } + match kcmp_vm(my_pid, other_pid) { + Ok(0) => true, + Ok(_) | Err(syscalls::Errno::ESRCH) => false, + // Treat any other error (`EPERM`, `EINVAL`, `ENOSYS`, etc.) + // conservatively as still sharing VM so a live `CLONE_VM` child's + // exec scratch is never freed prematurely. If a self-probe now + // also fails (e.g. because the target installed a seccomp filter + // blocking `kcmp` after startup), flip `KCMP_VM_AVAILABLE` off so + // subsequent `CLONE_VM` children switch to `set_tid_address` + // instead of leaking unboundedly; nodes parked before the target + // installed its filter (or just before the flag flipped) stay + // boundedly leaked. + Err(_) => { + if kcmp_vm(my_pid, my_pid).is_err() { + KCMP_VM_AVAILABLE.store(false, Ordering::Relaxed); + } + true + } + } + } + + #[inline] + fn set_tid_address(addr: *const AtomicI32) { + // SAFETY: `addr` is either null or points to a live `AtomicI32` that + // remains mapped while the calling `CLONE_VM` child is attached to the + // current `mm_struct`. + let _ = unsafe { syscalls::raw::syscall1(Sysno::set_tid_address as usize, addr.addr()) }; + } + + unsafe fn push_parked_exec_scratch(node: *mut ExecScratch) { + let mut head = PARKED_EXEC_SCRATCH.load(Ordering::Acquire); + loop { + // SAFETY: Caller owns `node` exclusively until CAS publishes it. + unsafe { (*node).next.store(head, Ordering::Relaxed) }; + match PARKED_EXEC_SCRATCH.compare_exchange_weak( + head, + node, + Ordering::AcqRel, + Ordering::Acquire, + ) { + Ok(_) => return, + Err(actual) => head = actual, + } + } + } + + /// Drops `node`'s arena and returns its page to the allocator. + /// + /// # Safety + /// + /// `node` must be a live `ExecScratch` that nothing else references. + unsafe fn free_exec_scratch(node: *mut ExecScratch) { + // SAFETY: forwarded from the caller contract. + unsafe { + ptr::drop_in_place(node); + PageAllocator + .deallocate(NonNull::new_unchecked(node).cast(), Layout::new::()); + } + } + + /// `fspy_elf_loader` hook invoked in the parent right after a trapped + /// `clone(CLONE_VM | CLONE_VFORK, non_null_stack)` returns with + /// `child_pid > 0` (once the child has already left the parent's + /// `mm_struct`). + unsafe fn reclaim_vfork_child(child_pid: i32) { + if PARKED_EXEC_SCRATCH.load(Ordering::Acquire).is_null() { + return; + } + let mut cur = PARKED_EXEC_SCRATCH.swap(ptr::null_mut(), Ordering::AcqRel); + while !cur.is_null() { + // SAFETY: `swap(null)` transferred exclusive ownership of this chain. + let next = unsafe { (*cur).next.load(Ordering::Relaxed) }; + // SAFETY: `cur` is a live node of the detached chain. + let reclaimable = unsafe { + (*cur).owner_pid == child_pid || (*cur).active_tid.load(Ordering::Acquire) == 0 + }; + if reclaimable { + // SAFETY: `child_pid` has already exited or exec'd (or failure + // cleanup released the node), so nothing references `cur`. + unsafe { free_exec_scratch(cur) }; + } else { + // SAFETY: `cur` is still in use by another child; park it again. + unsafe { push_parked_exec_scratch(cur) }; + } + cur = next; + } + } + + /// Frees parked `CLONE_VM` exec scratch whose child has exec'd or exited, + /// keeping parent memory bounded across any number of `vfork` / + /// `posix_spawn` children. + fn reclaim_exec_scratch() { + if PARKED_EXEC_SCRATCH.load(Ordering::Acquire).is_null() { + return; + } + let my_pid = current_pid(); + let mut cur = PARKED_EXEC_SCRATCH.swap(ptr::null_mut(), Ordering::AcqRel); + while !cur.is_null() { + // SAFETY: `swap(null)` transferred exclusive ownership of this chain. + let next = unsafe { (*cur).next.load(Ordering::Relaxed) }; + // SAFETY: `cur` is a live node of the detached chain. + let reclaimable = unsafe { + (*cur).active_tid.load(Ordering::Acquire) == 0 + || (!(*cur).used_set_tid_address && !shares_vm_with(my_pid, (*cur).owner_pid)) + }; + if reclaimable { + // SAFETY: The child left this memory (or failure cleanup + // released the node), so nothing references `cur`. Its + // `duped_fd` belonged to the child's descriptor table. + unsafe { free_exec_scratch(cur) }; + } else { + // SAFETY: `cur` is still in use by its child; park it again. + unsafe { push_parked_exec_scratch(cur) }; + } + cur = next; + } + } + + /// Failure cleanup invoked by `fspy_elf_loader` when `SYS_execve` returns + /// an error. + unsafe fn cleanup_exec_scratch(raw: *mut c_void) { + let node = raw.cast::(); + // SAFETY: `node` is the scratch of this failed exec, still owned by + // the calling thread, and `duped_fd` is open in its descriptor table. + unsafe { + let fd = *(*node).duped_fd.get(); + *(*node).duped_fd.get() = -1; + if fd >= 0 { + drop(OwnedFd::from_raw_fd(fd)); + } + if (*node).parked { + // Already published: release its arena and mark reclaimable. + if (*node).used_set_tid_address { + set_tid_address(ptr::null()); + } + *(*node).arena.get() = None; + (*node).active_tid.store(0, Ordering::Release); + } else { + free_exec_scratch(node); + } + } + } + + /// Resolves, validates, and prepares an `execve` / `execveat` call through + /// `fspy_preload_linux`, returning [`SyscallAction::Execve`] so + /// `fspy_elf_loader` releases the private `SIGSYS` stack before executing + /// the replacement `SYS_execve`. + #[expect( + clippy::too_many_arguments, + reason = "forwards raw trapped execve/execveat arguments plus caller signal state" + )] + fn handle_exec( + dirfd: Option>, + prog_ptr: usize, + argv_ptr: usize, + envp_ptr: usize, + flags: ExecAtFlags, + sigmask: u64, + sigsys_ignored: bool, + is_shared_vm_child: bool, + ) -> Result { + reclaim_exec_scratch(); + + let mem = PageAllocator.allocate(Layout::new::()).map_err(|_| Error::NOMEM)?; + let node = mem.cast::().as_ptr(); + // SAFETY: `node` is freshly page-allocated for an `ExecScratch`. + unsafe { + node.write(ExecScratch { + next: AtomicPtr::new(ptr::null_mut()), + active_tid: AtomicI32::new(0), + owner_pid: 0, + parked: false, + used_set_tid_address: false, + arena: UnsafeCell::new(Some(page_bump())), + duped_fd: UnsafeCell::new(-1), + }); + } + // SAFETY: `arena` was just set and lives until the node is freed. + let arena: &'static PageBump = unsafe { (*(*node).arena.get()).as_ref().unwrap() }; + let (raw_out, duped_fd) = match prepare_exec_in( + dirfd, + prog_ptr, + argv_ptr, + envp_ptr, + flags, + sigmask, + sigsys_ignored, + arena, + ) { + Ok(prepared) => prepared, + Err(err) => { + // SAFETY: the node was never published. + unsafe { free_exec_scratch(node) }; + return Err(err); + } + }; + // SAFETY: the node is owned by this thread until published below. + unsafe { + *(*node).duped_fd.get() = duped_fd; + if is_shared_vm_child { + let use_set_tid = !KCMP_VM_AVAILABLE.load(Ordering::Relaxed); + (*node).owner_pid = current_pid(); + (*node).parked = true; + (*node).used_set_tid_address = use_set_tid; + (*node).active_tid.store(1, Ordering::Release); + if use_set_tid { + // Register before publishing so `SIGKILL` cannot leave a + // permanently parked node with `active_tid == 1`. + set_tid_address(&raw const (*node).active_tid); + } + push_parked_exec_scratch(node); + } + } + Ok(SyscallAction::Execve { + prog: raw_out.prog.cast(), + argv: raw_out.argv.cast(), + envp: raw_out.envp.cast(), + cleanup: Some((cleanup_exec_scratch, node.cast())), + }) + } + + #[expect( + clippy::too_many_arguments, + reason = "forwards raw trapped execve/execveat arguments plus caller signal state" + )] + fn prepare_exec_in( + dirfd: Option>, + prog_ptr: usize, + argv_ptr: usize, + envp_ptr: usize, + flags: ExecAtFlags, + sigmask: u64, + sigsys_ignored: bool, + arena: &'static PageBump, + ) -> Result<(RawExec, RawFd)> { + let raw = RawExec { + prog: ptr::with_exposed_provenance(prog_ptr), + argv: ptr::with_exposed_provenance(argv_ptr), + envp: ptr::with_exposed_provenance(envp_ptr), + }; + // SAFETY: the pointers are the trapped syscall's own `execve` arguments. + let mut exec = unsafe { raw.to_exec(arena) }?; + let resolved = resolve_exec(&mut exec, dirfd, flags, report_exec_read)?; + fspy_elf_loader::validate_exec(resolved.file.as_fd())?; + + // Hand the validated descriptor itself to the new image instead of a + // pathname to reopen: the file may be replaced or unlinked meanwhile, + // and `/proc/self/fd/N` targets close with `FD_CLOEXEC` on exec. Keep + // `duped_fd` open across `SYS_execve` (`fcntl_dupfd` clears + // `FD_CLOEXEC`). If `prepare_exec_in` fails below, `OwnedFd` closes it + // automatically; once handed back as a raw fd, `cleanup_exec_scratch` + // closes it on `SYS_execve` failure while a successful exec transfers + // it to the child. + let duped_fd = fcntl_dupfd(resolved.file.as_fd(), 3)?; + + let rt = runtime(); + let target = Target::ResolvedFd { + fd: duped_fd.as_raw_fd(), + execfn: IpcStr::from_bytes(&resolved.execfn), + sigmask, + sigsys_ignored, + }; + let bootstrap = Bootstrap { + ipc_channel_conf: rt.ipc_channel_conf, + preload_path: rt.preload_path, + target, + }; + let encoded = encode_bootstrap(&bootstrap, arena); + ensure_bootstrap_env(&mut exec.envs, encoded)?; + + exec.program = copy_bytes(rt.preload_path.as_bytes(), arena); + let raw_out = RawExec::from_exec(exec); + let duped_raw = duped_fd.as_raw_fd(); + core::mem::forget(duped_fd); + Ok((raw_out, duped_raw)) + } +} diff --git a/crates/fspy_client_unix/.clippy.toml b/crates/fspy_preload_macos/.clippy.toml similarity index 100% rename from crates/fspy_client_unix/.clippy.toml rename to crates/fspy_preload_macos/.clippy.toml diff --git a/crates/fspy_preload_unix/Cargo.toml b/crates/fspy_preload_macos/Cargo.toml similarity index 54% rename from crates/fspy_preload_unix/Cargo.toml rename to crates/fspy_preload_macos/Cargo.toml index 8c9a1dc66..505f64240 100644 --- a/crates/fspy_preload_unix/Cargo.toml +++ b/crates/fspy_preload_macos/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "fspy_preload_unix" +name = "fspy_preload_macos" edition = "2024" license.workspace = true publish = false @@ -7,20 +7,16 @@ publish = false [lib] crate-type = ["cdylib"] -[target.'cfg(unix)'.dependencies] +[target.'cfg(target_os = "macos")'.dependencies] +allocator-api2 = { workspace = true, features = ["alloc"] } +bstr = { workspace = true } ctor = { workspace = true } -fspy_client_unix = { workspace = true } +fspy_nostd = { workspace = true } +fspy_nostd_alloc = { workspace = true } fspy_shared = { workspace = true } fspy_shared_unix = { workspace = true } libc = { workspace = true } -nix = { workspace = true, features = ["signal", "fs", "socket", "mman", "time"] } -fspy_nostd = { workspace = true } -allocator-api2 = { workspace = true } -fspy_nostd_alloc = { workspace = true } static_cell = { workspace = true } -[target.'cfg(target_os = "linux")'.dependencies] -syscalls = { workspace = true } - [lints] workspace = true diff --git a/crates/fspy_preload_macos/README.md b/crates/fspy_preload_macos/README.md new file mode 100644 index 000000000..8c3037f02 --- /dev/null +++ b/crates/fspy_preload_macos/README.md @@ -0,0 +1,7 @@ +## fspy_preload_macos + +Dynamic library (`cdylib`) injected into traced macOS processes via +`DYLD_INSERT_LIBRARIES` using dyld's `__DATA,__interpose` section. + +Exec calls are prepared in userland, reading the program to resolve `#!`, so +execute-only (`chmod 0111`) programs fail with `EACCES` under tracking. diff --git a/crates/fspy_preload_macos/src/client.rs b/crates/fspy_preload_macos/src/client.rs new file mode 100644 index 000000000..7e970da7a --- /dev/null +++ b/crates/fspy_preload_macos/src/client.rs @@ -0,0 +1,229 @@ +use std::sync::OnceLock; + +use allocator_api2::alloc::Allocator; +use bstr::BStr; +use fspy_nostd::{BorrowedFd, CStr, CWD, Error, Result, Thin}; +use fspy_nostd_alloc::fs::{fd_path, resolve_path_at}; +use fspy_shared::ipc::{AccessMode, IpcPath, channel::Sender}; +use fspy_shared_unix::{Exec, RawExec, macos::EncodedPayload}; +use libc::{c_char, c_int}; + +pub struct Client<'a> { + encoded_payload: EncodedPayload<'a>, + ipc_sender: Option, +} + +const _: () = { + const fn assert_send_sync() {} + assert_send_sync::>(); +}; + +#[cfg(not(test))] +impl<'a> Client<'a> { + fn from_env( + envs: impl Iterator, + allocator: impl Allocator + Clone + 'a, + ) -> Self { + let encoded_payload = EncodedPayload::from_env(envs, allocator.clone()); + let ipc_sender = encoded_payload.ipc_channel_conf().sender(allocator); + Self { encoded_payload, ipc_sender } + } +} + +impl Client<'_> { + /// Marks the trace incomplete, so the run is reported as untracked + /// instead of cached with a missing access. + pub fn report_loss(&self) { + if let Some(ipc_sender) = &self.ipc_sender { + ipc_sender.report_loss(); + } + } + + pub fn send_path(&self, mode: AccessMode, path: &BStr) { + let Some(ipc_sender) = &self.ipc_sender else { + return; + }; + let bytes: &[u8] = path.as_ref(); + if bytes.starts_with(b"/dev/") { + return; + } + ipc_sender.send(&mode.with_path(IpcPath::from_bytes(bytes))); + } + + /// Prepares an exec call for an already chosen program (callers search + /// `PATH` with [`crate::which::try_path_candidates`]). + /// + /// # Safety + /// + /// `raw_exec` must contain valid pointers satisfying [`RawExec::to_exec`]. + /// The returned [`RawExec`] borrows from `allocator`. + /// + /// # Errors + /// + /// Returns OS-compatible `errno` values from exec preparation. + pub unsafe fn handle_exec( + &self, + raw_exec: RawExec, + allocator: &A, + ) -> Result { + // SAFETY: caller upholds `RawExec::to_exec`'s pointer contract. + unsafe { self.handle_exec_in_dir(None, raw_exec, allocator) } + } + + /// Resolves and prepares an exec call, resolving relative paths against + /// `cwd` (when `Some`, e.g. from `posix_spawn_file_actions_addchdir_np`) + /// instead of the current working directory. + /// + /// # Safety + /// + /// `raw_exec` must contain valid pointers satisfying [`RawExec::to_exec`]. + /// The returned [`RawExec`] borrows from `allocator`. + /// + /// # Errors + /// + /// Returns OS-compatible `errno` values from exec preparation. + pub unsafe fn handle_exec_in_dir( + &self, + cwd: Option<&[u8]>, + raw_exec: RawExec, + allocator: &A, + ) -> Result { + // SAFETY: caller upholds `RawExec::to_exec`'s pointer contract. + let mut exec = unsafe { raw_exec.to_exec(allocator) }?; + self.encoded_payload.prepare_exec_in_dir(&mut exec, cwd, |path| { + self.send_path(AccessMode::Read, path); + })?; + Ok(RawExec::from_exec(exec)) + } + + /// Injects `DYLD_INSERT_LIBRARIES` and `FSPY_PAYLOAD` into `exec.envs` + /// without path resolution, shebang parsing, or SIP swapping. + /// + /// # Errors + /// + /// Returns [`Error::NOMEM`] if environment storage cannot be allocated. + pub fn inject_env(&self, exec: &mut Exec) -> Result<()> { + self.encoded_payload.inject_env(exec) + } +} + +static CLIENT: OnceLock> = OnceLock::new(); + +pub fn global_client() -> Option<&'static Client<'static>> { + CLIENT.get() +} + +pub fn set_errno(error: Error) { + // SAFETY: `__error()` returns a non-null pointer to thread-local `errno`. + unsafe { *::libc::__error() = error.raw_os_error() }; +} + +pub const fn open_flags_mode(flags: c_int) -> AccessMode { + match flags & ::libc::O_ACCMODE { + ::libc::O_RDWR => AccessMode::ReadWrite, + ::libc::O_WRONLY => AccessMode::Write, + _ if flags & (::libc::O_CREAT | ::libc::O_TRUNC) != 0 => AccessMode::ReadWrite, + _ => AccessMode::Read, + } +} + +/// Decodes a `fopen`/`freopen` mode string into an [`AccessMode`]. +/// +/// # Safety +/// +/// `mode` must be null or point to a valid NUL-terminated C string. +pub unsafe fn mode_str_to_access_mode(mode: *const c_char) -> AccessMode { + if mode.is_null() { + return AccessMode::Read; + } + // SAFETY: caller guarantees non-null `mode` points to a valid NUL-terminated string. + let mode_bytes = unsafe { CStr::::from_ptr(mode.cast()) }.count().as_units(); + if mode_bytes.contains(&b'+') { + AccessMode::ReadWrite + } else if mode_bytes.contains(&b'w') || mode_bytes.contains(&b'a') { + AccessMode::Write + } else { + AccessMode::Read + } +} + +/// Reports a path relative to `CWD`. +/// +/// # Safety +/// +/// `path` must point to a valid NUL-terminated C string. +pub unsafe fn handle_open_path(path: *const c_char, mode: AccessMode) { + // SAFETY: `CWD` is permanent and `path` is guaranteed valid by the caller. + unsafe { handle_open_at(CWD.as_raw_fd(), path, mode) }; +} + +/// Reports a path relative to `dirfd` (or ignored when `path` is absolute). +/// +/// # Safety +/// +/// `dirfd` must be `-1` or an open descriptor, and `path` must point to a valid +/// NUL-terminated C string. +pub unsafe fn handle_open_at(dirfd: c_int, path: *const c_char, mode: AccessMode) { + let Some(client) = global_client() else { + return; + }; + if path.is_null() { + return; + } + // SAFETY: non-null `path` is NUL-terminated for the duration of this call. + let c_path = unsafe { CStr::::from_ptr(path.cast()) }; + if c_path.count().as_units().is_empty() { + return; + } + let arena = fspy_nostd_alloc::pooled_bump(); + // SAFETY: `dirfd` is `-1` or open, and `path` is a non-null C string. + let dirfd = unsafe { BorrowedFd::try_borrow_raw(dirfd) }; + match resolve_path_at(&arena, dirfd, c_path) { + Ok(Some(resolved)) => client.send_path(mode, BStr::new(resolved.as_units())), + // The call fails with `EBADF` and accesses nothing. + Ok(None) if dirfd.is_none_or(|fd| !is_open_fd(fd)) => {} + // The access may happen, but its path is unknown (for example when + // opening `.` fails with `EMFILE`), so the trace is incomplete. + Ok(None) | Err(_) => client.report_loss(), + } +} + +/// Returns whether `fd` is an open descriptor, counting `AT_FDCWD`. +fn is_open_fd(fd: BorrowedFd<'_>) -> bool { + // SAFETY: `F_GETFD` only queries the descriptor's flags. + fd.as_raw_fd() == CWD.as_raw_fd() || unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_GETFD) } != -1 +} + +/// Reports an access on an open descriptor (such as `fdopendir`). +/// +/// # Safety +/// +/// `fd` must be `-1` or an open descriptor. +pub unsafe fn handle_open_fd(fd: c_int, mode: AccessMode) { + let Some(client) = global_client() else { + return; + }; + // SAFETY: `fd` is `-1` or an open descriptor. + let Some(fd) = (unsafe { BorrowedFd::try_borrow_raw(fd) }) else { + return; + }; + let arena = fspy_nostd_alloc::pooled_bump(); + match fd_path(&arena, fd) { + Ok(Some(resolved)) => client.send_path(mode, BStr::new(resolved.as_units())), + Ok(None) if !is_open_fd(fd) => {} + Ok(None) | Err(_) => client.report_loss(), + } +} + +#[cfg(not(test))] +#[ctor::ctor(unsafe)] +fn init_client() { + // SAFETY: the ctor only reads the process environment while constructing + // the client and does not retain borrowed environment views. + let current = unsafe { fspy_nostd::env::current() }.unwrap(); + static BUMP: static_cell::StaticCell = + static_cell::StaticCell::new(); + let bump: &'static fspy_nostd_alloc::PageBump = BUMP.init(fspy_nostd_alloc::page_bump()); + let client = Client::from_env(current.envs(), bump); + assert!(CLIENT.set(client).is_ok(), "client already initialized"); +} diff --git a/crates/fspy_preload_unix/src/interceptions/access.rs b/crates/fspy_preload_macos/src/interceptions/access.rs similarity index 52% rename from crates/fspy_preload_unix/src/interceptions/access.rs rename to crates/fspy_preload_macos/src/interceptions/access.rs index db220a314..69fd8e7b7 100644 --- a/crates/fspy_preload_unix/src/interceptions/access.rs +++ b/crates/fspy_preload_macos/src/interceptions/access.rs @@ -2,17 +2,15 @@ use fspy_shared::ipc::AccessMode; use libc::{c_char, c_int}; use crate::{ - client::{convert::PathAt, handle_open}, + client::{handle_open_at, handle_open_path}, macros::intercept, }; intercept!(access(64): unsafe extern "C" fn(pathname: *const c_char, mode: c_int) -> c_int); unsafe extern "C" fn access(pathname: *const c_char, mode: c_int) -> c_int { - // SAFETY: pathname is a valid C string pointer provided by the caller of the interposed function - unsafe { - handle_open(fspy_nostd::CStr::from_ptr(pathname.cast()), AccessMode::Read); - } - // SAFETY: calling the original libc access() with the same arguments forwarded from the interposed function + // SAFETY: pathname is a valid C string pointer provided by the caller. + unsafe { handle_open_path(pathname, AccessMode::Read) }; + // SAFETY: calling the original libc access() with forwarded arguments. unsafe { access::original()(pathname, mode) } } @@ -23,10 +21,8 @@ unsafe extern "C" fn faccessat( mode: c_int, flags: c_int, ) -> c_int { - // SAFETY: dirfd is -1 or a valid file descriptor, and pathname is a valid C string, provided by the caller of the interposed function - unsafe { - handle_open(PathAt::borrow_raw(dirfd, pathname), AccessMode::Read); - } - // SAFETY: calling the original libc faccessat() with the same arguments forwarded from the interposed function + // SAFETY: dirfd is -1 or valid, and pathname is a valid C string. + unsafe { handle_open_at(dirfd, pathname, AccessMode::Read) }; + // SAFETY: calling the original libc faccessat() with forwarded arguments. unsafe { faccessat::original()(dirfd, pathname, mode, flags) } } diff --git a/crates/fspy_preload_macos/src/interceptions/dirent.rs b/crates/fspy_preload_macos/src/interceptions/dirent.rs new file mode 100644 index 000000000..5d8c9d175 --- /dev/null +++ b/crates/fspy_preload_macos/src/interceptions/dirent.rs @@ -0,0 +1,85 @@ +use fspy_shared::ipc::AccessMode; +use libc::{DIR, c_char, c_int, c_long, c_void}; + +use crate::{ + client::{handle_open_fd, handle_open_path}, + macros::intercept, +}; + +intercept!(scandir(64): unsafe extern "C" fn( + dirname: *const c_char, + namelist: *mut c_void, + select: *const c_void, + compar: *const c_void, +) -> c_int); +unsafe extern "C" fn scandir( + dirname: *const c_char, + namelist: *mut c_void, + select: *const c_void, + compar: *const c_void, +) -> c_int { + // SAFETY: dirname is a valid C string pointer provided by the caller. + unsafe { handle_open_path(dirname, AccessMode::ReadDir) }; + // SAFETY: calling the original libc scandir() with forwarded arguments. + unsafe { scandir::original()(dirname, namelist, select, compar) } +} + +intercept!(scandir_b: unsafe extern "C" fn( + dirname: *const c_char, + namelist: *mut c_void, + select: *const c_void, + compar: *const c_void, +) -> c_int); +unsafe extern "C" fn scandir_b( + dirname: *const c_char, + namelist: *mut c_void, + select: *const c_void, + compar: *const c_void, +) -> c_int { + // SAFETY: dirname is a valid C string pointer provided by the caller. + unsafe { handle_open_path(dirname, AccessMode::ReadDir) }; + // SAFETY: calling the original libc scandir_b() with forwarded arguments. + unsafe { scandir_b::original()(dirname, namelist, select, compar) } +} + +intercept!(__getdirentries64: unsafe extern "C" fn(c_int, *mut u8, usize, *mut i64) -> isize); +unsafe extern "C" fn __getdirentries64( + fd: c_int, + buf: *mut u8, + buf_len: usize, + basep: *mut i64, +) -> isize { + // SAFETY: fd is -1 or a valid file descriptor provided by the caller. + unsafe { handle_open_fd(fd, AccessMode::ReadDir) }; + // SAFETY: calling the original libc __getdirentries64() with forwarded arguments. + unsafe { __getdirentries64::original()(fd, buf, buf_len, basep) } +} + +intercept!(getdirentries(64): unsafe extern "C" fn(fd: c_int, buf: *mut c_char, nbytes: c_int, basep: *mut c_long) -> c_int); +unsafe extern "C" fn getdirentries( + fd: c_int, + buf: *mut c_char, + nbytes: c_int, + basep: *mut c_long, +) -> c_int { + // SAFETY: fd is -1 or a valid file descriptor provided by the caller. + unsafe { handle_open_fd(fd, AccessMode::ReadDir) }; + // SAFETY: calling the original libc getdirentries() with forwarded arguments. + unsafe { getdirentries::original()(fd, buf, nbytes, basep) } +} + +intercept!(fdopendir(64): unsafe extern "C" fn(fd: c_int) -> *mut DIR); +unsafe extern "C" fn fdopendir(fd: c_int) -> *mut DIR { + // SAFETY: fd is -1 or a valid file descriptor provided by the caller. + unsafe { handle_open_fd(fd, AccessMode::ReadDir) }; + // SAFETY: calling the original libc fdopendir() with forwarded arguments. + unsafe { fdopendir::original()(fd) } +} + +intercept!(opendir(64): unsafe extern "C" fn(*const c_char) -> *mut DIR); +unsafe extern "C" fn opendir(dir_name: *const c_char) -> *mut DIR { + // SAFETY: dir_name is a valid C string pointer provided by the caller. + unsafe { handle_open_path(dir_name, AccessMode::ReadDir) }; + // SAFETY: calling the original libc opendir() with forwarded arguments. + unsafe { opendir::original()(dir_name) } +} diff --git a/crates/fspy_preload_unix/src/interceptions/dyld.rs b/crates/fspy_preload_macos/src/interceptions/dyld.rs similarity index 72% rename from crates/fspy_preload_unix/src/interceptions/dyld.rs rename to crates/fspy_preload_macos/src/interceptions/dyld.rs index 9ea93d026..bdf825039 100644 --- a/crates/fspy_preload_unix/src/interceptions/dyld.rs +++ b/crates/fspy_preload_macos/src/interceptions/dyld.rs @@ -16,6 +16,8 @@ //! [`RuntimeState::loadInsertedLibraries`]: https://github.com/apple-oss-distributions/dyld/blob/fd8d0c4d52320ebf64db34f3cb280310d905c5ae/dyld/DyldRuntimeState.cpp#L676-L680 //! [`normalizeImageIndex`]: https://github.com/apple-oss-distributions/dyld/blob/fd8d0c4d52320ebf64db34f3cb280310d905c5ae/dyld/DyldAPIs.cpp#L238-L253 +use std::sync::atomic::{AtomicU32, Ordering}; + use crate::{ libc::{c_char, intptr_t, mach_header}, macros::intercept, @@ -24,24 +26,46 @@ use crate::{ /// `MH_EXECUTE` from ``. const MH_EXECUTE: u32 = 0x2; -/// Maps an index in the presented order to dyld's actual index. -/// -/// The main executable is looked up on every call rather than cached: its -/// index stays fixed only because of undocumented dyld behavior. -fn actual_image_index(image_index: u32) -> u32 { +/// Sentinel indicating the main executable's dyld image index is not yet cached. +const UNSET_INDEX: u32 = u32::MAX; + +/// Cached dyld index of the `MH_EXECUTE` image. Verified in O(1) on every call +/// so we never rely on dyld keeping the index fixed across image mutations, +/// while avoiding an O(N) linear scan per query. +static MAIN_IMAGE_INDEX: AtomicU32 = AtomicU32::new(UNSET_INDEX); + +fn find_main_image_index() -> Option { + let cached = MAIN_IMAGE_INDEX.load(Ordering::Relaxed); + if cached != UNSET_INDEX { + // SAFETY: dyld returns null for out-of-range indices. + let header = unsafe { _dyld_get_image_header::original()(cached) }; + // SAFETY: a non-null header points to the loaded image's mach header. + if !header.is_null() && unsafe { (*header).filetype } == MH_EXECUTE { + return Some(cached); + } + } + let mut main_index = 0; loop { // SAFETY: dyld returns null for out-of-range indices. let header = unsafe { _dyld_get_image_header::original()(main_index) }; if header.is_null() { - return image_index; + return None; } // SAFETY: a non-null header points to the loaded image's mach header. if unsafe { (*header).filetype } == MH_EXECUTE { - break; + MAIN_IMAGE_INDEX.store(main_index, Ordering::Relaxed); + return Some(main_index); } main_index += 1; } +} + +/// Maps an index in the presented order to dyld's actual index. +fn actual_image_index(image_index: u32) -> u32 { + let Some(main_index) = find_main_image_index() else { + return image_index; + }; match image_index { 0 => main_index, index if index <= main_index => index - 1, diff --git a/crates/fspy_preload_unix/src/interceptions/mod.rs b/crates/fspy_preload_macos/src/interceptions/mod.rs similarity index 51% rename from crates/fspy_preload_unix/src/interceptions/mod.rs rename to crates/fspy_preload_macos/src/interceptions/mod.rs index 389462e18..019f9c098 100644 --- a/crates/fspy_preload_unix/src/interceptions/mod.rs +++ b/crates/fspy_preload_macos/src/interceptions/mod.rs @@ -1,11 +1,7 @@ mod access; mod dirent; -#[cfg(target_os = "macos")] mod dyld; mod namespace; mod open; mod spawn; mod stat; - -#[cfg(target_os = "linux")] -mod linux_syscall; diff --git a/crates/fspy_preload_macos/src/interceptions/namespace.rs b/crates/fspy_preload_macos/src/interceptions/namespace.rs new file mode 100644 index 000000000..fa83e07fa --- /dev/null +++ b/crates/fspy_preload_macos/src/interceptions/namespace.rs @@ -0,0 +1,124 @@ +//! Calls that make an entry at a path without opening it: mkdir, symlink, +//! and rename and hard link, which put an existing file or folder at a new +//! path. + +use fspy_shared::ipc::AccessMode; +use libc::{c_char, c_int, mode_t}; + +use crate::{ + client::{handle_open_at, handle_open_path}, + macros::intercept, +}; + +intercept!(mkdir: unsafe extern "C" fn(path: *const c_char, mode: mode_t) -> c_int); +unsafe extern "C" fn mkdir(path: *const c_char, mode: mode_t) -> c_int { + // SAFETY: path is a valid C string pointer provided by the caller. + unsafe { handle_open_path(path, AccessMode::Mkdir) }; + // SAFETY: calling the original libc mkdir() with forwarded arguments. + unsafe { mkdir::original()(path, mode) } +} + +intercept!(mkdirat: unsafe extern "C" fn(dirfd: c_int, path: *const c_char, mode: mode_t) -> c_int); +unsafe extern "C" fn mkdirat(dirfd: c_int, path: *const c_char, mode: mode_t) -> c_int { + // SAFETY: dirfd is -1 or valid, and path is a valid C string. + unsafe { handle_open_at(dirfd, path, AccessMode::Mkdir) }; + // SAFETY: calling the original libc mkdirat() with forwarded arguments. + unsafe { mkdirat::original()(dirfd, path, mode) } +} + +intercept!(rename: unsafe extern "C" fn(old: *const c_char, new: *const c_char) -> c_int); +unsafe extern "C" fn rename(old: *const c_char, new: *const c_char) -> c_int { + // SAFETY: new is a valid C string pointer provided by the caller. + unsafe { handle_open_path(new, AccessMode::RenameTarget) }; + // SAFETY: calling the original libc rename() with forwarded arguments. + unsafe { rename::original()(old, new) } +} + +intercept!(renameat: unsafe extern "C" fn(olddirfd: c_int, old: *const c_char, newdirfd: c_int, new: *const c_char) -> c_int); +unsafe extern "C" fn renameat( + olddirfd: c_int, + old: *const c_char, + newdirfd: c_int, + new: *const c_char, +) -> c_int { + // SAFETY: newdirfd is -1 or valid, and new is a valid C string. + unsafe { handle_open_at(newdirfd, new, AccessMode::RenameTarget) }; + // SAFETY: calling the original libc renameat() with forwarded arguments. + unsafe { renameat::original()(olddirfd, old, newdirfd, new) } +} + +intercept!(renamex_np: unsafe extern "C" fn(old: *const c_char, new: *const c_char, flags: libc::c_uint) -> c_int); +unsafe extern "C" fn renamex_np( + old: *const c_char, + new: *const c_char, + flags: libc::c_uint, +) -> c_int { + if flags & libc::RENAME_SWAP != 0 { + // SAFETY: old is a valid C string pointer provided by the caller. + unsafe { handle_open_path(old, AccessMode::RenameTarget) }; + } + // SAFETY: new is a valid C string pointer provided by the caller. + unsafe { handle_open_path(new, AccessMode::RenameTarget) }; + // SAFETY: calling the original libc renamex_np() with forwarded arguments. + unsafe { renamex_np::original()(old, new, flags) } +} + +intercept!(renameatx_np: unsafe extern "C" fn(olddirfd: c_int, old: *const c_char, newdirfd: c_int, new: *const c_char, flags: libc::c_uint) -> c_int); +unsafe extern "C" fn renameatx_np( + olddirfd: c_int, + old: *const c_char, + newdirfd: c_int, + new: *const c_char, + flags: libc::c_uint, +) -> c_int { + if flags & libc::RENAME_SWAP != 0 { + // SAFETY: olddirfd is -1 or valid, and old is a valid C string. + unsafe { handle_open_at(olddirfd, old, AccessMode::RenameTarget) }; + } + // SAFETY: newdirfd is -1 or valid, and new is a valid C string. + unsafe { handle_open_at(newdirfd, new, AccessMode::RenameTarget) }; + // SAFETY: calling the original libc renameatx_np() with forwarded arguments. + unsafe { renameatx_np::original()(olddirfd, old, newdirfd, new, flags) } +} + +intercept!(link: unsafe extern "C" fn(old: *const c_char, new: *const c_char) -> c_int); +unsafe extern "C" fn link(old: *const c_char, new: *const c_char) -> c_int { + // SAFETY: new is a valid C string pointer provided by the caller. + unsafe { handle_open_path(new, AccessMode::Write) }; + // SAFETY: calling the original libc link() with forwarded arguments. + unsafe { link::original()(old, new) } +} + +intercept!(linkat: unsafe extern "C" fn(olddirfd: c_int, old: *const c_char, newdirfd: c_int, new: *const c_char, flags: c_int) -> c_int); +unsafe extern "C" fn linkat( + olddirfd: c_int, + old: *const c_char, + newdirfd: c_int, + new: *const c_char, + flags: c_int, +) -> c_int { + // SAFETY: newdirfd is -1 or valid, and new is a valid C string. + unsafe { handle_open_at(newdirfd, new, AccessMode::Write) }; + // SAFETY: calling the original libc linkat() with forwarded arguments. + unsafe { linkat::original()(olddirfd, old, newdirfd, new, flags) } +} + +intercept!(symlink: unsafe extern "C" fn(target: *const c_char, link: *const c_char) -> c_int); +unsafe extern "C" fn symlink(target: *const c_char, link: *const c_char) -> c_int { + // SAFETY: link is a valid C string pointer provided by the caller. + unsafe { handle_open_path(link, AccessMode::Write) }; + // SAFETY: calling the original libc symlink() with forwarded arguments. + unsafe { symlink::original()(target, link) } +} + +intercept!(symlinkat: unsafe extern "C" fn(target: *const c_char, newdirfd: c_int, link: *const c_char) -> c_int); +unsafe extern "C" fn symlinkat( + target: *const c_char, + newdirfd: c_int, + link: *const c_char, +) -> c_int { + // SAFETY: newdirfd is -1 or valid, and link is a valid C string. + unsafe { handle_open_at(newdirfd, link, AccessMode::Write) }; + // SAFETY: calling the original libc symlinkat() with forwarded arguments. + unsafe { symlinkat::original()(target, newdirfd, link) } +} diff --git a/crates/fspy_preload_unix/src/interceptions/open.rs b/crates/fspy_preload_macos/src/interceptions/open.rs similarity index 50% rename from crates/fspy_preload_unix/src/interceptions/open.rs rename to crates/fspy_preload_macos/src/interceptions/open.rs index cb8ac5f3b..1f3fe60f6 100644 --- a/crates/fspy_preload_unix/src/interceptions/open.rs +++ b/crates/fspy_preload_macos/src/interceptions/open.rs @@ -1,41 +1,29 @@ use libc::FILE; use crate::{ - client::{ - convert::{ModeStr, OpenFlags, PathAt}, - handle_open, - }, + client::{handle_open_at, handle_open_path, mode_str_to_access_mode, open_flags_mode}, libc::{c_char, c_int}, macros::intercept, }; const fn has_mode_arg(o_flags: c_int) -> bool { - if o_flags & libc::O_CREAT != 0 { - return true; - } - #[cfg(target_os = "linux")] - if o_flags & libc::O_TMPFILE != 0 { - return true; - } - false + o_flags & libc::O_CREAT != 0 } -#[cfg(not(target_os = "macos"))] -type Mode = libc::mode_t; -#[cfg(target_os = "macos")] // https://github.com/tailhook/openat/issues/21#issuecomment-535914957 +// https://github.com/tailhook/openat/issues/21#issuecomment-535914957 type Mode = c_int; intercept!(open(64): unsafe extern "C" fn(*const c_char, c_int, args: ...) -> c_int); unsafe extern "C" fn open(path: *const c_char, flags: c_int, mut args: ...) -> c_int { - // SAFETY: path is a valid C string pointer provided by the caller of the interposed function - unsafe { handle_open(fspy_nostd::CStr::from_ptr(path.cast()), OpenFlags(flags)) }; + // SAFETY: path is a valid C string pointer provided by the caller. + unsafe { handle_open_path(path, open_flags_mode(flags)) }; if has_mode_arg(flags) { - // SAFETY: when O_CREAT or O_TMPFILE is set, a mode_t argument is required by the open() contract + // SAFETY: O_CREAT requires a mode argument. let mode: Mode = unsafe { args.next_arg() }; - // SAFETY: calling the original libc open() with the same arguments forwarded from the interposed function + // SAFETY: calling the original libc open() with forwarded arguments. unsafe { open::original()(path, flags, mode) } } else { - // SAFETY: calling the original libc open() with the same arguments forwarded from the interposed function + // SAFETY: calling the original libc open() with forwarded arguments. unsafe { open::original()(path, flags) } } } @@ -47,65 +35,59 @@ unsafe extern "C" fn openat( flags: c_int, mut args: ... ) -> c_int { - // SAFETY: dirfd is -1 or a valid file descriptor, and path is a valid C string, provided by the caller of the interposed function - unsafe { handle_open(PathAt::borrow_raw(dirfd, path), OpenFlags(flags)) }; - + // SAFETY: dirfd is -1 or valid, and path is a valid C string. + unsafe { handle_open_at(dirfd, path, open_flags_mode(flags)) }; if has_mode_arg(flags) { - // https://github.com/tailhook/openat/issues/21#issuecomment-535914957 - // SAFETY: when O_CREAT or O_TMPFILE is set, a mode_t argument is required by the openat() contract + // SAFETY: O_CREAT requires a mode argument. let mode: Mode = unsafe { args.next_arg() }; - // SAFETY: calling the original libc openat() with the same arguments forwarded from the interposed function + // SAFETY: calling the original libc openat() with forwarded arguments. unsafe { openat::original()(dirfd, path, flags, mode) } } else { - // SAFETY: calling the original libc openat() with the same arguments forwarded from the interposed function + // SAFETY: calling the original libc openat() with forwarded arguments. unsafe { openat::original()(dirfd, path, flags) } } } -#[cfg(target_os = "macos")] intercept!(open_nocancel: unsafe extern "C" fn(*const c_char, c_int, ...) -> c_int); -#[cfg(target_os = "macos")] unsafe extern "C" fn open_nocancel(path: *const c_char, flags: c_int, mut args: ...) -> c_int { - // SAFETY: path is a valid C string pointer provided by the caller of open$NOCANCEL - unsafe { handle_open(fspy_nostd::CStr::from_ptr(path.cast()), OpenFlags(flags)) }; + // SAFETY: path is a valid C string pointer provided by the caller. + unsafe { handle_open_path(path, open_flags_mode(flags)) }; if has_mode_arg(flags) { - // SAFETY: O_CREAT requires a mode argument, matching the open$NOCANCEL contract + // SAFETY: O_CREAT requires a mode argument. let mode: Mode = unsafe { args.next_arg() }; - // SAFETY: calling the original libc open$NOCANCEL() with the same arguments forwarded from the interposed function + // SAFETY: calling the original libc open$NOCANCEL() with forwarded arguments. unsafe { open_nocancel::original()(path, flags, mode) } } else { - // SAFETY: calling the original libc open$NOCANCEL() with the same arguments forwarded from the interposed function + // SAFETY: calling the original libc open$NOCANCEL() with forwarded arguments. unsafe { open_nocancel::original()(path, flags) } } } -#[cfg(target_os = "macos")] intercept!(openat_nocancel: unsafe extern "C" fn(c_int, *const c_char, c_int, ...) -> c_int); -#[cfg(target_os = "macos")] unsafe extern "C" fn openat_nocancel( dirfd: c_int, path: *const c_char, flags: c_int, mut args: ... ) -> c_int { - // SAFETY: dirfd is -1 or a valid file descriptor, and path is a valid C string, provided by the caller of openat$NOCANCEL - unsafe { handle_open(PathAt::borrow_raw(dirfd, path), OpenFlags(flags)) }; + // SAFETY: dirfd is -1 or valid, and path is a valid C string. + unsafe { handle_open_at(dirfd, path, open_flags_mode(flags)) }; if has_mode_arg(flags) { - // SAFETY: O_CREAT requires a mode argument, matching the openat$NOCANCEL contract + // SAFETY: O_CREAT requires a mode argument. let mode: Mode = unsafe { args.next_arg() }; - // SAFETY: calling the original libc openat$NOCANCEL() with the same arguments forwarded from the interposed function + // SAFETY: calling the original libc openat$NOCANCEL() with forwarded arguments. unsafe { openat_nocancel::original()(dirfd, path, flags, mode) } } else { - // SAFETY: calling the original libc openat$NOCANCEL() with the same arguments forwarded from the interposed function + // SAFETY: calling the original libc openat$NOCANCEL() with forwarded arguments. unsafe { openat_nocancel::original()(dirfd, path, flags) } } } intercept!(fopen(64): unsafe extern "C" fn(path: *const c_char, mode: *const c_char) -> *mut FILE); unsafe extern "C" fn fopen(path: *const c_char, mode: *const c_char) -> *mut libc::FILE { - // SAFETY: path and mode are valid C string pointers provided by the caller of the interposed function - unsafe { handle_open(fspy_nostd::CStr::from_ptr(path.cast()), ModeStr(mode)) }; - // SAFETY: calling the original libc fopen() with the same arguments forwarded from the interposed function + // SAFETY: path and mode are valid C string pointers provided by the caller. + unsafe { handle_open_path(path, mode_str_to_access_mode(mode)) }; + // SAFETY: calling the original libc fopen() with forwarded arguments. unsafe { fopen::original()(path, mode) } } @@ -115,8 +97,8 @@ unsafe extern "C" fn freopen( mode: *const c_char, stream: *mut FILE, ) -> *mut FILE { - // SAFETY: path and mode are valid C string pointers provided by the caller of the interposed function - unsafe { handle_open(fspy_nostd::CStr::from_ptr(path.cast()), ModeStr(mode)) }; - // SAFETY: calling the original libc freopen() with the same arguments forwarded from the interposed function + // SAFETY: path and mode are valid C string pointers provided by the caller. + unsafe { handle_open_path(path, mode_str_to_access_mode(mode)) }; + // SAFETY: calling the original libc freopen() with forwarded arguments. unsafe { freopen::original()(path, mode, stream) } } diff --git a/crates/fspy_preload_macos/src/interceptions/spawn/exec/mod.rs b/crates/fspy_preload_macos/src/interceptions/spawn/exec/mod.rs new file mode 100644 index 000000000..d1dc4a0b1 --- /dev/null +++ b/crates/fspy_preload_macos/src/interceptions/spawn/exec/mod.rs @@ -0,0 +1,169 @@ +use std::{ffi::VaList, ptr::null}; + +use allocator_api2::{alloc::Allocator, vec::Vec}; +use fspy_nostd::{CStr, Error, Result, Thin}; +use fspy_shared::ipc::AccessMode; +use fspy_shared_unix::RawExec; +use libc::{c_char, c_int}; + +use crate::{ + client::{global_client, set_errno}, + macros::intercept, + which, +}; + +unsafe fn environ() -> *const *const c_char { + // SAFETY: `_NSGetEnviron()` always returns a valid pointer to the process's `environ`. + unsafe { *(libc::_NSGetEnviron().cast()) } +} + +/// Collects `arg` and the variadic arguments after it into a NULL-terminated +/// argv array in `allocator` (never touching libc malloc). +/// +/// # Safety +/// +/// Unless `arg` is NULL, `va` must hold `*const c_char` arguments up to a +/// NULL pointer. +unsafe fn collect_argv( + allocator: A, + mut arg: *const c_char, + va: &mut VaList<'_>, +) -> Vec<*const c_char, A> { + let mut argv = Vec::new_in(allocator); + while !arg.is_null() { + argv.push(arg); + // SAFETY: caller guarantees arguments continue up to a NULL pointer. + arg = unsafe { va.next_arg() }; + } + argv.push(null()); + argv +} + +fn handle_exec( + allocator: impl Allocator, + search_path: bool, + prog: *const c_char, + argv: *const *const c_char, + envp: *const *const c_char, +) -> c_int { + let client = + global_client().expect("exec unexpectedly called before client initialized in ctor"); + let allocator = &allocator; + // Prepares and runs one candidate; returns only when the exec fails. + let exec_program = |prog: *const c_char, argv: *const *const c_char| -> Result<()> { + // SAFETY: prog, argv, and envp are forwarded from the interposed exec call. + let raw = unsafe { client.handle_exec(RawExec { prog, argv, envp }, allocator) }?; + // SAFETY: `raw` points into `allocator`, which outlives this call. + unsafe { execve::original()(raw.prog, raw.argv, raw.envp) }; + Err(Error::last_os_error()) + }; + let err = if search_path && !prog.is_null() { + // SAFETY: a non-null `prog` is the caller's NUL-terminated file name. + let file = unsafe { CStr::::from_ptr(prog.cast()) }.count(); + let result = which::try_path_candidates( + file.as_units(), + None, + allocator, + |candidate| client.send_path(AccessMode::Read, candidate), + |candidate| exec_program(candidate.as_ptr().cast(), argv), + // Like Darwin `execvp`, run a file without a recognized format with + // `/bin/sh`, through the same preparation (SIP copy, tracking). + |candidate| { + // SAFETY: `argv` is the caller's NULL-terminated argument array. + let shell_argv = unsafe { shell_argv(allocator, candidate, argv) }; + exec_program(c"/bin/sh".as_ptr(), shell_argv.as_ptr()) + }, + ); + result.err().unwrap_or(Error::NOENT) + } else { + exec_program(prog, argv).err().unwrap_or(Error::NOENT) + }; + set_errno(err); + -1 +} + +/// Builds `sh