diff --git a/CHANGELOG.md b/CHANGELOG.md index 772580ac..92b407ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,14 @@ inventory of all post-v1.1.0 changes. ### Added +- Confined local model execution (#72, F16): `forge suggest run` now executes + the consented adapter under OS confinement on macOS (deny-default Seatbelt + via `sandbox-exec`) and Linux (Landlock filesystem ruleset + seccomp-BPF + network deny), with verified-byte execution, cleared environment, bounded + output, and process-group cleanup on timeout or refusal. Execution fails + closed where no approved mechanism exists; Windows stays refused. Recorded- + response mode is unchanged. See `docs/local-model-confinement.md`. No new + dependencies. - Local container packaging (#63): multi-stage Dockerfile with digest-pinned bases and a non-root runtime, Docker Compose loopback workspace setup, and container usage documentation (`docs/container.md`). No conversion or diff --git a/docs/local-model-confinement.md b/docs/local-model-confinement.md new file mode 100644 index 00000000..76c85cd4 --- /dev/null +++ b/docs/local-model-confinement.md @@ -0,0 +1,119 @@ +# Local model confinement boundary + +`forge suggest run` can execute a consented local model executable +(`ProcessModelAdapter`) or replay a separately reviewed recorded response +(`--recorded-response`). Process execution is confined by the operating +system on macOS and Linux and **fails closed everywhere else**: if the +confinement mechanism cannot be established, FORGE refuses to run the adapter +rather than running it unconfined. This note records exactly what is confined, +the platform limitations, and how to verify the boundary. + +The design was approved Unix-first in the owner decision record of 2026-11-13 +(ticket #72 / F16). Windows remains refused pending a separate `windows-sys` +PRD 069 approval; no Windows confinement is implemented or claimed. + +## What is confined + +On both supported platforms the adapter child: + +- runs with a **cleared environment** (`env_clear`); +- is bound to **verified bytes**: the executable is re-hashed immediately + before spawn and refused if it differs from the consented + `executable_sha256`; +- leads a **fresh process group**, so a timeout or refusal kills every + descendant with one `killpg`, not just the leader; +- has **bounded stdout/stderr** (8 MiB / 64 KiB); an over-bound stream is a + refusal, never a silent truncation; +- must finish within the requested `--timeout`; descendants holding the pipes + open cannot extend it. After a kill, pipe draining is bounded by a short + grace period: a reader still blocked by an escaped descendant is detached + (not joined forever), and the scratch directory is kept rather than recycled + so a surviving descendant cannot write into a reused path. + +### macOS — Seatbelt via `sandbox-exec` + +The child is spawned through `/usr/bin/sandbox-exec` with a deny-default +profile. The profile allows: + +- read of the executable, its ancestor directories (path traversal), and the + system runtime (`/usr/lib`, `/bin`, `/usr/bin`, `/System`, the dyld cache + locations, `/dev/fd`); +- read/write of `/dev/null`, `/dev/zero`, `/dev/random`, `/dev/urandom`, + `/dev/tty`, `/dev/dtracehelper`; +- read/write of one private per-invocation scratch directory; +- `process*`, `signal`, `sysctl-read`, `mach*` (needed to launch and run). + +Everything else — including **all network access** and any file outside the +allowlist — is denied. The profile is inherited by every descendant. If +`sandbox-exec` is absent the adapter fails closed. + +### Linux — Landlock + seccomp-BPF + +Before `exec`, the child installs (via `libc`, no new dependency): + +- a **Landlock** filesystem ruleset (kernel ≥ 5.13) allowing read/execute of + the executable, read/execute of the runtime directories and linker cache, + read/write of the null/zero/random devices, and read/write/create within the + private scratch directory. All other filesystem access is denied. On a + kernel without Landlock the adapter refuses with a clear error. +- a **seccomp-BPF** filter that returns `EPERM` for every socket-creating + syscall (`socket`, `socketpair`, the `io_uring_*` family, and `socketcall` + on i386), + kills the process on a foreign ABI or the x32 syscall range, and allows the + rest. This blocks network egress including the `io_uring` bypass. The filter + is inherited across `fork`/`exec`. + +`no_new_privs` is set first, as both mechanisms require it. The seccomp policy +is defined for x86-64 and aarch64; other Linux architectures fail closed. + +## What is NOT confined + +The boundary is **filesystem and network only**. CPU time, memory, and process +count are not limited, and the executable runs with the operator's own user +identity inside the sandbox. A malicious model can still consume resources +until the timeout kills its group. Treat the executable as trusted code that +is being prevented from reaching data and networks it was not consented to, +not as a defense against arbitrary hostile computation. + +## Platform limitations + +- **Windows**: refused (`PROCESS_EXECUTION_UNAVAILABLE`). No mechanism is + implemented; a separate `windows-sys` approval is deferred. +- **Linux kernels < 5.13** (or Landlock disabled): refused with a clear + "Landlock is unavailable" error. +- **Linux containers with a blocking seccomp profile** (e.g. the Docker + default profile, which denies the `landlock_*` syscalls): the adapter fails + closed. To exercise confinement in such a container, run with + `--security-opt seccomp=unconfined` or a profile that permits the Landlock + syscalls; FORGE does not weaken confinement to accommodate the container. +- **macOS without `/usr/bin/sandbox-exec`**: refused. +- **Linux architectures other than x86-64/aarch64**: refused (no approved + seccomp policy). + +## How to verify + +The integration suite `tests/suggest_confinement_test.rs` exercises the +boundary on each platform (gated by `cfg`): + +```bash +cargo test --test suggest_confinement_test +``` + +It asserts: a replaced or deleted executable is refused before spawn; a +confined child cannot read or write outside the allowlist; a confined child +cannot create a socket or reach a listening socket (with an unconfined control +proving the listener is reachable); the exact payload is delivered; a timeout +kills every descendant; a pipe-holding descendant cannot extend the timeout; +and over-bound output and non-zero exits are refused. On hosts where the +mechanism is unavailable the tests assert the fail-closed refusal instead. + +To verify manually on Linux in Docker: + +```bash +docker run --rm --security-opt seccomp=unconfined \ + -v "$PWD":/w -w /w rust:1.90-bookworm \ + cargo test --test suggest_confinement_test +``` + +Recorded-response mode (`--recorded-response`) never spawns a process and is +unaffected by any of the above. \ No newline at end of file diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 76d0f59e..272c43f0 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -1916,7 +1916,7 @@ pub enum SuggestCommand { #[arg(long, value_enum, default_value_t = AuthorReportFormat::Text)] format: AuthorReportFormat, }, - /// Import a recorded response for a consented payload (process execution is disabled) + /// Run the consented adapter under OS confinement, or import a recorded response Run { /// The prepared forge.suggest-request/1 document #[arg(long)] @@ -1933,7 +1933,7 @@ pub enum SuggestCommand { /// Adapter timeout in seconds #[arg(long, default_value_t = crate::suggest::run::DEFAULT_TIMEOUT_SECS)] timeout: u64, - /// Import a recorded response; required while process execution is disabled + /// Import a recorded response instead of running the confined adapter #[arg(long)] recorded_response: Option, /// Print text or versioned JSON to stdout diff --git a/src/suggest/adapter.rs b/src/suggest/adapter.rs index 099c8ce5..a67f6491 100644 --- a/src/suggest/adapter.rs +++ b/src/suggest/adapter.rs @@ -1,8 +1,10 @@ -//! Recorded-response adapters and a fail-closed process boundary. +//! Recorded-response adapters and a confined process boundary. //! -//! Process execution is unavailable until FORGE can enforce filesystem and -//! network confinement, bind execution to verified bytes, and own descendants -//! on every supported platform. A local executable is not itself a sandbox. +//! On macOS and Linux a process adapter runs under OS filesystem/network +//! confinement (Seatbelt or Landlock+seccomp), bound to verified bytes, with +//! every descendant owned by FORGE. Where no approved mechanism exists the +//! adapter fails closed; a local executable is not itself a sandbox. See +//! `docs/local-model-confinement.md` for the exact boundary. use std::path::{Path, PathBuf}; use std::time::Duration; @@ -13,8 +15,9 @@ use super::request::MAX_ARG_BYTES; use super::response::MAX_RESPONSE_BYTES; use super::shared; -/// Why the process adapter cannot execute, shared by CLI and library callers. -pub const PROCESS_EXECUTION_UNAVAILABLE: &str = "process adapter execution is disabled until OS filesystem/network confinement, verified-byte execution and process-tree cleanup are available; use --recorded-response with a separately reviewed response file"; +/// Why the process adapter cannot execute on platforms without an approved +/// confinement mechanism, shared by CLI and library callers. +pub const PROCESS_EXECUTION_UNAVAILABLE: &str = "process adapter execution is disabled on this platform: no approved OS filesystem/network confinement mechanism exists; use --recorded-response with a separately reviewed response file"; /// Read a local executable the operator named, following symlinks to the file. /// @@ -31,8 +34,8 @@ pub(in crate::suggest) fn read_executable( path: &Path, max: u64, ) -> Result, crate::ForgeError> { - // Resolve shims for fingerprinting only. This digest does not authorize - // execution: invoke always refuses, including if this path is replaced. + // Resolve shims for fingerprinting. invoke re-reads the resolved bytes + // immediately before spawn and refuses any replacement. let resolved = std::fs::canonicalize(path)?; crate::io::read_bounded(&resolved, max) } @@ -68,11 +71,17 @@ pub trait LocalModelInvoke { } } -/// A fingerprinted local executable whose invocation currently fails closed. +/// A fingerprinted local executable executed under OS confinement. +/// +/// Invocation re-verifies the executable bytes, clears the environment, runs +/// the child under a deny-default filesystem/network sandbox in its own +/// process group, and kills the whole group on timeout or refusal. See +/// the `confinement` module and `docs/local-model-confinement.md`. #[derive(Debug)] pub struct ProcessModelAdapter { executable: PathBuf, executable_sha256: String, + argv: Vec, } impl ProcessModelAdapter { @@ -94,6 +103,7 @@ impl ProcessModelAdapter { Ok(Self { executable: executable.to_path_buf(), executable_sha256: crate::hashing::sha256_hex(&bytes), + argv: argv.to_vec(), }) } @@ -105,10 +115,14 @@ impl ProcessModelAdapter { } impl LocalModelInvoke for ProcessModelAdapter { - fn invoke(&self, _payload: &[u8], _timeout: Duration) -> Result { - // There is deliberately no spawn path or opt-out: env_clear and a - // pathname digest cannot enforce the promised isolation boundary. - Err(shared::error(PROCESS_EXECUTION_UNAVAILABLE)) + fn invoke(&self, payload: &[u8], timeout: Duration) -> Result { + super::confinement::invoke_confined( + &self.executable, + &self.executable_sha256, + &self.argv, + payload, + timeout, + ) } fn executable_sha256(&self) -> Option<&str> { @@ -178,15 +192,25 @@ mod tests { } #[test] - fn process_invocation_is_unavailable_on_every_platform_even_after_replacement() { + fn a_replaced_executable_is_refused_before_spawn() { let temp = tempfile::tempdir().unwrap(); let path = temp.path().join("adapter"); - std::fs::write(&path, b"placeholder executable").unwrap(); + std::fs::write(&path, b"#!/bin/sh\ncat\n").unwrap(); let adapter = ProcessModelAdapter::new(&path, &[]).unwrap(); assert_eq!(adapter.executable(), path); assert!(adapter.executable_sha256().is_some()); - std::fs::remove_file(&path).unwrap(); - // Even direct library callers cannot spawn or reopen a changed path. + std::fs::write(&path, b"#!/bin/sh\nprintf replaced\n").unwrap(); + let error = adapter.invoke(b"private payload", Duration::from_secs(5)).unwrap_err(); + assert!(error.to_string().contains("changed since it was fingerprinted")); + } + + #[cfg(not(unix))] + #[test] + fn process_invocation_is_unavailable_without_an_approved_mechanism() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("adapter"); + std::fs::write(&path, b"placeholder executable").unwrap(); + let adapter = ProcessModelAdapter::new(&path, &[]).unwrap(); let error = adapter.invoke(b"private payload", Duration::ZERO).unwrap_err(); assert!(error.to_string().contains(PROCESS_EXECUTION_UNAVAILABLE)); } diff --git a/src/suggest/confinement.rs b/src/suggest/confinement.rs new file mode 100644 index 00000000..f2eb85e4 --- /dev/null +++ b/src/suggest/confinement.rs @@ -0,0 +1,753 @@ +//! OS confinement for the local process adapter (PRD 066 S-1, F16). +//! +//! Two Unix mechanisms, both fail-closed: macOS spawns through +//! `/usr/bin/sandbox-exec` with a deny-default Seatbelt profile; Linux applies +//! a Landlock filesystem ruleset plus a seccomp-BPF filter before `exec`. Both +//! are inherited by every descendant. The child's environment is cleared, it +//! leads a fresh process group (so a timeout or refusal can kill every +//! descendant), and its stdout/stderr are drained under a byte cap. +//! +//! The boundary is filesystem and network only: CPU, memory and process-count +//! limits are not enforced, and the executable runs with the operator's own +//! user identity inside the sandbox. Windows has no approved mechanism and +//! stays refused. See `docs/local-model-confinement.md` for the exact +//! guarantees and how to verify them. + +use std::path::Path; +use std::process::Child; +#[cfg(unix)] +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +use crate::ForgeError; + +use super::adapter::AdapterOutput; +use super::response::MAX_RESPONSE_BYTES; +use super::shared; + +/// Drained stderr bound, in bytes. +const MAX_STDERR_BYTES: usize = 64 * 1024; +/// Poll interval while waiting for the child to exit. +const POLL: Duration = Duration::from_millis(5); +/// Grace period to drain the pipes after a kill before detaching readers. +const DRAIN_GRACE: Duration = Duration::from_secs(2); + +/// Run the verified executable under OS confinement and return its output. +/// +/// `executable` must resolve to the bytes that hash to `expected_sha`; the +/// bytes are re-read here immediately before spawn and a replacement is +/// refused. On platforms without an approved mechanism this always fails. +/// +/// # Errors +/// Returns an authoring error when confinement cannot be established, the +/// executable changed, the child exits non-zero, exceeds the timeout or an +/// output bound, or cannot be spawned. +pub(super) fn invoke_confined( + executable: &Path, + expected_sha: &str, + argv: &[String], + payload: &[u8], + timeout: Duration, +) -> Result { + let resolved = std::fs::canonicalize(executable)?; + let bytes = crate::io::read_bounded(&resolved, crate::suggest::prepare::MAX_ADAPTER_BYTES)?; + if crate::hashing::sha256_hex(&bytes) != expected_sha { + return Err(shared::error( + "the adapter executable changed since it was fingerprinted; re-run prepare and consent again", + )); + } + let scratch = tempfile::Builder::new().prefix("forge-model-").tempdir().map_err(|cause| { + shared::error(format!("cannot create the adapter scratch directory: {cause}")) + })?; + let scratch_path = scratch.path().canonicalize().map_err(|cause| { + shared::error(format!("cannot resolve the adapter scratch directory: {cause}")) + })?; + let started = Instant::now(); + let mut child = spawn(&resolved, argv, &scratch_path)?; + let (result, drained) = supervise(&mut child, payload, timeout, started); + if drained { + // All pipe threads are joined: no descendant can still write, so the + // scratch directory can be removed safely. + drop(scratch); + } else { + // Readers were detached: an escaped descendant may still write into + // the scratch directory. Keep it (never recycle the path) instead of + // deleting it under a live writer. + let _ = scratch.keep(); + } + result +} + +/// Spawn the confined child in its own process group with piped output. +#[cfg(unix)] +fn spawn(executable: &Path, argv: &[String], scratch: &Path) -> Result { + use std::os::unix::process::CommandExt as _; + + let mut command = platform_command(executable, argv, scratch)?; + command + .env_clear() + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + // A fresh group lets one killpg reach every descendant on refusal. + .process_group(0); + command + .spawn() + .map_err(|cause| shared::error(format!("cannot spawn the confined adapter: {cause}"))) +} + +#[cfg(not(unix))] +fn spawn(_executable: &Path, _argv: &[String], _scratch: &Path) -> Result { + Err(shared::error(super::adapter::PROCESS_EXECUTION_UNAVAILABLE)) +} + +/// Feed the payload, drain both pipes under their caps and enforce the timeout. +fn supervise( + child: &mut Child, + payload: &[u8], + timeout: Duration, + started: Instant, +) -> (Result, bool) { + let missing_pipe = || shared::error("the confined adapter lost a standard stream"); + let Some(stdout) = child.stdout.take() else { return (Err(missing_pipe()), true) }; + let Some(stderr) = child.stderr.take() else { return (Err(missing_pipe()), true) }; + let Some(mut stdin) = child.stdin.take() else { return (Err(missing_pipe()), true) }; + let stdout_cap = usize::try_from(MAX_RESPONSE_BYTES).unwrap_or(usize::MAX); + let stdout_reader = std::thread::spawn(move || read_capped(stdout, stdout_cap)); + let stderr_reader = std::thread::spawn(move || read_capped(stderr, MAX_STDERR_BYTES)); + let payload = payload.to_vec(); + let stdin_writer = std::thread::spawn(move || { + use std::io::Write as _; + // A refused child may close stdin early; a broken pipe is expected. + let _ = stdin.write_all(&payload); + }); + + let deadline = started + timeout; + let mut failure = None; + loop { + match child.try_wait() { + Ok(Some(status)) => { + if !status.success() { + failure = Some(shared::error(format!( + "the confined adapter exited with {}", + status.code().map_or_else( + || "a signal".to_string(), + |code| format!("status {code}") + ) + ))); + } + break; + } + Ok(None) => { + if Instant::now() >= deadline { + failure = Some(timeout_error()); + break; + } + std::thread::sleep(POLL); + } + Err(cause) => { + failure = + Some(shared::error(format!("cannot wait for the confined adapter: {cause}"))); + break; + } + } + } + if failure.is_some() { + kill_group(child); + } else { + // Descendants can hold the pipes open after the leader exits; the + // drain is part of the invocation and shares its deadline. + while !(stdout_reader.is_finished() && stderr_reader.is_finished()) { + if Instant::now() >= deadline { + failure = Some(timeout_error()); + kill_group(child); + break; + } + std::thread::sleep(POLL); + } + } + // An escaped descendant can survive killpg holding a pipe open. Bound the + // post-kill drain and detach any thread still blocked at the grace deadline + // so the invocation always returns within a bounded time. + let drain_deadline = Instant::now() + DRAIN_GRACE; + let drained = finished_by(&stdout_reader, drain_deadline) + && finished_by(&stderr_reader, drain_deadline) + && finished_by(&stdin_writer, drain_deadline); + if !drained { + return (Err(failure.unwrap_or_else(timeout_error)), false); + } + collect_output(child, stdout_reader, stderr_reader, failure, started) +} + +/// Join the drained readers and assemble the output. Reached only once every +/// pipe thread has finished, so the joins cannot block. +fn collect_output( + child: &mut Child, + stdout_reader: std::thread::JoinHandle, ForgeError>>, + stderr_reader: std::thread::JoinHandle, ForgeError>>, + failure: Option, + started: Instant, +) -> (Result, bool) { + let Ok(stdout) = stdout_reader.join() else { + return (Err(shared::error("the stdout reader failed")), true); + }; + let Ok(stderr) = stderr_reader.join() else { + return (Err(shared::error("the stderr reader failed")), true); + }; + if let Some(cause) = failure { + return (Err(cause), true); + } + // An over-bound or failed drain is a refusal too: the child may still be + // running, so kill its group before returning the error. + let stdout = match stdout { + Ok(bytes) => bytes, + Err(cause) => { + kill_group(child); + return (Err(cause), true); + } + }; + let stderr = match stderr { + Ok(bytes) => bytes, + Err(cause) => { + kill_group(child); + return (Err(cause), true); + } + }; + let status = match child.wait() { + Ok(status) => status, + Err(cause) => { + return ( + Err(shared::error(format!("cannot reap the confined adapter: {cause}"))), + true, + ); + } + }; + ( + Ok(AdapterOutput { + stdout, + stderr: crate::sanitize::strip_control_chars(&String::from_utf8_lossy(&stderr)), + elapsed: started.elapsed(), + exit_code: status.code(), + }), + true, + ) +} + +fn timeout_error() -> ForgeError { + shared::error("the confined adapter exceeded its timeout") +} + +/// Poll a thread until it finishes or the deadline passes; false means it is +/// still blocked and must be detached rather than joined. +fn finished_by(handle: &std::thread::JoinHandle, deadline: Instant) -> bool { + while !handle.is_finished() { + if Instant::now() >= deadline { + return false; + } + std::thread::sleep(POLL); + } + true +} + +/// Kill the child's whole process group (Unix) or the child itself. +fn kill_group(child: &mut Child) { + #[cfg(unix)] + { + // SAFETY: killpg only signals the group the child leads; the pid is a + // live child we own. + #[allow(unsafe_code)] + unsafe { + libc::killpg(child.id() as libc::pid_t, libc::SIGKILL); + } + } + let _ = child.kill(); + let _ = child.wait(); +} + +/// Read at most `cap` bytes; an over-cap stream is an error, not a truncation. +fn read_capped(mut reader: impl std::io::Read, cap: usize) -> Result, ForgeError> { + let mut bytes = Vec::new(); + let mut chunk = [0_u8; 8192]; + loop { + let read = reader + .read(&mut chunk) + .map_err(|cause| shared::error(format!("cannot drain the adapter output: {cause}")))?; + if read == 0 { + return Ok(bytes); + } + if bytes.len() + read > cap { + return Err(shared::error("the adapter output exceeded its byte bound")); + } + bytes.extend_from_slice(&chunk[..read]); + } +} + +// --------------------------------------------------------------------------- +// macOS: deny-default Seatbelt via /usr/bin/sandbox-exec +// --------------------------------------------------------------------------- + +#[cfg(target_os = "macos")] +fn platform_command( + executable: &Path, + argv: &[String], + scratch: &Path, +) -> Result { + const SANDBOX_EXEC: &str = "/usr/bin/sandbox-exec"; + let launcher = Path::new(SANDBOX_EXEC); + if !launcher.is_file() { + return Err(shared::error(format!( + "{SANDBOX_EXEC} is unavailable; refusing to run the adapter unconfined" + ))); + } + let profile = seatbelt_profile(executable, scratch)?; + let mut command = Command::new(launcher); + command.arg("-p").arg(profile).arg(executable).args(argv); + Ok(command) +} + +/// The deny-default profile: read-only runtime and executable, one private +/// writable scratch directory, no network. Children inherit it. +#[cfg(target_os = "macos")] +fn seatbelt_profile(executable: &Path, scratch: &Path) -> Result { + use std::fmt::Write as _; + let mut allow_read = Vec::new(); + // Ancestor directories need read access for path traversal. + for ancestor in executable.ancestors().skip(1) { + allow_read.push(format!("(literal \"{}\")", escape(ancestor)?)); + } + for ancestor in scratch.ancestors().skip(1) { + allow_read.push(format!("(literal \"{}\")", escape(ancestor)?)); + } + let mut profile = String::from( + "(version 1)\n(deny default)\n\ + (allow process*)\n(allow signal)\n(allow sysctl-read)\n(allow mach*)\n\ + (allow file-read* file-write* (literal \"/dev/null\") (literal \"/dev/zero\") \ + (literal \"/dev/random\") (literal \"/dev/urandom\") (literal \"/dev/tty\") \ + (literal \"/dev/dtracehelper\"))\n\ + (allow file-read* (subpath \"/usr/lib\") (subpath \"/bin\") (subpath \"/sbin\") \ + (subpath \"/usr/bin\") (subpath \"/usr/sbin\") (subpath \"/System\") \ + (subpath \"/private/var/db\") (subpath \"/private/var/select\") \ + (subpath \"/Library/Preferences\") (subpath \"/dev/fd\"))\n", + ); + let _ = writeln!( + profile, + "(allow file-read* {} (literal \"{}\"))", + allow_read.join(" "), + escape(executable)? + ); + let _ = writeln!(profile, "(allow file-read* file-write* (subpath \"{}\"))", escape(scratch)?); + Ok(profile) +} + +/// Quote a path for the Seatbelt profile language. +#[cfg(target_os = "macos")] +fn escape(path: &Path) -> Result { + let text = path.to_str().ok_or_else(|| shared::error("the adapter path must be UTF-8"))?; + if text.contains(['"', '\\', ')', '(', '\n', '\r']) { + return Err(shared::error( + "the adapter path contains characters the Seatbelt profile cannot quote", + )); + } + Ok(text.to_string()) +} + +// --------------------------------------------------------------------------- +// Linux: Landlock filesystem ruleset + seccomp-BPF network deny +// --------------------------------------------------------------------------- + +#[cfg(target_os = "linux")] +fn platform_command( + executable: &Path, + argv: &[String], + scratch: &Path, +) -> Result { + use std::os::unix::process::CommandExt as _; + + #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] + return Err(shared::error( + "no approved seccomp policy exists for this architecture; refusing to run the adapter unconfined", + )); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + { + // Probe Landlock before spawning so an unsupported kernel fails closed + // with a clear error instead of a killed child. + let abi = landlock_abi_version()?; + // Precompute every allocation before fork: after fork in a + // multi-threaded parent only async-signal-safe syscalls may run, so + // the closure below installs this plan without allocating. + let mut plan = linux_confinement(executable, scratch, abi)?; + let mut command = Command::new(executable); + command.args(argv); + // SAFETY: the closure installs the precomputed Landlock ruleset and + // seccomp filter between fork and exec using only async-signal-safe + // syscalls; on any failure it returns the raw errno and the child + // exits without executing the adapter. + #[allow(unsafe_code)] + unsafe { + command.pre_exec(move || plan.install()); + } + Ok(command) + } +} + +/// Landlock ABI version, or a clear refusal on kernels without Landlock. +#[cfg(target_os = "linux")] +fn landlock_abi_version() -> Result { + // SAFETY: a null attribute with the query flag only asks for the ABI. + #[allow(unsafe_code)] + let version = unsafe { + libc::syscall( + libc::SYS_landlock_create_ruleset, + std::ptr::null::(), + 0_usize, + LANDLOCK_CREATE_RULESET_VERSION, + ) + }; + if version < 1 { + return Err(shared::error(format!( + "Landlock is unavailable (kernel 5.13 or newer with Landlock enabled is required); \ + refusing to run the adapter unconfined (errno {})", + std::io::Error::last_os_error() + ))); + } + i32::try_from(version).map_err(|_| shared::error("unexpected Landlock ABI version")) +} + +#[cfg(target_os = "linux")] +const LANDLOCK_CREATE_RULESET_VERSION: u32 = 1; +#[cfg(target_os = "linux")] +const LANDLOCK_RULE_PATH_BENEATH: u32 = 1; + +// Landlock access bits (uapi/linux/landlock.h); libc does not expose them yet. +#[cfg(target_os = "linux")] +mod landlock_access { + pub const EXECUTE: u64 = 1 << 0; + pub const WRITE_FILE: u64 = 1 << 1; + pub const READ_FILE: u64 = 1 << 2; + pub const READ_DIR: u64 = 1 << 3; + pub const REMOVE_DIR: u64 = 1 << 4; + pub const REMOVE_FILE: u64 = 1 << 5; + pub const MAKE_CHAR: u64 = 1 << 6; + pub const MAKE_DIR: u64 = 1 << 7; + pub const MAKE_REG: u64 = 1 << 8; + pub const MAKE_SOCK: u64 = 1 << 9; + pub const MAKE_FIFO: u64 = 1 << 10; + pub const MAKE_BLOCK: u64 = 1 << 11; + pub const MAKE_SYM: u64 = 1 << 12; + pub const REFER: u64 = 1 << 13; + pub const TRUNCATE: u64 = 1 << 14; + + /// Every access right of ABI v1. + pub const V1: u64 = EXECUTE + | WRITE_FILE + | READ_FILE + | READ_DIR + | REMOVE_DIR + | REMOVE_FILE + | MAKE_CHAR + | MAKE_DIR + | MAKE_REG + | MAKE_SOCK + | MAKE_FIFO + | MAKE_BLOCK + | MAKE_SYM; +} + +#[cfg(target_os = "linux")] +#[repr(C)] +struct LandlockRulesetAttr { + handled_access_fs: u64, +} + +#[cfg(target_os = "linux")] +#[repr(C)] +struct LandlockPathBeneathAttr { + allowed_access: u64, + parent_fd: i32, +} + +/// Everything the child needs to install confinement, precomputed before +/// fork so the post-fork closure performs no allocation. +#[cfg(target_os = "linux")] +struct LinuxConfinement { + attr: LandlockRulesetAttr, + exe_c: std::ffi::CString, + scratch_c: std::ffi::CString, + scratch_access: u64, + /// Runtime paths (loader directories, linker cache, devices) and the + /// access each is granted; a missing path is skipped at install time. + runtime_rules: Vec<(std::ffi::CString, u64)>, + filter: Vec, + filter_len: u16, +} + +/// Precompute the Landlock ruleset and seccomp filter before fork. +#[cfg(target_os = "linux")] +fn linux_confinement( + executable: &Path, + scratch: &Path, + abi: i32, +) -> Result { + use std::os::unix::ffi::OsStrExt as _; + + let mut handled = landlock_access::V1; + if abi >= 2 { + handled |= landlock_access::REFER; + } + if abi >= 3 { + handled |= landlock_access::TRUNCATE; + } + let exe_c = std::ffi::CString::new(executable.as_os_str().as_bytes()) + .map_err(|_| shared::error("the executable path contains a NUL"))?; + let scratch_c = std::ffi::CString::new(scratch.as_os_str().as_bytes()) + .map_err(|_| shared::error("the scratch path contains a NUL"))?; + let read = landlock_access::READ_FILE | landlock_access::READ_DIR; + let mut runtime_rules = Vec::new(); + // The dynamic loader needs the runtime directories, the linker cache and + // null/zero/random devices. Missing paths (merged-usr layouts) are skipped + // at install; a present path that cannot be ruled fails closed. + for path in ["/usr/lib", "/lib", "/usr/bin", "/bin", "/usr/sbin", "/sbin"] { + runtime_rules.push((runtime_c(path)?, read | landlock_access::EXECUTE)); + } + runtime_rules.push((runtime_c("/etc/ld.so.cache")?, landlock_access::READ_FILE)); + for path in ["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"] { + runtime_rules + .push((runtime_c(path)?, landlock_access::READ_FILE | landlock_access::WRITE_FILE)); + } + let filter = seccomp_filter(); + let filter_len = u16::try_from(filter.len()) + .map_err(|_| shared::error("the seccomp filter is too large"))?; + Ok(LinuxConfinement { + attr: LandlockRulesetAttr { handled_access_fs: handled }, + exe_c, + scratch_c, + scratch_access: handled + & !(landlock_access::EXECUTE + | landlock_access::MAKE_SOCK + | landlock_access::MAKE_CHAR + | landlock_access::MAKE_BLOCK), + runtime_rules, + filter, + filter_len, + }) +} + +/// A constant runtime path as a `CString` (validated before fork). +#[cfg(target_os = "linux")] +fn runtime_c(path: &str) -> Result { + std::ffi::CString::new(path).map_err(|_| shared::error("a runtime path contains a NUL")) +} + +#[cfg(target_os = "linux")] +#[allow(unsafe_code)] +impl LinuxConfinement { + /// Install Landlock then seccomp between fork and exec. Only + /// async-signal-safe syscalls run here; errors carry the raw errno, which + /// std reports to the parent without allocating. Any failure leaves the + /// child un-exec'd (fail closed). + fn install(&mut self) -> std::io::Result<()> { + // SAFETY: all arguments are precomputed and live in `self`; the calls + // below are plain syscalls on the child between fork and exec. + unsafe { + // no_new_privs must precede both Landlock and seccomp. + if libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0 { + return Err(std::io::Error::last_os_error()); + } + let ruleset = libc::syscall( + libc::SYS_landlock_create_ruleset, + &raw const self.attr, + std::mem::size_of::(), + 0_u32, + ); + if ruleset < 0 { + return Err(std::io::Error::last_os_error()); + } + let ruleset = ruleset as i32; + let result = self.install_rules(ruleset); + libc::close(ruleset); + result?; + let program = + libc::sock_fprog { len: self.filter_len, filter: self.filter.as_mut_ptr() }; + if libc::prctl( + libc::PR_SET_SECCOMP, + libc::SECCOMP_MODE_FILTER, + &raw const program, + 0, + 0, + ) != 0 + { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + } + } + + unsafe fn install_rules(&self, ruleset: i32) -> std::io::Result<()> { + // SAFETY: ruleset is live and all paths are pre-built CStrings; only + // async-signal-safe syscalls run here. + unsafe { + // O_PATH opens without reading the file; the rules bind the inode. + let exe_fd = libc::open(self.exe_c.as_ptr(), libc::O_PATH | libc::O_CLOEXEC); + if exe_fd < 0 { + return Err(std::io::Error::last_os_error()); + } + let scratch_fd = libc::open(self.scratch_c.as_ptr(), libc::O_PATH | libc::O_CLOEXEC); + if scratch_fd < 0 { + let err = std::io::Error::last_os_error(); + libc::close(exe_fd); + return Err(err); + } + let result = Self::add_rule( + ruleset, + exe_fd, + landlock_access::READ_FILE | landlock_access::EXECUTE, + ) + .and_then(|()| Self::add_rule(ruleset, scratch_fd, self.scratch_access)) + .and_then(|()| { + for (path, access) in &self.runtime_rules { + let fd = libc::open(path.as_ptr(), libc::O_PATH | libc::O_CLOEXEC); + if fd < 0 { + let err = std::io::Error::last_os_error(); + if err.raw_os_error() == Some(libc::ENOENT) { + continue; + } + return Err(err); + } + let added = Self::add_rule(ruleset, fd, *access); + libc::close(fd); + added?; + } + Ok(()) + }) + .and_then(|()| { + if libc::syscall(libc::SYS_landlock_restrict_self, ruleset, 0_u32) < 0 { + Err(std::io::Error::last_os_error()) + } else { + Ok(()) + } + }); + libc::close(exe_fd); + libc::close(scratch_fd); + result + } + } + + /// SAFETY: `fd` is an open `O_PATH` descriptor and `ruleset` a live ruleset fd. + unsafe fn add_rule(ruleset: i32, fd: i32, access: u64) -> std::io::Result<()> { + let rule = LandlockPathBeneathAttr { allowed_access: access, parent_fd: fd }; + // SAFETY: rule is a valid path-beneath attribute for the live ruleset. + let rc = unsafe { + libc::syscall( + libc::SYS_landlock_add_rule, + ruleset, + LANDLOCK_RULE_PATH_BENEATH, + &raw const rule, + 0_u32, + ) + }; + if rc < 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + } +} + +/// Build the deny-list filter for the running architecture. +#[cfg(target_os = "linux")] +fn seccomp_filter() -> Vec { + let insn = |code: u16, k: u32| libc::sock_filter { code, jt: 0, jf: 0, k }; + let ret = |k: u32| insn((libc::BPF_RET | libc::BPF_K) as u16, k); + // seccomp_data: nr at offset 0, arch at offset 4. Check the architecture + // first, then reload the syscall number for the deny list. + let mut filter = vec![insn((libc::BPF_LD | libc::BPF_W | libc::BPF_ABS) as u16, 4)]; + #[cfg(target_arch = "x86_64")] + let arch: u32 = 0xC000_003E; // AUDIT_ARCH_X86_64 + #[cfg(target_arch = "aarch64")] + let arch: u32 = 0xC000_00B7; // AUDIT_ARCH_AARCH64 + // Unknown architecture: arch 0 never matches, so everything is killed. + #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] + let arch: u32 = 0; + // A foreign ABI (e.g. i386 on x86_64) must not slip past the deny list. + filter.push(libc::sock_filter { + code: (libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K) as u16, + jt: 1, + jf: 0, + k: arch, + }); + filter.push(ret(libc::SECCOMP_RET_KILL_PROCESS)); + filter.push(insn((libc::BPF_LD | libc::BPF_W | libc::BPF_ABS) as u16, 0)); + #[cfg(target_arch = "x86_64")] + { + // x32 syscalls carry bit 30; they are not in the deny list. + filter.push(libc::sock_filter { + code: (libc::BPF_JMP | libc::BPF_JGE | libc::BPF_K) as u16, + jt: 0, + jf: 1, + k: 0x4000_0000, + }); + filter.push(ret(libc::SECCOMP_RET_KILL_PROCESS)); + } + for syscall in denied_syscalls() { + filter.push(libc::sock_filter { + code: (libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K) as u16, + jt: 0, + jf: 1, + k: syscall, + }); + filter.push(ret(libc::SECCOMP_RET_ERRNO | libc::EPERM as u32)); + } + filter.push(ret(libc::SECCOMP_RET_ALLOW)); + filter +} + +/// Socket-creating syscalls present on this architecture. +#[cfg(target_os = "linux")] +fn denied_syscalls() -> Vec { + #[cfg_attr(not(target_arch = "x86"), allow(unused_mut))] + let mut numbers = vec![ + libc::SYS_socket as u32, + libc::SYS_socketpair as u32, + libc::SYS_io_uring_setup as u32, + libc::SYS_io_uring_enter as u32, + libc::SYS_io_uring_register as u32, + ]; + // i386 routes socket calls through one multiplexer; 64-bit architectures + // have no socketcall. + #[cfg(target_arch = "x86")] + numbers.push(libc::SYS_socketcall as u32); + numbers +} + +// --------------------------------------------------------------------------- +// Other Unix platforms: no approved mechanism, fail closed. +// --------------------------------------------------------------------------- + +#[cfg(all(unix, not(any(target_os = "macos", target_os = "linux"))))] +fn platform_command( + _executable: &Path, + _argv: &[String], + _scratch: &Path, +) -> Result { + Err(shared::error( + "no OS confinement mechanism is approved for this platform; refusing to run the adapter unconfined", + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn finished_by_detaches_a_thread_that_outlives_the_deadline() { + // A reader blocked on a pipe an escaped descendant holds open never + // finishes; finished_by must report false at the deadline so supervise + // detaches it instead of joining forever. + let blocked = std::thread::spawn(|| std::thread::sleep(Duration::from_secs(30))); + let start = Instant::now(); + assert!(!finished_by(&blocked, start + Duration::from_millis(50))); + assert!(start.elapsed() < Duration::from_secs(1), "the wait was not bounded"); + // A finished thread is reported immediately. + let done = std::thread::spawn(|| {}); + assert!(finished_by(&done, Instant::now() + Duration::from_secs(5))); + } +} diff --git a/src/suggest/mod.rs b/src/suggest/mod.rs index 47072674..8fa86277 100644 --- a/src/suggest/mod.rs +++ b/src/suggest/mod.rs @@ -12,6 +12,7 @@ pub mod adapter; pub mod bundle; +mod confinement; pub mod consent; pub mod disposition; pub mod eval; diff --git a/src/suggest/request.rs b/src/suggest/request.rs index 5b2a84b9..e02f4f5c 100644 --- a/src/suggest/request.rs +++ b/src/suggest/request.rs @@ -36,8 +36,8 @@ pub const MAX_UNIT_SPAN_BYTES: u64 = 1024 * 1024; /// Fixed notice written into every prepared preview. pub const DATA_HANDLING_NOTICE: &str = "The payload below is the exact prepared byte sequence. \ - Process adapter execution is disabled until OS filesystem/network confinement is available. \ - Use --recorded-response to import a separately reviewed response. FORGE starts no adapter and transmits nothing. \ + On macOS and Linux, process adapter execution is confined to a private writable scratch directory with read-only access to system runtimes, and no network access. \ + Use --recorded-response to import a separately reviewed response instead. FORGE transmits nothing. \ The adapter fingerprint and model identifier record the operator's prospective selection, not evidence of execution. \ Review this payload and the recorded response before sharing either artifact."; diff --git a/src/suggest/run.rs b/src/suggest/run.rs index c81233ad..76aebd23 100644 --- a/src/suggest/run.rs +++ b/src/suggest/run.rs @@ -1,7 +1,8 @@ -//! Crate-level `forge suggest run`: publish one bounded recorded response. +//! Crate-level `forge suggest run`: publish one bounded adapter response. //! //! Consent binds the frozen payload and prospective adapter identity. Process -//! execution fails closed until the required OS confinement exists. +//! execution runs under OS confinement on macOS and Linux and fails closed +//! everywhere else. use std::path::Path; diff --git a/tests/pr155_adversarial_review.rs b/tests/pr155_adversarial_review.rs index 610e9512..1dfcfab7 100644 --- a/tests/pr155_adversarial_review.rs +++ b/tests/pr155_adversarial_review.rs @@ -185,16 +185,12 @@ fn process_refusal_cannot_wait_on_descendant_pipes() { } #[test] -fn bare_adapter_name_cannot_bypass_the_process_execution_refusal() { +fn a_bare_adapter_name_still_enforces_the_verified_byte_binding() { use std::os::unix::fs::PermissionsExt; let (_temp, root) = project(); let local = root.join("review-adapter"); std::fs::write(&local, b"#!/bin/sh\nprintf verified-adapter\n").unwrap(); std::fs::set_permissions(&local, std::fs::Permissions::from_mode(0o755)).unwrap(); - std::fs::create_dir(root.join("bin")).unwrap(); - let different = root.join("bin/review-adapter"); - std::fs::write(&different, b"#!/bin/sh\nprintf unverified-path-adapter\n").unwrap(); - std::fs::set_permissions(&different, std::fs::Permissions::from_mode(0o755)).unwrap(); let output = run( &root, &[ @@ -214,10 +210,12 @@ fn bare_adapter_name_cannot_bypass_the_process_execution_refusal() { ], ); assert_exit(&output, 0); - let output = std::process::Command::new(env!("CARGO_BIN_EXE_forge")) - .current_dir(&root) - .env("PATH", root.join("bin")) - .args([ + // Replace the consented bytes after prepare: the bare name resolves to the + // same path, but the run must refuse it as a contract violation. + std::fs::write(&local, b"#!/bin/sh\nprintf unverified-path-adapter\n").unwrap(); + let output = run( + &root, + &[ "suggest", "run", "--request", @@ -226,13 +224,10 @@ fn bare_adapter_name_cannot_bypass_the_process_execution_refusal() { "prepared/consent.json", "--output-dir", "run-1", - ]) - .output() - .unwrap(); - assert_exit(&output, 1); - assert!( - String::from_utf8_lossy(&output.stderr).contains("process adapter execution is disabled") + ], ); + assert_exit(&output, 2); + assert!(String::from_utf8_lossy(&output.stderr).contains("changed since consent")); assert!(!root.join("prepared/run-1").exists()); } diff --git a/tests/suggest_confinement_test.rs b/tests/suggest_confinement_test.rs new file mode 100644 index 00000000..c4888515 --- /dev/null +++ b/tests/suggest_confinement_test.rs @@ -0,0 +1,288 @@ +//! F16 confined local model execution: refusal paths, verified bytes, +//! descendant cleanup, timeout, and the filesystem/network boundary. +//! +//! Platform tests are gated: macOS exercises Seatbelt through sandbox-exec, +//! Linux exercises Landlock + seccomp-BPF. On hosts where the mechanism is +//! unavailable (old kernel, missing sandbox-exec, a blocking container seccomp +//! profile) the adapter must fail closed, and the boundary tests assert that +//! refusal instead of an unconfined run. + +#![cfg(any(target_os = "linux", target_os = "macos"))] + +use std::path::Path; +use std::time::{Duration, Instant}; + +use forge::suggest::adapter::{LocalModelInvoke, ProcessModelAdapter}; + +fn sh_adapter(script: &str) -> ProcessModelAdapter { + ProcessModelAdapter::new(Path::new("/bin/sh"), &["-c".to_string(), script.to_string()]).unwrap() +} + +/// True when the host can establish confinement; false when the adapter must +/// (and does) fail closed. Probes with a trivial confined command. +fn confinement_available() -> bool { + sh_adapter("printf ok").invoke(b"", Duration::from_secs(10)).is_ok() +} + +#[test] +fn a_replaced_executable_is_refused_before_any_spawn() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("model"); + std::fs::write(&path, b"#!/bin/sh\ncat\n").unwrap(); + let adapter = ProcessModelAdapter::new(&path, &[]).unwrap(); + std::fs::write(&path, b"#!/bin/sh\nprintf replaced\n").unwrap(); + let error = adapter.invoke(b"payload", Duration::from_secs(5)).unwrap_err(); + assert!(error.to_string().contains("changed since it was fingerprinted")); +} + +#[test] +fn a_deleted_executable_is_refused() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("model"); + std::fs::write(&path, b"#!/bin/sh\ncat\n").unwrap(); + let adapter = ProcessModelAdapter::new(&path, &[]).unwrap(); + std::fs::remove_file(&path).unwrap(); + assert!(adapter.invoke(b"payload", Duration::from_secs(5)).is_err()); +} + +#[test] +fn a_confined_child_cannot_read_outside_the_allowlist() { + let temp = tempfile::tempdir().unwrap(); + let secret = temp.path().join("secret.txt"); + std::fs::write(&secret, b"unselected secret").unwrap(); + let script = format!( + "cat '{}' >/dev/null 2>&1 && echo READ-ESCAPED || echo read-denied", + secret.display() + ); + let adapter = sh_adapter(&script); + match adapter.invoke(b"payload", Duration::from_secs(10)) { + Ok(output) => { + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("read-denied"), "child read outside the allowlist: {stdout}"); + assert!(!stdout.contains("READ-ESCAPED")); + } + Err(cause) => { + // No mechanism on this host: the refusal is the guarantee. + assert!(!confinement_available(), "unexpected refusal: {cause}"); + } + } +} + +#[test] +fn a_confined_child_cannot_write_outside_the_scratch_directory() { + let temp = tempfile::tempdir().unwrap(); + let sink = temp.path().join("escaped.txt"); + let script = format!( + "printf leaked > '{}' 2>/dev/null && echo WRITE-ESCAPED || echo write-denied", + sink.display() + ); + let adapter = sh_adapter(&script); + match adapter.invoke(b"payload", Duration::from_secs(10)) { + Ok(output) => { + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + stdout.contains("write-denied"), + "child wrote outside the scratch dir: {stdout}" + ); + } + Err(cause) => { + assert!(!confinement_available(), "unexpected refusal: {cause}"); + } + } + assert!(!sink.exists(), "the adapter escaped the write boundary"); +} + +#[test] +fn a_confined_child_receives_the_exact_payload() { + if !confinement_available() { + return; // fail-closed hosts are covered by the refusal tests + } + let adapter = sh_adapter("cat"); + let output = adapter.invoke(b"the exact payload", Duration::from_secs(10)).unwrap(); + assert_eq!(output.stdout, b"the exact payload"); + assert_eq!(output.exit_code, Some(0)); +} + +#[test] +fn a_timeout_kills_every_descendant() { + let adapter = sh_adapter("sleep 31.4159 & sleep 31.4159 & echo started; sleep 31.4159"); + let started = Instant::now(); + let result = adapter.invoke(b"", Duration::from_millis(300)); + assert!(result.is_err(), "a hanging adapter must time out"); + assert!(started.elapsed() < Duration::from_secs(5), "timeout was not honored"); + // The whole process group must be dead, not just the leader. + std::thread::sleep(Duration::from_millis(200)); + let survivors = + std::process::Command::new("pgrep").args(["-f", "sleep 31.4159"]).output().unwrap(); + assert!( + survivors.stdout.is_empty(), + "descendants survived the timeout: {}", + String::from_utf8_lossy(&survivors.stdout) + ); +} + +#[test] +fn a_descendant_holding_the_pipes_cannot_extend_the_timeout() { + let adapter = sh_adapter("sleep 30 & exit 0"); + let started = Instant::now(); + let result = adapter.invoke(b"", Duration::from_millis(300)); + assert!(result.is_err()); + assert!(started.elapsed() < Duration::from_secs(5)); +} + +#[test] +fn output_past_the_bound_is_refused() { + if !confinement_available() { + return; + } + // One byte past MAX_RESPONSE_BYTES (8 MiB). + let adapter = sh_adapter("head -c 8388609 /dev/zero"); + let error = adapter.invoke(b"", Duration::from_secs(10)).unwrap_err(); + assert!(error.to_string().contains("byte bound")); +} + +#[test] +fn a_nonzero_exit_is_refused() { + if !confinement_available() { + return; + } + let adapter = sh_adapter("exit 3"); + let error = adapter.invoke(b"", Duration::from_secs(10)).unwrap_err(); + assert!(error.to_string().contains("status 3")); +} + +// --------------------------------------------------------------------------- +// macOS: sandbox-exec availability +// --------------------------------------------------------------------------- + +#[cfg(target_os = "macos")] +#[test] +fn a_missing_sandbox_exec_fails_closed() { + // The launcher path is fixed; when it is absent the adapter must refuse + // rather than fall back to an unconfined spawn. On a normal macOS host the + // binary exists, so this asserts the available path runs confined. + let adapter = sh_adapter("printf ok"); + let result = adapter.invoke(b"", Duration::from_secs(10)); + if Path::new("/usr/bin/sandbox-exec").is_file() { + assert!(result.is_ok(), "sandbox-exec present but invocation failed: {result:?}"); + } else { + let error = result.unwrap_err(); + assert!(error.to_string().contains("sandbox-exec")); + assert!(error.to_string().contains("unconfined")); + } +} + +// --------------------------------------------------------------------------- +// Linux: Landlock availability and the seccomp network deny +// --------------------------------------------------------------------------- + +#[cfg(target_os = "linux")] +#[allow(unsafe_code)] // raw Landlock ABI query mirrors the adapter's probe +#[test] +fn an_unavailable_landlock_fails_closed_with_a_clear_error() { + // Query the ABI the same way the adapter does. When Landlock is missing + // (old kernel) or blocked (container seccomp profile), invoke must refuse + // with a clear message and never run unconfined. + let abi = unsafe { + libc::syscall(libc::SYS_landlock_create_ruleset, std::ptr::null::(), 0_usize, 1_u32) + }; + let adapter = sh_adapter("printf ok"); + let result = adapter.invoke(b"", Duration::from_secs(10)); + if abi < 1 { + let error = result.unwrap_err(); + assert!(error.to_string().contains("Landlock"), "clear kernel error required: {error}"); + } else if result.is_err() { + // Landlock exists but a blocking seccomp profile (e.g. Docker default) + // prevents restrict_self: still a fail-closed refusal, never a run. + assert!(!confinement_available()); + } +} + +#[test] +fn a_confined_child_cannot_reach_a_listening_socket() { + use std::net::TcpListener; + + if !confinement_available() { + return; // fail-closed hosts are covered by the platform refusal tests + } + let Some(python) = which_python() else { + return; // no python3 on this host; the socket-creation deny is covered below + }; + // Bind a real listener so a successful connect is observable, then prove + // an unconfined child reaches it and a confined child cannot. + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let connect = format!( + "{python} -c 'import socket,sys; s=socket.socket(); s.settimeout(3); \ + s.connect((\"127.0.0.1\", {port})); sys.stdout.write(\"CONNECTED\")' 2>/dev/null || true" + ); + + // Control: unconfined, the same script connects. + let control = std::process::Command::new("/bin/sh").args(["-c", &connect]).output().unwrap(); + assert!( + String::from_utf8_lossy(&control.stdout).contains("CONNECTED"), + "the listener is not reachable even unconfined; test is invalid" + ); + let _ = listener.accept().unwrap(); + + // Confined: the connect must fail and the listener must see no connection. + let adapter = sh_adapter(&connect); + let output = adapter.invoke(b"", Duration::from_secs(10)).unwrap(); + assert!( + !String::from_utf8_lossy(&output.stdout).contains("CONNECTED"), + "the confined child reached the network" + ); + listener.set_nonblocking(true).unwrap(); + assert!(listener.accept().is_err(), "the confined child opened a connection"); +} + +#[cfg(target_os = "linux")] +#[test] +fn a_confined_child_cannot_create_a_socket() { + if !confinement_available() { + return; + } + let Some(python) = which_python() else { + return; + }; + // Minimal child: the probe arrives on stdin (argv rejects control + // characters) and every socket-creation attempt is guarded, so no + // uncaught exception can print a traceback echoing this source — the + // old false escape marker — or trigger Ubuntu's apport/apt hook. `-S` + // skips site-packages. The verdict is an exact stdout match, so stderr + // startup noise can never fake it. + let probe = r#"import errno, socket, sys +for attempt in (socket.socket, lambda: socket.socket(socket.AF_INET6), lambda: socket.socket(socket.AF_UNIX), socket.socketpair): + try: + attempt() + except OSError as e: + if e.errno != errno.EPERM: + sys.stdout.write("WRONG-ERRNO-%d" % e.errno) + sys.exit(0) + else: + sys.stdout.write("NET-ESCAPED") + sys.exit(0) +sys.stdout.write("SOCKET-DENIED")"#; + let adapter = sh_adapter(&format!("{python} -S -")); + let output = adapter.invoke(probe.as_bytes(), Duration::from_secs(10)).unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert_eq!( + stdout, "SOCKET-DENIED", + "socket creation was not denied with EPERM; stderr: {}", + output.stderr + ); +} + +/// Locate a python3 interpreter, or None when the host has none. +fn which_python() -> Option { + for candidate in ["python3", "/usr/bin/python3"] { + if std::process::Command::new(candidate) + .arg("--version") + .output() + .is_ok_and(|o| o.status.success()) + { + return Some(candidate.to_string()); + } + } + None +} diff --git a/tests/suggest_prepare_cli_test.rs b/tests/suggest_prepare_cli_test.rs index cc097546..9150ab82 100644 --- a/tests/suggest_prepare_cli_test.rs +++ b/tests/suggest_prepare_cli_test.rs @@ -160,7 +160,7 @@ fn the_preview_states_what_forge_does_and_does_not_control() { prepare_json(&root, &["--corpus", "corpus.json", "--include-document", "prior-access"]); let preview = std::fs::read_to_string(root.join("prepared/preview.txt")).unwrap(); assert!( - preview.contains("Process adapter execution is disabled"), + preview.contains("process adapter execution is confined"), "the notice must name the adapter boundary" ); assert!(preview.contains(payload.as_str())); diff --git a/tests/suggest_run_cli_test.rs b/tests/suggest_run_cli_test.rs index 0575cb40..c4be3c8d 100644 --- a/tests/suggest_run_cli_test.rs +++ b/tests/suggest_run_cli_test.rs @@ -225,18 +225,21 @@ fn a_missing_adapter_is_action_required_and_writes_nothing() { } #[test] -fn process_execution_is_refused_without_side_effects_or_json_contamination() { +fn confined_execution_cannot_escape_or_contaminate_json() { let (_temp, root) = project(); - // If spawned, this adapter would create a descendant and an unrelated file. - prepared(&root, "#!/bin/sh\n(sleep 30) & printf leaked > escaped.txt; printf response\n"); - let output = invoke(&root, &["--format", "json"]); - assert_exit(&output, 1); - assert_eq!(output.stdout, [] as [u8; 0]); - assert!( - String::from_utf8_lossy(&output.stderr).contains("process adapter execution is disabled") + // If confinement failed, this adapter would create a descendant and an + // unrelated file beside the project. The descendant exits immediately so + // it does not hold the output pipe (that case has its own test). + prepared( + &root, + "#!/bin/sh\n(printf descendant >/dev/null 2>&1) & printf leaked > escaped.txt; printf response\n", ); + let output = invoke(&root, &["--format", "json", "--timeout", "5"]); + assert_exit(&output, 0); + let record: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(record["mode"], json!("process")); + assert_eq!(std::fs::read(root.join(RUN_DIR).join("response.raw")).unwrap(), b"response"); assert!(!root.join("escaped.txt").exists()); - assert!(!root.join(RUN_DIR).exists()); } #[test]