Skip to main content

capsule_runtime/
sandbox.rs

1//! Kernel-level enforcement for the shell-subprocess tree spawned by `shell::execute_shell`.
2//!
3//! Today `execute_shell` is gated only by app-level checks (`policy.shell_allow` string
4//! equality, and `shell::build_shell_env`'s synthetic-HOME/credential-stripping). Nothing
5//! stops the spawned process — or anything it execs/forks — from making arbitrary syscalls:
6//! reading files outside its workdir, or connecting to hosts outside `policy.network_allow`.
7//! This module closes that gap for the shell subprocess tree specifically, using two Linux
8//! kernel primitives:
9//!
10//!   - **Landlock `Execute` rights** to allowlist exec by *path*, decided by the kernel on the
11//!     path it resolved itself. Each `shell.allow` binary — plus its ELF interpreter and its
12//!     `DT_NEEDED` closure — gets a narrow read+execute grant (`resolve_landlock_grants`), and the
13//!     capsule's own workdir gets `Execute` **only** when the manifest declares
14//!     `capabilities.filesystem.workdir_exec: true` (`linux_enforce::workdir_access_rights`). With
15//!     the default, nothing the capsule writes into its workdir can run under any name, so the
16//!     rename-to-an-allowlisted-basename bypass has no path left. `execve`/`execveat` are
17//!     ordinary allowed syscalls, decided entirely by the Landlock domain they run in.
18//!   - **classic seccomp-bpf argument matching** (`SECCOMP_RET_ERRNO`) on `socket(2)`'s `domain`,
19//!     to refuse whole address families outright — see `denied_socket_domains`. Unlike a
20//!     destination `sockaddr`, `domain` is an integer in a register, so the kernel's own BPF can
21//!     compare it with no userspace round-trip and no notification at all. This is what stops a
22//!     capsule reaching `/var/run/docker.sock` (host root) over `AF_UNIX`, which no other
23//!     mechanism here covers: a network namespace does not mediate `AF_UNIX` at all, and Landlock
24//!     ABI v1 does not mediate an abstract-namespace socket. `AF_NETLINK`/`AF_PACKET` are denied
25//!     unconditionally; `AF_UNIX` is denied unless `capabilities.network.unix_sockets` says
26//!     otherwise.
27//!   - **a default-deny syscall allowlist** modelled on the OCI/Docker default seccomp profile —
28//!     see `SECCOMP_SYSCALL_ALLOWLIST`. The filter's default action is `SECCOMP_RET_ERRNO(EPERM)`,
29//!     so a syscall named by neither that array nor one of the rules above is refused outright,
30//!     with no argument inspection at all. This is what puts `io_uring_*` (historically an
31//!     LSM-path-hook bypass, and so a candidate route around Landlock itself), `bpf`,
32//!     `userfaultfd`, `perf_event_open`, `ptrace` and the rest of `SECCOMP_MUST_STAY_DENIED` out
33//!     of a capsule's reach. The filter also sets `SCMP_FLTATR_CTL_LOG`, so each denial reaches
34//!     the kernel audit trail with a syscall number, pid and comm.
35//!   - **Landlock LSM** to scope filesystem access to the capsule's `workdir`. The workdir's own
36//!     grant deliberately withholds `MakeChar`/`MakeBlock`/`MakeSock`, and withholds `Execute`
37//!     unless `capabilities.filesystem.workdir_exec` is declared — see
38//!     `linux_enforce::WORKDIR_ACCESS_RIGHTS_NO_EXEC` and `linux_enforce::workdir_access_rights`.
39//!     Outside the workdir, alongside the derived
40//!     read+execute grants, a fixed three-device set is granted unconditionally — see
41//!     `CAPSULE_DEVICE_GRANTS`: `/dev/null` read+write (the only writable path outside the
42//!     workdir), `/dev/zero` and `/dev/urandom` read-only, and no other device at all.
43//!
44//! Both Linux tiers additionally strip the forked child's **Linux capabilities** (bounding set,
45//! then permitted/effective/inheritable, then `no_new_privs`) before `execve()` — see
46//! `linux_enforce::drop_all_capabilities`. Landlock and the capability model are independent,
47//! both-must-allow gates: a root-uid capsule keeps `CAP_MKNOD` no matter what Landlock permits,
48//! so the Landlock narrowing above does not subsume this.
49//!
50//! Both are Linux-only. macOS (and any other non-Linux target) has no equivalent kernel
51//! primitive and permanently falls back to the existing, unmodified synthetic-HOME/env-
52//! stripping mechanism in `shell.rs` — see `EnforcementTier::EnvironmentOnly`.
53//!
54//! ## Four-tier model
55//!
56//! - `KernelSealed` (Linux, everything `KernelFull` has, plus a usable unprivileged user+mount
57//!   namespace — AppArmor out of the way, `unshare` + `mount` verified by a real probe): the
58//!   subprocess tree additionally runs inside a private mount namespace pivoted onto a composed
59//!   root, so paths outside it are *absent* rather than denied. Landlock and seccomp still install,
60//!   inside the new root, as defence in depth — see [`crate::sealed`]. Only capsules that declare
61//!   `capabilities.containment: sealed` get this; see `applied_tier`.
62//! - `KernelFull` (Linux, Landlock ABI available — kernel 5.13+): seccomp syscall allowlist +
63//!   socket-domain denial + Landlock filesystem scoping, which is also what makes
64//!   `capabilities.shell.allow` enforceable (exec is a Landlock right, not a syscall filter).
65//! - `KernelSeccompOnly` (Linux, Landlock unavailable — kernel <5.13): seccomp syscall allowlist +
66//!   socket-domain denial only. Filesystem scope stays convention-only (`current_dir`) — a
67//!   documented gap, not a bug — and, since the exec supervisor was retired, so does
68//!   `shell.allow`: with no Landlock domain there is no kernel-level exec mediation on this tier
69//!   at all. `W-SEC-002` says so. The syscall allowlist and the socket-domain denial are identical
70//!   on both tiers: they are seccomp rules, so they do not depend on Landlock in any way.
71//! - `EnvironmentOnly` (macOS / any non-Linux target): no kernel primitive attempted at all.
72//!   Permanent, not a placeholder for a future slice.
73//!
74//! Tier detection is always a runtime capability probe (attempt Landlock ruleset
75//! construction, inspect the resulting `RulesetStatus`; fork a child and really call
76//! `unshare(CLONE_NEWUSER | CLONE_NEWNS)` followed by a `mount(2)`) — never a hardcoded
77//! kernel-version string parse, which is fragile against distro backports, and never a config
78//! file. Each reading is taken live, and a staged session takes exactly one for every consumer
79//! of that session to read; see [`HostProbe`].
80//!
81//! ## Fail-closed invariant
82//!
83//! If kernel enforcement setup fails unexpectedly on a Linux host (not the expected
84//! "Landlock unsupported, degrade to `KernelSeccompOnly`" signal, but something like seccomp
85//! filter install failing, or the namespace-socket handshake failing before spawn) —
86//! `prepare_enforcement` returns `Err` and `execute_shell` must not call `.spawn()` at all.
87//! There is no code path where a Linux host silently runs a shell subprocess with zero
88//! enforcement because setup failed.
89
90use std::net::IpAddr;
91use std::path::{Path, PathBuf};
92use std::sync::Arc;
93
94use murmur_artifact::security_warnings::{
95    security_warning_link, W_SEC_001, W_SEC_002, W_SEC_005, W_SEC_010,
96};
97use murmur_artifact::InterpreterRuntimeGrant;
98
99use crate::types::CapabilityPolicy;
100
101/// Kernel-enforcement tier for the current host, in descending order of enforcement
102/// strength. Always host-probed at launch time — never sourced from the manifest.
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub(crate) enum EnforcementTier {
105    /// Linux, and everything `KernelFull` has *plus* a private mount namespace pivoted onto a
106    /// composed root (see [`crate::sealed`]): the shipped AppArmor profile is loaded (or AppArmor
107    /// imposes no unprivileged-userns restriction), a real `unshare` + `mount` probe succeeded,
108    /// and the Landlock ABI is usable. Paths outside the composed root are *absent*, not merely
109    /// denied — and Landlock and seccomp still install inside it, as defence in depth.
110    ///
111    /// Ranked first because it is the strongest tier; the enum is documented weakest-last and
112    /// carries no `Ord`, so this position is documentation, not a comparison.
113    KernelSealed,
114    /// Linux, Landlock ABI available (kernel 5.13+): seccomp exec/network allowlisting
115    /// + Landlock filesystem scoping.
116    KernelFull,
117    /// Linux, Landlock unavailable (kernel <5.13): seccomp exec/network allowlisting
118    /// only. Filesystem scope stays convention-only (`current_dir`) — documented gap.
119    KernelSeccompOnly,
120    /// macOS (or any non-Linux target): no kernel sandboxing primitive exists. This is
121    /// PERMANENT, not a placeholder for a future slice.
122    EnvironmentOnly,
123}
124
125/// Pure decision: given whether the host is Linux, the outcome of a Landlock
126/// ruleset-restriction probe, and what [`crate::sealed::probe_sealed_support`] found, decide the
127/// tier. No syscalls here — fully unit-testable on any OS.
128///
129/// `KernelSealed` requires the whole conjunction — Linux, a usable Landlock ABI, AppArmor out of
130/// the way, and a namespace probe that really created one. Any missing element falls back to the
131/// tier that element still supports; nothing here ever reports a mechanism the host did not
132/// demonstrate.
133pub(crate) fn tier_from_probe(
134    is_linux: bool,
135    landlock_fully_enforced: Option<bool>,
136    sealed: crate::sealed::SealedProbe,
137) -> EnforcementTier {
138    if !is_linux {
139        return EnforcementTier::EnvironmentOnly;
140    }
141    match landlock_fully_enforced {
142        Some(true)
143            if sealed.userns_grant.permits_userns()
144                && sealed.namespace == crate::sealed::NamespaceProbe::Ok =>
145        {
146            EnforcementTier::KernelSealed
147        }
148        Some(true) => EnforcementTier::KernelFull,
149        Some(false) | None => EnforcementTier::KernelSeccompOnly,
150    }
151}
152
153/// The tier this *session* actually applies, which is never stronger than the host can back and
154/// never stronger than the capsule asked for.
155///
156/// A capsule declaring `scoped` on a sealed-capable host keeps running exactly as it does today:
157/// the composed root would otherwise silently delete host paths its `interpreter_runtime` grants
158/// legitimately point at — a narrowing of `scoped`'s behaviour, not added security. The
159/// declared floor is honoured, not merely met.
160///
161/// It is deliberately *not* symmetric with the achieved class recorded in the trace: `achieved`
162/// answers "what can this host back" (a host fact) and is probed independently, while this answers
163/// "what did this session install" (a session fact).
164pub(crate) fn applied_tier(
165    host_tier: EnforcementTier,
166    declared: murmur_artifact::ContainmentClass,
167) -> EnforcementTier {
168    match host_tier {
169        EnforcementTier::KernelSealed if declared < murmur_artifact::ContainmentClass::Sealed => {
170            EnforcementTier::KernelFull
171        }
172        other => other,
173    }
174}
175
176/// The host facts the tier decision is made from, taken together as one reading.
177///
178/// A staged session takes exactly one of these and every consumer of that session reads it — the
179/// containment-floor refusal, the `ScopeReport` written to the trace, and the tier
180/// [`ShellEnforcement::resolve`] installs. Two readings of a host that changed between them would
181/// let the trace describe a session that never ran under what it claims.
182#[derive(Debug, Clone, Copy)]
183pub struct HostProbe {
184    landlock_fully_enforced: Option<bool>,
185    sealed: crate::sealed::SealedProbe,
186}
187
188/// Probes taken since this process started. See [`HostProbe::probes_taken`].
189static PROBES_TAKEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
190
191impl HostProbe {
192    /// Reads the host as it is right now: on Linux a real Landlock ruleset restriction attempt
193    /// (`RulesetStatus::FullyEnforced` → `Some(true)`, `PartiallyEnforced`/`NotEnforced` or any
194    /// construction error → `Some(false)`, no Landlock ABI → `None`) plus a real
195    /// `unshare(CLONE_NEWUSER | CLONE_NEWNS)` and `mount(2)`. Off Linux it probes nothing and
196    /// claims nothing.
197    ///
198    /// Taken once per staged session, not once per process. That is affordable because both
199    /// halves do their work in a forked child and leave the calling process exactly as they found
200    /// it — `linux_enforce::probe_landlock_full_access` forks so the runtime is never placed
201    /// into a Landlock domain by a capability check, and [`crate::sealed::probe_sealed_support`]
202    /// forks because `unshare(CLONE_NEWUSER)` is irreversible for the task that calls it. Neither
203    /// is idempotency-sensitive, so a reading costs no more than the syscalls it makes: two
204    /// `fork`/`waitpid` pairs and three small `/proc` reads.
205    ///
206    /// The window this leaves open is one session wide. Between `runtime::stage_session` and the
207    /// last subprocess that session spawns the host is not re-read; a change inside that window is
208    /// caught by the mechanism installation itself failing closed, not by a second probe. A
209    /// process that stages repeatedly — `mur eval`, which stages once per dataset case — judges
210    /// each session against the host as it was when that session was staged.
211    pub fn probe() -> HostProbe {
212        PROBES_TAKEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
213        #[cfg(target_os = "linux")]
214        let probe = HostProbe {
215            landlock_fully_enforced: linux_enforce::probe_landlock_full_access(),
216            sealed: crate::sealed::probe_sealed_support(),
217        };
218        #[cfg(not(target_os = "linux"))]
219        let probe = HostProbe {
220            landlock_fully_enforced: None,
221            sealed: crate::sealed::SealedProbe::default(),
222        };
223        probe
224    }
225
226    /// A probe value assembled from known halves, without touching the host. The seam the
227    /// fail-closed tests use to assert what an all-negative reading resolves to on any OS.
228    #[cfg(test)]
229    pub(crate) fn from_parts(
230        landlock_fully_enforced: Option<bool>,
231        sealed: crate::sealed::SealedProbe,
232    ) -> HostProbe {
233        HostProbe {
234            landlock_fully_enforced,
235            sealed,
236        }
237    }
238
239    /// The tier this reading supports. `pub(crate)` because [`EnforcementTier`] is.
240    pub(crate) fn tier(&self) -> EnforcementTier {
241        tier_from_probe(
242            cfg!(target_os = "linux"),
243            self.landlock_fully_enforced,
244            self.sealed,
245        )
246    }
247
248    /// Which single mechanism keeps this reading below `sealed`, or `None` when nothing does.
249    pub fn sealed_blocker(&self) -> Option<crate::sealed::SealedBlocker> {
250        crate::sealed::sealed_blocker(
251            cfg!(target_os = "linux"),
252            self.landlock_fully_enforced == Some(true),
253            self.sealed,
254        )
255    }
256
257    /// Where this host's permission to create an unprivileged user namespace comes from, or
258    /// `None` off Linux, where the question has no answer rather than a negative one.
259    pub fn userns_grant(&self) -> Option<crate::sealed::UsernsGrant> {
260        if cfg!(target_os = "linux") {
261            Some(self.sealed.userns_grant)
262        } else {
263            None
264        }
265    }
266
267    /// How many probes this process has taken, counting from zero at startup and never
268    /// decreasing.
269    ///
270    /// The observability hook the freshness tests assert against — that staging twice advances it
271    /// by two, and that one `stage_session` advances it by one — and nothing else reads it. No
272    /// runtime decision depends on the count.
273    pub fn probes_taken() -> u64 {
274        PROBES_TAKEN.load(std::sync::atomic::Ordering::Relaxed)
275    }
276}
277
278/// The tier this host can back, from a reading taken here.
279///
280/// Answers a standalone host question — `mur doctor` and the escape-conformance harness ask it.
281/// A *session* must not: it reads its own [`HostProbe`] so its refusal, its trace and the
282/// mechanisms it installs describe one host at one moment.
283pub(crate) fn detect_enforcement_tier() -> EnforcementTier {
284    HostProbe::probe().tier()
285}
286
287/// Which single mechanism keeps this host below `sealed`, or `None` when nothing does, from a
288/// reading taken here.
289///
290/// Takes its own probe, as its neighbours do. What a session needs — that the refusal an operator
291/// sees and the tier the runtime installs cannot disagree about the host — is upheld by
292/// `runtime::stage_session` passing one [`HostProbe`] to both, not by this function.
293pub fn detect_sealed_blocker() -> Option<crate::sealed::SealedBlocker> {
294    HostProbe::probe().sealed_blocker()
295}
296
297/// Where this host's unprivileged-user-namespace permission comes from, or `None` off Linux, where
298/// the question has no answer rather than a negative one.
299///
300/// Takes its own probe, as its neighbours do; a session reads the provenance off its own
301/// [`HostProbe`] instead, so what it is shown and the tier it installs describe one host at one
302/// moment.
303pub fn detect_userns_grant() -> Option<crate::sealed::UsernsGrant> {
304    HostProbe::probe().userns_grant()
305}
306
307/// Resolves every host in `network_allow` (via `crate::network_policy::parse_network_allow_rules`,
308/// the same parser already used for the WASI-HTTP-facing allowlist) to concrete IP addresses
309/// via DNS, once. Returns the deduplicated union of all resolved addresses across all allowed
310/// hosts.
311///
312/// Hosts that fail to resolve are silently skipped, matching `resolve_exec_allowlist`'s precedent
313/// below: the resolved set feeds *only* the kernel-level (Landlock/seccomp) allow set for
314/// `shell.allow` subprocesses, so a host contributing zero IPs merely *shrinks* that set (deny
315/// direction, fail-closed). A DNS miss must not be fatal — resolution happens unconditionally at
316/// staging time, before any WASM loads and regardless of whether the capsule declares
317/// `shell.allow` at all, so hard-failing here turned any transient resolver outage or
318/// non-resolving allowlist host into an E-IO-003 that blocked the whole run.
319///
320/// This does not widen what the capsule may reach: the WASM component's own outbound WASI-HTTP
321/// calls are gated separately by `network_policy::NetworkAllowRule::matches`, a host-pattern
322/// match that never consults DNS. Malformed host *syntax* is still a hard error — it is caught by
323/// `parse_network_allow_rules` above, before this loop.
324pub(crate) fn resolve_network_allowlist_ips(
325    network_allow: &[String],
326) -> Result<Vec<IpAddr>, String> {
327    let rules = crate::network_policy::parse_network_allow_rules(network_allow)
328        .map_err(|error| error.to_string())?;
329
330    let mut ips = std::collections::BTreeSet::new();
331    for rule in &rules {
332        let host = rule.host.as_str();
333        match crate::dns_resolver::resolve(host) {
334            crate::dns_resolver::Resolution::Resolved(addresses) => ips.extend(addresses),
335            crate::dns_resolver::Resolution::DoesNotExist => {}
336            // Skipped like any other host that contributed no address, but said out loud: a
337            // resolver that did not answer is a transient condition an operator can act on,
338            // where a name that does not exist is a manifest to correct.
339            crate::dns_resolver::Resolution::DidNotAnswer(reason) => eprintln!(
340                "[capsule-runtime] warning: the network allowlist host '{host}' could not be \
341                 resolved at launch: {reason} (a subprocess reaching it by literal address is \
342                 denied for this run)"
343            ),
344        }
345    }
346
347    Ok(ips.into_iter().collect())
348}
349
350/// Resolves each `capabilities.shell.allow` entry to the canonical filesystem path(s) of the
351/// binary it names, once, at launch time. Entries containing a path separator are
352/// canonicalized directly; bare names (the common case, per the manifest schema's
353/// "bare binary name" rule) are looked up in the host `PATH` the way `execvp` would, then
354/// canonicalized (resolving symlinks, `..`, etc.).
355///
356/// Entries that resolve to nothing (binary not installed) are silently skipped — that only
357/// *shrinks* the kernel-level allow set (deny direction, fail-closed) and matches reality:
358/// an exec of a binary that does not exist at launch fails anyway, and a binary *created
359/// after launch* under an allowlisted name (the attack this exists to stop) must not become
360/// allowlisted by virtue of its name.
361///
362/// This canonical set — not the raw name strings — is what `resolve_landlock_grants` derives the
363/// narrow read+execute Landlock grants from, so `cp /usr/bin/nc ./bash && ./bash` is denied: the
364/// copy lives under the workdir, which carries no `Execute` right by default, and the grant that
365/// does carry one names the launch-time `bash`'s own inode, not a basename.
366pub(crate) fn resolve_exec_allowlist(shell_allow: &[String]) -> Vec<PathBuf> {
367    let path_dirs: Vec<PathBuf> = std::env::var_os("PATH")
368        .map(|path| std::env::split_paths(&path).collect())
369        .unwrap_or_default();
370    resolve_exec_allowlist_in(shell_allow, &path_dirs)
371}
372
373/// Testable core of `resolve_exec_allowlist`, with the `PATH` directory list injected. For a
374/// bare name, every executable `PATH` match is included (not just the first): all of them are
375/// binaries the operator's launch-time `PATH` exposes under that allowlisted name, and on
376/// merged-`/usr` distros `/bin/x` and `/usr/bin/x` canonicalize to the same entry anyway.
377fn resolve_exec_allowlist_in(shell_allow: &[String], path_dirs: &[PathBuf]) -> Vec<PathBuf> {
378    let mut resolved = std::collections::BTreeSet::new();
379    for entry in shell_allow {
380        if entry.is_empty() {
381            continue;
382        }
383        if entry.contains('/') {
384            if let Ok(canonical) = std::fs::canonicalize(entry) {
385                resolved.insert(canonical);
386            }
387            continue;
388        }
389        for dir in path_dirs {
390            let candidate = dir.join(entry);
391            if is_executable_file(&candidate) {
392                if let Ok(canonical) = std::fs::canonicalize(&candidate) {
393                    resolved.insert(canonical);
394                }
395            }
396        }
397    }
398    resolved.into_iter().collect()
399}
400
401/// Resolves the program name a shell tool invoked to the canonical filesystem path of the
402/// binary that `execvp` would actually run, for reporting purposes: `shell-event.binary`
403/// on the hook side and the `binary` key of `trace.jsonl`'s `shell` record.
404///
405/// Unlike [`resolve_exec_allowlist`] — which collects *every* `PATH` match because each one needs
406/// its own Landlock grant — this returns the **first** match, which is the one `execvp` picks and
407/// therefore the one that ran. Resolution rules are otherwise identical (same `PATH` source, same
408/// [`is_executable_file`] test, same `canonicalize`), so a reported path is always a member of the
409/// set the Landlock grants were derived from.
410///
411/// A name that resolves to nothing falls back to the bare invoked name, unchanged — never
412/// an error, never a panic, matching `resolve_exec_allowlist`'s "entries that resolve to
413/// nothing are silently skipped" precedent. Observability must not be able to fail a shell
414/// call that the OS is perfectly willing to run.
415pub(crate) fn resolve_invoked_binary_path(binary: &str) -> String {
416    let path_dirs: Vec<PathBuf> = std::env::var_os("PATH")
417        .map(|path| std::env::split_paths(&path).collect())
418        .unwrap_or_default();
419    resolve_invoked_binary_path_in(binary, &path_dirs)
420}
421
422/// Testable core of [`resolve_invoked_binary_path`], with the `PATH` directory list
423/// injected. `pub(crate)` because [`crate::reachability`] needs the same first-match resolution
424/// against an *injected* directory list — its own unit tests point `PATH` at a temp directory of
425/// synthetic script fixtures rather than at whatever the machine running the suite has installed.
426pub(crate) fn resolve_invoked_binary_path_in(binary: &str, path_dirs: &[PathBuf]) -> String {
427    let fallback = || binary.to_string();
428    if binary.is_empty() {
429        return fallback();
430    }
431    if binary.contains('/') {
432        return match std::fs::canonicalize(binary) {
433            Ok(canonical) => canonical.to_string_lossy().into_owned(),
434            Err(_) => fallback(),
435        };
436    }
437    for dir in path_dirs {
438        let candidate = dir.join(binary);
439        if is_executable_file(&candidate) {
440            if let Ok(canonical) = std::fs::canonicalize(&candidate) {
441                return canonical.to_string_lossy().into_owned();
442            }
443        }
444    }
445    fallback()
446}
447
448/// The first executable named `binary` on this process's `PATH`, or `None` when there is none.
449///
450/// First match wins, which is the one `execvp` would run — the same rule
451/// [`resolve_invoked_binary_path_in`] reports under, so a caller naming a binary and a caller
452/// reporting one cannot disagree about which file `PATH` means. The path is returned as found,
453/// not canonicalized: callers here name a binary to a person rather than derive a grant from it.
454pub fn find_on_path(binary: &str) -> Option<PathBuf> {
455    std::env::split_paths(&std::env::var_os("PATH")?)
456        .map(|dir| dir.join(binary))
457        .find(|candidate| is_executable_file(candidate))
458}
459
460fn is_executable_file(path: &Path) -> bool {
461    use std::os::unix::fs::PermissionsExt;
462    std::fs::metadata(path)
463        .map(|meta| meta.is_file() && meta.permissions().mode() & 0o111 != 0)
464        .unwrap_or(false)
465}
466
467// ---- derived Landlock read+execute grant set ----
468//
469// On `KernelFull`, Landlock scopes the shell subprocess tree to the workdir. The workdir rule
470// grants `linux_enforce::WORKDIR_ACCESS_RIGHTS` (everything in ABI v1 except device-node and
471// unix-socket creation), but — once `restrict_self()` lands — `Execute`/`ReadFile` are then denied
472// on every path *outside* the workdir, including the `shell.allow` binaries themselves, their ELF
473// interpreter (dynamic loader), and every shared library they pull in. That silently defeats the
474// seccomp exec-allowlist: each allowlisted `execve` fails with EACCES before it runs.
475//
476// The functions below derive the exact extra paths that must get a narrow read+execute grant
477// outside the workdir: the canonical `shell.allow` binaries (already resolved by
478// `resolve_exec_allowlist`), each one's `PT_INTERP`, and the transitive closure of the shared
479// libraries their ELF `DT_NEEDED` entries name (resolved via `DT_RPATH`/`DT_RUNPATH` first, then a
480// fixed set of standard library directories). Nothing broader — no directory is granted wholesale.
481//
482// All of this is *parsing and filesystem resolution*, so it runs in the parent at launch time
483// (inside `ShellEnforcement::resolve`) and the resulting `Vec<PathBuf>` is threaded into the
484// forked child's `pre_exec`, which only opens each path and adds a Landlock rule (no parsing in
485// the async-signal-safe window). Every resolution step is shrink-not-fail, matching
486// `resolve_exec_allowlist`: an entry that does not exist, does not parse as ELF, or names a
487// soname that does not resolve simply contributes nothing further — it never errors out.
488
489/// Standard Linux shared-library search directories used as the fallback resolution set for a
490/// `DT_NEEDED` soname when the binary declares no `DT_RPATH`/`DT_RUNPATH` (or it doesn't match).
491/// Covers both supported platform targets (`linux/x86_64` and `linux/aarch64`), including the
492/// Debian/Ubuntu multiarch-triplet subdirectories. Extend here for a platform this list does not
493/// cover — it is the single source of truth.
494const DEFAULT_LIBRARY_SEARCH_DIRS: &[&str] = &[
495    "/lib",
496    "/lib64",
497    "/usr/lib",
498    "/usr/lib64",
499    "/lib/x86_64-linux-gnu",
500    "/usr/lib/x86_64-linux-gnu",
501    "/lib/aarch64-linux-gnu",
502    "/usr/lib/aarch64-linux-gnu",
503];
504
505/// The subset of an ELF binary's dynamic-linking metadata that decides which extra files the
506/// dynamic loader will touch at load time: the interpreter path (`PT_INTERP`), the direct
507/// shared-library dependencies (`DT_NEEDED` sonames), and the runtime library search paths
508/// (`DT_RPATH`/`DT_RUNPATH`, already split on `:`, `$ORIGIN` left unexpanded here).
509#[derive(Debug, Default, PartialEq, Eq)]
510pub(crate) struct ElfDependencies {
511    pub(crate) interp: Option<String>,
512    pub(crate) needed: Vec<String>,
513    pub(crate) runpaths: Vec<String>,
514}
515
516fn read_u16(bytes: &[u8], off: usize, le: bool) -> Option<u16> {
517    let raw: [u8; 2] = bytes.get(off..off + 2)?.try_into().ok()?;
518    Some(if le {
519        u16::from_le_bytes(raw)
520    } else {
521        u16::from_be_bytes(raw)
522    })
523}
524
525fn read_u32(bytes: &[u8], off: usize, le: bool) -> Option<u32> {
526    let raw: [u8; 4] = bytes.get(off..off + 4)?.try_into().ok()?;
527    Some(if le {
528        u32::from_le_bytes(raw)
529    } else {
530        u32::from_be_bytes(raw)
531    })
532}
533
534fn read_u64(bytes: &[u8], off: usize, le: bool) -> Option<u64> {
535    let raw: [u8; 8] = bytes.get(off..off + 8)?.try_into().ok()?;
536    Some(if le {
537        u64::from_le_bytes(raw)
538    } else {
539        u64::from_be_bytes(raw)
540    })
541}
542
543/// Reads a NUL-terminated string starting at the beginning of `region` (used for both the
544/// `PT_INTERP` segment and dynamic-string-table entries).
545fn cstr_at_start(region: &[u8]) -> String {
546    let nul = region.iter().position(|&b| b == 0).unwrap_or(region.len());
547    String::from_utf8_lossy(&region[..nul]).into_owned()
548}
549
550/// Maps a virtual address into a file offset using the ELF's `PT_LOAD` segments — required
551/// because `DT_STRTAB` records the string table's virtual address, not its file offset.
552fn vaddr_to_file_offset(vaddr: u64, loads: &[(u64, u64, u64)]) -> Option<u64> {
553    for &(seg_vaddr, seg_off, seg_filesz) in loads {
554        if vaddr >= seg_vaddr && vaddr < seg_vaddr.checked_add(seg_filesz)? {
555            return Some(seg_off + (vaddr - seg_vaddr));
556        }
557    }
558    None
559}
560
561/// Pure ELF64 parser: extracts the dynamic-linking metadata that determines which extra files the
562/// loader touches. Returns `None` for anything that is not a well-formed ELF64 image (bad magic,
563/// 32-bit, truncated headers) — a non-ELF or unparseable binary simply contributes nothing to the
564/// grant set (shrink-not-fail). Deliberately hand-rolled (no crate dependency) and byte-slice-in /
565/// struct-out so it is fully unit-testable off-Linux with synthetic fixtures; it makes no syscalls.
566///
567/// Only ELF64 is parsed: both supported Linux targets (`x86_64`, `aarch64`) are 64-bit, so a
568/// 32-bit image is not a binary this runtime would exec and is treated as unparseable.
569pub(crate) fn parse_elf_dependencies(bytes: &[u8]) -> Option<ElfDependencies> {
570    // e_ident (16) + fixed ELF64 header fields extend to offset 64.
571    if bytes.len() < 64 || &bytes[0..4] != b"\x7fELF" {
572        return None;
573    }
574    // EI_CLASS: 2 == ELFCLASS64. EI_DATA: 1 == little-endian, 2 == big-endian.
575    if bytes[4] != 2 {
576        return None;
577    }
578    let le = match bytes[5] {
579        1 => true,
580        2 => false,
581        _ => return None,
582    };
583
584    let e_phoff = read_u64(bytes, 32, le)? as usize;
585    let e_phentsize = read_u16(bytes, 54, le)? as usize;
586    let e_phnum = read_u16(bytes, 56, le)? as usize;
587    // Each Elf64_Phdr is 56 bytes; a smaller entsize is not this layout.
588    if e_phentsize < 56 {
589        return None;
590    }
591
592    let mut interp: Option<String> = None;
593    let mut dynamic_region: Option<(u64, u64)> = None; // (file offset, size)
594    let mut loads: Vec<(u64, u64, u64)> = Vec::new(); // (p_vaddr, p_offset, p_filesz)
595
596    for i in 0..e_phnum {
597        let base = e_phoff.checked_add(i.checked_mul(e_phentsize)?)?;
598        let p_type = read_u32(bytes, base, le)?;
599        let p_offset = read_u64(bytes, base + 8, le)?;
600        let p_vaddr = read_u64(bytes, base + 16, le)?;
601        let p_filesz = read_u64(bytes, base + 32, le)?;
602        match p_type {
603            1 => loads.push((p_vaddr, p_offset, p_filesz)), // PT_LOAD
604            2 => dynamic_region = Some((p_offset, p_filesz)), // PT_DYNAMIC
605            3 => {
606                // PT_INTERP: a NUL-terminated interpreter path in the file image.
607                let start = p_offset as usize;
608                let end = start.checked_add(p_filesz as usize)?;
609                interp = Some(cstr_at_start(bytes.get(start..end)?));
610            }
611            _ => {}
612        }
613    }
614
615    // A static binary (no PT_DYNAMIC) contributes only itself — no interp, no needed libs.
616    let Some((dyn_off, dyn_size)) = dynamic_region else {
617        return Some(ElfDependencies {
618            interp,
619            needed: Vec::new(),
620            runpaths: Vec::new(),
621        });
622    };
623
624    let mut needed_offsets: Vec<u64> = Vec::new();
625    let mut runpath_offsets: Vec<u64> = Vec::new();
626    let mut strtab_vaddr: Option<u64> = None;
627    let mut strsz: Option<u64> = None;
628
629    let mut off = dyn_off as usize;
630    let dyn_end = off.checked_add(dyn_size as usize)?;
631    while off + 16 <= dyn_end {
632        let d_tag = read_u64(bytes, off, le)?;
633        let d_val = read_u64(bytes, off + 8, le)?;
634        match d_tag {
635            0 => break,                             // DT_NULL — end of dynamic array
636            1 => needed_offsets.push(d_val),        // DT_NEEDED
637            5 => strtab_vaddr = Some(d_val),        // DT_STRTAB (virtual address)
638            10 => strsz = Some(d_val),              // DT_STRSZ
639            15 | 29 => runpath_offsets.push(d_val), // DT_RPATH | DT_RUNPATH
640            _ => {}
641        }
642        off += 16;
643    }
644
645    let mut needed = Vec::new();
646    let mut runpaths = Vec::new();
647    if let (Some(strtab_vaddr), Some(strsz)) = (strtab_vaddr, strsz) {
648        if let Some(strtab_off) = vaddr_to_file_offset(strtab_vaddr, &loads) {
649            let start = strtab_off as usize;
650            // Prefer the declared string-table bounds, but tolerate an over-long DT_STRSZ by
651            // falling back to the rest of the file rather than dropping every soname.
652            let strtab = start
653                .checked_add(strsz as usize)
654                .and_then(|end| bytes.get(start..end))
655                .or_else(|| bytes.get(start..));
656            if let Some(strtab) = strtab {
657                for offset in needed_offsets {
658                    if let Some(region) = strtab.get(offset as usize..) {
659                        needed.push(cstr_at_start(region));
660                    }
661                }
662                for offset in runpath_offsets {
663                    if let Some(region) = strtab.get(offset as usize..) {
664                        for part in cstr_at_start(region).split(':') {
665                            if !part.is_empty() {
666                                runpaths.push(part.to_string());
667                            }
668                        }
669                    }
670                }
671            }
672        }
673    }
674
675    Some(ElfDependencies {
676        interp,
677        needed,
678        runpaths,
679    })
680}
681
682/// Expands a leading/embedded `$ORIGIN` (or `${ORIGIN}`) in an rpath entry to the directory of the
683/// binary that declared it — the dynamic loader's own rule for `DT_RUNPATH`/`DT_RPATH`.
684fn expand_origin(rpath: &str, origin_dir: &Path) -> PathBuf {
685    if rpath.contains("$ORIGIN") {
686        let origin = origin_dir.to_string_lossy();
687        PathBuf::from(
688            rpath
689                .replace("${ORIGIN}", &origin)
690                .replace("$ORIGIN", &origin),
691        )
692    } else {
693        PathBuf::from(rpath)
694    }
695}
696
697/// Resolves one `DT_NEEDED` soname to a canonical file path, mirroring the loader's search order:
698/// a soname containing a `/` is taken as a path (absolute, or relative to the binary's directory);
699/// otherwise the binary's own `DT_RUNPATH`/`DT_RPATH` entries (with `$ORIGIN` expanded) are tried
700/// first, then the standard `search_dirs`. Returns `None` (shrink-not-fail) if nothing matches.
701pub(crate) fn resolve_soname(
702    soname: &str,
703    origin_dir: &Path,
704    runpaths: &[String],
705    search_dirs: &[PathBuf],
706) -> Option<PathBuf> {
707    if soname.is_empty() {
708        return None;
709    }
710    if soname.contains('/') {
711        let candidate = if Path::new(soname).is_absolute() {
712            PathBuf::from(soname)
713        } else {
714            origin_dir.join(soname)
715        };
716        return std::fs::canonicalize(&candidate).ok();
717    }
718    for rpath in runpaths {
719        let candidate = expand_origin(rpath, origin_dir).join(soname);
720        if candidate.is_file() {
721            if let Ok(canonical) = std::fs::canonicalize(&candidate) {
722                return Some(canonical);
723            }
724        }
725    }
726    for dir in search_dirs {
727        let candidate = dir.join(soname);
728        if candidate.is_file() {
729            if let Ok(canonical) = std::fs::canonicalize(&candidate) {
730                return Some(canonical);
731            }
732        }
733    }
734    None
735}
736
737/// Derives the full set of canonical file paths that need a narrow read+execute Landlock grant
738/// *outside* the workdir so the `shell.allow` binaries can actually run: each allowlisted binary,
739/// its ELF interpreter, and the transitive closure of its `DT_NEEDED` shared libraries. Uses the
740/// standard [`DEFAULT_LIBRARY_SEARCH_DIRS`] as the soname fallback search set.
741///
742/// Every step is shrink-not-fail (a binary that can't be read/parsed, or a soname that doesn't
743/// resolve, contributes nothing further); the returned set is deduplicated and canonical. Runs in
744/// the parent at launch time — never in the forked child's `pre_exec`.
745pub(crate) fn resolve_landlock_grants(exec_allow_paths: &[PathBuf]) -> Vec<PathBuf> {
746    let search_dirs: Vec<PathBuf> = DEFAULT_LIBRARY_SEARCH_DIRS
747        .iter()
748        .map(PathBuf::from)
749        .collect();
750    resolve_landlock_grants_in(exec_allow_paths, &search_dirs)
751}
752
753/// Testable core of [`resolve_landlock_grants`], with the library search directories injected so
754/// unit tests can point it at synthetic fixtures instead of the real system directories.
755fn resolve_landlock_grants_in(
756    exec_allow_paths: &[PathBuf],
757    search_dirs: &[PathBuf],
758) -> Vec<PathBuf> {
759    let mut grants: std::collections::BTreeSet<PathBuf> = std::collections::BTreeSet::new();
760    let mut visited: std::collections::BTreeSet<PathBuf> = std::collections::BTreeSet::new();
761    let mut queue: std::collections::VecDeque<PathBuf> = std::collections::VecDeque::new();
762
763    for path in exec_allow_paths {
764        // The allowlist paths are already canonical/existing (from `resolve_exec_allowlist`), but
765        // canonicalize defensively — this both makes dedup against interp/library paths exact and
766        // drops any seed that no longer exists (shrink-not-fail: a vanished binary contributes
767        // nothing, and could not be exec'd anyway).
768        if let Ok(canonical) = std::fs::canonicalize(path) {
769            queue.push_back(canonical);
770        }
771    }
772
773    while let Some(path) = queue.pop_front() {
774        if !visited.insert(path.clone()) {
775            continue;
776        }
777        // The binary/library itself is granted. If it lives inside the workdir, the workdir's own
778        // full-access rule already covers it and this extra read+execute rule is simply redundant.
779        grants.insert(path.clone());
780
781        let Ok(bytes) = std::fs::read(&path) else {
782            continue;
783        };
784        let Some(deps) = parse_elf_dependencies(&bytes) else {
785            continue;
786        };
787        let origin_dir = path.parent().unwrap_or_else(|| Path::new("/"));
788
789        if let Some(interp) = &deps.interp {
790            if let Ok(canonical) = std::fs::canonicalize(interp) {
791                queue.push_back(canonical);
792            }
793        }
794        for soname in &deps.needed {
795            if let Some(resolved) = resolve_soname(soname, origin_dir, &deps.runpaths, search_dirs)
796            {
797                queue.push_back(resolved);
798            }
799        }
800    }
801
802    grants.into_iter().collect()
803}
804
805/// One resolved Landlock filesystem grant outside the workdir: a canonical path plus the two
806/// independent bits that decide the rule's access set.
807///
808/// `list_dir` decides enumerability (`ReadDir`):
809///
810///   - `false` → no `getdents64` on the granted directory itself. Landlock's read rights apply to
811///     the whole subtree beneath a granted directory, so a file *inside* it can still be opened by
812///     its exact name — the listing is what is denied. This is what every derived
813///     `DT_NEEDED`-closure grant gets — they are individual files, where `ReadDir` was always a
814///     no-op anyway (Landlock's `ReadDir` only has meaning on a directory inode).
815///   - `true` → adds enumerability, which a path-based interpreter's import machinery needs on
816///     each `sys.path` entry (CPython's `FileFinder` `listdir`-caches each one). Set by an author
817///     writing `list_dir: true` next to a specific `interpreter_runtime` directory, and by the
818///     whole-tree resolvers ([`resolve_staged_runtime_landlock_grants`],
819///     [`resolve_sealed_runtime_landlock_grants`] and, per entry, the directory half of
820///     [`resolve_sealed_etc_landlock_grants`]) where a tree is walked by definition — never
821///     inferred from anything else, and never applied to an ancestor or sibling of a granted
822///     directory.
823///
824/// `ReadDir` is meaningful only on a directory, and the kernel enforces that: `landlock_add_rule`
825/// returns `EINVAL` for a directory-only right on a non-directory. `open_landlock_fds` therefore
826/// narrows `list_dir` to `false` for any grant whose fd does not `fstat` as a directory, so this
827/// field is a request rather than a promise.
828///
829/// `executable` decides `Execute`, which is this runtime's exec allowlist: a path without an
830/// `Execute` rule cannot be `execve`d, and a path with one can. This is the canonical statement of
831/// that rule; the grant resolvers below cross-reference it rather than restating it.
832///
833///   - `true` → `Execute + ReadFile`, for a path the manifest asked to *run*: a `shell.allow`
834///     binary, its `DT_NEEDED` closure, and the interpreter/staged trees an author named.
835///   - `false` → `ReadFile` only (readable, and with `list_dir` enumerable, but not runnable).
836///     For a grant the *tier* issues rather than the manifest: see
837///     [`resolve_sealed_runtime_landlock_grants`], where granting `Execute` over `/usr`, `/bin`
838///     and `/sbin` wholesale would turn `shell.allow` into a no-op on `sealed`, and
839///     [`resolve_sealed_etc_landlock_grants`], where `/etc/alternatives` is a directory of
840///     symlinks into exactly those trees.
841///
842/// Affects `execve` only: a shared object mapped `PROT_EXEC` by `dlopen(3)` needs `ReadFile`, not
843/// `Execute`, so an interpreter still loads its C extensions out of an `executable: false` tree.
844#[derive(Debug, Clone, PartialEq, Eq)]
845pub(crate) struct LandlockGrant {
846    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
847    pub(crate) path: PathBuf,
848    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
849    pub(crate) list_dir: bool,
850    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
851    pub(crate) executable: bool,
852}
853
854impl LandlockGrant {
855    /// Wraps each derived `DT_NEEDED`-closure file path as a non-listable grant. A regular file
856    /// has no meaningful `ReadDir`, so `list_dir: false` costs nothing. `executable: true`: this
857    /// closure is exactly the set of paths `shell.allow` asked to run — see [`LandlockGrant`].
858    fn non_listable_files(paths: Vec<PathBuf>) -> Vec<LandlockGrant> {
859        paths
860            .into_iter()
861            .map(|path| LandlockGrant {
862                path,
863                list_dir: false,
864                executable: true,
865            })
866            .collect()
867    }
868}
869
870/// Turns each `capabilities.shell.interpreter_runtime` directory into a [`LandlockGrant`] carrying
871/// exactly the `list_dir` its author wrote. Pure and syscall-free (the declared paths need not
872/// exist here — `apply_landlock_scope` skips any that fail to open), so it is unit-testable on
873/// every platform, including non-Linux targets.
874///
875/// There is deliberately no path here that could widen a grant to a whole install prefix: it emits
876/// one grant per explicitly declared directory and copies the author's `list_dir` verbatim,
877/// inferring enumerability from nothing.
878pub(crate) fn resolve_interpreter_runtime_grants(
879    grants: &[InterpreterRuntimeGrant],
880) -> Vec<LandlockGrant> {
881    grants
882        .iter()
883        .flat_map(|grant| {
884            grant.dirs.iter().map(|dir| LandlockGrant {
885                path: PathBuf::from(&dir.path),
886                list_dir: dir.list_dir,
887                // Executable: an `interpreter_runtime` directory is named by an author precisely so
888                // the interpreter it belongs to can run out of it, helper binaries included.
889                executable: true,
890            })
891        })
892        .collect()
893}
894
895/// The host directories a composed root must carry *beyond* [`crate::sealed::SEALED_RUNTIME_PATHS`]
896/// for this capsule's `shell.allow` to keep working: the containing directory of each resolved
897/// allowlisted binary, and each declared `interpreter_runtime` directory.
898///
899/// Whole directories, deduplicated, and only the ones not already inside a fixed runtime path.
900/// This is the deliberate opposite of `resolve_landlock_grants`: no ELF parsing, no `DT_NEEDED`
901/// closure, no per-file grant — a bind mount carries a directory's whole contents, so the closure
902/// derivation `scoped` needs has nothing left to do here.
903///
904/// Every entry is **optional** by design — see `sealed::PlanBuilder::mirror`. A host missing one
905/// makes the composed root narrower rather than refusing the launch, which is why
906/// `capabilities.shell.staged_runtime` does *not* come through here: a declared runtime tree must
907/// fail closed, so it is resolved separately by [`resolve_staged_runtime_dirs`] and planned as a
908/// required bind. This function is additive to that, not replaced by it.
909///
910/// Pure and syscall-free, so it is unit-testable on any platform.
911pub(crate) fn resolve_sealed_bind_dirs(
912    exec_allow_paths: &[PathBuf],
913    policy: &CapabilityPolicy,
914) -> Vec<PathBuf> {
915    let fixed: Vec<&Path> = crate::sealed::SEALED_RUNTIME_PATHS
916        .iter()
917        .map(Path::new)
918        .collect();
919
920    let mut dirs: Vec<PathBuf> = Vec::new();
921    let candidates = exec_allow_paths
922        .iter()
923        .filter_map(|binary| binary.parent().map(Path::to_path_buf))
924        .chain(
925            policy
926                .shell_interpreter_runtime
927                .iter()
928                .flat_map(|grant| grant.dirs.iter().map(|dir| PathBuf::from(&dir.path))),
929        );
930
931    for candidate in candidates {
932        if !candidate.is_absolute() {
933            continue;
934        }
935        if fixed.iter().any(|root| candidate.starts_with(root)) {
936            continue;
937        }
938        if dirs.contains(&candidate) {
939            continue;
940        }
941        dirs.push(candidate);
942    }
943    dirs
944}
945
946/// The `source_path` of each declared `capabilities.shell.staged_runtime` grant, as the composed
947/// root's *required* read-only binds.
948///
949/// Deliberately not folded into [`resolve_sealed_bind_dirs`], and deliberately not filtered the
950/// way that function filters. Both differences follow from the same fact — these fail closed:
951///
952///   * A path already inside [`crate::sealed::SEALED_RUNTIME_PATHS`] is **not** dropped here.
953///     Dropping it would be sound for an optional bind (the fixed list already covers it) but it
954///     would quietly convert a required grant into a dependency on an unrelated list staying the
955///     way it is today. `plan_composed_root` runs the required loop first and deduplicates by
956///     target, so naming an already-covered path costs one registration and stays required.
957///   * A non-existent path is **not** filtered out, here or anywhere. The whole point is that a
958///     grant naming a tree this host does not have refuses the launch — see
959///     `sealed::PlanBuilder::require_bind`.
960///
961/// Relative paths are still skipped: a relative `source_path` cannot be re-based under the
962/// composed root's base at all, so it names nothing to fail *about*. The manifest parser is the
963/// layer that rejects one.
964///
965/// Pure and syscall-free, so it is unit-testable on any platform.
966pub(crate) fn resolve_staged_runtime_dirs(policy: &CapabilityPolicy) -> Vec<PathBuf> {
967    let mut dirs: Vec<PathBuf> = Vec::new();
968    for grant in &policy.shell_staged_runtime {
969        let path = PathBuf::from(&grant.source_path);
970        if !path.is_absolute() || dirs.contains(&path) {
971            continue;
972        }
973        dirs.push(path);
974    }
975    dirs
976}
977
978/// One listable [`LandlockGrant`] per staged runtime directory.
979///
980/// The bind mount alone does not make a staged tree usable, and the reason is easy to miss: the
981/// composed root is not the only thing standing between the subprocess and a path. `sealed` still
982/// installs Landlock *inside* the root as defence in depth (see `applied_tier` and the
983/// `KernelSealed` arm of `prepare_enforcement`), and Landlock denies any path with no matching
984/// rule. A staged tree that is bind-mounted but ungranted is therefore present, read-only, and
985/// unreadable — `open()` returns `EACCES` — which is indistinguishable from the capability not
986/// working at all.
987///
988/// So a grant is emitted here for exactly the same directories [`resolve_staged_runtime_dirs`]
989/// binds, and the two are resolved from the same list so they cannot drift apart. `list_dir: true`
990/// is not configurable, unlike `interpreter_runtime`'s per-directory flag: a staged tree is a whole
991/// runtime a program walks (an interpreter enumerating its stdlib, a toolchain resolving its
992/// libexec), and the author already made the enumerability decision by naming the tree. Landlock
993/// rules attach to the opened inode, so a rule taken on the host path in the parent covers the
994/// same inode reached through the bind inside the root.
995///
996/// Read and execute only — never write. The bind is `MS_RDONLY` regardless, so this is the second
997/// of two independent reasons the tree cannot be mutated from inside a session.
998///
999/// Pure and syscall-free, so it is unit-testable on any platform.
1000pub(crate) fn resolve_staged_runtime_landlock_grants(
1001    policy: &CapabilityPolicy,
1002) -> Vec<LandlockGrant> {
1003    resolve_staged_runtime_dirs(policy)
1004        .into_iter()
1005        .map(|path| LandlockGrant {
1006            path,
1007            list_dir: true,
1008            executable: true,
1009        })
1010        .collect()
1011}
1012
1013/// One listable [`LandlockGrant`] per [`crate::sealed::SEALED_RUNTIME_PATHS`] entry, and only on
1014/// `KernelSealed`.
1015///
1016/// `plan_composed_root` bind-mounts `/usr`, `/bin`, `/sbin`, `/lib`… read-only into every composed
1017/// root, but the Landlock ruleset installed inside that root denies any path with no matching rule.
1018/// The `shell.allow` ELF closure grants those files one at a time and non-listably, so a binary
1019/// opens by exact name while the directory holding it cannot be enumerated — enough to start an
1020/// interpreter, not enough to run it: CPython dies in `init_fs_encoding` because it cannot
1021/// `getdents64` `/usr/lib/python3.N` to find `encodings`. This grant makes the bound tree
1022/// enumerable.
1023///
1024/// `list_dir: true` is not configurable: a whole runtime tree a program walks is not a
1025/// case-by-case author choice. Writes are moot — the binds are `MS_RDONLY`.
1026///
1027/// `executable: false` (see [`LandlockGrant`]): this is the only grant covering whole host trees
1028/// the manifest never named, so it must enumerate them without becoming permission to run them.
1029///
1030/// Sealed-tier only: on `KernelFull` (where `scoped` runs) Landlock applies over the real host
1031/// filesystem, so `ReadDir` on `/usr` would expose host directory shape; under `KernelSealed` the
1032/// tree is a private read-only bind holding only what was staged, so enumerating it reveals
1033/// nothing. Empty on every other tier.
1034///
1035/// Pure and syscall-free (paths need not exist here — `apply_landlock_scope` skips any that fail
1036/// to open), so unit-testable on every platform.
1037pub(crate) fn resolve_sealed_runtime_landlock_grants(tier: EnforcementTier) -> Vec<LandlockGrant> {
1038    if tier != EnforcementTier::KernelSealed {
1039        return Vec::new();
1040    }
1041    crate::sealed::SEALED_RUNTIME_PATHS
1042        .iter()
1043        .map(|path| LandlockGrant {
1044            path: PathBuf::from(path),
1045            list_dir: true,
1046            executable: false,
1047        })
1048        .collect()
1049}
1050
1051/// One read [`LandlockGrant`] per [`crate::sealed::SEALED_ETC_PATHS`] entry, and only on
1052/// `KernelSealed`.
1053///
1054/// Exactly the same shape of bug as [`resolve_sealed_runtime_landlock_grants`], one directory over:
1055/// `plan_composed_root` bind-mounts the fixed `/etc` allowlist read-only into every composed root,
1056/// and the Landlock ruleset installed inside that root then denies every one of them, because a
1057/// path with no matching rule is denied. The mount is present and unopenable — the worst of both
1058/// answers. Most visibly this is the TLS trust store: `load_verify_locations` on
1059/// `/etc/ssl/certs/ca-certificates.crt` returns `EACCES`, so `pip`, `curl`, `wget` and `git` all
1060/// fail certificate verification over an otherwise-working TCP connection.
1061///
1062/// `list_dir` is per entry, taken from the `directory` bit each [`crate::sealed::SEALED_EtcPath`]
1063/// carries (see [`crate::sealed::SealedEtcPath`]) — unlike the runtime-path list, this one mixes
1064/// directories, regular files and symlinks.
1065/// Directories get `ReadDir` because enumeration is how the trust store is actually consumed
1066/// (`c_rehash` symlink lookup, `os.listdir('/etc/ssl/certs')`, `SSL_CERT_DIR`); files and symlinks
1067/// get `ReadFile` only, the same convention as [`LandlockGrant::non_listable_files`].
1068///
1069/// `executable: false` throughout (see [`LandlockGrant`] for what `Execute` decides). Nothing in
1070/// `/etc` is a program a manifest asked to run, and `/etc/alternatives` in particular is a
1071/// directory of symlinks *into* `/usr/bin`, so granting `Execute` here would be a second,
1072/// undeclared route to the exec bypass `resolve_sealed_runtime_landlock_grants` withholds it to
1073/// prevent.
1074///
1075/// No write right, ever: the binds are `MS_RDONLY`, and `/etc/resolv.conf` or `/etc/hosts` becoming
1076/// writable inside a capsule would be a name-resolution hijack of the capsule's own egress.
1077///
1078/// Sealed-tier only, for the same reason as the runtime-path grant: on `KernelFull` — the tier a
1079/// `scoped` capsule runs on — Landlock applies over the real host `/etc`, where these rules would
1080/// hand out the host's own trust store, `resolv.conf` and account databases. Under `KernelSealed`
1081/// the paths resolve inside a private read-only bind of an allowlist that was curated precisely so
1082/// reading it reveals nothing sensitive. Empty on every other tier.
1083///
1084/// Pure and syscall-free (paths need not exist here — `apply_landlock_scope` skips any that fail to
1085/// open), so unit-testable on every platform.
1086pub(crate) fn resolve_sealed_etc_landlock_grants(tier: EnforcementTier) -> Vec<LandlockGrant> {
1087    if tier != EnforcementTier::KernelSealed {
1088        return Vec::new();
1089    }
1090    crate::sealed::SEALED_ETC_PATHS
1091        .iter()
1092        .map(|entry| LandlockGrant {
1093            path: PathBuf::from(entry.path),
1094            list_dir: entry.directory,
1095            executable: false,
1096        })
1097        .collect()
1098}
1099
1100// ---- fixed capsule device set ------------------------------------------------------------
1101//
1102// Everything above derives its grants from the manifest: `shell.allow` binaries and their
1103// `DT_NEEDED` closure, `interpreter_runtime` directories. The device set below derives from
1104// nothing. It is a fixed property of the sandbox, like `linux_enforce::WORKDIR_ACCESS_RIGHTS`,
1105// present on every capsule that reaches `KernelFull` — there is no manifest key that adds a
1106// device, and none that takes one away.
1107//
1108// Why it has to exist at all: once `restrict_self()` lands, a path outside the workdir with no
1109// matching rule is denied, and `/dev/null` is outside every workdir. Programs treat `/dev/null`
1110// as infallible — `open("/dev/null")` failing is a case almost nothing handles — so without an
1111// explicit rule an ordinary tool dies in a way that reads as a runtime bug, not a policy denial.
1112
1113/// One fixed device path granted to every `KernelFull` capsule, with the access level it gets.
1114///
1115/// Deliberately *not* a [`LandlockGrant`]: that type means "an executable or library path the
1116/// manifest asked for, granted read(+list)+execute, never write". A device is a different intent
1117/// (I/O access to a character device, possibly writable) and a different lifetime (fixed at
1118/// compile time, not resolved per capsule), so it gets its own type rather than overloading
1119/// `list_dir` into a third meaning.
1120///
1121/// `writable` is the whole reason this type exists as more than a path list:
1122///
1123///   - `false` → `ReadFile` only. The device is readable and nothing more.
1124///   - `true` → `ReadFile | WriteFile`. Granted to exactly one path, `/dev/null`, and it is the
1125///     only writable path outside the workdir in the entire sandbox.
1126///
1127/// Only `mod linux_enforce` consumes this outside of tests, so on a non-Linux build the type and
1128/// the constant below are dead — the same deliberate cross-platform exception the rest of this
1129/// module's Linux-only surface carries.
1130#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1132pub(crate) struct CapsuleDeviceGrant {
1133    pub(crate) path: &'static str,
1134    pub(crate) writable: bool,
1135}
1136
1137/// The complete device set a capsule's shell subprocess tree can reach outside its workdir.
1138/// Three entries, no more — `apply_landlock_scope` adds one `PathBeneath` rule per entry, and
1139/// every device path *not* listed here (`/dev/random`, `/dev/full`, `/dev/tty`, `/dev/sda`, …)
1140/// stays denied by the same mechanism that already denies every other unlisted path: with
1141/// `handle_access` declaring the full ABI v1 right-set, "no rule" means "denied", not "ungoverned".
1142///
1143///   - **`/dev/null` — read *and* write.** This is the one deliberate exception to "nothing
1144///     outside the workdir is writable". A read-only grant would be broken, not merely strict:
1145///     bare-host `strace` shows Python's `subprocess.DEVNULL` opening it `O_RDWR|O_CLOEXEC`, and a
1146///     shell `2>/dev/null` redirect opening it `O_WRONLY|O_CREAT`. Both fail without `WriteFile`,
1147///     and `subprocess.DEVNULL` is reachable from any Python tool a capsule might run. Granting
1148///     write on a character device whose write side is defined to discard everything gives up no
1149///     confidentiality and no integrity — there is no state behind it to reach.
1150///     (The `O_CREAT` in the redirect costs nothing extra: Landlock only checks `MakeReg` when a
1151///     file is actually created, and `/dev/null` already exists.)
1152///   - **`/dev/zero` — read only.** Zero-fill reads and `MAP_PRIVATE` anonymous-mapping fallbacks
1153///     in older allocators. Writes to it are discarded like `/dev/null`'s, but nothing needs to
1154///     write there, so it does not get `WriteFile`.
1155///   - **`/dev/urandom` — read only.** Not for `getrandom(2)`, which is a syscall needing no
1156///     filesystem grant at all, but because OpenSSL and older glibc paths still `open()` the
1157///     device outright and fall over if they cannot.
1158///
1159/// **Why `/dev/random` is excluded.** Not because writing to it is dangerous: a plain `write()` to
1160/// `/dev/random` mixes bytes into the pool but credits **zero** entropy — crediting requires the
1161/// `RNDADDENTROPY` ioctl, which requires `CAP_SYS_ADMIN`, which the shell child has already
1162/// dropped. It is excluded for a duller reason: since Linux 5.6 `/dev/random` blocks until the CRNG
1163/// is initialized and `/dev/urandom` does not, and no workload needs the blocking variant when the
1164/// non-blocking one is granted. It stays out because nothing has demonstrated a need for it.
1165///
1166/// Widening this list is allowed but must be evidence-driven: add a fourth entry only after a real
1167/// workload has been observed failing on the missing device, and record that failure in the same
1168/// place this list is documented (`docs/content/reference/capsule-device-set-manual-verification.md`).
1169///
1170/// **Future shape.** Enumerating devices path by path is the `scoped`-containment-class answer.
1171/// Once a `sealed` class exists, the capsule gets a private `/dev` tmpfs carrying the OCI default
1172/// device set, and device access stops being a Landlock rule list entirely. A `sealed`
1173/// implementation should *retire* this constant, not merge with it.
1174#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1175pub(crate) const CAPSULE_DEVICE_GRANTS: &[CapsuleDeviceGrant] = &[
1176    CapsuleDeviceGrant {
1177        path: "/dev/null",
1178        writable: true,
1179    },
1180    CapsuleDeviceGrant {
1181        path: "/dev/zero",
1182        writable: false,
1183    },
1184    CapsuleDeviceGrant {
1185        path: "/dev/urandom",
1186        writable: false,
1187    },
1188];
1189
1190/// Network decision for one destination IP.
1191/// Empty allowlist denies everything (a capsule that declared no `network.allow` hosts has
1192/// no reason to open any subprocess socket).
1193#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1194pub(crate) fn network_ip_allowed(ip: IpAddr, network_allow_ips: &[IpAddr]) -> bool {
1195    network_allow_ips.contains(&ip)
1196}
1197
1198// `socket(2)`'s `domain` argument values, as Linux's ABI defines them. Spelled out as literals
1199// rather than `libc::AF_*`: the filter these feed is
1200// always compiled *for a Linux child*, so the numbers must be Linux's regardless of what host the
1201// build runs on — and `denied_socket_domains` has to stay compilable and unit-testable on a macOS
1202// non-Linux targets, where `libc::AF_NETLINK` and `libc::AF_PACKET` do not exist at all (the `libc`
1203// crate defines them only under `linux_like`). `libc::AF_UNIX` does exist on macOS, but taking one
1204// of the three from `libc` and two from literals would be worse than taking all three the same
1205// way. Values are stable kernel ABI: `include/linux/socket.h`.
1206const LINUX_AF_UNIX: i32 = 1;
1207const LINUX_AF_INET: i32 = 2;
1208const LINUX_AF_INET6: i32 = 10;
1209const LINUX_AF_NETLINK: i32 = 16;
1210const LINUX_AF_PACKET: i32 = 17;
1211
1212/// The `socket(2)` domains the child's seccomp filter refuses outright, given the capsule's
1213/// `capabilities.network.unix_sockets` declaration.
1214///
1215/// This is the *whole* policy decision behind the `socket()` rule in `install_seccomp_filter` —
1216/// deliberately pure, `libseccomp`-free, and platform-independent so it can be tested on any dev
1217/// machine (same split as `resolve_landlock_grants` vs. `apply_landlock_scope`).
1218///
1219/// Why a domain check is a classic BPF rule and not a notify:
1220/// `socket()`'s `domain` is a plain integer in a register, so the kernel's own BPF can compare it
1221/// directly. That is exactly what `connect()`'s destination address is *not* — it sits behind a
1222/// pointer BPF cannot dereference, so deciding on it needs a userspace round-trip that reads the
1223/// calling task's memory (see this module's header). Denying the domain at *creation* time needs
1224/// no round-trip, and is structurally immune to the TOCTOU class of problem that reading a
1225/// pointed-to argument out of another task's memory invites.
1226///
1227/// The three families, and why they are not symmetric:
1228///   - `AF_UNIX` is gated, not banned. `/var/run/docker.sock` is host root, so it cannot be open
1229///     by default — but "talk to a local daemon socket" is a legitimate thing for an agent to
1230///     need, so a capsule can declare `capabilities.network.unix_sockets: true` and take it back.
1231///     Note this is coarse: the opt-in is per *capsule*, per *domain* — not per socket path.
1232///   - `AF_NETLINK` (routing tables, interface and firewall state) and `AF_PACKET` (raw frame
1233///     capture and injection) are denied unconditionally, with no manifest key to widen them.
1234///     Neither has a shell-tool use case comparable to a local daemon socket, and both are
1235///     strictly more dangerous than one. Widening them would be a deliberate future decision with
1236///     its own justification, not an oversight to be fixed by adding a flag here.
1237///
1238/// `AF_INET`/`AF_INET6` are never denied here: they stay governed by the capsule's own network
1239/// namespace and egress proxy against `capabilities.network.allow`. This function only ever
1240/// *adds* denials, and is paired with [`allowed_socket_domains`], which names the families that
1241/// get a positive rule — since the filter's default action is a deny, a family named by neither
1242/// function is refused with the filter default (`EPERM`) rather than this rule's `EACCES`.
1243#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1244pub(crate) fn denied_socket_domains(unix_sockets_allowed: bool) -> Vec<i32> {
1245    let mut denied = vec![LINUX_AF_NETLINK, LINUX_AF_PACKET];
1246    if !unix_sockets_allowed {
1247        denied.push(LINUX_AF_UNIX);
1248    }
1249    denied
1250}
1251
1252/// The `socket(2)` domains the child's seccomp filter permits, given the capsule's
1253/// `capabilities.network.unix_sockets` declaration. The exact complement of
1254/// [`denied_socket_domains`] over the families anything in a shell toolchain actually opens.
1255///
1256/// This exists because the filter's default action is `Errno(EPERM)`, not `Allow`: `socket` needs
1257/// a positive rule or no socket of any family could be created at all. It is deliberately *not*
1258/// expressed as one unconditional `Allow` rule on `socket` — see `install_seccomp_filter` for why
1259/// that would silently delete the [`denied_socket_domains`] rules — and deliberately not as a
1260/// "not any of the denied families" rule either, so the two functions stay a pair of disjoint,
1261/// equality-matched sets that a test can check against each other.
1262///
1263/// The cost of naming families positively is that a family in neither set (`AF_ALG`, `AF_VSOCK`,
1264/// `AF_BLUETOOTH`, `AF_XDP`, ...) is now refused rather than allowed. That is stricter than
1265/// Docker's default profile, which allows every family except `AF_ALG`/`AF_VSOCK`; no shell,
1266/// coreutils, git, compiler or interpreter workload opens one, and the whole point of a
1267/// default-deny filter is that an unenumerated case fails closed. Add a family here (with a
1268/// reason) if a real workload needs it.
1269#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1270pub(crate) fn allowed_socket_domains(unix_sockets_allowed: bool) -> Vec<i32> {
1271    let mut allowed = vec![LINUX_AF_INET_DOMAIN, LINUX_AF_INET6_DOMAIN];
1272    if unix_sockets_allowed {
1273        allowed.push(LINUX_AF_UNIX);
1274    }
1275    allowed
1276}
1277
1278/// `socket(2)` `domain` values for the two IP families, named apart from the bare `LINUX_AF_*`
1279/// numbers above so a rule's argument type reads as a domain rather than as a loose integer.
1280///
1281/// Literals from the same `include/linux/socket.h` list as their neighbours above, for the same
1282/// reason: the filter is always compiled for a Linux child.
1283#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1284const LINUX_AF_INET_DOMAIN: i32 = LINUX_AF_INET;
1285#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1286const LINUX_AF_INET6_DOMAIN: i32 = LINUX_AF_INET6;
1287
1288/// The syscalls the child's seccomp filter permits outright, modelled on the OCI/Docker default
1289/// seccomp profile (reconciled against `containerd`'s `contrib/seccomp/seccomp_default.go`, which
1290/// is the maintained source of the same list Docker ships).
1291///
1292/// The filter's **default action is a deny** (`Errno(EPERM)`), so this array is the whole of what
1293/// a shell subprocess may call, minus two carve-outs handled by rules rather than by name here:
1294///
1295///   - `socket` is absent: it carries argument-conditional rules (see [`denied_socket_domains`] /
1296///     [`allowed_socket_domains`]), and an unconditional `Allow` rule would discard them.
1297///
1298/// `execve`/`execveat` are ordinary allowed syscalls here: they permit only *reaching the kernel*,
1299/// where the Landlock domain decides the exec on the path it resolved itself (see this module's
1300/// header for why they no longer carry `Notify` rules). Permitting them is not optional — the
1301/// child's very first act after this filter loads is the `execve` that turns it into the tool
1302/// binary, so a denial here refuses every capsule outright.
1303///
1304/// Everything else is refused by the default action. Without this list `io_uring_setup`, `bpf`,
1305/// `userfaultfd`, `perf_event_open`, `open_by_handle_at`, `keyctl` and `ptrace` are all reachable
1306/// from a capsule shell on bare metal, while the same probe under Docker gets `EPERM` for each.
1307/// `io_uring` is the one that
1308/// matters most: it has historically bypassed LSM path hooks, so leaving it reachable undermines
1309/// the Landlock filesystem boundary rather than merely widening the syscall surface. See
1310/// [`SECCOMP_MUST_STAY_DENIED`] for the full set that must never be added back.
1311///
1312/// Names, not numbers: `libseccomp` resolves each one for the architecture the filter is being
1313/// built on. A name this host's `libseccomp` does not know (a syscall newer than the library) or
1314/// that does not exist on this architecture (`open`, `dup2`, `poll`, ... on aarch64) is skipped,
1315/// leaving that syscall denied by default — see `install_seccomp_filter`. That is why legacy
1316/// x86_64-only spellings sit next to their modern equivalents here: on x86_64 glibc uses `open`
1317/// and `stat`, on aarch64 it uses `openat` and `newfstatat`, and the same array serves both.
1318#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1319pub(crate) const SECCOMP_SYSCALL_ALLOWLIST: &[&str] = &[
1320    // ---- process / thread lifecycle ----
1321    // `execve`/`execveat` reach the kernel; the Landlock domain decides them. See this array's
1322    // doc comment for the mechanism that replaced their former `Notify` rules.
1323    "execve",
1324    "execveat",
1325    // `clone`/`clone3` are allowed *unconditionally*, which is this filter's one significant
1326    // widening relative to Docker: Docker masks `clone`'s namespace-creation flags with an
1327    // argument comparison and forces `clone3` to `ENOSYS` so glibc falls back to the masked
1328    // `clone`. Reproducing that faithfully is possible for `clone` but pointless in isolation:
1329    // `unshare`/`setns`/`mount`/`pivot_root`/`chroot` all stay denied, so a new namespace stays
1330    // largely inert.
1331    "clone",
1332    "clone3",
1333    "fork",
1334    "vfork",
1335    "exit",
1336    "exit_group",
1337    "wait4",
1338    "waitid",
1339    "kill",
1340    "tkill",
1341    "tgkill",
1342    "rt_sigaction",
1343    "rt_sigprocmask",
1344    "rt_sigreturn",
1345    "rt_sigsuspend",
1346    "rt_sigpending",
1347    "rt_sigtimedwait",
1348    "rt_sigqueueinfo",
1349    "rt_tgsigqueueinfo",
1350    "sigaltstack",
1351    // The kernel re-issues an interrupted, restartable syscall as `restart_syscall`; denying it
1352    // would break every `sleep`/`read` that takes a signal.
1353    "restart_syscall",
1354    "pause",
1355    "set_tid_address",
1356    "set_robust_list",
1357    "get_robust_list",
1358    // glibc 2.35+ registers a restartable sequence on every thread start.
1359    "rseq",
1360    "prctl",
1361    "arch_prctl",
1362    "getpid",
1363    "getppid",
1364    "gettid",
1365    "getpgrp",
1366    "getpgid",
1367    "setpgid",
1368    "getsid",
1369    "setsid",
1370    "getpriority",
1371    "setpriority",
1372    "ioprio_get",
1373    "ioprio_set",
1374    "sched_yield",
1375    "sched_getaffinity",
1376    "sched_setaffinity",
1377    "sched_getparam",
1378    "sched_setparam",
1379    "sched_getscheduler",
1380    "sched_setscheduler",
1381    "sched_getattr",
1382    "sched_setattr",
1383    "sched_get_priority_max",
1384    "sched_get_priority_min",
1385    "sched_rr_get_interval",
1386    "getcpu",
1387    "capget",
1388    "capset",
1389    "prlimit64",
1390    "getrlimit",
1391    "setrlimit",
1392    "getrusage",
1393    "getitimer",
1394    "setitimer",
1395    "times",
1396    "uname",
1397    "sysinfo",
1398    // pidfd process handles: they only ever address a process the caller could already signal.
1399    "pidfd_open",
1400    "pidfd_send_signal",
1401    // ---- memory ----
1402    "mmap",
1403    "munmap",
1404    "mprotect",
1405    "mremap",
1406    "madvise",
1407    "brk",
1408    "mlock",
1409    "mlock2",
1410    "munlock",
1411    "mlockall",
1412    "munlockall",
1413    "membarrier",
1414    "msync",
1415    "mincore",
1416    "memfd_create",
1417    "pkey_alloc",
1418    "pkey_free",
1419    "pkey_mprotect",
1420    "shmget",
1421    "shmat",
1422    "shmdt",
1423    "shmctl",
1424    // ---- file I/O ----
1425    "open",
1426    "openat",
1427    "openat2",
1428    "creat",
1429    "close",
1430    "close_range",
1431    "read",
1432    "write",
1433    "pread64",
1434    "pwrite64",
1435    "readv",
1436    "writev",
1437    "preadv",
1438    "pwritev",
1439    "preadv2",
1440    "pwritev2",
1441    "lseek",
1442    "dup",
1443    "dup2",
1444    "dup3",
1445    "fcntl",
1446    "flock",
1447    "fsync",
1448    "fdatasync",
1449    "sync",
1450    "syncfs",
1451    "sync_file_range",
1452    "fadvise64",
1453    "readahead",
1454    "truncate",
1455    "ftruncate",
1456    "fallocate",
1457    "stat",
1458    "fstat",
1459    "lstat",
1460    "newfstatat",
1461    "statx",
1462    "access",
1463    "faccessat",
1464    "faccessat2",
1465    "getdents",
1466    "getdents64",
1467    "getcwd",
1468    "chdir",
1469    "fchdir",
1470    "mkdir",
1471    "mkdirat",
1472    "rmdir",
1473    "unlink",
1474    "unlinkat",
1475    "rename",
1476    "renameat",
1477    "renameat2",
1478    "link",
1479    "linkat",
1480    "symlink",
1481    "symlinkat",
1482    "readlink",
1483    "readlinkat",
1484    "chmod",
1485    "fchmod",
1486    "fchmodat",
1487    // glibc 2.39+ reaches for `fchmodat2` first; it has no `EPERM` fallback path, only an
1488    // `ENOSYS` one, so denying it would surface as a hard `chmod` failure.
1489    "fchmodat2",
1490    "chown",
1491    "fchown",
1492    "fchownat",
1493    "lchown",
1494    "umask",
1495    "utime",
1496    "utimes",
1497    "utimensat",
1498    "futimesat",
1499    // `mknod`/`mknodat` are allowed at the syscall layer and denied where the actual escape
1500    // lives: the Landlock workdir grant withholds `MakeChar`/`MakeBlock`/`MakeSock` (see
1501    // `linux_enforce::WORKDIR_ACCESS_RIGHTS`) and the child drops `CAP_MKNOD` before execve.
1502    "mknod",
1503    "mknodat",
1504    "sendfile",
1505    "copy_file_range",
1506    "splice",
1507    "tee",
1508    "vmsplice",
1509    "ioctl",
1510    "poll",
1511    "ppoll",
1512    "select",
1513    "pselect6",
1514    "epoll_create",
1515    "epoll_create1",
1516    "epoll_ctl",
1517    "epoll_wait",
1518    "epoll_pwait",
1519    "epoll_pwait2",
1520    "eventfd",
1521    "eventfd2",
1522    "pipe",
1523    "pipe2",
1524    "inotify_init",
1525    "inotify_init1",
1526    "inotify_add_watch",
1527    "inotify_rm_watch",
1528    "signalfd",
1529    "signalfd4",
1530    "timerfd_create",
1531    "timerfd_settime",
1532    "timerfd_gettime",
1533    "getxattr",
1534    "lgetxattr",
1535    "fgetxattr",
1536    "setxattr",
1537    "lsetxattr",
1538    "fsetxattr",
1539    "listxattr",
1540    "llistxattr",
1541    "flistxattr",
1542    "removexattr",
1543    "lremovexattr",
1544    "fremovexattr",
1545    "statfs",
1546    "fstatfs",
1547    // Harmless without its partner: `open_by_handle_at` (the syscall that turns a handle back
1548    // into an open file, ignoring the path it was reached by) stays denied.
1549    "name_to_handle_at",
1550    // Legacy POSIX AIO. Unlike `io_uring` it operates only on already-open fds and performs no
1551    // path resolution of its own, so it carries none of the LSM-bypass property that got the
1552    // `io_uring_*` family denied.
1553    "io_setup",
1554    "io_destroy",
1555    "io_submit",
1556    "io_cancel",
1557    "io_getevents",
1558    // ---- sockets ----
1559    // `socket` is NOT here (argument-conditional rules — see this array's doc comment).
1560    //
1561    // `connect`/`sendto` ARE here: allowing them permits only *reaching the kernel*, where the
1562    // capsule's own network namespace has no route to anything except the egress proxy. The
1563    // destination check lives there, not in this filter — see `crate::network_namespace`.
1564    "connect",
1565    "sendto",
1566    "socketpair",
1567    "bind",
1568    "listen",
1569    "accept",
1570    "accept4",
1571    "getsockname",
1572    "getpeername",
1573    "getsockopt",
1574    "setsockopt",
1575    "shutdown",
1576    "sendmsg",
1577    "sendmmsg",
1578    "recvfrom",
1579    "recvmsg",
1580    "recvmmsg",
1581    // ---- time ----
1582    "clock_gettime",
1583    "clock_getres",
1584    "clock_nanosleep",
1585    "nanosleep",
1586    "gettimeofday",
1587    "time",
1588    "timer_create",
1589    "timer_settime",
1590    "timer_gettime",
1591    "timer_getoverrun",
1592    "timer_delete",
1593    "alarm",
1594    // ---- System V / POSIX IPC ----
1595    "msgget",
1596    "msgsnd",
1597    "msgrcv",
1598    "msgctl",
1599    "semget",
1600    "semop",
1601    "semctl",
1602    "semtimedop",
1603    "mq_open",
1604    "mq_unlink",
1605    "mq_timedsend",
1606    "mq_timedreceive",
1607    "mq_notify",
1608    "mq_getsetattr",
1609    // ---- misc ----
1610    "getrandom",
1611    "futex",
1612    "futex_waitv",
1613    "getuid",
1614    "geteuid",
1615    "getgid",
1616    "getegid",
1617    "setuid",
1618    "setgid",
1619    "setreuid",
1620    "setregid",
1621    "setresuid",
1622    "setresgid",
1623    "getresuid",
1624    "getresgid",
1625    "getgroups",
1626    "setgroups",
1627    "setfsuid",
1628    "setfsgid",
1629];
1630
1631/// The syscalls that must **never** appear in [`SECCOMP_SYSCALL_ALLOWLIST`], with the reason each
1632/// one is out. A `#[test]` asserts the two lists stay disjoint, so re-permitting one of these can
1633/// only ever be a deliberate edit to *both* lists rather than an unnoticed line added to the
1634/// allowlist while reconciling it against a newer upstream profile.
1635///
1636/// Three groups, and they are not equally negotiable:
1637///
1638///   1. **Demonstrated reachable** — a probe reached these on bare metal while Docker refused
1639///      them: `io_uring_setup`/`io_uring_enter`/
1640///      `io_uring_register` (historically bypasses LSM path hooks, so it is a candidate route
1641///      around Landlock itself), `bpf`, `userfaultfd`, `perf_event_open`, `open_by_handle_at`,
1642///      `keyctl`/`add_key`/`request_key`, `process_vm_readv`/`process_vm_writev`, and `ptrace`
1643///      (which also has an availability dimension: a probe left wedged in `ptrace_stop` blocked
1644///      `mur` in `futex_wait` for twenty minutes). Docker's default profile actually *allows*
1645///      `ptrace`/`process_vm_readv`/`process_vm_writev` on kernels ≥ 4.8; this filter is
1646///      deliberately stricter there.
1647///   2. **Privileged / host-state operations** with no shell-toolchain use case: namespace and
1648///      mount manipulation, module loading, reboot, swap, accounting, quota, raw port I/O,
1649///      clock setting, NUMA policy, `fanotify`.
1650///   3. **Denied instead of argument-conditioned.** Docker allows these only for specific
1651///      argument values, which a per-syscall-name allowlist cannot express and which would
1652///      otherwise have to be routed through a userspace decision this filter no longer makes.
1653///      Omitting them outright costs nothing, because nothing in bash, coreutils, git, or a
1654///      standard compiler/interpreter toolchain needs them: `personality`, `kcmp`, `seccomp`
1655///      itself (a nested filter cannot loosen this one, but it can slow it down for no benefit).
1656// The list is a specification, not an input to the filter build: its one consumer is the
1657// regression test asserting no entry ever reappears in the allowlist. Deleting it would delete
1658// the thing that test checks against.
1659#[allow(dead_code)]
1660pub(crate) const SECCOMP_MUST_STAY_DENIED: &[&str] = &[
1661    // 1. demonstrated reachable on bare metal
1662    "io_uring_setup",
1663    "io_uring_enter",
1664    "io_uring_register",
1665    "bpf",
1666    "userfaultfd",
1667    "perf_event_open",
1668    "process_vm_readv",
1669    "process_vm_writev",
1670    "open_by_handle_at",
1671    "keyctl",
1672    "add_key",
1673    "request_key",
1674    "ptrace",
1675    // 2. privileged / host-state
1676    "mount",
1677    "umount2",
1678    "pivot_root",
1679    "chroot",
1680    "unshare",
1681    "setns",
1682    "init_module",
1683    "finit_module",
1684    "delete_module",
1685    "kexec_load",
1686    "kexec_file_load",
1687    "reboot",
1688    "swapon",
1689    "swapoff",
1690    "acct",
1691    "quotactl",
1692    "nfsservctl",
1693    "iopl",
1694    "ioperm",
1695    "vm86",
1696    "vm86old",
1697    "_sysctl",
1698    "sysfs",
1699    "uselib",
1700    "create_module",
1701    "get_kernel_syms",
1702    "query_module",
1703    "lookup_dcookie",
1704    "clock_adjtime",
1705    "clock_settime",
1706    "settimeofday",
1707    "stime",
1708    "adjtimex",
1709    "set_mempolicy",
1710    "get_mempolicy",
1711    "mbind",
1712    "migrate_pages",
1713    "move_pages",
1714    "fanotify_init",
1715    "fanotify_mark",
1716    // 3. denied instead of argument-conditioned
1717    "seccomp",
1718    "personality",
1719    "kcmp",
1720];
1721
1722/// The largest BPF program `linux_enforce::build_seccomp_filter` may compile to before this
1723/// project treats the filter as having outgrown its headroom. Held against the *measured* export
1724/// of the real filter by a test, not against an estimate: growing
1725/// [`SECCOMP_SYSCALL_ALLOWLIST`] past this fails `cargo test` with the measured count in the
1726/// message, instead of surfacing as a spawn that dies inside `pre_exec` on some host.
1727///
1728/// Set well below [`BPF_MAXINSNS_CEILING`] on purpose. It is a project budget, not a kernel one:
1729/// crossing it is a prompt to re-measure and decide, not evidence that the kernel would refuse.
1730/// `docs/content/reference/seccomp-filter-instruction-budget.md` records the measurement this
1731/// number was chosen against.
1732#[allow(dead_code)]
1733pub(crate) const SECCOMP_FILTER_INSTRUCTION_BUDGET: usize = 512;
1734
1735/// The kernel's `BPF_MAXINSNS` — the most instructions a *single* seccomp filter may contain.
1736/// A longer program is refused by `seccomp(SECCOMP_SET_MODE_FILTER)` with `EINVAL`, before the
1737/// filter is attached to anything. Measured rather than quoted: a test brackets it by loading
1738/// two filters that straddle it in forked children.
1739#[allow(dead_code)]
1740pub(crate) const BPF_MAXINSNS_CEILING: usize = 4096;
1741
1742/// The kernel's `MAX_INSNS_PER_PATH` — the most instructions the *whole chain* of filters
1743/// attached to one task may total, counting every filter it already carries plus a small
1744/// per-filter accounting overhead. An attach that would cross it is refused with `ENOMEM`,
1745/// which is the only seccomp path in the kernel that returns that errno. Measured rather than
1746/// quoted: a test stacks filters in a forked child until the refusal arrives.
1747#[allow(dead_code)]
1748pub(crate) const SECCOMP_MAX_INSNS_PER_PATH: usize = 32768;
1749
1750/// Bundles the resolved, host-independent enforcement inputs for one capsule session.
1751#[derive(Debug, Clone)]
1752pub(crate) struct ShellEnforcement {
1753    pub(crate) tier: EnforcementTier,
1754    /// Every `capabilities.network.allow` host resolved to concrete addresses once, at launch,
1755    /// by [`resolve_network_allowlist_ips`].
1756    ///
1757    /// The narrower of the egress proxy's two checks — the one applied to a destination the
1758    /// capsule reached without ever resolving a name for it (a hardcoded literal). See
1759    /// `egress_proxy::EgressPolicy::allows_connection`, which consults exactly this list through
1760    /// [`network_ip_allowed`].
1761    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1762    pub(crate) network_allow_ips: Vec<IpAddr>,
1763    /// The same allowlist in its *parsed*, name-keyed form — the ordinary path. The egress proxy
1764    /// checks a name when it resolves it and again when the connection to the address that name
1765    /// produced is accepted, which is what a resolved-IP set alone cannot express (one address,
1766    /// many tenants) in either direction.
1767    ///
1768    /// The same `NetworkAllowRule` type and the same parser the WASI-HTTP path uses, so a manifest
1769    /// entry cannot mean one thing to a WASM guest and another to a subprocess.
1770    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1771    pub(crate) network_allow_rules: Vec<crate::network_policy::NetworkAllowRule>,
1772    /// The TCP ports the capsule's network namespace opens listeners on, derived from the
1773    /// allowlist by `egress_proxy::egress_listen_ports`. A port no allow entry implies gets no
1774    /// listener at all, so a connection to it is refused by the kernel with nothing in userspace
1775    /// consulted — the strongest form the refusal can take.
1776    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1777    pub(crate) egress_tcp_ports: Vec<u16>,
1778    /// `capabilities.network.unix_sockets`, threaded through to the seccomp `socket()` rule.
1779    /// `false` (the default) means the forked child cannot create an `AF_UNIX` socket at all, so
1780    /// a local daemon socket — `/var/run/docker.sock` above all — is unreachable regardless of
1781    /// what any Landlock ABI does or does not mediate for pathname sockets. Consumed only by
1782    /// `linux_enforce::install_seccomp_filter` (via `denied_socket_domains`); resolved on every
1783    /// platform for parity but never read off Linux.
1784    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1785    pub(crate) unix_sockets_allowed: bool,
1786    /// `capabilities.filesystem.workdir_exec`, threaded through to the workdir's own Landlock
1787    /// rule. `false` (the default) withholds the `Execute` right from it, which is what makes
1788    /// `shell_allow` enforceable at all now that the exec supervisor is gone: nothing the capsule
1789    /// writes into its workdir can run, under any name. Consumed only by
1790    /// `linux_enforce::workdir_access_rights` on the Landlock tiers; resolved on every platform
1791    /// for parity but never read off Linux.
1792    ///
1793    /// It has no seccomp counterpart on `KernelSeccompOnly` — without a Landlock domain there is
1794    /// nothing to withhold — which is part of why that tier cannot reach `scoped`.
1795    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1796    pub(crate) workdir_exec: bool,
1797    /// Narrow read (never write) Landlock grants *outside* the workdir so the allowlisted
1798    /// binaries can actually exec, dynamically link, and (for a path-based interpreter) reach their
1799    /// stdlib. Five origins, combined here:
1800    ///
1801    ///   - the `DT_NEEDED`-closure files (`shell.allow` binaries, their ELF interpreter, their
1802    ///     shared-library closure), from `resolve_landlock_grants` — each wrapped `list_dir: false`
1803    ///     (they are individual files, where `ReadDir` was always a no-op);
1804    ///   - one grant per `capabilities.shell.interpreter_runtime` directory, from
1805    ///     `resolve_interpreter_runtime_grants` — each carrying exactly the `list_dir` its author
1806    ///     declared;
1807    ///   - one listable grant per `capabilities.shell.staged_runtime` tree, from
1808    ///     `resolve_staged_runtime_landlock_grants`;
1809    ///   - on `KernelSealed` **only**, one listable but *non-executable* grant per fixed
1810    ///     [`crate::sealed::SEALED_RUNTIME_PATHS`] entry, from
1811    ///     `resolve_sealed_runtime_landlock_grants` — the composed root's own bind-mounted runtime
1812    ///     tree, which nothing else grants;
1813    ///   - on `KernelSealed` **only**, one non-executable read grant per fixed
1814    ///     [`crate::sealed::SEALED_ETC_PATHS`] entry, from `resolve_sealed_etc_landlock_grants`
1815    ///     (`list_dir` per entry, since that list mixes directories and files) — the composed
1816    ///     root's `/etc` allowlist, likewise granted by nothing else.
1817    ///
1818    /// The first three carry `executable: true`; the two tier-issued ones do not, and that
1819    /// asymmetry is load-bearing — see [`LandlockGrant`].
1820    ///
1821    /// Resolved once at launch (in the parent) and threaded into the forked child's `pre_exec`,
1822    /// where `apply_landlock_scope` turns each into a per-path `PathBeneath` rule with an access
1823    /// set that depends on `list_dir` and `executable`. Only consulted on `KernelFull` and
1824    /// `KernelSealed`; resolved on every platform for parity but never read off Linux.
1825    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1826    pub(crate) landlock_grants: Vec<LandlockGrant>,
1827    /// Host directories this capsule needs bind-mounted read-only into its composed root *beyond*
1828    /// the fixed [`crate::sealed::SEALED_RUNTIME_PATHS`]: the containing directory of each
1829    /// resolved `shell.allow` binary, and each `capabilities.shell.interpreter_runtime` directory.
1830    ///
1831    /// Whole directories, never files: a bind carries a directory's whole contents, so this must
1832    /// not grow into a second ELF-closure derivation. Consumed only on `KernelSealed`; resolved on
1833    /// every platform for parity, exactly like `landlock_grants` above.
1834    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1835    pub(crate) sealed_bind_dirs: Vec<PathBuf>,
1836    /// The `source_path` of each declared `capabilities.shell.staged_runtime` grant, bind-mounted
1837    /// read-only into the composed root at its own absolute path.
1838    ///
1839    /// Separate from `sealed_bind_dirs` above because the failure semantics are opposite, and that
1840    /// is the capability: `sealed_bind_dirs` shrinks the root when the host is missing something,
1841    /// while a staged tree that cannot be mounted aborts the composed-root construction before
1842    /// `pivot_root`, which surfaces as `RuntimeError::SealedRootConstructionFailed` (`E-RUN-014`)
1843    /// and is session-fatal. A capsule never gets a shell tool call inside a root missing a
1844    /// runtime tree it declared. Consumed only on `KernelSealed`; resolved on every platform for
1845    /// parity, exactly like the two fields above.
1846    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1847    pub(crate) staged_runtime_dirs: Vec<PathBuf>,
1848    /// Fully-resolved OS-level bounds for every subprocess this session spawns — `rlimit(2)`
1849    /// ceilings applied before `execve`, plus the values the cgroup scope below was built from.
1850    /// Unlike everything above it, this is enforced on **every** platform: `setrlimit` is POSIX,
1851    /// so macOS gets the per-process bounds even though it can never get the aggregate (cgroup)
1852    /// half. See [`crate::resources`].
1853    pub(crate) resource_limits: crate::resources::HostResourceLimits,
1854    /// The runtime's own uid task count, measured once here in the parent by
1855    /// `crate::resources::uid_task_count`, in whichever unit this platform's `RLIMIT_NPROC` is
1856    /// enforced against. `RLIMIT_NPROC` is a per-uid limit, so `resource_limits.max_processes` is
1857    /// applied as headroom above this rather than as an absolute ceiling — see
1858    /// `crate::resources::apply_hard_rlimits`. `0` when the host cannot be asked, which makes the
1859    /// declared value apply literally (the tighter reading).
1860    pub(crate) nproc_baseline: u64,
1861    /// The session's cgroup v2 scope, when the host could delegate one (Linux only, and only
1862    /// for capsules that can actually spawn a native subprocess). `None` on macOS always, and on
1863    /// Linux only for capsules with no subprocess capability at all — a Linux capsule that *can*
1864    /// spawn one and could not be given a scope never reaches here, because the launch is
1865    /// refused first with `RuntimeError::CgroupDelegationUnavailable`.
1866    pub(crate) cgroup_scope: Option<Arc<crate::cgroup::CgroupScope>>,
1867    /// The session's periodic workdir-size check. Consulted before every subprocess spawn, so a
1868    /// disk filler stops writing at the first spawn after the ceiling is crossed rather than
1869    /// only at the next agent turn.
1870    pub(crate) workdir_guard: Option<Arc<crate::resources::WorkdirGuard>>,
1871}
1872
1873impl ShellEnforcement {
1874    /// Resolves tier + network allowlist + canonical exec allowlist once, at launch time.
1875    ///
1876    /// The rlimit half of [`crate::resources`] is resolved here too (it needs nothing but the
1877    /// policy), while the cgroup scope and workdir guard are session-scoped live handles the
1878    /// caller creates and attaches with [`Self::with_host_bounding`].
1879    ///
1880    /// `declared` is the already-combined containment floor for the session. It is what decides
1881    /// whether a sealed-capable host actually installs a composed root — see [`applied_tier`].
1882    ///
1883    /// `probe` is the session's own [`HostProbe`], taken by `runtime::stage_session` and carried
1884    /// on the `StagedSession`. Passed in rather than taken here so the mechanisms this installs
1885    /// are the ones the session's trace already claims.
1886    pub(crate) fn resolve(
1887        policy: &CapabilityPolicy,
1888        declared: murmur_artifact::ContainmentClass,
1889        probe: HostProbe,
1890    ) -> Result<Self, String> {
1891        let tier = applied_tier(probe.tier(), declared);
1892        let network_allow_ips = resolve_network_allowlist_ips(&policy.network_allow)?;
1893        let network_allow_rules =
1894            crate::network_policy::parse_network_allow_rules(&policy.network_allow)
1895                .map_err(|error| error.to_string())?;
1896        let egress_tcp_ports = crate::egress_proxy::egress_listen_ports(&network_allow_rules);
1897        let exec_allow_paths = resolve_exec_allowlist(&policy.shell_allow);
1898        // The `DT_NEEDED`-closure files (individual files → non-listable) plus one grant
1899        // per author-declared `interpreter_runtime` directory (each with its own `list_dir`). A
1900        // directory not named in the manifest never receives a rule, regardless of what it holds.
1901        let mut landlock_grants =
1902            LandlockGrant::non_listable_files(resolve_landlock_grants(&exec_allow_paths));
1903        landlock_grants.extend(resolve_interpreter_runtime_grants(
1904            &policy.shell_interpreter_runtime,
1905        ));
1906        // Plus one per staged runtime tree. Without this the tree is bind-mounted into the
1907        // composed root and then denied by the Landlock ruleset installed inside it — see
1908        // `resolve_staged_runtime_landlock_grants`.
1909        landlock_grants.extend(resolve_staged_runtime_landlock_grants(policy));
1910        // Plus, on `KernelSealed` only, one listable grant per fixed `SEALED_RUNTIME_PATHS`
1911        // directory — the composed root binds them but Landlock inside the root still denies
1912        // enumerating them. Gated on `tier`, not on the manifest: on `KernelFull` (the tier a
1913        // `scoped` capsule runs on) the same grant would expose real host directory shape. The
1914        // resolver applies that gate itself and returns nothing on every other tier.
1915        landlock_grants.extend(resolve_sealed_runtime_landlock_grants(tier));
1916        // And, on `KernelSealed` only, one read grant per fixed `SEALED_ETC_PATHS` entry — the same
1917        // mounted-but-denied bug one directory over, and the reason TLS certificate verification
1918        // failed inside a composed root. Tier-gated by the resolver itself, exactly as above: on
1919        // `KernelFull` these rules would apply to the *host's* /etc.
1920        landlock_grants.extend(resolve_sealed_etc_landlock_grants(tier));
1921        let sealed_bind_dirs = resolve_sealed_bind_dirs(&exec_allow_paths, policy);
1922        let staged_runtime_dirs = resolve_staged_runtime_dirs(policy);
1923        Ok(Self {
1924            tier,
1925            network_allow_ips,
1926            network_allow_rules,
1927            egress_tcp_ports,
1928            unix_sockets_allowed: policy.unix_sockets_allowed,
1929            workdir_exec: policy.workdir_exec_allowed,
1930            landlock_grants,
1931            sealed_bind_dirs,
1932            staged_runtime_dirs,
1933            resource_limits: policy.resources,
1934            nproc_baseline: crate::resources::uid_task_count().unwrap_or(0),
1935            cgroup_scope: None,
1936            workdir_guard: None,
1937        })
1938    }
1939
1940    /// Attach the session-scoped host-bounding handles: the cgroup v2 scope (Linux, when the
1941    /// capsule can spawn a subprocess) and the workdir-size guard (every platform).
1942    ///
1943    /// Separate from [`Self::resolve`] because both are *live* per-session resources with
1944    /// lifetimes and side effects — a directory under `/sys/fs/cgroup` and a running thread —
1945    /// while `resolve` is a pure resolution of manifest and host facts. The caller owns their
1946    /// creation so the fail-closed launch refusal can happen with a typed error before this is
1947    /// ever reached.
1948    pub(crate) fn with_host_bounding(
1949        mut self,
1950        cgroup_scope: Option<Arc<crate::cgroup::CgroupScope>>,
1951        workdir_guard: Option<Arc<crate::resources::WorkdirGuard>>,
1952    ) -> Self {
1953        self.cgroup_scope = cgroup_scope;
1954        self.workdir_guard = workdir_guard;
1955        self
1956    }
1957
1958    /// The latched workdir-size breach, if the guard has seen one.
1959    pub(crate) fn workdir_breach(&self) -> Option<crate::resources::WorkdirBreach> {
1960        self.workdir_guard.as_ref().and_then(|guard| guard.breach())
1961    }
1962
1963    /// Refuse to spawn once the workdir ceiling has been crossed.
1964    ///
1965    /// Called by both subprocess spawn paths before `Command::spawn()`. Stopping at the spawn
1966    /// boundary is what keeps a disk filler from writing another byte while the session unwinds:
1967    /// the periodic check notices the breach, and the very next subprocess never starts.
1968    pub(crate) fn check_workdir_budget(&self) -> Result<(), String> {
1969        match self.workdir_breach() {
1970            Some(breach) => Err(crate::resources::workdir_breach_message(breach)),
1971            None => Ok(()),
1972        }
1973    }
1974
1975    /// The permanent macOS/non-Linux value, and also what tests should construct directly to
1976    /// exercise `execute_shell` without depending on real kernel enforcement machinery. This
1977    /// is not a fake test-only bypass — it's the literal value real macOS hosts get. (Only
1978    /// test code calls this directly today — production always goes through `resolve()`,
1979    /// which independently arrives at the same tier value on non-Linux hosts.)
1980    #[cfg_attr(not(test), allow(dead_code))]
1981    pub(crate) fn environment_only() -> Self {
1982        Self {
1983            tier: EnforcementTier::EnvironmentOnly,
1984            network_allow_ips: Vec::new(),
1985            network_allow_rules: Vec::new(),
1986            egress_tcp_ports: Vec::new(),
1987            // Denied, matching every other grant this constructor zeroes out. Inert on this tier
1988            // (no seccomp filter is installed at all), but it must not read as "allowed".
1989            unix_sockets_allowed: false,
1990            // Denied, like every other grant this constructor zeroes out. Inert on this tier (no
1991            // Landlock domain exists to withhold anything from), but it must not read as "allowed".
1992            workdir_exec: false,
1993            landlock_grants: Vec::new(),
1994            sealed_bind_dirs: Vec::new(),
1995            staged_runtime_dirs: Vec::new(),
1996            // Defaults, not "no limits": the rlimit ceilings apply unchanged on this tier, so
1997            // zeroing them out here would misrepresent what a real macOS host does.
1998            resource_limits: crate::resources::HostResourceLimits::default(),
1999            nproc_baseline: crate::resources::uid_task_count().unwrap_or(0),
2000            cgroup_scope: None,
2001            workdir_guard: None,
2002        }
2003    }
2004}
2005
2006/// Core messages shared between the stderr line and `logs/bootstrap.log` line for each tier
2007/// warning, matching the shared-const convention used by `runtime::BASH_NETWORK_BYPASS_WARNING`.
2008/// Full detail lives on the diagnostics doc page (`security_warning_link`); keep each to
2009/// one or two concise sentences.
2010///
2011/// The Landlock filesystem scope now derives a narrow read+execute grant (the `shell.allow`
2012/// binaries, their ELF interpreter, and their shared-library closure) *outside* the workdir, in
2013/// addition to the workdir's own grant (which withholds device-node and unix-socket creation, see
2014/// `linux_enforce::WORKDIR_ACCESS_RIGHTS`) — so allowlisted programs can actually exec and
2015/// dynamically link, and the only writable path outside the workdir is `/dev/null`, one of the
2016/// three fixed devices in `CAPSULE_DEVICE_GRANTS`. Seccomp additionally refuses the
2017/// `socket(2)` domains in `denied_socket_domains` — closing the `/var/run/docker.sock` path, which
2018/// no Landlock ABI mediates for pathname sockets. The forked shell child also
2019/// drops every Linux capability before `execve` (see `linux_enforce::drop_all_capabilities`).
2020/// `KernelFull` warns (`W_SEC_005`) rather than staying silent: the tier is a filesystem and
2021/// syscall scope, not a namespace, so what it does and does not cover has to reach the operator.
2022const KERNEL_ENFORCEMENT_NOTICE: &str = "capabilities.shell.allow is non-empty and this host \
2023resolved to a Linux kernel-enforcement tier (Landlock/seccomp). Landlock now grants a narrow, \
2024derived read+execute scope outside the workdir (the allowlisted binaries, their loader, and their \
2025shared libraries — nothing writable, no directory granted wholesale), plus a fixed device set \
2026every capsule gets unconditionally: /dev/null read+write (the only writable path outside the \
2027workdir), \
2028/dev/zero and /dev/urandom read-only, and no other device — /dev/random, /dev/full, /dev/tty and \
2029raw block devices stay denied. The workdir's own grant also \
2030withholds device-node and unix-socket creation; seccomp refuses socket(AF_UNIX) outright unless \
2031capabilities.network.unix_sockets is declared, and always refuses AF_NETLINK/AF_PACKET, so a \
2032capsule cannot reach a host daemon socket such as /var/run/docker.sock; the seccomp filter now \
2033defaults to deny and permits only a fixed syscall allowlist modelled on the OCI/Docker default \
2034profile, so io_uring, bpf, userfaultfd, perf_event_open, ptrace and similar are refused outright; \
2035and the forked shell child \
2036drops every Linux capability and sets no_new_privs before execve. Paths outside the workdir are \
2037denied, not absent: stat, access and readlink on an ungranted path still succeed.";
2038
2039/// `KernelSealed`'s counterpart to [`KERNEL_ENFORCEMENT_NOTICE`], carrying the same `W_SEC_005`
2040/// code: a silent strongest tier would imply the boundary has no documented exceptions, and it
2041/// has one. Names what `sealed` adds over `scoped` so the warning is not a louder copy of it.
2042const KERNEL_SEALED_ENFORCEMENT_NOTICE: &str = "capabilities.shell.allow is non-empty and this \
2043host resolved to the sealed kernel-enforcement tier: the subprocess tree runs in a private mount \
2044namespace pivoted onto a composed root (host runtime bind-mounted read-only, the session workdir \
2045the only writable path, a private /dev tmpfs carrying the OCI default device set), with Landlock \
2046and seccomp still installed inside it as defence in depth. Paths outside that root are absent \
2047rather than denied — with one documented exception: /proc is a bind of the host's, not a masked \
2048private procfs, because mounting one unprivileged needs a PID namespace this tier does not create, \
2049so host process metadata stays visible there exactly as it is under scoped.";
2050
2051const SECCOMP_ONLY_WARNING: &str = "capabilities.shell.allow is non-empty and this Linux kernel \
2052lacks Landlock (kernel <5.13) — filesystem access outside the capsule workdir is not \
2053kernel-enforced at all, and the seccomp exec/network enforcement that would apply has not been \
2054verified on real Linux hardware. The fixed capsule device set the Full tier applies (/dev/null \
2055read+write, /dev/zero and /dev/urandom read-only, every other device denied) is a Landlock \
2056mechanism, so it does not apply here either: on this tier every device under /dev is reachable \
2057exactly as it would be without any sandbox. Seccomp also refuses socket(AF_UNIX) unless \
2058capabilities.network.unix_sockets is declared, and always refuses AF_NETLINK/AF_PACKET — that \
2059rule needs no Landlock and so applies identically on this tier, but it has not been verified \
2060either. The same is true of the default-deny syscall allowlist (modelled on the OCI/Docker default \
2061profile), which refuses io_uring, bpf, userfaultfd, perf_event_open, ptrace and similar on this \
2062tier too. The forked shell child still drops every Linux capability and \
2063sets no_new_privs before execve on this tier, independently of Landlock, but that has not been \
2064verified either. Treat shell subprocess isolation as experimental on this host.";
2065
2066const ENVIRONMENT_ONLY_WARNING: &str = "capabilities.shell.allow is non-empty but this \
2067platform has no kernel-level subprocess sandbox (Landlock/seccomp are Linux-only) — \
2068enforcement is environment-only (synthetic HOME + credential env-stripping). This is \
2069permanent on this platform.";
2070
2071/// Tier-aware replacement for calling `runtime::warn_if_bash_network_bypass` unconditionally.
2072///
2073///   - `KernelFull` → warns (if `shell_allow` is non-empty) that the Linux kernel enforcement
2074///     is unverified and must not be trusted yet — NOT silent. See the const doc above for why.
2075///   - `KernelSeccompOnly` → warns (if `shell_allow` is non-empty) that Landlock is unavailable
2076///     (filesystem scope unenforced) AND that the remaining seccomp enforcement is unverified.
2077///   - `EnvironmentOnly` → warns (if `shell_allow` is non-empty) that there is no kernel
2078///     sandboxing primitive at all on this platform, and this is permanent. Also still calls
2079///     `runtime::warn_if_bash_network_bypass`, which remains accurate on this tier since
2080///     nothing is kernel-enforced.
2081///
2082/// Pure tier→warning-text decision, split out of `warn_for_enforcement_tier` so tests can
2083/// assert what each tier warns without capturing stderr.
2084pub(crate) fn tier_warning(
2085    tier: EnforcementTier,
2086    shell_allow_is_empty: bool,
2087) -> Option<(&'static str, &'static str)> {
2088    if shell_allow_is_empty {
2089        return None;
2090    }
2091    match tier {
2092        EnforcementTier::KernelSealed => Some((W_SEC_005, KERNEL_SEALED_ENFORCEMENT_NOTICE)),
2093        EnforcementTier::KernelFull => Some((W_SEC_005, KERNEL_ENFORCEMENT_NOTICE)),
2094        EnforcementTier::KernelSeccompOnly => Some((W_SEC_002, SECCOMP_ONLY_WARNING)),
2095        EnforcementTier::EnvironmentOnly => Some((W_SEC_001, ENVIRONMENT_ONLY_WARNING)),
2096    }
2097}
2098
2099const NO_AGGREGATE_BOUNDING_WARNING: &str = "this capsule can spawn native subprocesses, but \
2100this platform has no cgroup v2 (Linux-only), so no aggregate bound exists across the subprocess \
2101tree: nothing caps its total memory, task count or CPU. Per-process rlimits from \
2102capabilities.resources still apply (hard, not soft), but RLIMIT_NPROC is a per-uid ceiling and \
2103does NOT stop a fork bomb of distinct, short-lived processes — only a cgroup's pids.max does. \
2104This is permanent on this platform, not a placeholder for a future slice.";
2105
2106/// Pure decision for the aggregate-bounding warning, split out of
2107/// [`warn_for_missing_aggregate_bounding`] the same way [`tier_warning`] is split out of
2108/// [`warn_for_enforcement_tier`], so tests can assert it without capturing stderr.
2109///
2110/// Fires only where the gap is both real and unclosable: a non-Linux host running a capsule that
2111/// can spawn a subprocess. On Linux the same condition is not a warning at all — a capsule that
2112/// can spawn a subprocess and has no scope never launches (`CgroupDelegationUnavailable`), so
2113/// there is no running session left to warn about.
2114pub(crate) fn aggregate_bounding_warning(
2115    is_linux: bool,
2116    requires_bounding: bool,
2117    has_scope: bool,
2118) -> Option<(&'static str, &'static str)> {
2119    if is_linux || !requires_bounding || has_scope {
2120        return None;
2121    }
2122    Some((W_SEC_010, NO_AGGREGATE_BOUNDING_WARNING))
2123}
2124
2125/// Fires at every launch, not just once.
2126pub(crate) fn warn_for_missing_aggregate_bounding(
2127    workdir: &Path,
2128    requires_bounding: bool,
2129    has_scope: bool,
2130) {
2131    let is_linux = cfg!(target_os = "linux");
2132    if let Some((code, message)) =
2133        aggregate_bounding_warning(is_linux, requires_bounding, has_scope)
2134    {
2135        let link = security_warning_link(code);
2136        eprintln!("[capsule-runtime] warning[{code}]: {message} ({link})");
2137        crate::agent::append_bootstrap_log(
2138            workdir,
2139            &format!("[capability-policy] warning[{code}]: {message} ({link})"),
2140        );
2141    }
2142}
2143
2144/// Fires at every launch, not just once.
2145pub(crate) fn warn_for_enforcement_tier(
2146    tier: EnforcementTier,
2147    workdir: &Path,
2148    policy: &CapabilityPolicy,
2149) {
2150    if let Some((code, message)) = tier_warning(tier, policy.shell_allow.is_empty()) {
2151        let link = security_warning_link(code);
2152        eprintln!("[capsule-runtime] warning[{code}]: {message} ({link})");
2153        crate::agent::append_bootstrap_log(
2154            workdir,
2155            &format!("[capability-policy] warning[{code}]: {message} ({link})"),
2156        );
2157    }
2158    if tier == EnforcementTier::EnvironmentOnly {
2159        crate::runtime::warn_if_bash_network_bypass(workdir, policy);
2160    }
2161}
2162
2163/// Handle to the (possibly no-op) side-channel machinery attached to one subprocess spawn. On
2164/// Linux tiers, the background thread is already running by the time this is returned by
2165/// `prepare_enforcement` — started BEFORE the caller calls `.spawn()`, not after.
2166///
2167/// This ordering is required, not incidental. The child builds its network namespace inside
2168/// `pre_exec` and hands the namespace's listening sockets back over a `SOCK_DGRAM` socketpair;
2169/// `std::process::Command::spawn()`'s parent side then blocks internally (via a close-on-exec
2170/// error pipe) until the child's `execve` resolves. If the receiving thread only started after
2171/// `.spawn()` returned, the capsule's very first outbound connection could beat the egress proxy
2172/// to its own socket. Starting the thread first — racing concurrently with the fork/exec inside
2173/// `.spawn()`, not gated behind it — closes that window.
2174///
2175/// The name is historical: nothing is "supervised" here any more (the seccomp-notify loops it once
2176/// ran are retired — see this module's header). What is left is the fd hand-off, the egress
2177/// proxy's lifetime, and the child's diagnostic pipe.
2178#[derive(Debug)]
2179pub(crate) enum SupervisorHandle {
2180    Noop,
2181    #[cfg(target_os = "linux")]
2182    Linux {
2183        /// Carries the started egress proxy back from the receiving thread, so the proxy's
2184        /// lifetime ends with the subprocess tree it serves rather than outliving it. `None`
2185        /// travels through here too — the hand-off can fail, and that is reported (and fatal to
2186        /// the spawn) on its own path.
2187        proxy_rx: std::sync::mpsc::Receiver<Option<crate::egress_proxy::EgressProxyHandle>>,
2188        /// Read end of the `CLOEXEC` diagnostic pipe whose write end was moved into the forked
2189        /// child's `pre_exec` closure. On a successful `execve` the write end closes
2190        /// automatically with nothing written (so a read yields immediate EOF); on a `pre_exec`
2191        /// setup failure the child writes the real error message here before returning `Err`,
2192        /// letting `execute_shell` fold that legible detail into the error it returns instead of
2193        /// the bare, undifferentiated `EINVAL` that `Command::spawn()` surfaces.
2194        diag_read: std::os::fd::OwnedFd,
2195    },
2196}
2197
2198impl SupervisorHandle {
2199    /// Shuts the session's egress proxy down, with a short bound so the shell call never hangs.
2200    /// In practice the receive returns immediately: the thread's only blocking step is the
2201    /// namespace-socket hand-off, which completed before the child could `execve` at all — long
2202    /// before the caller finished waiting on the child.
2203    ///
2204    /// A proxy outliving its namespace would be serving sockets whose peers no longer exist, so
2205    /// this is the teardown, not merely a thread join.
2206    pub(crate) fn join_best_effort(self) {
2207        match self {
2208            SupervisorHandle::Noop => {}
2209            #[cfg(target_os = "linux")]
2210            SupervisorHandle::Linux { proxy_rx, .. } => {
2211                if let Ok(Some(proxy)) = proxy_rx.recv_timeout(std::time::Duration::from_secs(5)) {
2212                    proxy.shutdown();
2213                }
2214                // Deliberately not joining the underlying `JoinHandle`: dropping it without
2215                // joining leaves the thread detached (it keeps running to completion in the
2216                // background, reclaimed by the OS on exit), which is fine here since the value
2217                // received above is the only thing it produces.
2218            }
2219        }
2220    }
2221
2222    /// Best-effort read of any failure detail the forked child wrote to the diagnostic pipe
2223    /// before its `pre_exec` closure returned `Err`. Only consulted by `execute_shell` when
2224    /// `Command::spawn()` itself returns `Err` — on the success path this is never called, so
2225    /// there is zero cost there.
2226    ///
2227    /// The caller must have already released every *parent-side* copy of the pipe's write end
2228    /// (the one captured by the `pre_exec` closure stored in the `Command`) — otherwise the
2229    /// read below never sees EOF. `execute_shell` guarantees this by dropping the `Command`
2230    /// before calling this. Returns `None` when there is no pipe (the `Noop` handle used for
2231    /// `EnvironmentOnly`/non-Linux) or when the child wrote nothing (e.g. a failure with no
2232    /// message, or a `spawn` failure that never ran `pre_exec` at all, like `fork()` itself
2233    /// failing).
2234    pub(crate) fn read_diagnostic(&self) -> Option<String> {
2235        match self {
2236            SupervisorHandle::Noop => None,
2237            #[cfg(target_os = "linux")]
2238            SupervisorHandle::Linux { diag_read, .. } => {
2239                use std::os::fd::AsRawFd;
2240                linux_enforce::read_diagnostic_pipe(diag_read.as_raw_fd())
2241            }
2242        }
2243    }
2244}
2245
2246// Forced-failure seam for the fail-closed contract: inducing a real kernel-level setup failure
2247// requires already-hostile conditions, so tests simulate one here instead. Only compiled into
2248// test builds; production `prepare_enforcement` has no bypass or injection point.
2249#[cfg(test)]
2250thread_local! {
2251    pub(crate) static FORCE_PREPARE_FAILURE: std::cell::Cell<bool> =
2252        const { std::cell::Cell::new(false) };
2253}
2254
2255#[cfg(test)]
2256fn forced_prepare_failure() -> Result<(), String> {
2257    if FORCE_PREPARE_FAILURE.with(|flag| flag.get()) {
2258        return Err("sandbox: kernel enforcement setup failed (forced by test seam)".to_string());
2259    }
2260    Ok(())
2261}
2262
2263// Child-side (`pre_exec`) forced-failure seams, one per distinct setup step that can fail
2264// independently: the explicit `no_new_privs` `prctl` and the Landlock ruleset construction.
2265// Unlike `FORCE_PREPARE_FAILURE` (which fails the *outer*, pre-fork `prepare_enforcement` path),
2266// these are read from inside the forked child's `pre_exec` closure — `fork()` copy-on-write
2267// duplicates the calling thread's TLS block, so a flag set `true` in the parent thread before
2268// `command.spawn()` remains readable as `true` inside `pre_exec` with no cross-process IPC.
2269// Only compiled into Linux test builds (their only readers — `set_no_new_privs` and
2270// `apply_landlock_scope` — are Linux-only); production has no bypass or injection point.
2271#[cfg(all(test, target_os = "linux"))]
2272thread_local! {
2273    pub(crate) static FORCE_NO_NEW_PRIVS_FAILURE: std::cell::Cell<bool> =
2274        const { std::cell::Cell::new(false) };
2275    pub(crate) static FORCE_LANDLOCK_FAILURE: std::cell::Cell<bool> =
2276        const { std::cell::Cell::new(false) };
2277    /// Fails the composed-root step of a `KernelSealed` launch. Exists because the real step can
2278    /// only fail on a host that can attempt it at all, and the thing under test — that a
2279    /// composed-root failure keeps its identity from the child's diagnostic pipe all the way to
2280    /// the CLI's `E-RUN-014` — must be verifiable on any Linux host, including the CI containers
2281    /// that can never reach `KernelSealed`. Short-circuits before any real namespace syscall.
2282    pub(crate) static FORCE_SEALED_ROOT_FAILURE: std::cell::Cell<bool> =
2283        const { std::cell::Cell::new(false) };
2284}
2285
2286/// RAII arm for [`FORCE_SEALED_ROOT_FAILURE`]. Lives beside the flag rather than in one test
2287/// module because two of them need it: `sandbox`'s (which checks what `execute_shell` returns)
2288/// and `runtime`'s (which checks what the dispatch layer does with it).
2289#[cfg(all(test, target_os = "linux"))]
2290pub(crate) struct ForceSealedRootFailureGuard;
2291
2292#[cfg(all(test, target_os = "linux"))]
2293impl ForceSealedRootFailureGuard {
2294    pub(crate) fn new() -> Self {
2295        FORCE_SEALED_ROOT_FAILURE.with(|flag| flag.set(true));
2296        Self
2297    }
2298}
2299
2300#[cfg(all(test, target_os = "linux"))]
2301impl Drop for ForceSealedRootFailureGuard {
2302    fn drop(&mut self) {
2303        FORCE_SEALED_ROOT_FAILURE.with(|flag| flag.set(false));
2304    }
2305}
2306
2307/// A `KernelSealed` enforcement with no grants, for the forced-failure tests. The parent-side
2308/// half of the sealed mechanism still runs for real against it (the composed root is planned and
2309/// its spec built); only the child's execution of that spec is short-circuited by the seam above,
2310/// which is what makes these tests run identically on a sealed-capable host and on one that could
2311/// never reach `KernelSealed` at all.
2312#[cfg(all(test, target_os = "linux"))]
2313pub(crate) fn sealed_test_enforcement() -> ShellEnforcement {
2314    ShellEnforcement {
2315        tier: EnforcementTier::KernelSealed,
2316        ..ShellEnforcement::environment_only()
2317    }
2318}
2319
2320/// Attach the OS-level *process* bounds — hard rlimits, and cgroup membership where a scope
2321/// exists — to `command`, so they apply to the spawned process and everything it forks.
2322///
2323/// Deliberately independent of the tier machinery above. Landlock and seccomp are Linux kernel
2324/// primitives that exist on some hosts; `setrlimit` is POSIX and exists on all of them, and the
2325/// cgroup self-move is a single `write(2)` to a descriptor the parent already opened. Splitting
2326/// this out is what lets the two subprocess spawn paths converge: `execute_shell` gets it as
2327/// part of `prepare_enforcement`, and `dispatch_native_tool` — which installs no seccomp or
2328/// Landlock at all, a standing gap — gets it on its own.
2329///
2330/// Everything the returned closure does runs in the forked child between `fork` and `execve`,
2331/// so it is restricted to syscalls: `getrlimit`/`setrlimit` pairs and one `write`. No
2332/// allocation, no locking, no path resolution.
2333#[cfg(unix)]
2334pub(crate) fn attach_process_limits(
2335    command: &mut std::process::Command,
2336    enforcement: &ShellEnforcement,
2337) {
2338    use std::os::unix::process::CommandExt;
2339
2340    let limits = enforcement.resource_limits;
2341    let nproc_baseline = enforcement.nproc_baseline;
2342    let cgroup_scope = enforcement.cgroup_scope.clone();
2343
2344    // SAFETY: the closure runs in the forked child before `execve`, where only async-signal-safe
2345    // operations are permitted. It performs `getrlimit`/`setrlimit` pairs and, when a cgroup
2346    // scope exists, a single `write` to a descriptor opened by the parent before the fork —
2347    // no allocation, no locks, no path lookups.
2348    #[allow(unsafe_code)]
2349    unsafe {
2350        command.pre_exec(move || {
2351            crate::resources::apply_hard_rlimits(&limits, nproc_baseline)?;
2352            if let Some(scope) = cgroup_scope.as_ref() {
2353                scope.join_current_process()?;
2354            }
2355            Ok(())
2356        });
2357    }
2358}
2359
2360/// Lowest file descriptor the fd-hygiene step touches. Everything from here upward is marked
2361/// close-on-exec in the forked child; fds 0, 1 and 2 are deliberately left alone.
2362///
2363/// **Stdio is NOT marked close-on-exec, and is NOT reopened.** The `Stdio::piped()` handles both
2364/// spawn paths install *before* `pre_exec` runs exist so the exec'd program inherits them across
2365/// its own `execve` and talks to the parent over them — `execute_shell` reads the subprocess's
2366/// stdout/stderr, and `dispatch_native_tool` additionally writes its `ToolInput` JSON to the
2367/// subprocess's stdin and parses its `ToolResult` JSON back off stdout. Marking 0/1/2
2368/// close-on-exec would leave the exec'd program with those descriptors closed, breaking every
2369/// invocation on both paths, and there is nothing meaningful to reopen them onto: the pipes
2370/// themselves are the intended destination. The gap this constant closes is everything *above*
2371/// stdio, where inheritance was never intended and was only ever prevented by the empirical
2372/// accident of nothing else happening to be open at spawn time.
2373///
2374/// Its only non-test reader is Linux-only (`linux_enforce::mark_inherited_fds_cloexec`), so this
2375/// carries the same cross-platform `dead_code` exception the other Linux-consumed items in this
2376/// module carry.
2377#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
2378pub(crate) const FD_HYGIENE_FIRST_FD: u32 = 3;
2379
2380/// Non-Linux counterpart of [`apply_fd_hygiene`]: a documented no-op.
2381///
2382/// `close_range(2)` is Linux-only, and this mirrors the shape `prepare_enforcement` already
2383/// uses on non-Linux targets — no `pre_exec` closure is installed at all, rather than one that
2384/// does nothing. macOS is `EnforcementTier::EnvironmentOnly` by construction; there is no
2385/// kernel primitive here to call.
2386#[cfg(not(target_os = "linux"))]
2387pub(crate) fn apply_fd_hygiene(_command: &mut std::process::Command) {}
2388
2389/// Attaches the fd-hygiene step — mark every fd >= [`FD_HYGIENE_FIRST_FD`] close-on-exec — to a
2390/// `Command` that is about to be spawned, for spawn paths that do **not** go through
2391/// `prepare_enforcement`.
2392///
2393/// This exists so `runtime::dispatch_native_tool` (which has no `ShellEnforcement`, no tier and
2394/// no kernel sandboxing of its own) gets exactly the same fd-inheritance guarantee
2395/// `execute_shell` gets, without pulling the seccomp/Landlock apparatus into it. It is
2396/// deliberately a free function over `&mut Command` taking no policy input: fd hygiene is
2397/// unconditional — it is not derived from `CapabilityPolicy`, the manifest, or the enforcement
2398/// tier, and there is no configuration under which a subprocess should inherit an fd the
2399/// runtime did not deliberately hand it.
2400///
2401/// Do **not** call this on a `Command` that also goes through `prepare_enforcement`:
2402/// `linux_enforce::child_install_enforcement` already performs the same step as its first
2403/// statement, and `pre_exec` closures run in registration order, so a second one would be a
2404/// redundant syscall rather than an additional guarantee.
2405///
2406/// On a kernel older than 5.11 this makes `.spawn()` itself fail — see
2407/// [`linux_enforce::mark_inherited_fds_cloexec`] for that fail-closed consequence, which
2408/// applies identically here.
2409#[cfg(target_os = "linux")]
2410#[allow(unsafe_code)]
2411pub(crate) fn apply_fd_hygiene(command: &mut std::process::Command) {
2412    use std::os::unix::process::CommandExt;
2413
2414    // SAFETY: this closure runs in the forked child, after fork() but before execve() — the
2415    // narrow pre_exec window where only async-signal-safe operations are permitted. Its body is
2416    // a single `close_range(2)` syscall plus, on failure only, one `io::Error` construction: no
2417    // allocation on the success path, no locks, no captured state at all.
2418    unsafe {
2419        command.pre_exec(linux_enforce::mark_inherited_fds_cloexec);
2420    }
2421}
2422
2423/// Installs kernel-level exec/network/filesystem enforcement into `command` so it applies to
2424/// the spawned process and everything it forks/execs. The Landlock/seccomp half is a no-op when
2425/// `enforcement.tier == EnvironmentOnly` — it does not even attempt those calls in that case —
2426/// but the rlimit half below is not: `setrlimit` is POSIX and applies on every platform this
2427/// runtime targets, so a macOS capsule still gets per-process ceilings even though this tier has
2428/// no kernel sandbox at all.
2429#[cfg(not(target_os = "linux"))]
2430pub(crate) fn prepare_enforcement(
2431    command: &mut std::process::Command,
2432    enforcement: &ShellEnforcement,
2433    _accessible_workdir: &Path,
2434    _session_workdir: &Path,
2435) -> Result<SupervisorHandle, String> {
2436    #[cfg(test)]
2437    forced_prepare_failure()?;
2438
2439    debug_assert_eq!(
2440        enforcement.tier,
2441        EnforcementTier::EnvironmentOnly,
2442        "non-Linux targets must always resolve to EnforcementTier::EnvironmentOnly"
2443    );
2444    attach_process_limits(command, enforcement);
2445    Ok(SupervisorHandle::Noop)
2446}
2447
2448/// Linux implementation of `prepare_enforcement`. See the module-level docs and the `linux_enforce`
2449/// submodule for the mechanics (socketpair fd-passing side channel + `pre_exec` seccomp/Landlock
2450/// installation + background namespace-socket receiving thread).
2451#[cfg(target_os = "linux")]
2452#[allow(unsafe_code)]
2453pub(crate) fn prepare_enforcement(
2454    command: &mut std::process::Command,
2455    enforcement: &ShellEnforcement,
2456    accessible_workdir: &Path,
2457    session_workdir: &Path,
2458) -> Result<SupervisorHandle, String> {
2459    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
2460    use std::os::unix::process::CommandExt;
2461
2462    #[cfg(test)]
2463    forced_prepare_failure()?;
2464
2465    if enforcement.tier == EnforcementTier::EnvironmentOnly {
2466        // No kernel sandbox to install, but the POSIX rlimit ceilings still apply — this tier is
2467        // only reachable on Linux from tests, and even there it must not read as "unbounded".
2468        attach_process_limits(command, enforcement);
2469        return Ok(SupervisorHandle::Noop);
2470    }
2471
2472    // Resolve/open every Landlock path in the PARENT, before fork(). Failing to open the workdir
2473    // is a normal synchronous error here — it names the path and returns before any subprocess is
2474    // spawned — rather than an `open()` that, buried inside `pre_exec`, would collapse to a bare
2475    // EINVAL at the `.spawn()` call site. Grant paths that fail to open are silently dropped
2476    // (shrink-not-fail), exactly as before; only the *where* of the open moved. Landlock rules
2477    // only apply on `KernelFull`, so `KernelSeccompOnly` opens nothing.
2478    let landlock_fds = if matches!(
2479        enforcement.tier,
2480        EnforcementTier::KernelFull | EnforcementTier::KernelSealed
2481    ) {
2482        Some(linux_enforce::open_landlock_fds(
2483            accessible_workdir,
2484            session_workdir,
2485            &enforcement.landlock_grants,
2486            &landlock_device_grants(enforcement.tier),
2487            enforcement.workdir_exec,
2488            enforcement.tier,
2489        )?)
2490    } else {
2491        None
2492    };
2493
2494    // Resolve the whole composed root in the PARENT for the same reason the Landlock fds are
2495    // opened here: every path lookup, every `PathBuf::join` and every allocation the child would
2496    // otherwise perform inside `pre_exec` — the window where the allocator lock may be held by a
2497    // thread that no longer exists — happens now instead, synchronously, where a failure names
2498    // itself. See `crate::sealed` for the plan/execute split.
2499    let sealed_spec = if enforcement.tier == EnforcementTier::KernelSealed {
2500        Some(build_sealed_root(
2501            accessible_workdir,
2502            session_workdir,
2503            &enforcement.sealed_bind_dirs,
2504            &enforcement.staged_runtime_dirs,
2505        )?)
2506    } else {
2507        None
2508    };
2509
2510    let mut fds = [0i32; 2];
2511    // SAFETY: `fds` is a 2-element stack array, exactly the size `socketpair` writes into;
2512    // no other precondition applies.
2513    let rc = unsafe {
2514        libc::socketpair(
2515            libc::AF_UNIX,
2516            libc::SOCK_DGRAM | libc::SOCK_CLOEXEC,
2517            0,
2518            fds.as_mut_ptr(),
2519        )
2520    };
2521    if rc != 0 {
2522        return Err(format!(
2523            "sandbox: socketpair() failed: {}",
2524            std::io::Error::last_os_error()
2525        ));
2526    }
2527    // SAFETY: both fds were just returned by the successful socketpair() call above; nothing
2528    // else has taken ownership of them yet, so wrapping them in OwnedFd is exclusive/sound.
2529    let (parent_sock, child_sock) =
2530        unsafe { (OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1])) };
2531
2532    // Dedicated CLOEXEC pipe carrying failure detail out of the child. The write end is moved
2533    // into the `pre_exec` closure; because it is CLOEXEC, a successful `execve` closes it with
2534    // nothing written (the parent's read then returns immediate EOF — zero cost on the success
2535    // path), while any `pre_exec` setup failure writes its real message here before the closure
2536    // returns `Err`. Raw `pipe2` mirrors the raw `socketpair` convention used just above.
2537    let mut diag_fds = [0i32; 2];
2538    // SAFETY: `diag_fds` is a 2-element stack array, exactly the size `pipe2` writes into; no
2539    // other precondition applies.
2540    let rc = unsafe { libc::pipe2(diag_fds.as_mut_ptr(), libc::O_CLOEXEC) };
2541    if rc != 0 {
2542        return Err(format!(
2543            "sandbox: pipe2() for enforcement diagnostics failed: {}",
2544            std::io::Error::last_os_error()
2545        ));
2546    }
2547    // SAFETY: both fds were just returned by the successful pipe2() call above; nothing else has
2548    // taken ownership of them yet, so wrapping them in OwnedFd is exclusive/sound.
2549    let (diag_read, diag_write) = unsafe {
2550        (
2551            OwnedFd::from_raw_fd(diag_fds[0]),
2552            OwnedFd::from_raw_fd(diag_fds[1]),
2553        )
2554    };
2555
2556    // Everything the child's namespace construction needs, resolved here in the parent: the
2557    // `pre_exec` window permits no allocation, and `getuid()` in particular has to be read
2558    // *before* the `unshare` — inside a fresh user namespace with no map written yet it reports
2559    // the overflow id, and writing that back is refused on every host.
2560    let netns_plan =
2561        crate::network_namespace::CapsuleNetnsPlan::resolve(enforcement.egress_tcp_ports.clone());
2562    let expected_namespace_sockets = netns_plan.socket_count();
2563    let egress_policy = crate::egress_proxy::EgressPolicy::new(
2564        enforcement.network_allow_rules.clone(),
2565        enforcement.network_allow_ips.clone(),
2566    );
2567
2568    let tier = enforcement.tier;
2569    // Copied out before the `move` closure below takes ownership of everything it touches, the
2570    // same clone-before-move shape `tier` and the Landlock fds already use. Note the fd-passing
2571    // socketpair above is created in the *parent*, before fork, so the child's own `sendmsg` over
2572    // it is unaffected by a filter that denies `socket(AF_UNIX, ...)`.
2573    let unix_sockets_allowed = enforcement.unix_sockets_allowed;
2574    // Same clone-before-move shape. `HostResourceLimits` is `Copy`; the cgroup scope is an `Arc`
2575    // whose `cgroup.procs` descriptor was opened in the parent at scope-creation time, so the
2576    // child performs no path lookup to join it.
2577    let resource_limits = enforcement.resource_limits;
2578    let nproc_baseline = enforcement.nproc_baseline;
2579    let cgroup_scope = enforcement.cgroup_scope.clone();
2580
2581    // SAFETY: this closure runs in the forked child, after fork() but before execve() — the
2582    // narrow pre_exec window where only async-signal-safe operations are permitted. It performs
2583    // the capability-dropping `prctl`/`capset` sequence (bounding-set drop, capset clear, and the
2584    // explicit `no_new_privs` `prctl`) plus one allocation-free `open`/`read`/`close` of
2585    // `/proc/sys/kernel/cap_last_cap`, libseccomp filter construction/load (kernel syscalls), one
2586    // `sendmsg` batch handing the network namespace's sockets to the parent over `child_sock`, and
2587    // (KernelFull only)
2588    // Landlock ruleset construction/`restrict_self` against already-open fds (also kernel
2589    // syscalls) — no `open()`/`canonicalize()` beyond that one `cap_last_cap` read, no locks
2590    // beyond what those syscalls need. On any failure it writes the real error message to the
2591    // CLOEXEC diagnostic pipe (best-effort, bounded, raw `write` loop) before returning `Err`.
2592    // `child_sock`, `diag_write`, and the Landlock fds are moved in and close automatically when
2593    // the closure body finishes.
2594    unsafe {
2595        command.pre_exec(move || {
2596            // Ordered first, before any seccomp filter is installed: these are the bounds that
2597            // must hold even if a later step in this closure fails, and `prlimit64`/`setrlimit`
2598            // plus `write` are all already in `SECCOMP_SYSCALL_ALLOWLIST` either way.
2599            if let Err(error) =
2600                crate::resources::apply_hard_rlimits(&resource_limits, nproc_baseline)
2601            {
2602                linux_enforce::write_diagnostic(diag_write.as_raw_fd(), &error.to_string());
2603                return Err(error);
2604            }
2605            if let Some(scope) = cgroup_scope.as_ref() {
2606                if let Err(error) = scope.join_current_process() {
2607                    linux_enforce::write_diagnostic(diag_write.as_raw_fd(), &error.to_string());
2608                    return Err(error);
2609                }
2610            }
2611
2612            let sock_fd = child_sock.as_raw_fd();
2613            match linux_enforce::child_install_enforcement(
2614                tier,
2615                &netns_plan,
2616                sealed_spec.as_ref(),
2617                landlock_fds.as_ref(),
2618                sock_fd,
2619                unix_sockets_allowed,
2620            ) {
2621                Ok(()) => Ok(()),
2622                Err(error) => {
2623                    linux_enforce::write_diagnostic(diag_write.as_raw_fd(), &error.to_string());
2624                    Err(error)
2625                }
2626            }
2627        });
2628    }
2629
2630    // Start the namespace-socket receiving thread now — BEFORE the caller calls `.spawn()`. See
2631    // `SupervisorHandle`'s doc comment for why this ordering (not "after spawn") is required.
2632    Ok(linux_enforce::start_supervisor(
2633        parent_sock,
2634        egress_policy,
2635        expected_namespace_sockets,
2636        diag_read,
2637    ))
2638}
2639
2640/// Which fixed device set Landlock grants, keyed on the tier.
2641///
2642/// Landlock keeps mediating inside a composed root, so the two device *lists* have to agree: a
2643/// device present in the sealed `/dev` but absent from the Landlock rules would exist and be
2644/// unopenable, which reads as a runtime bug rather than as policy. `KernelFull` keeps
2645/// [`CAPSULE_DEVICE_GRANTS`], which services `scoped`, while `KernelSealed` derives its own from
2646/// [`crate::sealed::SEALED_DEVICE_NODES`], the same list the private `/dev` tmpfs is built from.
2647///
2648/// The parent opens these paths on the *host*, before the namespace exists; because the composed
2649/// root bind-mounts the host's own nodes rather than creating new ones, the inodes the rules name
2650/// are the inodes the capsule reaches.
2651#[cfg(target_os = "linux")]
2652fn landlock_device_grants(tier: EnforcementTier) -> Vec<CapsuleDeviceGrant> {
2653    match tier {
2654        EnforcementTier::KernelSealed => crate::sealed::SEALED_DEVICE_NODES
2655            .iter()
2656            .map(|device| CapsuleDeviceGrant {
2657                path: device.path,
2658                writable: device.writable,
2659            })
2660            .collect(),
2661        _ => CAPSULE_DEVICE_GRANTS.to_vec(),
2662    }
2663}
2664
2665/// Creates (idempotently) the directory inside the session workdir that backs `/tmp` in the
2666/// composed root, returning its host path.
2667///
2668/// Two callers need it and neither may assume the other ran first: `build_sealed_root` binds it at
2669/// `/tmp`, and `open_landlock_fds` opens it to give that bind a Landlock rule. They are called in
2670/// that reverse order by `prepare_enforcement` today, so the creation lives here rather than in
2671/// either of them — one `create_dir_all`, one message, no ordering dependency between the two.
2672/// See [`crate::sealed::SEALED_TMP_DIR_NAME`] for why `/tmp` is workdir-backed rather than a second
2673/// tmpfs.
2674#[cfg(target_os = "linux")]
2675fn ensure_sealed_tmp_store(session_workdir: &Path) -> Result<PathBuf, String> {
2676    let tmp_store = session_workdir.join(crate::sealed::SEALED_TMP_DIR_NAME);
2677    std::fs::create_dir_all(&tmp_store).map_err(|error| {
2678        format!(
2679            "sealed: failed to create the workdir-backed /tmp store at {}: {error}",
2680            tmp_store.display()
2681        )
2682    })?;
2683    Ok(tmp_store)
2684}
2685
2686/// Writes (idempotently) the synthetic `/etc/passwd`/`/etc/group` the composed root binds in place
2687/// of the host's, returning their host paths in [`crate::sealed::SEALED_ETC_PATHS`] order.
2688///
2689/// Sibling of [`ensure_sealed_tmp_store`] in every respect that matters: plain `std::fs`, no
2690/// privilege, and two callers in different phases that must not depend on each other's ordering —
2691/// `build_sealed_root` binds these files, `open_landlock_fds` opens them to grant them. Content is
2692/// a pure function of the workdir, so both calls write the same bytes.
2693///
2694/// Runs in the parent, never in `pre_exec`: composing a root is the child's job, but *producing
2695/// content* is work the parent can do, and this module's rule is that the `pre_exec` window does
2696/// nothing the parent could have done for it.
2697///
2698/// The rewrite is deliberately in place (`fs::write` truncates; it does not replace). The Landlock
2699/// rule the earlier caller took is bound to the file's inode, so writing a fresh file over the path
2700/// would leave that rule pointing at an inode the composed root no longer binds — `/etc/passwd`
2701/// mounted and `EACCES`.
2702#[cfg(target_os = "linux")]
2703fn ensure_sealed_identity_files(session_workdir: &Path) -> Result<Vec<PathBuf>, String> {
2704    use std::os::unix::fs::MetadataExt;
2705
2706    let staging = session_workdir.join(crate::sealed::SEALED_ETC_STAGING_DIR_NAME);
2707    std::fs::create_dir_all(&staging).map_err(|error| {
2708        format!(
2709            "sealed: failed to create the synthetic /etc staging directory at {}: {error}",
2710            staging.display()
2711        )
2712    })?;
2713
2714    // The workdir was created by this process, so its owner is the identity the capsule's
2715    // subprocesses run as — no `getuid(2)` FFI needed under `#![deny(unsafe_code)]`.
2716    let owner = std::fs::metadata(session_workdir).map_err(|error| {
2717        format!(
2718            "sealed: failed to stat the session workdir {} for the capsule's uid/gid: {error}",
2719            session_workdir.display()
2720        )
2721    })?;
2722    // The same string `build_shell_env` puts in `$HOME`, from the same constant, resolved against
2723    // the same directory: the synthetic home lives in the session workdir, so a `pw_dir` composed
2724    // against the accessible one would name a directory that does not exist.
2725    let home = session_workdir.join(crate::shell::SYNTHETIC_HOME_DIR_NAME);
2726    let home = home.to_string_lossy().into_owned();
2727    let identity = crate::sealed::SealedAccountIdentity {
2728        uid: owner.uid(),
2729        gid: owner.gid(),
2730        home: &home,
2731    };
2732
2733    let mut written = Vec::new();
2734    for entry in crate::sealed::SEALED_ETC_PATHS {
2735        let Some(file) = entry.synthetic else {
2736            continue;
2737        };
2738        let path = crate::sealed::synthetic_etc_source(session_workdir, file);
2739        std::fs::write(&path, file.render(&identity)?).map_err(|error| {
2740            format!(
2741                "sealed: failed to write the synthetic {} at {}: {error}",
2742                entry.path,
2743                path.display()
2744            )
2745        })?;
2746        written.push(path);
2747    }
2748    Ok(written)
2749}
2750
2751/// Parent-side half of the sealed mechanism: pick a base, plan the composed root against the real
2752/// host layout, create the workdir-backed `/tmp` store, and lower the plan into the C-string form
2753/// the forked child executes.
2754///
2755/// Every failure here is synchronous and named, before `.spawn()` is called at all — the same
2756/// reason `open_landlock_fds` moved its `open()` calls out of `pre_exec`. A capsule that reaches
2757/// this point has already cleared `check_containment_floor`, so a failure here is a genuine
2758/// host-state surprise (an unwritable workdir, a host with none of the base candidates), not a
2759/// declared-vs-achieved mismatch.
2760///
2761/// `staged_runtime_read_only` is passed straight through to the planner rather than validated
2762/// here. A missing `source_path` is *not* diagnosed in this function on purpose: a parent-side
2763/// error would return `Err(String)`, which converts to the ordinary, retryable
2764/// `ShellExecError::Failed`. Letting the required bind fail at `mount(2)` in the child instead
2765/// routes it to the session-fatal `SealedRootConstructionFailed` (`E-RUN-014`) — the correct
2766/// classification for a capsule that did not get a runtime tree it declared.
2767#[cfg(target_os = "linux")]
2768fn build_sealed_root(
2769    accessible_workdir: &Path,
2770    session_workdir: &Path,
2771    extra_read_only: &[PathBuf],
2772    staged_runtime_read_only: &[PathBuf],
2773) -> Result<crate::sealed::SealedRootSpec, String> {
2774    use crate::sealed;
2775
2776    // The workdir must be absolute for its path to mean the same thing inside the composed root,
2777    // and `launch_session` always creates it as one — but the composed root's whole design rests
2778    // on it, so it is checked rather than assumed.
2779    if !accessible_workdir.is_absolute() {
2780        return Err(format!(
2781            "sealed: capsule workdir {} is not absolute; a composed root reproduces the workdir at \
2782             its own absolute path",
2783            accessible_workdir.display()
2784        ));
2785    }
2786
2787    let base = sealed::choose_root_base(
2788        accessible_workdir,
2789        sealed::SEALED_ROOT_BASE_CANDIDATES,
2790        |path| path.is_dir(),
2791    )
2792    .ok_or_else(|| {
2793        format!(
2794            "sealed: no usable base directory for the composed root; none of {:?} exists outside \
2795             the session workdir's own path",
2796            sealed::SEALED_ROOT_BASE_CANDIDATES
2797        )
2798    })?;
2799
2800    // `/tmp` inside the composed root is backed by this directory, so it is created here rather
2801    // than from inside `pre_exec`. `open_landlock_fds` — which runs earlier and must open the same
2802    // directory to grant it — creates it through the same idempotent helper.
2803    ensure_sealed_tmp_store(session_workdir)?;
2804
2805    // `/etc/passwd` and `/etc/group` inside the composed root are binds of these files, so they
2806    // exist on disk before the plan that names them is built — and long before the child executes
2807    // it. Same idempotent helper `open_landlock_fds` called earlier to grant them.
2808    ensure_sealed_identity_files(session_workdir)?;
2809
2810    let plan = sealed::plan_composed_root(
2811        accessible_workdir,
2812        session_workdir,
2813        &base,
2814        extra_read_only,
2815        staged_runtime_read_only,
2816        &sealed::RealHostLayout,
2817    );
2818    sealed::build_sealed_root_spec(&plan)
2819}
2820
2821/// Linux-only mechanics: fd-passing side channel, seccomp filter construction, Landlock
2822/// application, and the background thread that receives the capsule's network-namespace sockets.
2823///
2824/// Nothing here uses `libseccomp`'s notify facility. `connect`/`sendto` are enforced by the
2825/// network namespace and `execve`/`execveat` by Landlock `Execute` rights, both of which decide
2826/// from kernel-held state. A `Notify` rule would reintroduce a `/proc/<pid>/mem` read on the hot
2827/// path, where the value read can change between the decision and the kernel's own dereference.
2828#[cfg_attr(target_os = "linux", allow(unsafe_code))]
2829#[cfg(target_os = "linux")]
2830mod linux_enforce {
2831    use std::io;
2832    use std::os::fd::{AsFd, AsRawFd, OwnedFd, RawFd};
2833    use std::path::Path;
2834
2835    use landlock::{make_bitflags, AccessFs, BitFlags};
2836
2837    use super::{EnforcementTier, LandlockGrant, SupervisorHandle};
2838
2839    /// Longest diagnostic message written to (or read from) the child-failure pipe. A message
2840    /// naming the failed step is far shorter than this; the bound just keeps the best-effort
2841    /// `write`/`read` loops trivially terminating.
2842    const MAX_DIAG_LEN: usize = 1024;
2843
2844    /// One Landlock grant path, opened (`O_PATH | O_CLOEXEC`) in the PARENT before fork(), paired
2845    /// with the two bits that decide its rule's access set: `list_dir` (`ReadDir`) and
2846    /// `executable` (`Execute`). Only the already-open fd crosses into the child's `pre_exec` —
2847    /// never a path to re-open there.
2848    pub(super) struct OpenLandlockGrant {
2849        fd: OwnedFd,
2850        list_dir: bool,
2851        executable: bool,
2852    }
2853
2854    /// One entry of [`CAPSULE_DEVICE_GRANTS`], opened (`O_PATH | O_CLOEXEC`) in the PARENT before
2855    /// fork(), paired with the `writable` bit that decides whether its rule carries `WriteFile` on
2856    /// top of `ReadFile`. Structurally a sibling of [`OpenLandlockGrant`] rather than the same
2857    /// type, mirroring the split between [`CapsuleDeviceGrant`](super::CapsuleDeviceGrant) and
2858    /// [`LandlockGrant`]: read+execute-a-binary and read/write-a-device are different intents and
2859    /// their bits must not be confusable.
2860    pub(super) struct OpenDeviceGrant {
2861        fd: OwnedFd,
2862        writable: bool,
2863    }
2864
2865    /// All Landlock file descriptors resolved in the parent for one shell subprocess: the
2866    /// workdir's fd (scoped by [`workdir_access_rights`]), the workdir-backed `/tmp` store's fd on
2867    /// `KernelSealed`, each successfully-opened grant fd, and each successfully-opened fixed-device
2868    /// fd.
2869    /// Handed by reference into the child's `pre_exec`, where `apply_landlock_scope` builds rules
2870    /// against these fds without performing a single `open()`.
2871    pub(super) struct LandlockChildFds {
2872        workdir_fd: OwnedFd,
2873        /// The capsule's `capabilities.filesystem.workdir_exec`, carried alongside the fd it
2874        /// applies to so `apply_landlock_scope` — which runs in `pre_exec` and must read nothing
2875        /// but its argument — has the whole workdir rule decided for it before fork.
2876        workdir_exec: bool,
2877        /// `<workdir>/.mur-tmp` — the directory `plan_composed_root` bind-mounts at `/tmp` inside
2878        /// the composed root — opened on `KernelSealed` and `None` on every other tier, which has
2879        /// no composed root and therefore no such bind.
2880        ///
2881        /// It needs an fd of its own even though it lives *inside* the workdir: Landlock resolves a
2882        /// path by walking dentries up to each mount root, so an access to `/tmp/x` inside the root
2883        /// is matched against the `.mur-tmp` inode (the bind's root) and then against the composed
2884        /// root's own `/tmp` mountpoint — never against the workdir inode. The workdir's rule
2885        /// therefore does not reach the bind, and without this fd every `/tmp` access is `EACCES`
2886        /// on a mount that is genuinely writable.
2887        sealed_tmp_fd: Option<OwnedFd>,
2888        /// The parent-written synthetic `/etc/passwd`/`/etc/group`
2889        /// ([`crate::sealed::SEALED_ETC_STAGING_DIR_NAME`]), opened on `KernelSealed` and empty on
2890        /// every other tier.
2891        ///
2892        /// Exactly the [`Self::sealed_tmp_fd`] problem, one directory over. The grant list already
2893        /// carries `/etc/passwd`, but that rule is taken on the fd opened at the *host's*
2894        /// `/etc/passwd` — a different inode from the file the composed root actually binds there.
2895        /// Landlock matches inodes, not path strings, and the walk from a bind-mounted file starts
2896        /// at the bound file's own inode, so without these fds both account databases would be
2897        /// mounted and `EACCES`: `getpwuid(3)` fails, and a shell cannot expand `~`.
2898        ///
2899        /// Read-only, like every other `SEALED_ETC_PATHS` rule — the mount is `MS_RDONLY` too, and
2900        /// nothing inside a capsule has any business editing an account database.
2901        sealed_identity_fds: Vec<OwnedFd>,
2902        grants: Vec<OpenLandlockGrant>,
2903        devices: Vec<OpenDeviceGrant>,
2904    }
2905
2906    impl LandlockChildFds {
2907        /// The workdir-backed `/tmp` fd, for the tier-gate test. Keeps the struct's fields private
2908        /// like every other one: nothing outside `apply_landlock_scope` needs the fd itself.
2909        #[cfg(test)]
2910        pub(super) fn sealed_tmp_fd(&self) -> Option<&OwnedFd> {
2911            self.sealed_tmp_fd.as_ref()
2912        }
2913
2914        /// How many synthetic-`/etc` fds were opened, for the tier-gate test. A count, not the fds:
2915        /// the same "nothing outside `apply_landlock_scope` needs the fd itself" rule as above.
2916        #[cfg(test)]
2917        pub(super) fn sealed_identity_fd_count(&self) -> usize {
2918            self.sealed_identity_fds.len()
2919        }
2920    }
2921
2922    /// The Landlock ABI v1 rights granted on the capsule **workdir's own** `PathBeneath` rule,
2923    /// *excluding* `Execute` — see [`workdir_access_rights`], which adds it back for a capsule that
2924    /// declared `capabilities.filesystem.workdir_exec: true`.
2925    ///
2926    /// Spelled out variant by variant rather than `AccessFs::from_all(ABI::V1)` for two reasons:
2927    /// `from_all` hides what is actually handed to the capsule, and four of ABI v1's thirteen
2928    /// rights are withheld from this constant.
2929    ///
2930    ///   - `Execute` — the one this constant withholds *conditionally*. Withholding it is what
2931    ///     makes `capabilities.shell.allow` a complete, sound statement: Landlock refuses the exec
2932    ///     on the path the kernel itself resolved, so a binary the capsule wrote into its workdir
2933    ///     cannot run under any name — including an allowlisted basename, the exact bypass a prior
2934    ///     release shipped. The cost: a binary the capsule legitimately compiled in its workdir
2935    ///     cannot run either, which is what `workdir_exec: true` buys back.
2936    ///   - `MakeChar` / `MakeBlock` — creating a device node inside the workdir escapes this
2937    ///     whole scope. A capsule running as root could `mknod` a node for the host's own disk
2938    ///     (e.g. major/minor `8:0` = `sda`) *inside* the granted directory — which Landlock
2939    ///     permits, because the new inode lives beneath a granted path — then `open()` it and
2940    ///     read the raw host filesystem underneath every other restriction. No known workload
2941    ///     creates device nodes in its working tree.
2942    ///   - `MakeSock` — binding an `AF_UNIX` socket file. Withheld by the same rule (no
2943    ///     filesystem object with a kernel-side identity beyond a regular file), but unlike the
2944    ///     two device rights this one is a genuine open question: some build tooling and some
2945    ///     language-toolchain daemons `bind()` a unix socket in their working tree, and a fix
2946    ///     that breaks those is not a fix. The manual acceptance procedure in
2947    ///     `docs/content/reference/workdir-device-node-manual-verification.md` carries an
2948    ///     explicit unix-socket scenario for exactly this; if the team's
2949    ///     real-hardware run finds a workload that needs it, add `MakeSock` back to this list.
2950    ///
2951    /// `MakeFifo` stays granted: real build tooling does create named pipes in its working tree,
2952    /// and a FIFO carries none of the raw-device risk above.
2953    ///
2954    /// Because `apply_landlock_scope`'s `handle_access` still declares the *full*
2955    /// `from_all(ABI::V1)` set, a right this rule withholds is not merely "not extra-granted" — it
2956    /// is **denied on every path this rule covers**, workdir included, once `restrict_self()` takes
2957    /// effect — so withholding `Execute` here is enforcement, not a mere omission. The three
2958    /// `Make*` rights are denied domain-wide because no other rule grants them either; `Execute`
2959    /// is denied *on the workdir specifically*, while the narrow read+execute grants below still
2960    /// carry it for the allowlisted binaries outside it: exec where the operator named a binary,
2961    /// nowhere the capsule writes.
2962    pub(super) const WORKDIR_ACCESS_RIGHTS_NO_EXEC: BitFlags<AccessFs> = make_bitflags!(AccessFs::{
2963        WriteFile
2964            | ReadFile
2965            | ReadDir
2966            | RemoveDir
2967            | RemoveFile
2968            | MakeDir
2969            | MakeReg
2970            | MakeFifo
2971            | MakeSym
2972    });
2973
2974    /// The workdir's `PathBeneath` rights for one capsule: [`WORKDIR_ACCESS_RIGHTS_NO_EXEC`], plus
2975    /// `Execute` only when the manifest declared `capabilities.filesystem.workdir_exec: true`.
2976    ///
2977    /// A function rather than a second constant so the two cases cannot drift: adding a right to
2978    /// the workdir grant is one edit, and the `workdir_exec` axis stays exactly one bit wide.
2979    /// Note what this does *not* consult — `shell.allow`, the exec allowlist, any resolved path.
2980    /// The whole point of the default is that the workdir grant is no longer name-based at all.
2981    pub(super) fn workdir_access_rights(workdir_exec: bool) -> BitFlags<AccessFs> {
2982        if workdir_exec {
2983            WORKDIR_ACCESS_RIGHTS_NO_EXEC | AccessFs::Execute
2984        } else {
2985            WORKDIR_ACCESS_RIGHTS_NO_EXEC
2986        }
2987    }
2988
2989    /// Probes real Landlock support by building a ruleset granting full access to `/` and
2990    /// calling `restrict_self()` **in a forked child**, so the host process is never placed
2991    /// into a Landlock domain by a mere capability check.
2992    ///
2993    /// Forking is required, not defensive. The rights the ruleset grants are beside the point:
2994    /// entering *any* Landlock domain — even one permitting everything — permanently forbids the
2995    /// mount family to the task and every descendant it will ever have, which is how Landlock
2996    /// stops a sandbox being escaped through a nested namespace. [`HostProbe::probe`] runs this
2997    /// before the sealed probe, and a session's probe is taken before any fork that would
2998    /// build a composed root, so restricting in-process poisons `sealed` on every host and every
2999    /// invocation: the namespace is created and then `mount` is refused, with nothing in the error
3000    /// to suggest the runtime did it to itself.
3001    ///
3002    /// The ruleset is built in the parent because creating one and adding rules restricts
3003    /// nothing; only `restrict_self` applies it. That keeps everything the child does after
3004    /// the fork down to a `prctl` and one syscall.
3005    pub(super) fn probe_landlock_full_access() -> Option<bool> {
3006        use landlock::{
3007            Access, AccessFs, CompatLevel, Compatible, PathBeneath, PathFd, Ruleset, RulesetAttr,
3008            RulesetCreatedAttr, RulesetStatus, ABI,
3009        };
3010
3011        // The child reports which of the three outcomes it reached through its exit status;
3012        // nothing else crosses the fork.
3013        const PROBE_FULLY_ENFORCED: i32 = 0;
3014        const PROBE_PARTIAL: i32 = 1;
3015        const PROBE_FAILED: i32 = 2;
3016
3017        let abi = ABI::V1;
3018        let access_all = AccessFs::from_all(abi);
3019
3020        let root_fd = PathFd::new("/").ok()?;
3021
3022        let ruleset = Ruleset::default()
3023            .set_compatibility(CompatLevel::BestEffort)
3024            .handle_access(access_all)
3025            .ok()?
3026            .create()
3027            .ok()?
3028            .add_rule(PathBeneath::new(root_fd, access_all))
3029            .ok()?;
3030
3031        // SAFETY: `fork()` from a possibly-multithreaded process is sound as long as the child
3032        // confines itself to async-signal-safe work. Everything this child does is the
3033        // `restrict_self` syscall pair and `_exit`; the allocating part of building the
3034        // ruleset already happened above, in the parent.
3035        let pid = unsafe { libc::fork() };
3036        if pid < 0 {
3037            return None;
3038        }
3039        if pid == 0 {
3040            let code = match ruleset.restrict_self() {
3041                Ok(status) => {
3042                    if matches!(status.ruleset, RulesetStatus::FullyEnforced) {
3043                        PROBE_FULLY_ENFORCED
3044                    } else {
3045                        PROBE_PARTIAL
3046                    }
3047                }
3048                Err(_) => PROBE_FAILED,
3049            };
3050            // SAFETY: forked-child context; `_exit` skips every destructor and atexit hook,
3051            // which is what keeps the parent's state untouched.
3052            unsafe { libc::_exit(code) }
3053        }
3054
3055        let mut wait_status: libc::c_int = 0;
3056        // SAFETY: `pid` is the child just forked; `wait_status` is a live local.
3057        let waited = unsafe { libc::waitpid(pid, &mut wait_status, 0) };
3058        if waited < 0 || !libc::WIFEXITED(wait_status) {
3059            return None;
3060        }
3061        match libc::WEXITSTATUS(wait_status) {
3062            PROBE_FULLY_ENFORCED => Some(true),
3063            PROBE_PARTIAL => Some(false),
3064            // A `restrict_self` that errored tells us nothing either way, which is the same
3065            // answer the pre-fork version gave by propagating `None` out of `.ok()?`.
3066            _ => None,
3067        }
3068    }
3069
3070    /// Runs inside the forked child, pre-exec: builds the capsule's network namespace and hands
3071    /// its listening sockets to the parent over `child_sock_fd`, strips the child's Linux
3072    /// capabilities, installs the seccomp filter (the `socket()` domain denials keyed on
3073    /// `unix_sockets_allowed`, over a default-deny syscall allowlist), and (on
3074    /// `KernelFull`/`KernelSealed`) applies the Landlock filesystem scope — which is also what
3075    /// enforces `capabilities.shell.allow`. Returning `Err` here aborts the exec (std's `Command`
3076    /// machinery propagates it back to the parent's `.spawn()` call as an `io::Error`) — the
3077    /// fail-closed path for setup failures that happen after fork.
3078    ///
3079    /// `child_sock_fd` carries exactly one hand-off: the namespace sockets.
3080    pub(super) fn child_install_enforcement(
3081        tier: EnforcementTier,
3082        netns_plan: &crate::network_namespace::CapsuleNetnsPlan,
3083        sealed_spec: Option<&crate::sealed::SealedRootSpec>,
3084        landlock_fds: Option<&LandlockChildFds>,
3085        child_sock_fd: RawFd,
3086        unix_sockets_allowed: bool,
3087    ) -> io::Result<()> {
3088        // FIRST, on every kernel tier: the capsule's own network namespace. It has to precede
3089        // everything below it for three separate reasons:
3090        //
3091        //   * `SECCOMP_MUST_STAY_DENIED` denies `unshare` and the filter installed further down
3092        //     denies `socket(AF_NETLINK)`, so this is the only window in which the namespace can
3093        //     be built at all — the same argument the composed root makes.
3094        //   * `drop_all_capabilities` (below) removes the `CAP_NET_ADMIN` that bringing `lo` up
3095        //     and installing the local route require. The namespace is configured while the child
3096        //     still holds them *inside its own new user namespace*, and never afterwards.
3097        //   * on `KernelSealed`, the composed root's own `unshare(CLONE_NEWUSER)` nests a second
3098        //     user namespace inside this one. A task in a descendant user namespace holds no
3099        //     capability in the ancestor, so once that has happened the capsule cannot reconfigure
3100        //     the network namespace it is confined to — which only holds if this runs first.
3101        //
3102        // This is what replaced the `connect`/`sendto` seccomp-notify interception. There is no
3103        // path that skips it and falls back: a host that cannot do this refused the launch back in
3104        // `stage_session` (`RuntimeError::EgressNamespaceUnavailable`, `E-CAP-005`).
3105        //
3106        // SAFETY: post-`fork()`, pre-exec child context — exactly the window this function
3107        // documents itself as running in, and the one `create_capsule_netns` requires.
3108        unsafe { crate::network_namespace::create_capsule_netns(netns_plan, child_sock_fd)? };
3109
3110        // NEXT, and only on `KernelSealed`: build the private mount namespace and pivot onto the
3111        // composed root. This has to precede every *remaining* step in this closure, because
3112        // `SECCOMP_MUST_STAY_DENIED` denies `unshare`, `mount` and `pivot_root` to every process
3113        // the filter below covers, permanently and deliberately.
3114        // The composed root is therefore built by this process while it still has its pre-filter
3115        // credentials, never by a syscall the sandboxed subprocess is later permitted to make.
3116        // The three steps that follow then run *inside* the new root: `drop_all_capabilities`
3117        // strips the (namespace-local) capabilities `unshare` handed out, seccomp installs, and
3118        // Landlock's rules — built from fds the parent opened, so unaffected by the pivot —
3119        // re-scope the same inodes under their new pathnames. Defence in depth, in that order.
3120        if tier == EnforcementTier::KernelSealed {
3121            if let Some(spec) = sealed_spec {
3122                #[cfg(test)]
3123                if super::FORCE_SEALED_ROOT_FAILURE.with(|flag| flag.get()) {
3124                    return Err(io::Error::other(format!(
3125                        "{} unshare(CLONE_NEWUSER|CLONE_NEWNS) failed (forced by test seam)",
3126                        crate::sealed::SEALED_ROOT_FAILURE_PREFIX
3127                    )));
3128                }
3129                crate::sealed::construct_composed_root(spec)
3130                    .map_err(|failure| io::Error::other(spec.describe(failure)))?;
3131            }
3132        }
3133
3134        // Before anything else in this window, on every kernel tier: shut the fd-inheritance
3135        // door. Landlock (KernelFull only) mediates *new* filesystem operations against the
3136        // ruleset installed further down this function — it can do nothing about a descriptor
3137        // the child already holds open at that point, because that fd was opened before the
3138        // ruleset existed and there is no operation left for the ruleset to intercept. Until
3139        // this call existed, the only thing stopping a spawned shell from inheriting an
3140        // arbitrary open fd was the empirical accident that nothing else happened to be open in
3141        // the runtime process at spawn time; one `open()` added anywhere before a spawn — a
3142        // config read, a lock file, a log handle — would have leaked silently into every
3143        // subsequent subprocess, on every platform and every tier, with no test to catch it.
3144        //
3145        // Running it first is also what makes it cover this function's *own* descriptors: the
3146        // namespace-socket socketpair end, the diagnostic pipe and the Landlock grant fds are all used
3147        // below but must never survive the `execve`.
3148        mark_inherited_fds_cloexec()?;
3149
3150        // Next, and on every kernel tier (not just `KernelFull`): Landlock and the Linux
3151        // capability model are independent, both-must-allow gates, so narrowing the Landlock
3152        // workdir grant does not by itself take `CAP_MKNOD` away from a root-uid capsule. This
3153        // must also run *before* `install_seccomp_filter`, because it is what sets
3154        // `no_new_privs` — which `seccomp(2)` requires once `CAP_SYS_ADMIN` is gone. Setting it
3155        // here (rather than depending on libseccomp's `SCMP_FLTATR_CTL_NNP` default) also means a
3156        // failure is its own distinct, fail-closed error path before any filter is installed.
3157        drop_all_capabilities()?;
3158
3159        // The child stays *non-dumpable*, inherited from the runtime process
3160        // (`security::harden_process_dumpable`). Nothing reads the child's memory, so nothing
3161        // needs it dumpable. Marking it dumpable opens same-uid `ptrace`, `environ` and core-dump
3162        // access for the whole life of every shell subprocess: do not do so without a reader that
3163        // requires it.
3164        install_seccomp_filter(unix_sockets_allowed)?;
3165
3166        if matches!(
3167            tier,
3168            EnforcementTier::KernelFull | EnforcementTier::KernelSealed
3169        ) {
3170            if let Some(fds) = landlock_fds {
3171                apply_landlock_scope(fds).map_err(io::Error::other)?;
3172            }
3173        }
3174
3175        Ok(())
3176    }
3177
3178    /// Marks every file descriptor at or above [`super::FD_HYGIENE_FIRST_FD`] close-on-exec, so
3179    /// the only descriptors that survive into the exec'd program are the ones the runtime
3180    /// deliberately set up (stdio) rather than whatever happened to be open.
3181    ///
3182    /// `CLOSE_RANGE_CLOEXEC` sets the flag rather than closing the descriptors outright. That is
3183    /// the required semantics here, not a softer variant of it: several fds in this range are
3184    /// still needed *inside* this `pre_exec` window — the socketpair end `create_capsule_netns`
3185    /// sends the namespace's listening sockets over, the diagnostic pipe a failure further down
3186    /// writes to, and the Landlock grant fds `apply_landlock_scope` builds rules
3187    /// from. Closing them here would break the very enforcement setup that follows; flagging
3188    /// them means they keep working until `execve`, which then closes them for us.
3189    ///
3190    /// The range starts at 3, never 0 — see [`super::FD_HYGIENE_FIRST_FD`] for the recorded
3191    /// stdio decision and its reasoning.
3192    ///
3193    /// **Kernel range narrowing:** `close_range(2)` landed in Linux 5.9 and
3194    /// `CLOSE_RANGE_CLOEXEC` in Linux 5.11. On an older kernel this call fails (`ENOSYS`, or
3195    /// `EINVAL` for the flag on 5.9/5.10), the error propagates, and `Command::spawn()` fails —
3196    /// so every shell spawn on a `KernelSeccompOnly` *or* `KernelFull` host with such a kernel
3197    /// now fails rather than silently running without fd hygiene. That is deliberate and it is
3198    /// this module's established fail-closed discipline (`drop_all_capabilities`,
3199    /// `install_seccomp_filter` and `apply_landlock_scope` all abort the spawn on an unexpected
3200    /// error rather than degrade), but it is a real, user-visible narrowing of the supported
3201    /// kernel range for kernel-enforcement tiers.
3202    pub(super) fn mark_inherited_fds_cloexec() -> io::Result<()> {
3203        // SAFETY: this issues the `close_range` syscall directly through `libc::syscall`. The
3204        // three variadic arguments are all `c_uint` scalars and the kernel dereferences none of
3205        // them. It is a single syscall, so it is safe to make in the post-fork/pre-exec window.
3206        // `c_uint::MAX` as the `last` argument is the documented "to the end of the table"
3207        // spelling from `close_range(2)`.
3208        let rc = unsafe {
3209            libc::syscall(
3210                libc::SYS_close_range,
3211                super::FD_HYGIENE_FIRST_FD,
3212                libc::c_uint::MAX,
3213                libc::CLOSE_RANGE_CLOEXEC,
3214            )
3215        };
3216        if rc != 0 {
3217            return Err(io::Error::last_os_error());
3218        }
3219        Ok(())
3220    }
3221
3222    /// Capability-version word for the 64-bit, two-`__u32`-word capability ABI
3223    /// (`_LINUX_CAPABILITY_VERSION_3`, Linux 2.6.26+). Passing it tells the kernel the
3224    /// `cap_user_data` argument is a **two element** array. The older version-1 word would cover
3225    /// only capabilities 0–31 and make the kernel log a deprecation warning.
3226    const LINUX_CAPABILITY_VERSION_3: u32 = 0x2008_0522;
3227
3228    /// Upper bound for the bounding-set loop when `/proc/sys/kernel/cap_last_cap` cannot be read.
3229    /// 63 is the architectural ceiling — `capset`'s two 32-bit words address exactly 64
3230    /// capabilities — so this can never under-cover. Numbers the running kernel does not define
3231    /// return `EINVAL`, which the loop skips.
3232    const CAP_LAST_CAP_FALLBACK: u32 = 63;
3233
3234    /// `cap_user_header_t` from `<linux/capability.h>`. `libc` 0.2 exposes `SYS_capset` but
3235    /// neither this struct, its data counterpart, nor a safe `capset()` wrapper — so both are
3236    /// hand-rolled here, for the same reason `send_fd_over_socket` hand-rolls its
3237    /// `msghdr`/`cmsghdr` handling.
3238    ///
3239    /// `dead_code` is allowed because the kernel reads these fields through the raw pointer
3240    /// handed to `capset(2)`; Rust itself only ever writes them.
3241    #[repr(C)]
3242    #[allow(dead_code)]
3243    struct CapUserHeader {
3244        version: u32,
3245        pid: libc::c_int,
3246    }
3247
3248    /// One word of `cap_user_data_t` from `<linux/capability.h>`. Under
3249    /// [`LINUX_CAPABILITY_VERSION_3`] the kernel expects an array of exactly two of these: word 0
3250    /// carries capabilities 0–31, word 1 carries 32–63. See [`CapUserHeader`] for the `dead_code`
3251    /// note.
3252    #[repr(C)]
3253    #[derive(Clone, Copy)]
3254    #[allow(dead_code)]
3255    struct CapUserData {
3256        effective: u32,
3257        permitted: u32,
3258        inheritable: u32,
3259    }
3260
3261    /// Strips every Linux capability from the forked child before `execve()`, in three steps
3262    /// whose **order matters**:
3263    ///
3264    ///   1. drop the whole capability **bounding set** (`PR_CAPBSET_DROP`) — while this process
3265    ///      still holds `CAP_SETPCAP` in its *effective* set, because that is exactly what
3266    ///      `PR_CAPBSET_DROP` checks (`capabilities(7)`, `prctl(2)`).
3267    ///   2. clear this process's own permitted/effective/inheritable sets via `capset(2)`.
3268    ///      Shrinking your own permitted set to any subset — including empty — never requires
3269    ///      `CAP_SETPCAP`, so running it after step 1 costs nothing. Clearing permitted and
3270    ///      inheritable also empties the *ambient* set, which the kernel maintains as a subset of
3271    ///      both — that is what covers a non-root capsule handed an unexpected ambient
3272    ///      `CAP_MKNOD` (e.g. a systemd unit with `AmbientCapabilities=`).
3273    ///   3. set `no_new_privs`, so `execve()` cannot regain privilege through a set-user-ID or
3274    ///      file-capability binary, and so the seccomp filter installed next can load without
3275    ///      `CAP_SYS_ADMIN` (which step 2 just removed). Setting it here explicitly means this no
3276    ///      longer depends on libseccomp's default `SCMP_FLTATR_CTL_NNP` attribute having set it
3277    ///      as a side effect.
3278    ///
3279    /// **Why steps 1 and 2 are in this order** (it is the reverse of the obvious "clear my sets,
3280    /// then clear the bounding set"): `PR_CAPBSET_DROP` requires `CAP_SETPCAP` in the *effective*
3281    /// set of the caller. Clearing effective first would strip `CAP_SETPCAP`, after which every
3282    /// `PR_CAPBSET_DROP` returns `EPERM` — and because `EPERM` is (correctly) non-fatal for a
3283    /// genuinely unprivileged caller, the bounding set would silently survive while this function
3284    /// still reported success.
3285    ///
3286    /// **Why the bounding set is the load-bearing step for a root-uid capsule:** `execve(2)`'s
3287    /// capability transition treats a file's permitted set as all-ones when the process's real
3288    /// uid is 0, so the new program's permitted set comes out as `P(bounding)`. Step 2 alone
3289    /// would be undone by the very next `execve`; emptying the bounding set is what makes the
3290    /// post-exec permitted (and hence effective) set empty, which is what actually takes
3291    /// `CAP_MKNOD` away from the shell.
3292    ///
3293    /// Note this also removes `CAP_DAC_OVERRIDE` from a root-run capsule's shell subprocess, so
3294    /// it no longer bypasses ordinary file-permission checks. That is intended — least privilege
3295    /// — and strictly narrows what the subprocess can reach.
3296    fn drop_all_capabilities() -> io::Result<()> {
3297        drop_capability_bounding_set()?;
3298        clear_capability_sets()?;
3299        set_no_new_privs()
3300    }
3301
3302    /// Step 1 of [`drop_all_capabilities`]. Two errnos are expected and skipped:
3303    ///
3304    ///   - `EINVAL` — `cap` is not a capability this kernel defines, so there is nothing to drop.
3305    ///   - `EPERM` — the caller holds no `CAP_SETPCAP`, i.e. it is a genuinely unprivileged
3306    ///     process that never held the capability being dropped either. Hard-failing here would
3307    ///     break every non-root `mur run`.
3308    ///
3309    /// Any other errno is unexpected and propagates, aborting the exec — this module's
3310    /// fail-closed invariant: no silently-unenforced spawn.
3311    #[allow(unsafe_code)]
3312    fn drop_capability_bounding_set() -> io::Result<()> {
3313        let zero: libc::c_ulong = 0;
3314
3315        for cap in 0..=kernel_last_cap() {
3316            let cap_arg = libc::c_ulong::from(cap);
3317            // SAFETY: `prctl(PR_CAPBSET_DROP, ...)` takes an integer capability number and three
3318            // ignored arguments — no pointers and no borrowed memory are involved.
3319            let rc = unsafe { libc::prctl(libc::PR_CAPBSET_DROP, cap_arg, zero, zero, zero) };
3320            if rc == 0 {
3321                continue;
3322            }
3323
3324            let error = io::Error::last_os_error();
3325            match error.raw_os_error() {
3326                Some(libc::EINVAL) | Some(libc::EPERM) => continue,
3327                _ => return Err(error),
3328            }
3329        }
3330
3331        Ok(())
3332    }
3333
3334    /// Step 2 of [`drop_all_capabilities`]. Always expected to succeed: the kernel's `capset`
3335    /// checks are all "is the new set a subset of the old one", and the empty set is a subset of
3336    /// everything. Any error is therefore unexpected and fails closed.
3337    #[allow(unsafe_code)]
3338    fn clear_capability_sets() -> io::Result<()> {
3339        let header = CapUserHeader {
3340            version: LINUX_CAPABILITY_VERSION_3,
3341            // 0 means "the calling thread" — the only pid `capset` accepts for a capability
3342            // change since Linux 2.6.25.
3343            pid: 0,
3344        };
3345        let data = [CapUserData {
3346            effective: 0,
3347            permitted: 0,
3348            inheritable: 0,
3349        }; 2];
3350
3351        // SAFETY: both pointers refer to stack locals that outlive this single `capset` call, and
3352        // `data` is exactly the two-element array `LINUX_CAPABILITY_VERSION_3` makes the kernel
3353        // expect. The kernel only reads through them.
3354        let rc = unsafe {
3355            libc::syscall(
3356                libc::SYS_capset,
3357                &header as *const CapUserHeader,
3358                data.as_ptr(),
3359            )
3360        };
3361        if rc != 0 {
3362            return Err(io::Error::last_os_error());
3363        }
3364
3365        Ok(())
3366    }
3367
3368    /// Step 3 of [`drop_all_capabilities`]. Setting `no_new_privs` can only ever *reduce* a
3369    /// process's privilege and is never refused for a well-formed call, so any error is
3370    /// unexpected and fails closed. Same call convention and fail-closed style as
3371    /// `security::harden_process_dumpable`'s `PR_SET_DUMPABLE` `prctl`, but a different call site
3372    /// and lifetime: this is per-shell-subprocess, inside `pre_exec`, not the once-at-`main()`
3373    /// whole-process hardening.
3374    #[allow(unsafe_code)]
3375    fn set_no_new_privs() -> io::Result<()> {
3376        #[cfg(test)]
3377        if super::FORCE_NO_NEW_PRIVS_FAILURE.with(|flag| flag.get()) {
3378            return Err(io::Error::other(
3379                "sandbox: no_new_privs (prctl PR_SET_NO_NEW_PRIVS, 1) failed (forced by test seam)",
3380            ));
3381        }
3382        // The kernel rejects `PR_SET_NO_NEW_PRIVS` unless arg2 is exactly 1 and arg3/4/5 are
3383        // exactly 0, so these are typed as `c_ulong` rather than left as untyped literals whose
3384        // upper 32 bits would be unspecified in a variadic call on aarch64.
3385        let enable: libc::c_ulong = 1;
3386        let zero: libc::c_ulong = 0;
3387
3388        // SAFETY: `prctl(PR_SET_NO_NEW_PRIVS, ...)` takes four integer arguments — no pointers
3389        // and no borrowed memory are involved.
3390        let rc = unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, enable, zero, zero, zero) };
3391        if rc != 0 {
3392            return Err(io::Error::last_os_error());
3393        }
3394
3395        Ok(())
3396    }
3397
3398    /// Highest capability number this kernel defines, read from `/proc/sys/kernel/cap_last_cap`.
3399    /// Uses raw `open`/`read` into a stack buffer so it stays allocation-free in the post-`fork()`
3400    /// window. Any failure — file absent on a pre-2.6.25 kernel, unreadable, contents that do not
3401    /// parse — falls back to [`CAP_LAST_CAP_FALLBACK`], which over-covers rather than
3402    /// under-covers, since undefined capability numbers just return the `EINVAL` the caller skips.
3403    #[allow(unsafe_code)]
3404    fn kernel_last_cap() -> u32 {
3405        const PATH: &[u8] = b"/proc/sys/kernel/cap_last_cap\0";
3406
3407        // SAFETY: `PATH` is a NUL-terminated byte literal with `'static` lifetime, and `open`
3408        // only reads through the pointer.
3409        let fd = unsafe {
3410            libc::open(
3411                PATH.as_ptr() as *const libc::c_char,
3412                libc::O_RDONLY | libc::O_CLOEXEC,
3413            )
3414        };
3415        if fd < 0 {
3416            return CAP_LAST_CAP_FALLBACK;
3417        }
3418
3419        let mut buf = [0u8; 16];
3420        // SAFETY: `fd` was just opened successfully; `buf` is a stack array and its exact length
3421        // is passed, so `read` cannot write past it.
3422        let read = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut libc::c_void, buf.len()) };
3423        // SAFETY: `fd` is open and exclusively owned here; nothing else holds or will reuse it.
3424        unsafe { libc::close(fd) };
3425
3426        if read <= 0 {
3427            return CAP_LAST_CAP_FALLBACK;
3428        }
3429
3430        let parsed = std::str::from_utf8(&buf[..read as usize])
3431            .ok()
3432            .and_then(|text| text.trim().parse::<u32>().ok());
3433
3434        match parsed {
3435            Some(last) if last <= CAP_LAST_CAP_FALLBACK => last,
3436            _ => CAP_LAST_CAP_FALLBACK,
3437        }
3438    }
3439
3440    /// The Landlock syscalls the child still has to make after its seccomp filter is loaded, each
3441    /// with the syscall number to fall back on when this host's libseccomp is too old to resolve
3442    /// the name (they were added in libseccomp 2.5.4; Ubuntu 22.04 ships 2.5.3 on a kernel that
3443    /// does support Landlock, so this is a real combination, not a hypothetical one).
3444    ///
3445    /// Linux assigned these numbers uniformly across architectures in 5.13 — 444/445/446 on
3446    /// x86_64, aarch64 and every other arch with Landlock — so a single number per name is
3447    /// correct for all of them, unlike the legacy syscalls where numbers diverge per arch.
3448    const LANDLOCK_SYSCALLS: [(&str, i32); 3] = [
3449        ("landlock_create_ruleset", 444),
3450        ("landlock_add_rule", 445),
3451        ("landlock_restrict_self", 446),
3452    ];
3453
3454    /// Builds the child's seccomp filter and returns it unloaded, so that the same construction
3455    /// the spawn path uses can also be measured. [`install_seccomp_filter`] is the only caller
3456    /// that loads it; the measurement of what it compiles to, the kernel ceilings that number is
3457    /// held against and the headroom between them are recorded in
3458    /// `docs/content/reference/seccomp-filter-instruction-budget.md`.
3459    ///
3460    /// **This filter raises no notifications and needs no supervisor.** Network enforcement lives
3461    /// in [`crate::network_namespace`] plus [`crate::egress_proxy`], and exec enforcement in the
3462    /// Landlock domain `apply_landlock_scope` installs — see this module's own header for why no
3463    /// `Notify` rule may come back.
3464    ///
3465    /// One mechanism plus a default:
3466    ///
3467    ///   - `socket` gets classic, register-value `Errno` rules, one per denied domain. `domain` is
3468    ///     a plain integer argument, so the comparison compiles straight into the loaded BPF
3469    ///     program and is evaluated in-kernel at syscall time: no notification is raised and no
3470    ///     memory of another task is read. That is what makes it structurally immune to the
3471    ///     pointer-read TOCTOU class of problem in the first place.
3472    ///   - the filter's **default action**, which is a deny (`Errno(EPERM)`): a syscall named by
3473    ///     neither [`super::SECCOMP_SYSCALL_ALLOWLIST`] nor a rule here is refused, without any
3474    ///     argument being inspected. That is what makes `io_uring_setup`, `bpf`, `userfaultfd`,
3475    ///     `perf_event_open`, `ptrace` and the rest of [`super::SECCOMP_MUST_STAY_DENIED`]
3476    ///     unreachable — they are simply absent, not argument-matched.
3477    fn build_seccomp_filter(
3478        unix_sockets_allowed: bool,
3479    ) -> io::Result<libseccomp::ScmpFilterContext> {
3480        // Default-deny. `EPERM` matches what the OCI/Docker default profile returns for a syscall
3481        // outside its allowlist, and is deliberately a *different* errno from the `EACCES` that the
3482        // `socket()` domain rules (and Landlock) return: `EACCES` means "the sandbox looked at this
3483        // call's arguments and refused it", `EPERM` means "this syscall is not part of the
3484        // capsule's syscall surface at all". Keeping them distinct is what lets an operator tell an
3485        // unmediated-surface problem from a policy decision.
3486        let mut filter =
3487            libseccomp::ScmpFilterContext::new(libseccomp::ScmpAction::Errno(libc::EPERM))
3488                .map_err(to_io_err)?;
3489
3490        // Ask the kernel to record every action this filter takes that is not `Allow` in the
3491        // audit trail, so a denial is attributable after the fact to a syscall number, pid and
3492        // comm. The denied process itself still observes nothing but `EPERM` — `SECCOMP_RET_ERRNO`
3493        // has no channel for anything richer — so this is the only way an operator debugging a
3494        // workload that dies on an unexpected denial gets a syscall name to look at.
3495        //
3496        // Best-effort on purpose, and the one place in this function where an error is swallowed:
3497        // `SCMP_FLTATR_CTL_LOG` needs libseccomp API level 3 (libseccomp 2.4.0+), and the crate
3498        // reports an older runtime library as an error here. That is a *diagnosability* shortfall,
3499        // not an enforcement one — the default-deny action and every rule below are unaffected —
3500        // and turning it into a hard failure would take a host with an old libseccomp from
3501        // "denials are logged less legibly" to "no capsule can spawn a shell at all".
3502        //
3503        // Setting the attribute is necessary but not sufficient: the kernel only logs an action
3504        // whose type also appears in `/proc/sys/kernel/seccomp/actions_logged`, which is host
3505        // configuration this process does not control.
3506        // `ESCAPE_CONFORMANCE_HARNESS.md` at the repository root carries the hand-run procedure
3507        // these denials are verified by.
3508        let _ = filter.set_ctl_log(true);
3509
3510        // Deny the dangerous `socket(2)` domains at creation time. `EACCES` (not `EPERM`) is the
3511        // errno this sandbox uses for "the sandbox looked at this call's arguments and refused it",
3512        // as opposed to the default action's `EPERM` for "this syscall is not part of the capsule's
3513        // surface at all". It also matches what Landlock returns for a denied exec, so a capsule
3514        // sees one consistent errno across both argument-level mechanisms.
3515        //
3516        // Untouched by the network-namespace work, and deliberately so: a network namespace does
3517        // not mediate `AF_UNIX` at all — pathname or abstract — so this register-level rule is
3518        // still the only thing standing between a capsule and `/var/run/docker.sock`.
3519        //
3520        // `add_rule_conditional` (not `..._exact`) on purpose: the non-exact form lets libseccomp
3521        // adapt the rule to the architectures in the filter — on an arch where `socket` is
3522        // reached through `socketcall(2)` rather than as its own syscall, the exact form would
3523        // fail the whole install instead. Fail-closed is preserved either way, since any error
3524        // here propagates out of `pre_exec` and aborts the spawn.
3525        //
3526        // One rule per domain rather than one rule with three comparators: comparators within a
3527        // single rule are AND-ed, and no `socket()` call has a `domain` that is simultaneously
3528        // `AF_UNIX` and `AF_NETLINK`, so a combined rule would match nothing.
3529        let socket_syscall = libseccomp::ScmpSyscall::from_name("socket").map_err(to_io_err)?;
3530        for domain in super::denied_socket_domains(unix_sockets_allowed) {
3531            filter
3532                .add_rule_conditional(
3533                    libseccomp::ScmpAction::Errno(libc::EACCES),
3534                    socket_syscall,
3535                    &[libseccomp::ScmpArgCompare::new(
3536                        0,
3537                        libseccomp::ScmpCompareOp::Equal,
3538                        domain as u64,
3539                    )],
3540                )
3541                .map_err(to_io_err)?;
3542        }
3543
3544        // The permitted domains need positive rules of their own now that the filter's default is
3545        // a deny — without them `socket()` would be refused for every family, IP included.
3546        //
3547        // Equality rules per allowed domain, and NOT one unconditional `Allow` rule for `socket`:
3548        // libseccomp resolves an unconditional rule for a syscall by *discarding* every
3549        // argument-conditional chain already recorded for it (`db.c`: "syscall exists with chains
3550        // but the new filter has no chains so the existing chains must be cleared"), so a broad
3551        // `Allow` here would silently delete the AF_UNIX/AF_NETLINK/AF_PACKET denials directly
3552        // above and reopen the `/var/run/docker.sock` path they exist to close. containerd's
3553        // default profile carries the same warning against combining a broad `socket` allow with
3554        // explicit errno rules, and works around it the same way — with argument-matched rules
3555        // only. The two domain sets are disjoint by construction (a test pins that), so no
3556        // `socket()` call can match both an allow and a deny rule.
3557        for domain in super::allowed_socket_domains(unix_sockets_allowed) {
3558            filter
3559                .add_rule_conditional(
3560                    libseccomp::ScmpAction::Allow,
3561                    socket_syscall,
3562                    &[libseccomp::ScmpArgCompare::new(
3563                        0,
3564                        libseccomp::ScmpCompareOp::Equal,
3565                        domain as u64,
3566                    )],
3567                )
3568                .map_err(to_io_err)?;
3569        }
3570
3571        // The allowlist proper. Two failure modes are both handled by skipping the name:
3572        //
3573        //   - `from_name` fails when this host's libseccomp does not know the syscall (a name
3574        //     newer than the installed library);
3575        //   - `add_rule` fails with `EDOM` when the name resolves to a pseudo-syscall that does
3576        //     not exist on this architecture — every legacy x86_64 spelling in the array
3577        //     (`open`, `dup2`, `poll`, `stat`, ...) hits this on aarch64.
3578        //
3579        // Skipping is fail-closed: a name that gets no rule stays denied by the default action,
3580        // so the filter can only ever come out *narrower* than intended, never wider. Propagating
3581        // instead would abort every single spawn on the first arch-specific name, which is why
3582        // this is the deliberate exception to the module's otherwise-strict error handling.
3583        for name in super::SECCOMP_SYSCALL_ALLOWLIST {
3584            if let Ok(syscall) = libseccomp::ScmpSyscall::from_name(name) {
3585                let _ = filter.add_rule(libseccomp::ScmpAction::Allow, syscall);
3586            }
3587        }
3588
3589        // Landlock's three syscalls, which `child_install_enforcement` calls *after* this filter
3590        // is loaded (`apply_landlock_scope`, on `KernelFull`). Without these rules the default
3591        // deny would refuse the child's own filesystem scoping and abort every spawn on that
3592        // tier. Allowing them costs nothing: a Landlock domain can only ever narrow the process
3593        // that installs it, never widen it, and Docker's default profile allows them too.
3594        //
3595        // Resolved by name where possible, with the syscall number as a fallback, because these
3596        // names only became known to libseccomp in 2.5.4 — the "skip what does not resolve"
3597        // policy above would silently turn an older libseccomp into "no capsule can run a shell
3598        // on a Landlock-capable host". The numbers are the same on every architecture Linux has
3599        // added Landlock to (they were assigned after the syscall-number unification), so the
3600        // fallback is not architecture-specific.
3601        for (name, fallback_nr) in LANDLOCK_SYSCALLS {
3602            let syscall = libseccomp::ScmpSyscall::from_name(name)
3603                .unwrap_or_else(|_| libseccomp::ScmpSyscall::from(fallback_nr));
3604            filter
3605                .add_rule(libseccomp::ScmpAction::Allow, syscall)
3606                .map_err(to_io_err)?;
3607        }
3608
3609        Ok(filter)
3610    }
3611
3612    /// Loads the filter [`build_seccomp_filter`] produces into the calling task. Irreversible:
3613    /// the filter stays in force for the rest of this task's life and is inherited across the
3614    /// `execve` that follows, which is why nothing outside a forked child ever calls this.
3615    fn install_seccomp_filter(unix_sockets_allowed: bool) -> io::Result<()> {
3616        // Dropping the context after `load()` is safe: libseccomp's `seccomp_release()` (invoked
3617        // on Drop) only frees the userspace filter-building context, while the filter itself is
3618        // already installed in the kernel and is inherited across the `execve` that follows.
3619        build_seccomp_filter(unix_sockets_allowed)?
3620            .load()
3621            .map_err(to_io_err)
3622    }
3623
3624    fn to_io_err<E: std::fmt::Display>(error: E) -> io::Error {
3625        io::Error::other(error.to_string())
3626    }
3627
3628    /// Size of one `struct sock_filter`, the record `seccomp_export_bpf` writes per BPF
3629    /// instruction. Dividing an export's length by it is what turns bytes into an instruction
3630    /// count.
3631    #[cfg(test)]
3632    const SOCK_FILTER_BYTES: usize = 8;
3633
3634    /// Writes `export` — one of libseccomp's two exporters — into an anonymous in-memory file and
3635    /// returns what it wrote.
3636    ///
3637    /// Both exporters take a descriptor and nothing else, so the buffer has to come from
3638    /// somewhere. A `memfd` rather than a temporary file because it touches no filesystem the
3639    /// sandbox might already have scoped away, and because `tempfile` is a dev-dependency of this
3640    /// crate and so is unavailable to anything outside a test build.
3641    #[cfg(test)]
3642    fn export_to_memfd<F>(export: F) -> io::Result<Vec<u8>>
3643    where
3644        F: FnOnce(&OwnedFd) -> Result<(), libseccomp::error::SeccompError>,
3645    {
3646        use std::io::{Read, Seek, SeekFrom};
3647        use std::os::fd::FromRawFd;
3648
3649        // SAFETY: `memfd_create` reads a NUL-terminated name (a `c"..."` literal, static
3650        // lifetime) and returns a fresh descriptor or -1. No flags, so no cloexec and no sealing:
3651        // the descriptor lives and dies inside this function.
3652        let raw = unsafe { libc::memfd_create(c"murmur-seccomp-export".as_ptr(), 0) };
3653        if raw < 0 {
3654            return Err(io::Error::last_os_error());
3655        }
3656        // SAFETY: `raw` is a descriptor `memfd_create` just returned and nothing else owns, which
3657        // is exactly the precondition for handing it to `OwnedFd`.
3658        let memfd = unsafe { OwnedFd::from_raw_fd(raw) };
3659
3660        export(&memfd).map_err(to_io_err)?;
3661
3662        let mut file = std::fs::File::from(memfd);
3663        file.seek(SeekFrom::Start(0))?;
3664        let mut exported = Vec::new();
3665        file.read_to_end(&mut exported)?;
3666        Ok(exported)
3667    }
3668
3669    /// The number of BPF instructions the filter [`build_seccomp_filter`] produces compiles to on
3670    /// this host, for the given `unix_sockets_allowed`.
3671    ///
3672    /// Measured, never assumed: `seccomp_export_bpf` writes the generated program as a sequence of
3673    /// 8-byte `struct sock_filter` records, so the instruction count is the exported length
3674    /// divided by that record size. The number depends on the host — how many
3675    /// [`super::SECCOMP_SYSCALL_ALLOWLIST`] names this architecture and this libseccomp resolve —
3676    /// which is why it is measured here rather than written down.
3677    ///
3678    /// `export_bpf` and not `export_bpf_mem`: the latter binds `seccomp_export_bpf_mem`, which
3679    /// first appeared in libseccomp 2.6.0, and a host on 2.5.x would fail to resolve the symbol.
3680    #[cfg(test)]
3681    fn seccomp_filter_instruction_count(unix_sockets_allowed: bool) -> io::Result<usize> {
3682        let filter = build_seccomp_filter(unix_sockets_allowed)?;
3683        let exported = export_to_memfd(|fd| filter.export_bpf(fd))?;
3684        Ok(exported.len() / SOCK_FILTER_BYTES)
3685    }
3686
3687    /// The filter [`build_seccomp_filter`] produces, rendered as libseccomp's pseudo filter code:
3688    /// one block per syscall carrying a rule, each block naming the argument comparisons and the
3689    /// action. It is the only view of a built context that shows the rule *shape* rather than the
3690    /// compiled program's size, which is what a test pinning the rule sequence needs.
3691    #[cfg(test)]
3692    fn seccomp_filter_pfc(unix_sockets_allowed: bool) -> io::Result<String> {
3693        let filter = build_seccomp_filter(unix_sockets_allowed)?;
3694        let exported = export_to_memfd(|fd| filter.export_pfc(fd))?;
3695        String::from_utf8(exported).map_err(to_io_err)
3696    }
3697
3698    /// Scopes the shell subprocess tree's filesystem access with Landlock. Four kinds of rule:
3699    ///
3700    ///   - the workdir gets [`workdir_access_rights`] — read/write plus directory, regular-file,
3701    ///     FIFO and symlink creation, but **not** `MakeChar`/`MakeBlock`/`MakeSock`, and **not**
3702    ///     `Execute` unless the capsule declared `capabilities.filesystem.workdir_exec: true` (see
3703    ///     [`WORKDIR_ACCESS_RIGHTS_NO_EXEC`] for why each right is withheld). Withholding `Execute`
3704    ///     is what enforces `capabilities.shell.allow` completely: the kernel refuses the exec on
3705    ///     the path it resolved itself, so nothing the capsule writes into its workdir can run;
3706    ///   - on `KernelSealed` only, the workdir-backed `/tmp` store gets that **same** right-set
3707    ///     from the same local binding. `plan_composed_root` binds `<workdir>/.mur-tmp` at `/tmp`
3708    ///     read-write, but Landlock matches an access to `/tmp/x` against the bind's own root inode
3709    ///     rather than the workdir's, so without this rule the mount is writable and every access
3710    ///     to it is nevertheless `EACCES` — bash heredocs, `mktemp`, a compiler's intermediate
3711    ///     objects and a package manager's build scratch all fail. Identical rights are the honest
3712    ///     ones: it is the same storage, counted by the same `workdir_max_bytes` guard, so it must
3713    ///     be neither more nor less runnable than the workdir itself;
3714    ///   - each [`LandlockGrant`] (the `shell.allow` binaries, their ELF interpreter, their
3715    ///     shared-library closure, any `interpreter_runtime` or `staged_runtime` directory, and on
3716    ///     `KernelSealed` the fixed [`crate::sealed::SEALED_RUNTIME_PATHS`] and
3717    ///     [`crate::sealed::SEALED_ETC_PATHS`], all *outside* the workdir) gets a **narrow read**
3718    ///     grant — never write — with two bits added on top.
3719    ///     Whether it carries `ReadDir` (i.e. the directory's own entries are enumerable) is
3720    ///     exactly the grant's `list_dir`: the derived closure files are all `false` (a regular
3721    ///     file has no meaningful `ReadDir`), while an `interpreter_runtime` directory carries
3722    ///     whatever its author wrote. `ReadDir` is granted only on the specific inode a rule names
3723    ///     — never on an ancestor or sibling — so naming one subdirectory never makes `/usr/lib`
3724    ///     (or any parent) enumerable. Whether it carries `Execute` is the grant's `executable`,
3725    ///     `true` everywhere except the two tier-issued sealed grants, which are deliberately
3726    ///     readable (and, on a directory, enumerable) but not runnable;
3727    ///   - each entry of the fixed [`CAPSULE_DEVICE_GRANTS`] set gets `ReadFile`, plus `WriteFile`
3728    ///     if its `writable` bit is set. That bit is set for exactly one path — `/dev/null` — which
3729    ///     is therefore the *only* writable path outside the workdir in the whole sandbox. This
3730    ///     list is a compile-time constant, not manifest-derived: no capability declaration widens
3731    ///     or narrows it. Every device path it does not name stays denied by the ordinary
3732    ///     no-matching-rule path below.
3733    ///
3734    /// Without the second kind of rule, `restrict_self()` denies `Execute`/`ReadFile` on every
3735    /// path outside the workdir, so every allowlisted binary's `execve` fails with EACCES before
3736    /// it runs (and even a binary placed *inside* the workdir can't be loaded, because its dynamic
3737    /// loader must still read `ld-linux`/libc outside it). The narrow grants fix that while keeping
3738    /// the security story honest: apart from `/dev/null`, nothing outside the workdir is writable,
3739    /// so a write to any other outside path — including one of these read+execute grant paths — is
3740    /// still denied.
3741    ///
3742    /// `handle_access` must declare the union of every access bit any rule uses, and it stays the
3743    /// **full** ABI v1 set deliberately: a bit declared there but granted by no rule is denied for
3744    /// the whole domain, which is exactly how the rights missing from
3745    /// [`WORKDIR_ACCESS_RIGHTS_NO_EXEC`] become denied rather than merely un-granted, and it is also what
3746    /// makes every device outside [`CAPSULE_DEVICE_GRANTS`] denied. A grant path — or a device
3747    /// path, on a host where one of the three is missing — that
3748    /// fails to *open* is skipped
3749    /// (shrink-not-fail, matching `resolve_exec_allowlist`) rather than failing the whole scope —
3750    /// it only narrows what is allowed. A genuine ruleset-construction failure still returns `Err`,
3751    /// preserving the module's fail-closed invariant.
3752    fn apply_landlock_scope(fds: &LandlockChildFds) -> Result<(), String> {
3753        #[cfg(test)]
3754        if super::FORCE_LANDLOCK_FAILURE.with(|flag| flag.get()) {
3755            return Err("landlock: ruleset construction failed (forced by test seam)".to_string());
3756        }
3757
3758        use landlock::{
3759            Access, AccessFs, CompatLevel, Compatible, PathBeneath, Ruleset, RulesetAttr,
3760            RulesetCreatedAttr, ABI,
3761        };
3762
3763        let abi = ABI::V1;
3764        let access_all = AccessFs::from_all(abi);
3765        // Enough for the loader to open, read, and map-execute a binary or shared library, and to
3766        // open a file inside a granted directory by exact name — but no write access, and (without
3767        // `ReadDir`) no enumeration of the directory's own entries.
3768        let read_execute = AccessFs::Execute | AccessFs::ReadFile;
3769        // Adds enumerability (`getdents64`) — only for a grant carrying `list_dir: true`.
3770        let read_execute_list = read_execute | AccessFs::ReadDir;
3771        // `ReadFile + ReadDir`, no `Execute` — readable and enumerable but not runnable. See
3772        // `resolve_sealed_runtime_landlock_grants` and `resolve_sealed_etc_landlock_grants` for why
3773        // `Execute` is withheld from a tier-issued grant over trees the manifest never named.
3774        let read_list = AccessFs::ReadFile | AccessFs::ReadDir;
3775        // `ReadFile` alone: the same tier-issued grant on an entry that is a *file* rather than a
3776        // directory (most of `SEALED_ETC_PATHS`). Not cosmetic — `landlock_append_fs_rule` rejects
3777        // `ReadDir` on a non-directory with `EINVAL`, and a rejected rule fails the launch below.
3778        let read_only: BitFlags<AccessFs> = AccessFs::ReadFile.into();
3779        // Device rights. No `Execute` (a character device is never exec'd) and no `ReadDir` (it is
3780        // not a directory) — only the two data bits, with `WriteFile` reserved for `/dev/null`.
3781        let device_read: BitFlags<AccessFs> = AccessFs::ReadFile.into();
3782        let device_read_write = device_read | AccessFs::WriteFile;
3783
3784        // The one writable right-set in this function, resolved once and used by both rules that
3785        // carry it. The composed root's `/tmp` is a bind of a directory inside the workdir — the
3786        // same storage, under the same size guard — so it gets the same rights, `Execute` axis
3787        // included: `workdir_exec: false` must no more permit running a binary from `/tmp` than
3788        // from the workdir it is stored in. Sharing the binding is what keeps that true; two
3789        // separate calls could drift apart.
3790        let writable_rights = workdir_access_rights(fds.workdir_exec);
3791
3792        // Every fd here was already opened in the parent (before fork). This function performs no
3793        // `open()`/`canonicalize()` — only the Landlock ruleset syscalls against already-open fds,
3794        // so a failure here can only be the kernel call itself, not an unrelated path resolution.
3795        let mut ruleset = Ruleset::default()
3796            .set_compatibility(CompatLevel::HardRequirement)
3797            .handle_access(access_all)
3798            .map_err(|error| format!("landlock: handle_access failed: {error}"))?
3799            .create()
3800            .map_err(|error| format!("landlock: ruleset create failed: {error}"))?
3801            .add_rule(PathBeneath::new(fds.workdir_fd.as_fd(), writable_rights))
3802            .map_err(|error| format!("landlock: add_rule failed: {error}"))?;
3803
3804        // `KernelSealed` only — on every other tier there is no composed root and this is `None`.
3805        // A rule on the workdir alone does not reach the bind mounted over `/tmp`; see
3806        // [`LandlockChildFds::sealed_tmp_fd`].
3807        if let Some(sealed_tmp_fd) = &fds.sealed_tmp_fd {
3808            ruleset = ruleset
3809                .add_rule(PathBeneath::new(sealed_tmp_fd.as_fd(), writable_rights))
3810                .map_err(|error| {
3811                    format!("landlock: add_rule for the workdir-backed /tmp failed: {error}")
3812                })?;
3813        }
3814
3815        // `KernelSealed` only — empty on every other tier. `ReadFile` alone: these are the two
3816        // synthetic account databases the root binds read-only at `/etc/passwd`/`/etc/group`, and
3817        // the grant loop's rules for those two paths are taken on the host's files, not on these.
3818        for identity_fd in &fds.sealed_identity_fds {
3819            ruleset = ruleset
3820                .add_rule(PathBeneath::new(identity_fd.as_fd(), read_only))
3821                .map_err(|error| {
3822                    format!("landlock: add_rule for a synthetic /etc file failed: {error}")
3823                })?;
3824        }
3825
3826        for grant in &fds.grants {
3827            // Grant paths that failed to open in the parent were already dropped (shrink-not-fail),
3828            // so every fd reaching here is valid. A rule that still fails to add is a genuine
3829            // ruleset-construction failure and propagates as `Err` (fail-closed).
3830            let access = match (grant.executable, grant.list_dir) {
3831                (true, true) => read_execute_list,
3832                (true, false) => read_execute,
3833                (false, true) => read_list,
3834                (false, false) => read_only,
3835            };
3836            ruleset = ruleset
3837                .add_rule(PathBeneath::new(grant.fd.as_fd(), access))
3838                .map_err(|error| format!("landlock: add_rule for grant failed: {error}"))?;
3839        }
3840
3841        for device in &fds.devices {
3842            // Same convention as the grant loop above: a device that failed to open in the parent
3843            // was already dropped, so a failure here is a genuine ruleset-construction failure and
3844            // propagates as `Err` (fail-closed).
3845            let access = if device.writable {
3846                device_read_write
3847            } else {
3848                device_read
3849            };
3850            ruleset = ruleset
3851                .add_rule(PathBeneath::new(device.fd.as_fd(), access))
3852                .map_err(|error| format!("landlock: add_rule for device failed: {error}"))?;
3853        }
3854
3855        ruleset
3856            .restrict_self()
3857            .map_err(|error| format!("landlock: restrict_self failed: {error}"))?;
3858
3859        Ok(())
3860    }
3861
3862    /// Opens (in the PARENT, before fork) the workdir fd and every grant fd Landlock needs, using
3863    /// `O_PATH | O_CLOEXEC` — the exact flags `landlock::PathFd` uses. Moving these `open()` calls
3864    /// out of the child's `pre_exec` window is the whole point: a workdir that cannot be resolved
3865    /// now fails here, synchronously, with a message naming the path — before any subprocess is
3866    /// spawned — instead of collapsing to a bare EINVAL inside `pre_exec`. A grant path that fails
3867    /// to open is dropped (shrink-not-fail), matching the previous per-grant `continue`.
3868    ///
3869    /// It is also where each grant's `list_dir` is reconciled against the fd that was actually
3870    /// opened — see the comment on the grant loop. Same discipline as the drop above: narrowing
3871    /// only, never widening.
3872    ///
3873    /// `device_grants` — the tier's fixed device set, [`super::CAPSULE_DEVICE_GRANTS`] on
3874    /// `KernelFull` and the composed root's own OCI default set on `KernelSealed`, chosen by
3875    /// `super::landlock_device_grants` — is opened here too, by the same rules: the list is a
3876    /// compile-time constant rather than manifest-derived, and a host where one entry cannot be
3877    /// opened — unusual, but a broken or minimal `/dev` is possible — loses that one device rather
3878    /// than failing the launch. Losing `/dev/null` here degrades to exactly the behavior that
3879    /// existed before this mechanism, which is a strictly narrower scope, never a wider one.
3880    ///
3881    /// `tier` decides one thing only: whether the workdir-backed `/tmp` store
3882    /// ([`crate::sealed::SEALED_TMP_DIR_NAME`]) is created and opened. It is on `KernelSealed`,
3883    /// where `plan_composed_root` unconditionally binds it at `/tmp`, and on no other tier — none
3884    /// of which composes a root at all. Both the creation and the open are fail-closed — an `Err`
3885    /// naming the path, exactly like the workdir's own open above, never the grant loops'
3886    /// shrink-not-fail `continue`. That bind is not manifest-optional, and silently dropping its fd
3887    /// would leave `/tmp` mounted-but-denied, which is precisely the defect the rule exists to fix.
3888    pub(super) fn open_landlock_fds(
3889        accessible_workdir: &Path,
3890        session_workdir: &Path,
3891        landlock_grants: &[LandlockGrant],
3892        device_grants: &[super::CapsuleDeviceGrant],
3893        workdir_exec: bool,
3894        tier: EnforcementTier,
3895    ) -> Result<LandlockChildFds, String> {
3896        let workdir_fd = open_o_path(accessible_workdir)
3897            .map(OwnedFd::from)
3898            .map_err(|error| {
3899                format!(
3900                    "sandbox: failed to open workdir {} for Landlock scoping: {error}",
3901                    accessible_workdir.display()
3902                )
3903            })?;
3904
3905        // `prepare_enforcement` calls this function *before* `build_sealed_root`, so `.mur-tmp`
3906        // need not exist yet; the shared helper creates it (idempotently — `build_sealed_root`
3907        // calls the same one) so there is something here to open.
3908        let sealed_tmp_fd = if tier == EnforcementTier::KernelSealed {
3909            let tmp_store = super::ensure_sealed_tmp_store(session_workdir)?;
3910            let tmp_store_file = open_o_path(&tmp_store).map_err(|error| {
3911                format!(
3912                    "sandbox: failed to open the workdir-backed /tmp store {} for Landlock \
3913                     scoping: {error}",
3914                    tmp_store.display()
3915                )
3916            })?;
3917            Some(OwnedFd::from(tmp_store_file))
3918        } else {
3919            None
3920        };
3921
3922        // Same story, same tier gate, same fail-closed handling: the composed root binds these two
3923        // files at `/etc/passwd`/`/etc/group`, and the grant loop below opens the *host's* files of
3924        // those names, whose inodes the capsule never sees. See `LandlockChildFds`.
3925        let sealed_identity_fds = if tier == EnforcementTier::KernelSealed {
3926            let mut fds = Vec::new();
3927            for path in super::ensure_sealed_identity_files(session_workdir)? {
3928                let file = open_o_path(&path).map_err(|error| {
3929                    format!(
3930                        "sandbox: failed to open the synthetic /etc file {} for Landlock scoping: \
3931                         {error}",
3932                        path.display()
3933                    )
3934                })?;
3935                fds.push(OwnedFd::from(file));
3936            }
3937            fds
3938        } else {
3939            Vec::new()
3940        };
3941
3942        let mut grants = Vec::with_capacity(landlock_grants.len());
3943        for grant in landlock_grants {
3944            match open_o_path(&grant.path) {
3945                Ok(file) => grants.push(OpenLandlockGrant {
3946                    // `ReadDir` is meaningful only on a directory, and the kernel does not merely
3947                    // ignore it elsewhere: `landlock_append_fs_rule` returns `EINVAL` for a
3948                    // directory-only right on a non-directory, and the rule loop in
3949                    // `apply_landlock_scope` is fail-closed, so one such rule would refuse the
3950                    // whole launch. Every `list_dir: true` reaching here is a *claim* — an author's
3951                    // `interpreter_runtime` entry, or the static `directory` bit on a
3952                    // `SEALED_ETC_PATHS` entry — so it is checked against the fd actually opened
3953                    // and narrowed rather than trusted. Narrowing only: this can drop `ReadDir`,
3954                    // never add it.
3955                    list_dir: grant.list_dir
3956                        && file.metadata().map(|meta| meta.is_dir()).unwrap_or(false),
3957                    fd: OwnedFd::from(file),
3958                    executable: grant.executable,
3959                }),
3960                Err(_) => continue,
3961            }
3962        }
3963
3964        let mut devices = Vec::with_capacity(device_grants.len());
3965        for device in device_grants {
3966            match open_o_path(Path::new(device.path)) {
3967                Ok(file) => devices.push(OpenDeviceGrant {
3968                    fd: OwnedFd::from(file),
3969                    writable: device.writable,
3970                }),
3971                Err(_) => continue,
3972            }
3973        }
3974
3975        Ok(LandlockChildFds {
3976            workdir_fd,
3977            workdir_exec,
3978            sealed_tmp_fd,
3979            sealed_identity_fds,
3980            grants,
3981            devices,
3982        })
3983    }
3984
3985    /// Opens `path` with `O_PATH | O_CLOEXEC` (identity/lifetime handle only, never a data fd),
3986    /// suitable for `landlock::PathBeneath`. Same open the vendored `landlock::PathFd::new`
3987    /// performs, done in the parent so the resulting fd can be moved into the child's `pre_exec`
3988    /// closure.
3989    ///
3990    /// Returns the `File` rather than a bare `OwnedFd` so the caller can `fstat` it — see the
3991    /// `list_dir` narrowing in [`open_landlock_fds`], which needs the kind of *this* fd and must
3992    /// not perform a second path lookup to get it.
3993    fn open_o_path(path: &Path) -> io::Result<std::fs::File> {
3994        use std::os::unix::fs::OpenOptionsExt;
3995        std::fs::OpenOptions::new()
3996            .read(true)
3997            .custom_flags(libc::O_PATH | libc::O_CLOEXEC)
3998            .open(path)
3999    }
4000
4001    /// Best-effort write of a bounded failure message to the child-diagnostic pipe from inside
4002    /// `pre_exec`, using a raw `write` loop (allocation for the message itself already happened
4003    /// upstream — `child_install_enforcement`'s error paths use `format!`). Never fails the caller:
4004    /// a lost diagnostic only costs legibility, never the fail-closed guarantee (the closure still
4005    /// returns `Err`, so `execve` is still aborted).
4006    #[allow(unsafe_code)]
4007    pub(super) fn write_diagnostic(fd: RawFd, message: &str) {
4008        let bytes = message.as_bytes();
4009        let len = bytes.len().min(MAX_DIAG_LEN);
4010        let mut written = 0;
4011        while written < len {
4012            // SAFETY: `fd` is the valid, open write end of the diagnostic pipe; the pointer/len
4013            // name a live sub-slice of `bytes` for the duration of this single `write` call.
4014            let n = unsafe {
4015                libc::write(
4016                    fd,
4017                    bytes[written..len].as_ptr() as *const libc::c_void,
4018                    len - written,
4019                )
4020            };
4021            if n < 0 {
4022                if io::Error::last_os_error().raw_os_error() == Some(libc::EINTR) {
4023                    continue;
4024                }
4025                break;
4026            }
4027            if n == 0 {
4028                break;
4029            }
4030            written += n as usize;
4031        }
4032    }
4033
4034    /// Parent-side read of whatever the child wrote to the diagnostic pipe before its `pre_exec`
4035    /// closure returned `Err`. Blocks until EOF, which arrives once every write end is closed —
4036    /// the child's (on `_exit`) and the parent's captured copy (which `execute_shell` drops before
4037    /// calling this). Returns `None` when nothing was written (the success-path EOF, or a `spawn`
4038    /// failure that never ran `pre_exec`).
4039    #[allow(unsafe_code)]
4040    pub(super) fn read_diagnostic_pipe(fd: RawFd) -> Option<String> {
4041        let mut buf = Vec::new();
4042        let mut chunk = [0u8; 256];
4043        loop {
4044            // SAFETY: `fd` is the valid, open read end of the diagnostic pipe; `chunk` is a live
4045            // stack buffer of exactly the length passed.
4046            let n = unsafe { libc::read(fd, chunk.as_mut_ptr() as *mut libc::c_void, chunk.len()) };
4047            if n < 0 {
4048                if io::Error::last_os_error().raw_os_error() == Some(libc::EINTR) {
4049                    continue;
4050                }
4051                break;
4052            }
4053            if n == 0 {
4054                break;
4055            }
4056            buf.extend_from_slice(&chunk[..n as usize]);
4057            if buf.len() >= MAX_DIAG_LEN {
4058                break;
4059            }
4060        }
4061        if buf.is_empty() {
4062            None
4063        } else {
4064            Some(String::from_utf8_lossy(&buf).into_owned())
4065        }
4066    }
4067
4068    /// Spawns the background thread that receives the capsule network namespace's listening
4069    /// sockets from the child and starts serving them through the egress proxy — blocking on that
4070    /// receive, racing concurrently with the caller's (not-yet-issued) `.spawn()` call rather than
4071    /// running after it, per [`SupervisorHandle`]'s doc comment.
4072    ///
4073    /// The child sends exactly one `SCM_RIGHTS` batch over this socketpair, from
4074    /// `create_capsule_netns` — the first thing its `pre_exec` window does. The thread finishes as
4075    /// soon as the proxy is up and hands the live handle back over `proxy_rx` for
4076    /// [`SupervisorHandle::join_best_effort`] to shut down, so the proxy stops when the shell
4077    /// call has finished waiting on the subprocess tree. Both the foreground path and a demoted
4078    /// command's own thread drain the child's pipes to EOF before that shutdown, which is what
4079    /// makes them wait for every descendant holding the pipe.
4080    ///
4081    /// If the sockets never arrive (e.g. `fork()` itself failed, or the child's `pre_exec` closure
4082    /// errored before reaching the send), there is no live child left unserved:
4083    /// `Command::spawn()` surfaces that same underlying failure as its own `Err`, via the
4084    /// close-on-exec error pipe, independently of this thread.
4085    pub(super) fn start_supervisor(
4086        parent_sock: OwnedFd,
4087        egress_policy: crate::egress_proxy::EgressPolicy,
4088        expected_namespace_sockets: usize,
4089        diag_read: OwnedFd,
4090    ) -> SupervisorHandle {
4091        let (proxy_tx, proxy_rx) = std::sync::mpsc::channel();
4092        std::thread::spawn(move || {
4093            let proxy = start_namespace_proxy(
4094                parent_sock.as_raw_fd(),
4095                expected_namespace_sockets,
4096                egress_policy,
4097            );
4098            // A closed receiver means the caller gave up waiting (its bounded `recv_timeout`
4099            // elapsed). Dropping the handle here then shuts the proxy down on this thread instead,
4100            // which is the same outcome by a different route — never a proxy left running.
4101            if let Err(returned) = proxy_tx.send(proxy) {
4102                if let Some(proxy) = returned.0 {
4103                    proxy.shutdown();
4104                }
4105            }
4106        });
4107
4108        SupervisorHandle::Linux {
4109            proxy_rx,
4110            diag_read,
4111        }
4112    }
4113
4114    /// Receives the in-namespace listening sockets and starts serving them.
4115    ///
4116    /// Returns `None` when the hand-off failed, which is not a silent degradation: the same
4117    /// `pre_exec` failure that prevented the send also makes the child return `Err`, so
4118    /// `Command::spawn()` reports it and no subprocess runs. There is no path where the capsule
4119    /// starts with a namespace whose proxy never came up — that would be a capsule with no
4120    /// network at all rather than an unbounded one, but it would present as an inexplicable
4121    /// outage, so it is logged here too.
4122    fn start_namespace_proxy(
4123        sock_fd: RawFd,
4124        expected: usize,
4125        policy: crate::egress_proxy::EgressPolicy,
4126    ) -> Option<crate::egress_proxy::EgressProxyHandle> {
4127        let sockets = match crate::network_namespace::receive_namespace_sockets(sock_fd, expected) {
4128            Ok(sockets) => sockets,
4129            Err(error) => {
4130                eprintln!(
4131                    "[capsule-runtime] warning: failed to receive the capsule's network \
4132                     namespace sockets: {error} (the subprocess spawn reports the underlying \
4133                     pre_exec failure independently)"
4134                );
4135                return None;
4136            }
4137        };
4138        match crate::egress_proxy::start_egress_proxy(sockets, policy) {
4139            Ok(proxy) => Some(proxy),
4140            Err(error) => {
4141                eprintln!(
4142                    "[capsule-runtime] warning: failed to serve the capsule's network namespace \
4143                     sockets: {error} (the subprocess tree has no route off this host, so its \
4144                     network calls fail closed)"
4145                );
4146                None
4147            }
4148        }
4149    }
4150
4151    /// What the child's seccomp filter costs, and the two kernel ceilings that cost is held
4152    /// against — all four numbers produced by running code on the host under test, never quoted.
4153    ///
4154    /// The written record these tests feed is
4155    /// `docs/content/reference/seccomp-filter-instruction-budget.md`.
4156    ///
4157    /// Nothing here ever loads a filter into the test process. A loaded seccomp filter is
4158    /// irreversible for the life of the task, so an in-process load would silently apply to the
4159    /// rest of the test binary and to everything it spawns. Every load happens in a forked child
4160    /// that does nothing else and then `_exit`s.
4161    #[cfg(test)]
4162    mod seccomp_budget {
4163        use std::io;
4164        use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
4165
4166        // `seccomp_filter_instruction_count` is absent from this list because the test that
4167        // reports it carries the same name; it is called as `super::` throughout.
4168        use super::{
4169            build_seccomp_filter, export_to_memfd, seccomp_filter_pfc, to_io_err,
4170            LANDLOCK_SYSCALLS, SOCK_FILTER_BYTES,
4171        };
4172        use crate::sandbox::{
4173            allowed_socket_domains, denied_socket_domains, detect_enforcement_tier,
4174            EnforcementTier, BPF_MAXINSNS_CEILING, SECCOMP_FILTER_INSTRUCTION_BUDGET,
4175            SECCOMP_MAX_INSNS_PER_PATH, SECCOMP_SYSCALL_ALLOWLIST,
4176        };
4177
4178        /// The kernel charges each filter already attached to a task four instructions on top of
4179        /// its own length when it decides whether the next attach fits under
4180        /// [`SECCOMP_MAX_INSNS_PER_PATH`].
4181        ///
4182        /// It is only part of the arithmetic. The length the kernel adds up is that of the
4183        /// *converted* program — `seccomp_prepare_filter` translates the classic BPF that
4184        /// `export_bpf` writes into eBPF before the chain is measured, and the translation comes
4185        /// out slightly longer. So a load count predicted from the exported classic length is an
4186        /// upper bound on the load count the kernel actually allows, never an equality, which is
4187        /// why the cumulative probe brackets it rather than pinning it.
4188        const KERNEL_PER_FILTER_OVERHEAD_INSNS: usize = 4;
4189
4190        /// The exit code a load probe's child reports on a refusal libseccomp gave no errno for.
4191        /// Every real errno is a small positive number, and 0 is reserved for a load that
4192        /// succeeded, so this cannot collide with either.
4193        const PROBE_ERRNO_UNKNOWN: i32 = 254;
4194
4195        /// A filter built only to be measured or refused: default `Allow`, and `rules`
4196        /// argument-conditional `Errno` rules on a syscall no probe child ever makes.
4197        ///
4198        /// Default `Allow` rather than the real filter's default deny, for two reasons that both
4199        /// matter. A child has to survive its own load long enough to `_exit` and, in the
4200        /// cumulative probe, to call `seccomp(2)` again — the real filter denies `seccomp` on
4201        /// purpose, so it cannot be stacked on itself. And libseccomp drops a rule whose action
4202        /// equals the default action, so the rules have to carry an action the default does not:
4203        /// `Errno` against a default of `Allow` is the inverse of the shipped filter and keeps
4204        /// every rule in the program.
4205        ///
4206        /// `set_api_sysrawrc` is what makes the errno observable at all: without it libseccomp
4207        /// collapses every `seccomp(2)` attach failure to `ECANCELED`, which would hide the very
4208        /// `EINVAL`/`ENOMEM` distinction these probes exist to establish.
4209        fn probe_filter(rules: usize) -> io::Result<(libseccomp::ScmpFilterContext, usize)> {
4210            let mut filter = libseccomp::ScmpFilterContext::new(libseccomp::ScmpAction::Allow)
4211                .map_err(to_io_err)?;
4212            filter.set_api_sysrawrc(true).map_err(to_io_err)?;
4213
4214            let syscall = libseccomp::ScmpSyscall::from_name("ptrace").map_err(to_io_err)?;
4215            for value in 0..rules {
4216                filter
4217                    .add_rule_conditional(
4218                        libseccomp::ScmpAction::Errno(libc::EPERM),
4219                        syscall,
4220                        &[libseccomp::ScmpArgCompare::new(
4221                            0,
4222                            libseccomp::ScmpCompareOp::Equal,
4223                            value as u64,
4224                        )],
4225                    )
4226                    .map_err(to_io_err)?;
4227            }
4228
4229            let exported = export_to_memfd(|fd| filter.export_bpf(fd))?;
4230            Ok((filter, exported.len() / SOCK_FILTER_BYTES))
4231        }
4232
4233        /// The smallest probe-filter rule count whose compiled program is longer than
4234        /// `instructions`. Doubling to bracket, then bisecting: the instruction count grows
4235        /// monotonically with the rule count, so both halves are sound and the whole search
4236        /// costs a couple of dozen exports rather than thousands.
4237        fn first_rule_count_above(instructions: usize) -> io::Result<usize> {
4238            let mut under = 1;
4239            let mut over = 8;
4240            while probe_filter(over)?.1 <= instructions {
4241                under = over;
4242                over *= 2;
4243                assert!(
4244                    over <= 1 << 20,
4245                    "no probe filter of up to {over} rules exceeded {instructions} instructions — \
4246                     the probe is not growing the program the way this search assumes"
4247                );
4248            }
4249            while over - under > 1 {
4250                let mid = under + (over - under) / 2;
4251                if probe_filter(mid)?.1 <= instructions {
4252                    under = mid;
4253                } else {
4254                    over = mid;
4255                }
4256            }
4257            Ok(over)
4258        }
4259
4260        /// The raw errno behind a libseccomp failure, for a context built by [`probe_filter`] and
4261        /// therefore carrying `SCMP_FLTATR_API_SYSRAWRC`. Known errnos come back as
4262        /// `ErrorKind::Errno`, anything else as the raw code; both are mapped here so the caller
4263        /// only ever sees a plain `libc` value.
4264        fn refusal_errno(error: &libseccomp::error::SeccompError) -> i32 {
4265            use libseccomp::error::SeccompErrno;
4266
4267            if let Some(raw) = error.sysrawrc() {
4268                return -raw;
4269            }
4270            match error.errno() {
4271                Some(SeccompErrno::EACCES) => libc::EACCES,
4272                Some(SeccompErrno::ECANCELED) => libc::ECANCELED,
4273                Some(SeccompErrno::EINVAL) => libc::EINVAL,
4274                Some(SeccompErrno::ENOMEM) => libc::ENOMEM,
4275                _ => PROBE_ERRNO_UNKNOWN,
4276            }
4277        }
4278
4279        /// Loads `filter` in a forked child and reports what the kernel said: `Ok(())` for a load
4280        /// that took, `Err(errno)` for one the kernel refused.
4281        ///
4282        /// The filter is built by the caller, before the fork, so the child's whole post-fork
4283        /// window is `load()` and `_exit`.
4284        fn load_in_child(filter: &libseccomp::ScmpFilterContext) -> Result<(), i32> {
4285            // SAFETY: `fork()` from a possibly-multithreaded process is sound as long as the
4286            // child confines itself to work that does not depend on another thread's state. This
4287            // child calls `load()` and then `_exit`. `load()` allocates — libseccomp generates
4288            // the BPF program on every load and does not cache the one `export_bpf` produced —
4289            // so this probe is not async-signal-safe in the strict sense; it is bounded to a
4290            // child that touches nothing else and dies immediately.
4291            let pid = unsafe { libc::fork() };
4292            assert!(pid >= 0, "fork failed: {}", io::Error::last_os_error());
4293
4294            if pid == 0 {
4295                let code = match filter.load() {
4296                    Ok(()) => 0,
4297                    Err(error) => refusal_errno(&error),
4298                };
4299                // SAFETY: forked-child context; `_exit` skips every destructor and atexit hook,
4300                // which is what keeps libtest's state in the parent untouched.
4301                unsafe { libc::_exit(code) }
4302            }
4303
4304            let mut status: libc::c_int = 0;
4305            // SAFETY: `pid` is the child just forked; `status` is a live local.
4306            let waited = unsafe { libc::waitpid(pid, &mut status, 0) };
4307            assert!(waited == pid, "waitpid: {}", io::Error::last_os_error());
4308            assert!(
4309                libc::WIFEXITED(status),
4310                "the load probe child did not exit normally (status {status})"
4311            );
4312            match libc::WEXITSTATUS(status) {
4313                0 => Ok(()),
4314                errno => Err(errno),
4315            }
4316        }
4317
4318        /// The number of distinct syscalls the allowlist actually contributes a rule for on this
4319        /// host, counted the way `build_seccomp_filter` contributes them — resolve the name, try
4320        /// the rule, keep what libseccomp accepted — but against a scratch context, so the count
4321        /// is an independent measurement rather than a restatement of the filter under test.
4322        fn resolvable_allowlist_syscalls() -> io::Result<usize> {
4323            use std::collections::HashSet;
4324
4325            let mut scratch =
4326                libseccomp::ScmpFilterContext::new(libseccomp::ScmpAction::Errno(libc::EPERM))
4327                    .map_err(to_io_err)?;
4328            let mut accepted = HashSet::new();
4329            for name in SECCOMP_SYSCALL_ALLOWLIST {
4330                if let Ok(syscall) = libseccomp::ScmpSyscall::from_name(name) {
4331                    if scratch
4332                        .add_rule(libseccomp::ScmpAction::Allow, syscall)
4333                        .is_ok()
4334                    {
4335                        accepted.insert(i32::from(syscall));
4336                    }
4337                }
4338            }
4339            Ok(accepted.len())
4340        }
4341
4342        /// The line both ceiling probes print instead of running, on a host where no seccomp
4343        /// filter can be loaded at all.
4344        fn skip_without_seccomp(what: &str) -> bool {
4345            let tier = detect_enforcement_tier();
4346            if tier == EnforcementTier::EnvironmentOnly {
4347                eprintln!(
4348                    "SKIP — PROVES NOTHING ON THIS HOST: measuring {what} requires a host that \
4349                     can load a seccomp filter at all, which is every tier above \
4350                     EnforcementTier::EnvironmentOnly; detected {tier:?}"
4351                );
4352                return true;
4353            }
4354            false
4355        }
4356
4357        /// What the real filter compiles to, against the budget this project holds itself to and
4358        /// the ceiling the kernel holds it to.
4359        ///
4360        /// Both `unix_sockets_allowed` settings, because they build different rule sets — one
4361        /// moves `AF_UNIX` from the denied domains to the allowed ones — and the budget has to
4362        /// cover the larger of the two.
4363        #[test]
4364        fn seccomp_filter_instruction_count() {
4365            for unix_sockets_allowed in [false, true] {
4366                let count = super::seccomp_filter_instruction_count(unix_sockets_allowed)
4367                    .expect("export the built seccomp filter");
4368
4369                eprintln!(
4370                    "seccomp filter instruction count: unix_sockets_allowed={unix_sockets_allowed} \
4371                     -> {count} instructions; budget {SECCOMP_FILTER_INSTRUCTION_BUDGET}; kernel \
4372                     per-filter ceiling {BPF_MAXINSNS_CEILING} ({:.1}x headroom); kernel \
4373                     cumulative ceiling {SECCOMP_MAX_INSNS_PER_PATH} ({:.1}x headroom)",
4374                    BPF_MAXINSNS_CEILING as f64 / count as f64,
4375                    SECCOMP_MAX_INSNS_PER_PATH as f64 / count as f64,
4376                );
4377
4378                assert!(
4379                    count > 0,
4380                    "the exported filter is empty, so nothing was measured — \
4381                     `export_bpf` wrote no `struct sock_filter` records at all"
4382                );
4383                assert!(
4384                    count <= SECCOMP_FILTER_INSTRUCTION_BUDGET,
4385                    "the child's seccomp filter compiles to {count} instructions with \
4386                     unix_sockets_allowed={unix_sockets_allowed}, over this project's budget of \
4387                     {SECCOMP_FILTER_INSTRUCTION_BUDGET} (the kernel refuses a single filter over \
4388                     {BPF_MAXINSNS_CEILING} with EINVAL). Re-measure, decide whether the rule set \
4389                     still earns its size, and raise SECCOMP_FILTER_INSTRUCTION_BUDGET \
4390                     deliberately — updating \
4391                     docs/content/reference/seccomp-filter-instruction-budget.md with the new \
4392                     numbers — rather than letting the filter grow into a spawn failure"
4393                );
4394            }
4395        }
4396
4397        /// The rule sequence `build_seccomp_filter` lays down, pinned against the filter's own
4398        /// pseudo-filter-code export so a change to the shape is a test failure rather than a
4399        /// silent change of policy.
4400        ///
4401        /// The `EACCES` count is the load-bearing one. An unconditional `Allow` on `socket`
4402        /// anywhere in this function would make libseccomp discard every argument-conditional
4403        /// chain already recorded for that syscall — reopening `AF_UNIX`, `AF_NETLINK` and
4404        /// `AF_PACKET` — and it would show up here as zero `EACCES` actions.
4405        #[test]
4406        fn seccomp_filter_rule_shape() {
4407            let allowlist_syscalls =
4408                resolvable_allowlist_syscalls().expect("count the resolvable allowlist syscalls");
4409            assert!(
4410                allowlist_syscalls > 0,
4411                "no SECCOMP_SYSCALL_ALLOWLIST name resolved on this host, so this test would pass \
4412                 for the wrong reason"
4413            );
4414
4415            for unix_sockets_allowed in [false, true] {
4416                let filter =
4417                    build_seccomp_filter(unix_sockets_allowed).expect("build the seccomp filter");
4418                assert_eq!(
4419                    filter.get_act_default().expect("read the default action"),
4420                    libseccomp::ScmpAction::Errno(libc::EPERM),
4421                    "the filter's default action is no longer a deny with EPERM, which is what \
4422                     makes every syscall outside the allowlist unreachable"
4423                );
4424
4425                let pfc =
4426                    seccomp_filter_pfc(unix_sockets_allowed).expect("export the filter's pfc");
4427                let denied = denied_socket_domains(unix_sockets_allowed);
4428                let allowed = allowed_socket_domains(unix_sockets_allowed);
4429
4430                // One block per syscall carrying at least one rule: `socket`, every allowlist
4431                // name libseccomp accepted, and the three Landlock syscalls.
4432                let syscall_blocks = pfc.matches("# filter for syscall ").count();
4433                assert_eq!(
4434                    syscall_blocks,
4435                    1 + allowlist_syscalls + LANDLOCK_SYSCALLS.len(),
4436                    "the built filter carries rules for {syscall_blocks} syscalls, not the \
4437                     socket rule plus {allowlist_syscalls} allowlist syscalls plus {} Landlock \
4438                     syscalls this code adds",
4439                    LANDLOCK_SYSCALLS.len()
4440                );
4441
4442                let deny_actions = pfc
4443                    .matches(&format!("action ERRNO({});", libc::EACCES))
4444                    .count();
4445                assert_eq!(
4446                    deny_actions,
4447                    denied.len(),
4448                    "the built filter carries {deny_actions} EACCES rules, not one per denied \
4449                     socket domain ({denied:?}) — an unconditional Allow on `socket` would look \
4450                     exactly like this, and would have discarded every domain denial with it"
4451                );
4452
4453                // Every non-`socket` block contributes exactly one `Allow`; the `socket` block
4454                // contributes one per allowed domain.
4455                let allow_actions = pfc.matches("action ALLOW;").count();
4456                assert_eq!(
4457                    allow_actions,
4458                    allowed.len() + allowlist_syscalls + LANDLOCK_SYSCALLS.len(),
4459                    "the built filter carries {allow_actions} Allow rules, not one per allowed \
4460                     socket domain ({allowed:?}) plus one per allowlist syscall plus one per \
4461                     Landlock syscall"
4462                );
4463
4464                for (name, _) in LANDLOCK_SYSCALLS {
4465                    assert!(
4466                        pfc.contains(&format!("\"{name}\"")),
4467                        "{name} has no rule in the built filter, so `apply_landlock_scope` would \
4468                         be refused by the filter installed just before it"
4469                    );
4470                }
4471
4472                eprintln!(
4473                    "seccomp filter rule shape: unix_sockets_allowed={unix_sockets_allowed} -> \
4474                     default ERRNO(EPERM); {} socket EACCES rules; {} socket ALLOW rules; \
4475                     {allowlist_syscalls} allowlist syscalls; {} Landlock syscalls",
4476                    denied.len(),
4477                    allowed.len(),
4478                    LANDLOCK_SYSCALLS.len(),
4479                );
4480            }
4481        }
4482
4483        /// Brackets `BPF_MAXINSNS`, the kernel's limit on a *single* filter's length, by loading
4484        /// two filters that straddle it and observing that the kernel takes one and refuses the
4485        /// other with `EINVAL`.
4486        ///
4487        /// `EINVAL`, not `ENOMEM`: an `ENOMEM` out of a seccomp attach never came from this
4488        /// ceiling, whatever the filter's length.
4489        #[test]
4490        fn seccomp_per_filter_ceiling() {
4491            if skip_without_seccomp("the kernel's per-filter instruction ceiling") {
4492                return;
4493            }
4494
4495            let over_rules = first_rule_count_above(BPF_MAXINSNS_CEILING)
4496                .expect("bracket the per-filter ceiling");
4497            let (under_filter, under_count) =
4498                probe_filter(over_rules - 1).expect("build the under-ceiling probe filter");
4499            let (over_filter, over_count) =
4500                probe_filter(over_rules).expect("build the over-ceiling probe filter");
4501
4502            assert!(
4503                under_count <= BPF_MAXINSNS_CEILING && over_count > BPF_MAXINSNS_CEILING,
4504                "the two probe filters ({under_count} and {over_count} instructions) do not \
4505                 straddle BPF_MAXINSNS_CEILING ({BPF_MAXINSNS_CEILING}), so this test would prove \
4506                 nothing about where the ceiling is"
4507            );
4508
4509            let under_outcome = load_in_child(&under_filter);
4510            let over_outcome = load_in_child(&over_filter);
4511
4512            eprintln!(
4513                "seccomp per-filter ceiling: largest filter that loaded = {under_count} \
4514                 instructions; smallest that did not = {over_count} instructions, refused with \
4515                 errno {} (EINVAL is {}); recorded BPF_MAXINSNS_CEILING = {BPF_MAXINSNS_CEILING}",
4516                over_outcome.err().unwrap_or(0),
4517                libc::EINVAL,
4518            );
4519
4520            assert_eq!(
4521                under_outcome,
4522                Ok(()),
4523                "a {under_count}-instruction filter was refused, below the \
4524                 {BPF_MAXINSNS_CEILING}-instruction ceiling this test expects the kernel to hold"
4525            );
4526            assert_eq!(
4527                over_outcome,
4528                Err(libc::EINVAL),
4529                "a {over_count}-instruction filter was not refused with EINVAL, so \
4530                 BPF_MAXINSNS_CEILING ({BPF_MAXINSNS_CEILING}) is not where this kernel puts its \
4531                 per-filter limit"
4532            );
4533        }
4534
4535        /// Measures `MAX_INSNS_PER_PATH`, the kernel's limit on the *whole chain* of filters one
4536        /// task carries, by stacking filters in a forked child until the kernel refuses.
4537        ///
4538        /// `ENOMEM` is what this ceiling returns, and it is the only seccomp attach path in the
4539        /// kernel that returns it — so an `ENOMEM` from a runtime that installs exactly one
4540        /// filter of a few hundred instructions, and that had not yet reached `load()` when it
4541        /// failed, did not come from the kernel's seccomp code.
4542        #[test]
4543        fn seccomp_cumulative_ceiling() {
4544            if skip_without_seccomp("the kernel's cumulative filter-chain ceiling") {
4545                return;
4546            }
4547
4548            // A probe of roughly the shipped filter's size, so the number of stacked loads reads
4549            // directly as "how many filters like ours one task could carry".
4550            let (filter, count) = probe_filter(120).expect("build the cumulative probe filter");
4551            let per_filter_cost = count + KERNEL_PER_FILTER_OVERHEAD_INSNS;
4552            // Enough headroom past the ceiling that a kernel which never refuses is caught by the
4553            // cap rather than by the test hanging.
4554            let max_loads = SECCOMP_MAX_INSNS_PER_PATH / per_filter_cost + 16;
4555
4556            let mut fds = [0 as libc::c_int; 2];
4557            // SAFETY: `fds` is a live two-element array, which is what `pipe2` writes into.
4558            let rc = unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) };
4559            assert!(rc == 0, "pipe2: {}", io::Error::last_os_error());
4560            // SAFETY: both descriptors are fresh out of `pipe2` and owned by nothing else.
4561            let (read_fd, write_fd) =
4562                unsafe { (OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1])) };
4563
4564            // SAFETY: `fork()` from a possibly-multithreaded process is sound as long as the
4565            // child confines itself to work that does not depend on another thread's state. This
4566            // child calls `load()` in a loop, writes eight bytes and `_exit`s.
4567            let pid = unsafe { libc::fork() };
4568            assert!(pid >= 0, "fork failed: {}", io::Error::last_os_error());
4569
4570            if pid == 0 {
4571                let mut loads: u32 = 0;
4572                let mut refusal: i32 = 0;
4573                while loads < max_loads as u32 {
4574                    match filter.load() {
4575                        Ok(()) => loads += 1,
4576                        Err(error) => {
4577                            refusal = refusal_errno(&error);
4578                            break;
4579                        }
4580                    }
4581                }
4582
4583                let mut report = [0u8; 8];
4584                report[..4].copy_from_slice(&loads.to_ne_bytes());
4585                report[4..].copy_from_slice(&refusal.to_ne_bytes());
4586                // SAFETY: forked-child context; `write` is async-signal-safe, `report` is a live
4587                // local of exactly the length passed, and the descriptor is the pipe's write end.
4588                unsafe { libc::write(write_fd.as_raw_fd(), report.as_ptr().cast(), report.len()) };
4589                // SAFETY: forked-child context; `_exit` skips every destructor and atexit hook.
4590                unsafe { libc::_exit(0) }
4591            }
4592
4593            drop(write_fd);
4594            let mut report = [0u8; 8];
4595            std::io::Read::read_exact(&mut std::fs::File::from(read_fd), &mut report)
4596                .expect("read the cumulative probe child's report");
4597            let loads = u32::from_ne_bytes(report[..4].try_into().unwrap()) as usize;
4598            let refusal = i32::from_ne_bytes(report[4..].try_into().unwrap());
4599
4600            let mut status: libc::c_int = 0;
4601            // SAFETY: `pid` is the child just forked; `status` is a live local.
4602            let waited = unsafe { libc::waitpid(pid, &mut status, 0) };
4603            assert!(waited == pid, "waitpid: {}", io::Error::last_os_error());
4604
4605            let stacked = loads * count;
4606            let cumulative_at_refusal = count + loads * per_filter_cost;
4607            let loads_if_counted_classic = SECCOMP_MAX_INSNS_PER_PATH / per_filter_cost;
4608            let shipped = super::seccomp_filter_instruction_count(false)
4609                .expect("measure the shipped filter for comparison");
4610
4611            eprintln!(
4612                "seccomp cumulative ceiling: {loads} loads of a {count}-instruction filter \
4613                 succeeded ({stacked} instructions stacked, {cumulative_at_refusal} counted the \
4614                 way the kernel counts once the {KERNEL_PER_FILTER_OVERHEAD_INSNS}-instruction \
4615                 per-filter overhead is added); load {} was refused with errno {refusal} (ENOMEM \
4616                 is {}), against the recorded SECCOMP_MAX_INSNS_PER_PATH of \
4617                 {SECCOMP_MAX_INSNS_PER_PATH} — which the exported classic length puts at at most \
4618                 {loads_if_counted_classic} loads. The runtime installs ONE filter of {shipped} \
4619                 instructions, so reaching this ceiling would take {} of them in a single task.",
4620                loads + 1,
4621                libc::ENOMEM,
4622                SECCOMP_MAX_INSNS_PER_PATH / shipped,
4623            );
4624
4625            assert!(
4626                loads >= 2,
4627                "the kernel refused the filter chain after only {loads} load(s), so this is not \
4628                 a cumulative limit and the ENOMEM it returns is not the one being ruled out"
4629            );
4630            assert_eq!(
4631                refusal,
4632                libc::ENOMEM,
4633                "stacking filters past SECCOMP_MAX_INSNS_PER_PATH was refused with errno \
4634                 {refusal}, not ENOMEM ({}) — the rule-out in \
4635                 docs/content/reference/seccomp-filter-instruction-budget.md rests on ENOMEM \
4636                 being what this ceiling returns",
4637                libc::ENOMEM
4638            );
4639            assert!(
4640                loads <= loads_if_counted_classic,
4641                "the kernel took {loads} loads of a {count}-instruction filter — more than the \
4642                 {loads_if_counted_classic} that fit under SECCOMP_MAX_INSNS_PER_PATH \
4643                 ({SECCOMP_MAX_INSNS_PER_PATH}) even before the conversion to eBPF lengthens \
4644                 each one, so this kernel's ceiling is higher than the recorded value"
4645            );
4646            // Loose on purpose: the exported classic length under-counts what the kernel adds
4647            // up, so the bound below tolerates any plausible conversion expansion while still
4648            // refusing a ceiling of a different order of magnitude — a kernel that stopped at,
4649            // say, BPF_MAXINSNS would fail here.
4650            assert!(
4651                loads * 2 > loads_if_counted_classic,
4652                "the kernel refused after {loads} loads of a {count}-instruction filter, far \
4653                 short of the {loads_if_counted_classic} that SECCOMP_MAX_INSNS_PER_PATH \
4654                 ({SECCOMP_MAX_INSNS_PER_PATH}) implies — the ceiling being measured is not the \
4655                 one recorded"
4656            );
4657            assert!(
4658                shipped * 2 < SECCOMP_MAX_INSNS_PER_PATH,
4659                "the shipped filter ({shipped} instructions) is within a factor of two of the \
4660                 cumulative ceiling, which would make the rule-out this test supports untrue"
4661            );
4662        }
4663    }
4664}
4665
4666#[cfg(test)]
4667mod tests {
4668    use super::*;
4669    use murmur_artifact::security_warnings::W_SEC_003;
4670
4671    /// Content check only: this asserts the *constant*, not the security property. Spawning a
4672    /// subprocess and asserting it cannot see an inherited fd passes vacuously without kernel
4673    /// enforcement, so it would read as evidence while proving nothing.
4674    ///
4675    /// It does catch the one silent, catastrophic edit: a `0` here marks stdio close-on-exec and
4676    /// breaks every subprocess invocation on both spawn paths.
4677    #[test]
4678    fn fd_hygiene_range_starts_above_stdio() {
4679        assert_eq!(
4680            FD_HYGIENE_FIRST_FD, 3,
4681            "fd hygiene must start at 3 — 0/1/2 are the stdio pipes both spawn paths need to \
4682             survive execve"
4683        );
4684    }
4685
4686    /// `mark_inherited_fds_cloexec` reaches `close_range` through `libc::syscall`, so its failure
4687    /// convention is the raw one: `-1` with `errno` set. That convention is what turns a kernel
4688    /// that rejects the call into a failed `Command::spawn()` rather than a spawn that silently
4689    /// runs without fd hygiene.
4690    ///
4691    /// The rejection is provoked with an all-bits-set flag word, which the kernel refuses during
4692    /// argument validation before it touches any descriptor — so this exercises the errno path
4693    /// without closing or flagging a single fd of the test process. A kernel older than 5.11
4694    /// rejects the production call with a different errno and the identical convention — see the
4695    /// **Kernel range narrowing** paragraph on `mark_inherited_fds_cloexec`.
4696    #[cfg(target_os = "linux")]
4697    #[allow(unsafe_code)]
4698    #[test]
4699    fn close_range_syscall_reports_failure_as_minus_one_and_errno() {
4700        // SAFETY: `close_range` takes three scalar arguments and dereferences nothing. Every flag
4701        // bit is set here, so the kernel rejects the call on argument validation and no descriptor
4702        // of this process is closed or marked close-on-exec.
4703        let rc = unsafe {
4704            libc::syscall(
4705                libc::SYS_close_range,
4706                FD_HYGIENE_FIRST_FD,
4707                libc::c_uint::MAX,
4708                libc::c_uint::MAX,
4709            )
4710        };
4711
4712        assert_eq!(rc, -1, "an invalid flag word must not be accepted");
4713        assert_eq!(
4714            std::io::Error::last_os_error().raw_os_error(),
4715            Some(libc::EINVAL),
4716            "the two statements the production path runs on failure must carry the kernel's errno"
4717        );
4718    }
4719
4720    /// A host that can back the sealed mechanism: AppArmor out of the way, and a namespace probe
4721    /// that really created one.
4722    fn sealed_capable() -> crate::sealed::SealedProbe {
4723        crate::sealed::SealedProbe {
4724            userns_grant: crate::sealed::UsernsGrant::ProfileConfining,
4725            namespace: crate::sealed::NamespaceProbe::Ok,
4726        }
4727    }
4728
4729    /// A host that cannot: the default, which claims nothing.
4730    fn sealed_incapable() -> crate::sealed::SealedProbe {
4731        crate::sealed::SealedProbe::default()
4732    }
4733
4734    /// A probe that learned nothing: no Landlock answer and a sealed half that claims nothing.
4735    /// The reading a host gives when neither half of the probe could run.
4736    fn unprobed() -> HostProbe {
4737        HostProbe::from_parts(None, crate::sealed::SealedProbe::default())
4738    }
4739
4740    /// A probe that could not run must land on the weakest Linux tier, not on either kernel tier
4741    /// it failed to demonstrate. This is the fail-closed direction, asserted at the one place the
4742    /// tier is decided from a reading.
4743    #[test]
4744    fn an_unprobed_host_resolves_to_seccomp_only() {
4745        let tier = unprobed().tier();
4746        if cfg!(target_os = "linux") {
4747            assert_eq!(tier, EnforcementTier::KernelSeccompOnly);
4748        } else {
4749            assert_eq!(tier, EnforcementTier::EnvironmentOnly);
4750        }
4751        assert_ne!(tier, EnforcementTier::KernelSealed);
4752        assert_ne!(tier, EnforcementTier::KernelFull);
4753    }
4754
4755    /// A reading that demonstrated nothing must still name what is missing: a refusal with no
4756    /// blocker is a refusal an operator cannot act on.
4757    #[test]
4758    fn an_unprobed_host_names_a_blocker() {
4759        assert!(unprobed().sealed_blocker().is_some());
4760    }
4761
4762    /// The achieved class the trace records for an unprobed host stays strictly below `sealed`,
4763    /// so nothing downstream can read a failed probe as a met floor.
4764    #[test]
4765    fn an_unprobed_host_achieves_less_than_sealed() {
4766        let achieved = crate::containment::achieved_class_for_tier(unprobed().tier());
4767        assert!(achieved < murmur_artifact::ContainmentClass::Sealed);
4768    }
4769
4770    /// The whole point of the direction: a capsule declaring `sealed` against a reading that
4771    /// demonstrated nothing is refused, with the shortfall naming the mechanism.
4772    #[test]
4773    fn an_unprobed_host_refuses_a_declared_sealed_floor() {
4774        let probe = unprobed();
4775        let achieved = crate::containment::achieved_class_for_tier(probe.tier());
4776        let error = crate::containment::check_containment_floor(
4777            murmur_artifact::ContainmentClass::Sealed,
4778            achieved,
4779            probe.sealed_blocker(),
4780            false,
4781        )
4782        .expect_err("an unprobed host cannot back a declared sealed floor");
4783        assert!(matches!(
4784            error,
4785            crate::errors::RuntimeError::ContainmentFloorUnmet { .. }
4786        ));
4787    }
4788
4789    /// The tier decision reads only `UsernsGrant::permits_userns()`, so every grant that permits
4790    /// the namespace has to reach the same tier — otherwise reporting provenance would have
4791    /// changed an outcome, which is exactly what naming the grant set out not to do.
4792    #[test]
4793    fn tier_from_probe_is_identical_across_every_permitting_userns_grant() {
4794        use crate::sealed::{NamespaceProbe, SealedProbe, UsernsGrant};
4795
4796        for grant in UsernsGrant::ALL {
4797            let probe = SealedProbe {
4798                userns_grant: *grant,
4799                namespace: NamespaceProbe::Ok,
4800            };
4801            let expected = if grant.permits_userns() {
4802                EnforcementTier::KernelSealed
4803            } else {
4804                EnforcementTier::KernelFull
4805            };
4806            assert_eq!(
4807                tier_from_probe(true, Some(true), probe),
4808                expected,
4809                "grant {grant:?} must decide the tier only through permits_userns()"
4810            );
4811        }
4812    }
4813
4814    #[test]
4815    fn tier_from_probe_non_linux_is_always_environment_only() {
4816        for landlock in [None, Some(true), Some(false)] {
4817            for sealed in [sealed_capable(), sealed_incapable()] {
4818                assert_eq!(
4819                    tier_from_probe(false, landlock, sealed),
4820                    EnforcementTier::EnvironmentOnly
4821                );
4822            }
4823        }
4824    }
4825
4826    #[test]
4827    fn tier_from_probe_linux_fully_enforced_is_kernel_full() {
4828        assert_eq!(
4829            tier_from_probe(true, Some(true), sealed_incapable()),
4830            EnforcementTier::KernelFull
4831        );
4832    }
4833
4834    #[test]
4835    fn tier_from_probe_linux_partially_enforced_is_seccomp_only() {
4836        assert_eq!(
4837            tier_from_probe(true, Some(false), sealed_incapable()),
4838            EnforcementTier::KernelSeccompOnly
4839        );
4840    }
4841
4842    #[test]
4843    fn tier_from_probe_linux_no_probe_result_is_seccomp_only() {
4844        assert_eq!(
4845            tier_from_probe(true, None, sealed_incapable()),
4846            EnforcementTier::KernelSeccompOnly
4847        );
4848    }
4849
4850    /// The whole conjunction, one element removed at a time: `KernelSealed` needs Linux, a usable
4851    /// Landlock ABI, AppArmor out of the way, and a namespace probe that succeeded — and drops to
4852    /// exactly the tier the missing element still supports, never further.
4853    #[test]
4854    fn tier_from_probe_reaches_sealed_only_when_every_precondition_holds() {
4855        use crate::sealed::{NamespaceProbe, SealedProbe};
4856
4857        assert_eq!(
4858            tier_from_probe(true, Some(true), sealed_capable()),
4859            EnforcementTier::KernelSealed
4860        );
4861
4862        // No AppArmor profile (and the restriction is on) → the mechanism is unavailable, but
4863        // Landlock still is: `scoped`, not `advisory`.
4864        assert_eq!(
4865            tier_from_probe(
4866                true,
4867                Some(true),
4868                SealedProbe {
4869                    userns_grant: crate::sealed::UsernsGrant::Withheld,
4870                    namespace: NamespaceProbe::Ok
4871                }
4872            ),
4873            EnforcementTier::KernelFull
4874        );
4875
4876        // The container case, and its three other namespace failure modes.
4877        for namespace in [
4878            NamespaceProbe::Denied,
4879            NamespaceProbe::MapDenied,
4880            NamespaceProbe::MountDenied,
4881            NamespaceProbe::Unsupported,
4882        ] {
4883            assert_eq!(
4884                tier_from_probe(
4885                    true,
4886                    Some(true),
4887                    SealedProbe {
4888                        userns_grant: crate::sealed::UsernsGrant::ProfileConfining,
4889                        namespace
4890                    }
4891                ),
4892                EnforcementTier::KernelFull,
4893                "namespace probe {namespace:?} must fall back to KernelFull, never below it"
4894            );
4895        }
4896
4897        // Landlock missing: sealed keeps Landlock inside as defence in depth, so a host without it
4898        // cannot reach sealed no matter how good its namespaces are.
4899        assert_eq!(
4900            tier_from_probe(true, Some(false), sealed_capable()),
4901            EnforcementTier::KernelSeccompOnly
4902        );
4903        assert_eq!(
4904            tier_from_probe(true, None, sealed_capable()),
4905            EnforcementTier::KernelSeccompOnly
4906        );
4907
4908        // Not Linux at all.
4909        assert_eq!(
4910            tier_from_probe(false, Some(true), sealed_capable()),
4911            EnforcementTier::EnvironmentOnly
4912        );
4913    }
4914
4915    /// A capsule that declared the weaker class keeps the weaker mechanism, even where the host
4916    /// could give it more. Silently installing a composed root under a `scoped` declaration would
4917    /// delete host paths its `interpreter_runtime` grants legitimately name.
4918    #[test]
4919    fn applied_tier_never_installs_a_composed_root_for_a_weaker_declaration() {
4920        use murmur_artifact::ContainmentClass;
4921
4922        assert_eq!(
4923            applied_tier(EnforcementTier::KernelSealed, ContainmentClass::Sealed),
4924            EnforcementTier::KernelSealed
4925        );
4926        for declared in [ContainmentClass::Advisory, ContainmentClass::Scoped] {
4927            assert_eq!(
4928                applied_tier(EnforcementTier::KernelSealed, declared),
4929                EnforcementTier::KernelFull,
4930                "declaring {declared} must not opt a capsule into the composed root"
4931            );
4932        }
4933
4934        // Every other tier is passed through untouched, whatever was declared — the declared floor
4935        // can only ever weaken the applied mechanism, never strengthen it past the host.
4936        for host_tier in [
4937            EnforcementTier::KernelFull,
4938            EnforcementTier::KernelSeccompOnly,
4939            EnforcementTier::EnvironmentOnly,
4940        ] {
4941            for declared in [
4942                ContainmentClass::Advisory,
4943                ContainmentClass::Scoped,
4944                ContainmentClass::Sealed,
4945            ] {
4946                assert_eq!(applied_tier(host_tier, declared), host_tier);
4947            }
4948        }
4949    }
4950
4951    #[test]
4952    fn sealed_bind_dirs_are_whole_directories_outside_the_fixed_runtime_paths() {
4953        use murmur_artifact::{InterpreterRuntimeDir, InterpreterRuntimeGrant};
4954
4955        let policy = CapabilityPolicy {
4956            shell_interpreter_runtime: vec![InterpreterRuntimeGrant {
4957                binary: "python3".to_string(),
4958                dirs: vec![
4959                    // Already inside /usr, which the fixed list binds wholesale.
4960                    InterpreterRuntimeDir {
4961                        path: "/usr/lib/python3.11".to_string(),
4962                        list_dir: true,
4963                    },
4964                    InterpreterRuntimeDir {
4965                        path: "/opt/py/lib".to_string(),
4966                        list_dir: true,
4967                    },
4968                    // A duplicate, and a relative path that names nothing absolute.
4969                    InterpreterRuntimeDir {
4970                        path: "/opt/py/lib".to_string(),
4971                        list_dir: false,
4972                    },
4973                    InterpreterRuntimeDir {
4974                        path: "relative/lib".to_string(),
4975                        list_dir: false,
4976                    },
4977                ],
4978            }],
4979            ..CapabilityPolicy::default()
4980        };
4981        let exec_allow = vec![
4982            PathBuf::from("/usr/bin/python3"),
4983            PathBuf::from("/opt/toolchain/bin/cc"),
4984        ];
4985
4986        assert_eq!(
4987            resolve_sealed_bind_dirs(&exec_allow, &policy),
4988            vec![
4989                PathBuf::from("/opt/toolchain/bin"),
4990                PathBuf::from("/opt/py/lib")
4991            ]
4992        );
4993    }
4994
4995    /// Staged trees are resolved by a different rule than `sealed_bind_dirs` above, and the
4996    /// differences are the point: a path inside a fixed runtime path is kept (dropping it would
4997    /// silently make a required grant depend on an unrelated list), duplicates collapse, and a
4998    /// relative path — which cannot be re-based under the composed root at all — is skipped.
4999    #[test]
5000    fn staged_runtime_dirs_keep_fixed_path_overlaps_and_drop_only_duplicates_and_relatives() {
5001        use murmur_artifact::StagedRuntimeGrant;
5002
5003        let grant = |binary: &str, source: &str| StagedRuntimeGrant {
5004            binary: binary.to_string(),
5005            source_path: source.to_string(),
5006            pin: "pin-1".to_string(),
5007        };
5008        let policy = CapabilityPolicy {
5009            shell_staged_runtime: vec![
5010                grant("python3", "/opt/py"),
5011                // Inside /usr, which the fixed list already binds. Kept anyway — unlike
5012                // `resolve_sealed_bind_dirs`, which drops exactly this case.
5013                grant("perl", "/usr/lib/perl5"),
5014                // A duplicate of the first, and a relative path naming nothing absolute.
5015                grant("python3.12", "/opt/py"),
5016                grant("ruby", "relative/ruby"),
5017            ],
5018            ..CapabilityPolicy::default()
5019        };
5020
5021        assert_eq!(
5022            resolve_staged_runtime_dirs(&policy),
5023            vec![PathBuf::from("/opt/py"), PathBuf::from("/usr/lib/perl5")]
5024        );
5025    }
5026
5027    /// The bind is only half of it: `sealed` keeps Landlock installed inside the composed root, so
5028    /// a staged tree with no Landlock rule is mounted-but-unreadable (`EACCES`). Both resolvers
5029    /// must therefore cover the same directories.
5030    #[test]
5031    fn every_staged_runtime_dir_also_gets_a_listable_landlock_grant() {
5032        use murmur_artifact::StagedRuntimeGrant;
5033
5034        let policy = CapabilityPolicy {
5035            shell_staged_runtime: vec![StagedRuntimeGrant {
5036                binary: "python3".to_string(),
5037                source_path: "/opt/py".to_string(),
5038                pin: "pin-1".to_string(),
5039            }],
5040            ..CapabilityPolicy::default()
5041        };
5042
5043        let dirs = resolve_staged_runtime_dirs(&policy);
5044        let grants = resolve_staged_runtime_landlock_grants(&policy);
5045
5046        assert_eq!(
5047            grants,
5048            vec![LandlockGrant {
5049                path: PathBuf::from("/opt/py"),
5050                list_dir: true,
5051                executable: true,
5052            }],
5053            "a staged tree is walked by the runtime that uses it, so it must be listable",
5054        );
5055        assert_eq!(
5056            grants
5057                .iter()
5058                .map(|grant| grant.path.clone())
5059                .collect::<Vec<_>>(),
5060            dirs,
5061            "the bound set and the granted set must not drift apart",
5062        );
5063    }
5064
5065    #[test]
5066    fn every_sealed_runtime_path_gets_a_listable_non_executable_landlock_grant() {
5067        let grants = resolve_sealed_runtime_landlock_grants(EnforcementTier::KernelSealed);
5068
5069        assert_eq!(
5070            grants,
5071            crate::sealed::SEALED_RUNTIME_PATHS
5072                .iter()
5073                .map(|path| LandlockGrant {
5074                    path: PathBuf::from(path),
5075                    list_dir: true,
5076                    executable: false,
5077                })
5078                .collect::<Vec<_>>(),
5079            "the composed root binds exactly these, so exactly these must be enumerable — \
5080             the bound set and the granted set must not drift apart",
5081        );
5082        assert!(
5083            grants.iter().all(|grant| grant.list_dir),
5084            "a runtime tree an interpreter walks is useless without getdents64",
5085        );
5086        assert!(
5087            grants.iter().all(|grant| !grant.executable),
5088            "Execute is the exec allowlist: granting it over /usr, /bin and /sbin would let a \
5089             sealed capsule run every binary the host ships, whatever shell.allow says",
5090        );
5091    }
5092
5093    #[test]
5094    fn sealed_runtime_landlock_grants_are_sealed_tier_only() {
5095        for tier in [
5096            EnforcementTier::KernelFull,
5097            EnforcementTier::KernelSeccompOnly,
5098            EnforcementTier::EnvironmentOnly,
5099        ] {
5100            assert!(
5101                resolve_sealed_runtime_landlock_grants(tier).is_empty(),
5102                "{tier:?} has no composed root, so granting ReadDir on SEALED_RUNTIME_PATHS \
5103                 would enumerate the real host filesystem",
5104            );
5105        }
5106    }
5107
5108    /// The gate as `ShellEnforcement::resolve` actually applies it. `applied_tier` never returns
5109    /// `KernelSealed` for a capsule declaring `scoped`, on any host, so this half is host-
5110    /// independent; the `sealed` half asserts against whatever tier this host resolved to, which
5111    /// is the only honest thing a test can do about a kernel capability it may not have.
5112    #[test]
5113    fn shell_enforcement_grants_sealed_runtime_paths_only_when_sealed_applies() {
5114        let policy = CapabilityPolicy::default();
5115        let usr = PathBuf::from("/usr");
5116
5117        let scoped = ShellEnforcement::resolve(
5118            &policy,
5119            murmur_artifact::ContainmentClass::Scoped,
5120            HostProbe::probe(),
5121        )
5122        .expect("an empty policy resolves");
5123        assert!(
5124            !scoped.landlock_grants.iter().any(|grant| grant.path == usr),
5125            "a scoped capsule runs Landlock over the real host filesystem — /usr must stay \
5126             unenumerable there",
5127        );
5128
5129        let sealed = ShellEnforcement::resolve(
5130            &policy,
5131            murmur_artifact::ContainmentClass::Sealed,
5132            HostProbe::probe(),
5133        )
5134        .expect("an empty policy resolves");
5135        let granted: Vec<&LandlockGrant> = sealed
5136            .landlock_grants
5137            .iter()
5138            .filter(|grant| {
5139                crate::sealed::SEALED_RUNTIME_PATHS.contains(&grant.path.to_str().unwrap_or(""))
5140            })
5141            .collect();
5142        if sealed.tier == EnforcementTier::KernelSealed {
5143            assert_eq!(
5144                granted.len(),
5145                crate::sealed::SEALED_RUNTIME_PATHS.len(),
5146                "a sealed session must carry one listable grant per bound runtime path",
5147            );
5148            assert!(granted
5149                .iter()
5150                .all(|grant| grant.list_dir && !grant.executable));
5151        } else {
5152            assert!(
5153                granted.is_empty(),
5154                "this host fell back to {:?}, where there is no composed root to enumerate",
5155                sealed.tier,
5156            );
5157        }
5158    }
5159
5160    #[test]
5161    fn every_sealed_etc_path_gets_a_non_executable_landlock_grant() {
5162        let grants = resolve_sealed_etc_landlock_grants(EnforcementTier::KernelSealed);
5163
5164        assert_eq!(
5165            grants,
5166            crate::sealed::SEALED_ETC_PATHS
5167                .iter()
5168                .map(|entry| LandlockGrant {
5169                    path: PathBuf::from(entry.path),
5170                    list_dir: entry.directory,
5171                    executable: false,
5172                })
5173                .collect::<Vec<_>>(),
5174            "the composed root binds exactly these /etc entries, so exactly these must be \
5175             readable — the bound set and the granted set must not drift apart",
5176        );
5177        assert!(
5178            grants.iter().all(|grant| !grant.executable),
5179            "Execute is the exec allowlist, and nothing in /etc is a program a manifest asked to \
5180             run — /etc/alternatives is a directory of symlinks into /usr/bin",
5181        );
5182
5183        // The `directory` classification itself, spelled out independently of the constant so a
5184        // silent reclassification (which would cost an entry its ReadDir, or claim ReadDir on a
5185        // regular file) shows up as a test failure rather than as a TLS bug on a real host.
5186        let listable: Vec<&str> = grants
5187            .iter()
5188            .filter(|grant| grant.list_dir)
5189            .map(|grant| grant.path.to_str().unwrap())
5190            .collect();
5191        assert_eq!(
5192            listable,
5193            vec![
5194                "/etc/ld.so.conf.d",
5195                "/etc/alternatives",
5196                "/etc/ssl",
5197                "/etc/pki",
5198                "/etc/ca-certificates",
5199                "/etc/terminfo",
5200            ],
5201            "ReadDir belongs to exactly the directory entries: os.listdir('/etc/ssl/certs') and \
5202             the c_rehash symlink lookup need it, and a regular file has no meaningful ReadDir",
5203        );
5204    }
5205
5206    #[test]
5207    fn sealed_etc_landlock_grants_are_sealed_tier_only() {
5208        for tier in [
5209            EnforcementTier::KernelFull,
5210            EnforcementTier::KernelSeccompOnly,
5211            EnforcementTier::EnvironmentOnly,
5212        ] {
5213            assert!(
5214                resolve_sealed_etc_landlock_grants(tier).is_empty(),
5215                "{tier:?} has no composed root, so these rules would hand out the real host's \
5216                 /etc — its trust store, resolv.conf and account databases",
5217            );
5218        }
5219    }
5220
5221    /// The gate as `ShellEnforcement::resolve` actually applies it, modelled on
5222    /// `shell_enforcement_grants_sealed_runtime_paths_only_when_sealed_applies`: the `scoped` half
5223    /// is host-independent (`applied_tier` never returns `KernelSealed` for a `scoped`
5224    /// declaration), and the `sealed` half asserts against whatever tier this host resolved to.
5225    #[test]
5226    fn shell_enforcement_grants_sealed_etc_paths_only_when_sealed_applies() {
5227        let policy = CapabilityPolicy::default();
5228        let is_etc_grant = |grant: &LandlockGrant| {
5229            crate::sealed::SEALED_ETC_PATHS
5230                .iter()
5231                .any(|entry| Path::new(entry.path) == grant.path)
5232        };
5233
5234        let scoped = ShellEnforcement::resolve(
5235            &policy,
5236            murmur_artifact::ContainmentClass::Scoped,
5237            HostProbe::probe(),
5238        )
5239        .expect("an empty policy resolves");
5240        assert!(
5241            !scoped.landlock_grants.iter().any(is_etc_grant),
5242            "a scoped capsule runs Landlock over the real host filesystem — /etc/shadow's \
5243             neighbours must not become readable there",
5244        );
5245
5246        let sealed = ShellEnforcement::resolve(
5247            &policy,
5248            murmur_artifact::ContainmentClass::Sealed,
5249            HostProbe::probe(),
5250        )
5251        .expect("an empty policy resolves");
5252        let granted: Vec<&LandlockGrant> = sealed
5253            .landlock_grants
5254            .iter()
5255            .filter(|grant| is_etc_grant(grant))
5256            .collect();
5257        if sealed.tier == EnforcementTier::KernelSealed {
5258            assert_eq!(
5259                granted.len(),
5260                crate::sealed::SEALED_ETC_PATHS.len(),
5261                "a sealed session must carry one read grant per bound /etc entry",
5262            );
5263            assert!(granted.iter().all(|grant| !grant.executable));
5264        } else {
5265            assert!(
5266                granted.is_empty(),
5267                "this host fell back to {:?}, where there is no composed root and /etc is the \
5268                 host's own",
5269                sealed.tier,
5270            );
5271        }
5272    }
5273
5274    #[test]
5275    fn resolve_network_allowlist_ips_empty_list_is_empty() {
5276        let ips = resolve_network_allowlist_ips(&[]).unwrap();
5277        assert!(ips.is_empty());
5278    }
5279
5280    #[test]
5281    fn resolve_network_allowlist_ips_resolves_localhost_to_loopback() {
5282        let ips = resolve_network_allowlist_ips(&["localhost".to_string()]).unwrap();
5283        assert!(
5284            !ips.is_empty(),
5285            "localhost should resolve to at least one address"
5286        );
5287        assert!(
5288            ips.iter().all(|ip| ip.is_loopback()),
5289            "every resolved localhost address should be loopback, got {ips:?}"
5290        );
5291    }
5292
5293    #[test]
5294    fn resolve_network_allowlist_ips_rejects_invalid_host_syntax_cleanly() {
5295        let error = resolve_network_allowlist_ips(&["".to_string()]).unwrap_err();
5296        assert!(!error.is_empty());
5297    }
5298
5299    /// A host that does not resolve contributes zero IPs instead of failing the whole call. The
5300    /// resolved set only ever *shrinks* the kernel-level `shell.allow` enforcement set, so a DNS
5301    /// miss is fail-closed, not fatal. `.invalid` is reserved by RFC 2606 and is guaranteed never
5302    /// to resolve, which keeps this test independent of the host's DNS.
5303    #[test]
5304    fn resolve_network_allowlist_ips_skips_unresolvable_host_without_failing() {
5305        let ips =
5306            resolve_network_allowlist_ips(&["definitely-not-a-real-host.invalid".to_string()])
5307                .expect("an unresolvable host must not be a hard error");
5308        assert!(
5309            ips.is_empty(),
5310            "an unresolvable host should contribute no IPs, got {ips:?}"
5311        );
5312    }
5313
5314    /// The unresolvable host is skipped while the resolvable one still contributes its IPs — the
5315    /// loop continues rather than aborting on the first miss.
5316    #[test]
5317    fn resolve_network_allowlist_ips_keeps_resolvable_hosts_when_another_is_unresolvable() {
5318        let ips = resolve_network_allowlist_ips(&[
5319            "definitely-not-a-real-host.invalid".to_string(),
5320            "localhost".to_string(),
5321        ])
5322        .expect("a mix of resolvable and unresolvable hosts must not be a hard error");
5323
5324        assert!(
5325            !ips.is_empty(),
5326            "localhost's addresses should survive alongside an unresolvable host"
5327        );
5328        assert!(
5329            ips.iter().all(|ip| ip.is_loopback()),
5330            "only localhost should have contributed addresses, got {ips:?}"
5331        );
5332    }
5333
5334    #[test]
5335    fn resolve_network_allowlist_ips_dedupes_across_hosts() {
5336        // Two entries that both resolve to loopback should not produce duplicate IPs beyond
5337        // what's actually distinct.
5338        let ips =
5339            resolve_network_allowlist_ips(&["localhost".to_string(), "localhost:8080".to_string()])
5340                .unwrap();
5341        let mut sorted = ips.clone();
5342        sorted.sort();
5343        sorted.dedup();
5344        assert_eq!(
5345            ips.len(),
5346            sorted.len(),
5347            "resolved IPs should already be deduplicated"
5348        );
5349    }
5350
5351    #[test]
5352    fn environment_only_has_no_resolved_ips_and_environment_only_tier() {
5353        let enforcement = ShellEnforcement::environment_only();
5354        assert_eq!(enforcement.tier, EnforcementTier::EnvironmentOnly);
5355        assert!(enforcement.network_allow_ips.is_empty());
5356    }
5357
5358    fn make_executable(path: &Path, contents: &str) {
5359        use std::os::unix::fs::PermissionsExt;
5360        std::fs::write(path, contents).unwrap();
5361        let mut perms = std::fs::metadata(path).unwrap().permissions();
5362        perms.set_mode(0o755);
5363        std::fs::set_permissions(path, perms).unwrap();
5364    }
5365
5366    fn bootstrap_log_contents(workdir: &Path) -> String {
5367        std::fs::read_to_string(workdir.join("logs").join("bootstrap.log")).unwrap_or_default()
5368    }
5369
5370    // ---- exec allowlist resolution (identity, not names) ----
5371
5372    #[test]
5373    fn resolve_exec_allowlist_resolves_bare_name_via_path_dirs() {
5374        let temp = tempfile::tempdir().unwrap();
5375        let bin_dir = temp.path().join("bin");
5376        std::fs::create_dir(&bin_dir).unwrap();
5377        let tool = bin_dir.join("mytool");
5378        make_executable(&tool, "#!/bin/sh\nexit 0\n");
5379
5380        let resolved = resolve_exec_allowlist_in(&["mytool".to_string()], &[bin_dir]);
5381        assert_eq!(resolved, vec![std::fs::canonicalize(&tool).unwrap()]);
5382    }
5383
5384    #[test]
5385    fn resolve_exec_allowlist_skips_entries_that_do_not_resolve() {
5386        let temp = tempfile::tempdir().unwrap();
5387        let resolved = resolve_exec_allowlist_in(
5388            &["definitely-not-a-real-binary".to_string(), String::new()],
5389            &[temp.path().to_path_buf()],
5390        );
5391        assert!(
5392            resolved.is_empty(),
5393            "unresolvable entries must shrink (not fail) the allow set: {resolved:?}"
5394        );
5395    }
5396
5397    #[test]
5398    fn resolve_exec_allowlist_ignores_non_executable_path_matches() {
5399        let temp = tempfile::tempdir().unwrap();
5400        std::fs::write(temp.path().join("mytool"), "not executable").unwrap();
5401        let resolved =
5402            resolve_exec_allowlist_in(&["mytool".to_string()], &[temp.path().to_path_buf()]);
5403        assert!(resolved.is_empty());
5404    }
5405
5406    #[test]
5407    fn resolve_exec_allowlist_canonicalizes_path_entries_through_symlinks() {
5408        let temp = tempfile::tempdir().unwrap();
5409        let real = temp.path().join("real-tool");
5410        make_executable(&real, "#!/bin/sh\nexit 0\n");
5411        let link = temp.path().join("link-tool");
5412        std::os::unix::fs::symlink(&real, &link).unwrap();
5413
5414        let resolved = resolve_exec_allowlist_in(&[link.to_string_lossy().into_owned()], &[]);
5415        assert_eq!(resolved, vec![std::fs::canonicalize(&real).unwrap()]);
5416    }
5417
5418    // ---- invoked-binary reporting (shell-event.binary / trace.jsonl `binary`) ----
5419
5420    #[test]
5421    fn resolve_invoked_binary_path_resolves_bare_name_via_path_dirs() {
5422        let temp = tempfile::tempdir().unwrap();
5423        let bin_dir = temp.path().join("bin");
5424        std::fs::create_dir(&bin_dir).unwrap();
5425        let tool = bin_dir.join("mytool");
5426        make_executable(&tool, "#!/bin/sh\nexit 0\n");
5427
5428        let resolved = resolve_invoked_binary_path_in("mytool", &[bin_dir]);
5429        assert_eq!(
5430            resolved,
5431            std::fs::canonicalize(&tool)
5432                .unwrap()
5433                .to_string_lossy()
5434                .into_owned(),
5435            "a resolvable name must report the canonical absolute path, not the bare name"
5436        );
5437    }
5438
5439    #[test]
5440    fn resolve_invoked_binary_path_falls_back_to_bare_name_when_unresolvable() {
5441        let temp = tempfile::tempdir().unwrap();
5442        let path_dirs = [temp.path().to_path_buf()];
5443        let resolved = resolve_invoked_binary_path_in("definitely-not-a-real-binary", &path_dirs);
5444        assert_eq!(
5445            resolved, "definitely-not-a-real-binary",
5446            "an unresolvable name must fall back to the bare name, never error"
5447        );
5448        assert_eq!(resolve_invoked_binary_path_in("", &[]), "");
5449    }
5450
5451    #[test]
5452    fn resolve_invoked_binary_path_takes_the_first_path_match() {
5453        let temp = tempfile::tempdir().unwrap();
5454        let first = temp.path().join("first");
5455        let second = temp.path().join("second");
5456        std::fs::create_dir(&first).unwrap();
5457        std::fs::create_dir(&second).unwrap();
5458        make_executable(&first.join("mytool"), "#!/bin/sh\nexit 0\n");
5459        make_executable(&second.join("mytool"), "#!/bin/sh\nexit 1\n");
5460
5461        let resolved = resolve_invoked_binary_path_in("mytool", &[first.clone(), second]);
5462        assert_eq!(
5463            resolved,
5464            std::fs::canonicalize(first.join("mytool"))
5465                .unwrap()
5466                .to_string_lossy()
5467                .into_owned(),
5468            "reporting must match execvp: the first PATH hit is the one that ran"
5469        );
5470    }
5471
5472    #[test]
5473    fn resolve_invoked_binary_path_ignores_non_executable_path_matches() {
5474        let temp = tempfile::tempdir().unwrap();
5475        std::fs::write(temp.path().join("mytool"), "not executable").unwrap();
5476        assert_eq!(
5477            resolve_invoked_binary_path_in("mytool", &[temp.path().to_path_buf()]),
5478            "mytool"
5479        );
5480    }
5481
5482    #[test]
5483    fn resolve_invoked_binary_path_canonicalizes_a_path_entry_through_symlinks() {
5484        let temp = tempfile::tempdir().unwrap();
5485        let real = temp.path().join("real-tool");
5486        make_executable(&real, "#!/bin/sh\nexit 0\n");
5487        let link = temp.path().join("link-tool");
5488        std::os::unix::fs::symlink(&real, &link).unwrap();
5489
5490        assert_eq!(
5491            resolve_invoked_binary_path_in(&link.to_string_lossy(), &[]),
5492            std::fs::canonicalize(&real)
5493                .unwrap()
5494                .to_string_lossy()
5495                .into_owned()
5496        );
5497    }
5498
5499    // ---- ELF dependency parsing (pure, synthetic fixtures — runs on every OS) ----
5500
5501    /// Builds a minimal but well-formed ELF64 image exercising exactly the fields
5502    /// `parse_elf_dependencies` reads: a single identity-mapped `PT_LOAD` (so virtual address ==
5503    /// file offset), an optional `PT_INTERP`, and — when any dynamic metadata is requested — a
5504    /// `PT_DYNAMIC` with `DT_NEEDED`/`DT_RUNPATH`/`DT_STRTAB`/`DT_STRSZ`/`DT_NULL` entries.
5505    fn build_elf64(interp: Option<&str>, needed: &[&str], runpath: Option<&str>) -> Vec<u8> {
5506        let has_dynamic = !needed.is_empty() || runpath.is_some();
5507
5508        let mut phnum: u16 = 1; // PT_LOAD
5509        if interp.is_some() {
5510            phnum += 1;
5511        }
5512        if has_dynamic {
5513            phnum += 1;
5514        }
5515
5516        let ehsize = 64usize;
5517        let phentsize = 56usize;
5518        let phoff = ehsize;
5519        let body_start = phoff + phentsize * phnum as usize;
5520
5521        // Dynamic string table: index 0 is a NUL, then each soname and the runpath.
5522        let mut strtab: Vec<u8> = vec![0];
5523        let mut needed_offsets = Vec::new();
5524        for name in needed {
5525            needed_offsets.push(strtab.len() as u64);
5526            strtab.extend_from_slice(name.as_bytes());
5527            strtab.push(0);
5528        }
5529        let runpath_offset = runpath.map(|r| {
5530            let off = strtab.len() as u64;
5531            strtab.extend_from_slice(r.as_bytes());
5532            strtab.push(0);
5533            off
5534        });
5535
5536        let mut body: Vec<u8> = Vec::new();
5537
5538        let interp_offset = body_start + body.len();
5539        if let Some(i) = interp {
5540            body.extend_from_slice(i.as_bytes());
5541            body.push(0);
5542        }
5543
5544        // Align the dynamic array to 8 bytes.
5545        while !(body_start + body.len()).is_multiple_of(8) {
5546            body.push(0);
5547        }
5548        let dyn_offset = body_start + body.len();
5549        let num_dyn = needed.len() + runpath.map_or(0, |_| 1) + 3; // + DT_STRTAB, DT_STRSZ, DT_NULL
5550        let dyn_size = num_dyn * 16;
5551        let strtab_offset = dyn_offset + dyn_size;
5552
5553        if has_dynamic {
5554            let mut push_dyn = |tag: u64, val: u64| {
5555                body.extend_from_slice(&tag.to_le_bytes());
5556                body.extend_from_slice(&val.to_le_bytes());
5557            };
5558            for &o in &needed_offsets {
5559                push_dyn(1, o); // DT_NEEDED
5560            }
5561            if let Some(ro) = runpath_offset {
5562                push_dyn(29, ro); // DT_RUNPATH
5563            }
5564            push_dyn(5, strtab_offset as u64); // DT_STRTAB (vaddr == offset, identity PT_LOAD)
5565            push_dyn(10, strtab.len() as u64); // DT_STRSZ
5566            push_dyn(0, 0); // DT_NULL
5567            assert_eq!(body_start + body.len(), strtab_offset);
5568            body.extend_from_slice(&strtab);
5569        }
5570
5571        let total_len = body_start + body.len();
5572        let mut out = vec![0u8; total_len];
5573        out[0..4].copy_from_slice(b"\x7fELF");
5574        out[4] = 2; // ELFCLASS64
5575        out[5] = 1; // little-endian
5576        out[6] = 1; // EI_VERSION
5577        out[16..18].copy_from_slice(&3u16.to_le_bytes()); // e_type = ET_DYN
5578        out[18..20].copy_from_slice(&0x3eu16.to_le_bytes()); // e_machine = x86_64 (irrelevant)
5579        out[20..24].copy_from_slice(&1u32.to_le_bytes()); // e_version
5580        out[32..40].copy_from_slice(&(phoff as u64).to_le_bytes()); // e_phoff
5581        out[54..56].copy_from_slice(&(phentsize as u16).to_le_bytes()); // e_phentsize
5582        out[56..58].copy_from_slice(&phnum.to_le_bytes()); // e_phnum
5583
5584        let mut phdrs: Vec<(u32, u64, u64, u64)> = Vec::new(); // (p_type, p_offset, p_vaddr, p_filesz)
5585        phdrs.push((1, 0, 0, total_len as u64)); // PT_LOAD identity-maps the whole file
5586        if let Some(i) = interp {
5587            phdrs.push((
5588                3,
5589                interp_offset as u64,
5590                interp_offset as u64,
5591                i.len() as u64 + 1,
5592            ));
5593        }
5594        if has_dynamic {
5595            phdrs.push((2, dyn_offset as u64, dyn_offset as u64, dyn_size as u64));
5596        }
5597        for (idx, (p_type, p_offset, p_vaddr, p_filesz)) in phdrs.iter().enumerate() {
5598            let base = phoff + idx * phentsize;
5599            out[base..base + 4].copy_from_slice(&p_type.to_le_bytes());
5600            out[base + 8..base + 16].copy_from_slice(&p_offset.to_le_bytes());
5601            out[base + 16..base + 24].copy_from_slice(&p_vaddr.to_le_bytes());
5602            out[base + 32..base + 40].copy_from_slice(&p_filesz.to_le_bytes());
5603        }
5604
5605        out[body_start..total_len].copy_from_slice(&body);
5606        out
5607    }
5608
5609    #[test]
5610    fn parse_elf_extracts_interp_needed_and_runpath() {
5611        let bytes = build_elf64(
5612            Some("/lib64/ld-linux-x86-64.so.2"),
5613            &["libc.so.6", "libm.so.6"],
5614            Some("$ORIGIN/../lib:/opt/custom/lib"),
5615        );
5616        let deps = parse_elf_dependencies(&bytes).expect("well-formed ELF64 must parse");
5617        assert_eq!(deps.interp.as_deref(), Some("/lib64/ld-linux-x86-64.so.2"));
5618        assert_eq!(
5619            deps.needed,
5620            vec!["libc.so.6".to_string(), "libm.so.6".to_string()]
5621        );
5622        assert_eq!(
5623            deps.runpaths,
5624            vec!["$ORIGIN/../lib".to_string(), "/opt/custom/lib".to_string()],
5625            "DT_RUNPATH must be split on ':' with empty parts dropped"
5626        );
5627    }
5628
5629    #[test]
5630    fn parse_elf_static_binary_contributes_only_itself() {
5631        // No PT_INTERP, no PT_DYNAMIC — a statically linked binary.
5632        let bytes = build_elf64(None, &[], None);
5633        let deps = parse_elf_dependencies(&bytes).expect("a static ELF64 is still valid ELF");
5634        assert_eq!(deps, ElfDependencies::default());
5635    }
5636
5637    #[test]
5638    fn parse_elf_rejects_non_elf_and_non_elf64() {
5639        assert!(parse_elf_dependencies(b"not an elf at all, way too short").is_none());
5640        // Correct magic but ELFCLASS32 (byte 4 == 1) must be rejected.
5641        let mut elf32 = build_elf64(Some("/lib/ld.so"), &["libc.so.6"], None);
5642        elf32[4] = 1;
5643        assert!(
5644            parse_elf_dependencies(&elf32).is_none(),
5645            "32-bit ELF is not a binary this runtime execs and must not parse"
5646        );
5647    }
5648
5649    // ---- soname resolution (loader search-order, synthetic fixtures) ----
5650
5651    #[test]
5652    fn resolve_soname_finds_via_search_dirs_and_runpath_origin() {
5653        let temp = tempfile::tempdir().unwrap();
5654        let origin = temp.path().join("app");
5655        std::fs::create_dir(&origin).unwrap();
5656        let libs = temp.path().join("libs");
5657        std::fs::create_dir(&libs).unwrap();
5658        std::fs::write(libs.join("libc.so.6"), "x").unwrap();
5659
5660        // Found in a standard search directory.
5661        assert_eq!(
5662            resolve_soname("libc.so.6", &origin, &[], std::slice::from_ref(&libs)),
5663            Some(std::fs::canonicalize(libs.join("libc.so.6")).unwrap())
5664        );
5665        // Unresolvable soname → None (shrink-not-fail).
5666        assert_eq!(
5667            resolve_soname("libmissing.so", &origin, &[], std::slice::from_ref(&libs)),
5668            None
5669        );
5670
5671        // Found via a `$ORIGIN`-relative DT_RUNPATH, taking precedence over the search dirs.
5672        let origin_lib = origin.join("lib");
5673        std::fs::create_dir(&origin_lib).unwrap();
5674        std::fs::write(origin_lib.join("libfoo.so"), "x").unwrap();
5675        assert_eq!(
5676            resolve_soname("libfoo.so", &origin, &["$ORIGIN/lib".to_string()], &[]),
5677            Some(std::fs::canonicalize(origin_lib.join("libfoo.so")).unwrap())
5678        );
5679    }
5680
5681    // ---- transitive Landlock grant derivation (synthetic ELF + fake libs) ----
5682
5683    #[test]
5684    fn resolve_landlock_grants_derives_interp_and_needed_closure() {
5685        let temp = tempfile::tempdir().unwrap();
5686        let bin_dir = temp.path().join("bin");
5687        let lib_dir = temp.path().join("lib");
5688        std::fs::create_dir(&bin_dir).unwrap();
5689        std::fs::create_dir(&lib_dir).unwrap();
5690
5691        // A fake interpreter and a fake shared library, both outside any "workdir".
5692        let interp = bin_dir.join("ld-fake.so");
5693        std::fs::write(&interp, "not really elf").unwrap();
5694        std::fs::write(lib_dir.join("libfake.so.1"), "not really elf").unwrap();
5695
5696        // A synthetic dynamically-linked binary naming that interp + that soname.
5697        let prog = bin_dir.join("prog");
5698        let elf = build_elf64(Some(interp.to_str().unwrap()), &["libfake.so.1"], None);
5699        std::fs::write(&prog, &elf).unwrap();
5700
5701        let grants =
5702            resolve_landlock_grants_in(std::slice::from_ref(&prog), std::slice::from_ref(&lib_dir));
5703
5704        let expect = |p: PathBuf| std::fs::canonicalize(p).unwrap();
5705        assert!(
5706            grants.contains(&expect(prog)),
5707            "the binary itself must be granted: {grants:?}"
5708        );
5709        assert!(
5710            grants.contains(&expect(interp)),
5711            "the ELF interpreter must be granted: {grants:?}"
5712        );
5713        assert!(
5714            grants.contains(&expect(lib_dir.join("libfake.so.1"))),
5715            "each resolved DT_NEEDED library must be granted: {grants:?}"
5716        );
5717    }
5718
5719    #[test]
5720    fn resolve_landlock_grants_skips_unresolvable_deps_and_missing_binaries() {
5721        let temp = tempfile::tempdir().unwrap();
5722        let bin_dir = temp.path().join("bin");
5723        std::fs::create_dir(&bin_dir).unwrap();
5724
5725        // A binary naming a soname that resolves nowhere, plus an interp that doesn't exist.
5726        let prog = bin_dir.join("prog");
5727        std::fs::write(
5728            &prog,
5729            build_elf64(Some("/definitely/not/here.so"), &["libnope.so"], None),
5730        )
5731        .unwrap();
5732        let missing = bin_dir.join("does-not-exist");
5733
5734        let grants =
5735            resolve_landlock_grants_in(&[prog.clone(), missing], std::slice::from_ref(&bin_dir));
5736
5737        // Only the real binary survives; the missing binary, missing interp, and unresolvable
5738        // soname each contribute nothing (shrink-not-fail).
5739        assert_eq!(grants, vec![std::fs::canonicalize(&prog).unwrap()]);
5740    }
5741
5742    // ---- interpreter_runtime → LandlockGrant construction (pure, syscall-free, every OS) ----
5743
5744    fn interp_grant(binary: &str, dirs: &[(&str, bool)]) -> InterpreterRuntimeGrant {
5745        InterpreterRuntimeGrant {
5746            binary: binary.to_string(),
5747            dirs: dirs
5748                .iter()
5749                .map(|(path, list_dir)| murmur_artifact::InterpreterRuntimeDir {
5750                    path: path.to_string(),
5751                    list_dir: *list_dir,
5752                })
5753                .collect(),
5754        }
5755    }
5756
5757    #[test]
5758    fn resolve_interpreter_runtime_grants_copies_list_dir_verbatim() {
5759        // Two directories under the same binary, opposite `list_dir` — proving enumerability is
5760        // per-directory and copied exactly, not inferred or unified.
5761        let grants = resolve_interpreter_runtime_grants(&[interp_grant(
5762            "python3",
5763            &[
5764                ("/usr/lib/python3.11", true),
5765                ("/usr/lib/python3.11/lib-dynload", false),
5766            ],
5767        )]);
5768
5769        assert_eq!(
5770            grants,
5771            vec![
5772                LandlockGrant {
5773                    path: PathBuf::from("/usr/lib/python3.11"),
5774                    list_dir: true,
5775                    executable: true,
5776                },
5777                LandlockGrant {
5778                    path: PathBuf::from("/usr/lib/python3.11/lib-dynload"),
5779                    list_dir: false,
5780                    executable: true,
5781                },
5782            ]
5783        );
5784    }
5785
5786    #[test]
5787    fn resolve_interpreter_runtime_grants_flattens_multiple_grants_and_needs_no_existing_path() {
5788        // The declared paths need not exist on this host (this is pure resolution — `apply_landlock_
5789        // scope` skips any that fail to open), and multiple grants flatten in order.
5790        let grants = resolve_interpreter_runtime_grants(&[
5791            interp_grant("python3", &[("/opt/py/nonexistent", false)]),
5792            interp_grant("ruby", &[("/opt/rb/also-nonexistent", true)]),
5793        ]);
5794
5795        assert_eq!(
5796            grants,
5797            vec![
5798                LandlockGrant {
5799                    path: PathBuf::from("/opt/py/nonexistent"),
5800                    list_dir: false,
5801                    executable: true,
5802                },
5803                LandlockGrant {
5804                    path: PathBuf::from("/opt/rb/also-nonexistent"),
5805                    list_dir: true,
5806                    executable: true,
5807                },
5808            ]
5809        );
5810        assert!(resolve_interpreter_runtime_grants(&[]).is_empty());
5811    }
5812
5813    #[test]
5814    fn non_listable_files_marks_every_closure_file_non_enumerable() {
5815        // The DT_NEEDED closure yields individual files; wrapping them must never set `list_dir`
5816        // (ReadDir on a regular file is a no-op anyway).
5817        let wrapped = LandlockGrant::non_listable_files(vec![
5818            PathBuf::from("/lib/x86_64-linux-gnu/libc.so.6"),
5819            PathBuf::from("/usr/bin/bash"),
5820        ]);
5821        assert!(wrapped.iter().all(|grant| !grant.list_dir), "{wrapped:?}");
5822        assert_eq!(
5823            wrapped.iter().map(|g| g.path.clone()).collect::<Vec<_>>(),
5824            vec![
5825                PathBuf::from("/lib/x86_64-linux-gnu/libc.so.6"),
5826                PathBuf::from("/usr/bin/bash"),
5827            ]
5828        );
5829    }
5830
5831    // ---- `CAPSULE_DEVICE_GRANTS` (fixed device set) ----------------------------------------
5832    //
5833    // The canonical statement of what the *content* checks in this file are worth, referenced by
5834    // the `denied_socket_domains` and `SECCOMP_SYSCALL_ALLOWLIST` sections below: they assert what
5835    // a Rust constant holds, NOT that any kernel grants or refuses anything. A green run is not
5836    // evidence that `/dev/null` is writable inside a capsule or that `/dev/random` is refused —
5837    // on a host below `KernelFull`, `apply_landlock_scope` never runs at all. A content check
5838    // buys one thing: changing a constant cannot happen by accident.
5839    //
5840    // The enforcement claim for this constant is verified only by the manual procedure in
5841    // `docs/content/reference/capsule-device-set-manual-verification.md`, on real,
5842    // uncontainerized Linux hardware.
5843
5844    #[test]
5845    fn capsule_device_grants_are_exactly_three_devices_with_only_dev_null_writable() {
5846        let listed: Vec<(&str, bool)> = CAPSULE_DEVICE_GRANTS
5847            .iter()
5848            .map(|device| (device.path, device.writable))
5849            .collect();
5850        assert_eq!(
5851            listed,
5852            vec![
5853                ("/dev/null", true),
5854                ("/dev/zero", false),
5855                ("/dev/urandom", false),
5856            ],
5857            "the capsule device set is fixed at exactly these three paths and these access \
5858             levels. /dev/null must stay writable — Python's subprocess.DEVNULL opens it O_RDWR \
5859             and a shell `2>/dev/null` redirect opens it O_WRONLY, so a read-only grant breaks \
5860             both. Widening this list is allowed only on demonstrated workload failure, and the \
5861             failure gets recorded alongside the widening (see the manual acceptance procedure on \
5862             the diagnostics reference page)."
5863        );
5864    }
5865
5866    #[test]
5867    fn capsule_device_grants_exclude_the_devices_deliberately_left_out() {
5868        // `/dev/random` is the one with a reasoning trap attached: a plain write() to it credits
5869        // *zero* entropy (crediting needs the RNDADDENTROPY ioctl under CAP_SYS_ADMIN, which the
5870        // shell child has dropped). It is excluded because nothing needs a blocking RNG when
5871        // /dev/urandom is granted — not because writing to it would poison the kernel pool.
5872        for excluded in [
5873            "/dev/random",
5874            "/dev/full",
5875            "/dev/tty",
5876            "/dev/console",
5877            "/dev/mem",
5878            "/dev/sda",
5879            "/dev",
5880        ] {
5881            assert!(
5882                !CAPSULE_DEVICE_GRANTS
5883                    .iter()
5884                    .any(|device| device.path == excluded),
5885                "{excluded} must not be in the capsule device set — it is denied by the ordinary \
5886                 no-matching-rule path, and adding it here would be the only way to change that"
5887            );
5888        }
5889    }
5890
5891    #[test]
5892    fn capsule_device_grants_name_absolute_paths_under_dev() {
5893        // The list is opened verbatim with `O_PATH` in the parent: a relative path would resolve
5894        // against whatever cwd the host process happens to have.
5895        for device in CAPSULE_DEVICE_GRANTS {
5896            assert!(
5897                device.path.starts_with("/dev/"),
5898                "{} must be an absolute path under /dev",
5899                device.path
5900            );
5901        }
5902    }
5903
5904    // ---- `denied_socket_domains` ----------------------------------------------------------
5905    //
5906    // Content checks — see the `CAPSULE_DEVICE_GRANTS` section above for what that is and is not
5907    // worth. That `socket(AF_UNIX, ...)` is actually denied on a real host is verified only by the
5908    // manual procedure in `docs/content/reference/af-unix-sockets-manual-verification.md`, on
5909    // real Linux hardware.
5910
5911    #[test]
5912    fn denied_socket_domains_denies_unix_by_default() {
5913        let denied = denied_socket_domains(false);
5914        assert!(
5915            denied.contains(&LINUX_AF_UNIX),
5916            "AF_UNIX must be denied when the manifest does not declare \
5917             capabilities.network.unix_sockets — this is the /var/run/docker.sock escape"
5918        );
5919    }
5920
5921    #[test]
5922    fn denied_socket_domains_omits_unix_only_when_explicitly_allowed() {
5923        let denied = denied_socket_domains(true);
5924        assert!(
5925            !denied.contains(&LINUX_AF_UNIX),
5926            "a capsule that declared capabilities.network.unix_sockets: true must get no \
5927             AF_UNIX deny rule at all"
5928        );
5929    }
5930
5931    /// Netlink and packet sockets have no manifest key that widens them: the deny list must be
5932    /// identical for both values of the one flag that exists.
5933    #[test]
5934    fn denied_socket_domains_always_denies_netlink_and_packet() {
5935        for unix_sockets_allowed in [false, true] {
5936            let denied = denied_socket_domains(unix_sockets_allowed);
5937            assert!(
5938                denied.contains(&LINUX_AF_NETLINK),
5939                "AF_NETLINK must be denied unconditionally (unix_sockets_allowed = \
5940                 {unix_sockets_allowed})"
5941            );
5942            assert!(
5943                denied.contains(&LINUX_AF_PACKET),
5944                "AF_PACKET must be denied unconditionally (unix_sockets_allowed = \
5945                 {unix_sockets_allowed})"
5946            );
5947        }
5948    }
5949
5950    /// The rule only ever subtracts: IP sockets stay governed by the capsule's own network
5951    /// namespace and egress proxy against `capabilities.network.allow`, never by a domain-level
5952    /// deny.
5953    #[test]
5954    fn denied_socket_domains_never_denies_ip_families() {
5955        for unix_sockets_allowed in [false, true] {
5956            let denied = denied_socket_domains(unix_sockets_allowed);
5957            assert!(!denied.contains(&LINUX_AF_INET_DOMAIN));
5958            assert!(!denied.contains(&LINUX_AF_INET6_DOMAIN));
5959        }
5960    }
5961
5962    /// Pins the exact sets, so widening either one is a deliberate edit to this test rather than
5963    /// an unnoticed side effect of touching the function.
5964    #[test]
5965    fn denied_socket_domains_returns_exactly_the_documented_sets() {
5966        assert_eq!(
5967            denied_socket_domains(false),
5968            vec![LINUX_AF_NETLINK, LINUX_AF_PACKET, LINUX_AF_UNIX]
5969        );
5970        assert_eq!(
5971            denied_socket_domains(true),
5972            vec![LINUX_AF_NETLINK, LINUX_AF_PACKET]
5973        );
5974    }
5975
5976    /// The domain constants are Linux ABI numbers spelled as literals (see their doc comment),
5977    /// so nothing checks them against `libc` at compile time. On a Linux build machine, assert
5978    /// they really do agree with `libc`; on macOS this test compiles away, because
5979    /// `libc::AF_NETLINK`/`AF_PACKET` do not exist there at all — which is the whole reason the
5980    /// constants are literals.
5981    #[cfg(target_os = "linux")]
5982    #[test]
5983    fn linux_socket_domain_constants_match_libc() {
5984        assert_eq!(LINUX_AF_UNIX, libc::AF_UNIX);
5985        assert_eq!(LINUX_AF_NETLINK, libc::AF_NETLINK);
5986        assert_eq!(LINUX_AF_PACKET, libc::AF_PACKET);
5987        assert_eq!(LINUX_AF_INET_DOMAIN, libc::AF_INET);
5988        assert_eq!(LINUX_AF_INET6_DOMAIN, libc::AF_INET6);
5989    }
5990
5991    /// The allow and deny domain sets feed two rule loops on the *same* syscall and argument, so
5992    /// an overlap would mean one `socket()` call matching both an `Allow` and an `Errno` rule —
5993    /// a filter whose behavior depends on libseccomp's internal rule ordering rather than on
5994    /// anything stated here.
5995    #[test]
5996    fn socket_domain_allow_and_deny_sets_never_overlap() {
5997        for unix_sockets_allowed in [false, true] {
5998            let denied = denied_socket_domains(unix_sockets_allowed);
5999            for domain in allowed_socket_domains(unix_sockets_allowed) {
6000                assert!(
6001                    !denied.contains(&domain),
6002                    "socket domain {domain} is both allowed and denied \
6003                     (unix_sockets_allowed = {unix_sockets_allowed})"
6004                );
6005            }
6006        }
6007    }
6008
6009    /// `capabilities.network.unix_sockets` is the only manifest key either set consults, and it
6010    /// must move `AF_UNIX` from one set to the other — never leave it in neither, which under a
6011    /// default-deny filter would silently keep unix sockets refused even after a capsule declared
6012    /// the capability.
6013    #[test]
6014    fn allowed_socket_domains_takes_unix_back_exactly_when_declared() {
6015        assert_eq!(
6016            allowed_socket_domains(false),
6017            vec![LINUX_AF_INET_DOMAIN, LINUX_AF_INET6_DOMAIN]
6018        );
6019        assert_eq!(
6020            allowed_socket_domains(true),
6021            vec![LINUX_AF_INET_DOMAIN, LINUX_AF_INET6_DOMAIN, LINUX_AF_UNIX]
6022        );
6023    }
6024
6025    // ---- `SECCOMP_SYSCALL_ALLOWLIST` -------------------------------------------------------
6026    //
6027    // Content checks — see the `CAPSULE_DEVICE_GRANTS` section above for what that is and is not
6028    // worth. These assert the allowlist's contents, not that the kernel denies anything. They buy
6029    // one thing: re-permitting a dangerous syscall cannot happen by accident while reconciling
6030    // the allowlist against a newer upstream profile.
6031
6032    #[test]
6033    fn allowlist_contains_no_syscall_that_must_stay_denied() {
6034        for name in SECCOMP_MUST_STAY_DENIED {
6035            assert!(
6036                !SECCOMP_SYSCALL_ALLOWLIST.contains(name),
6037                "{name} is in SECCOMP_MUST_STAY_DENIED but was added to \
6038                 SECCOMP_SYSCALL_ALLOWLIST — if this is deliberate, remove it from the deny list \
6039                 in the same edit and say why in the commit"
6040            );
6041        }
6042    }
6043
6044    /// `execve`/`execveat` must be *present*: the default-deny action applies to anything unnamed,
6045    /// so omitting them would refuse the child's own first `execve` and no capsule could run a
6046    /// shell tool at all. Exec is decided by the Landlock domain instead; see
6047    /// `linux_enforce::workdir_access_rights` and `resolve_landlock_grants`.
6048    #[test]
6049    fn allowlist_permits_exec_because_landlock_now_decides_it() {
6050        for name in ["execve", "execveat"] {
6051            assert!(
6052                SECCOMP_SYSCALL_ALLOWLIST.contains(&name),
6053                "{name} must reach the kernel — the default action is a deny, so omitting it \
6054                 refuses the child's own exec and nothing runs"
6055            );
6056        }
6057    }
6058
6059    /// `socket` carries argument-conditional rules, and libseccomp resolves an unconditional rule
6060    /// for a syscall by discarding every conditional chain already recorded for it. A bare
6061    /// `"socket"` in the allowlist array would therefore delete the AF_UNIX/AF_NETLINK/AF_PACKET
6062    /// denials at filter-build time, with nothing at runtime to show for it.
6063    #[test]
6064    fn allowlist_excludes_socket_which_is_ruled_on_by_domain() {
6065        assert!(
6066            !SECCOMP_SYSCALL_ALLOWLIST.contains(&"socket"),
6067            "socket must be permitted per-domain by allowed_socket_domains, never unconditionally"
6068        );
6069    }
6070
6071    /// A duplicate is harmless to the kernel but means two edits disagree about the same syscall,
6072    /// which is exactly the state where one of them later gets removed and the other is missed.
6073    #[test]
6074    fn allowlist_has_no_duplicates() {
6075        let mut seen = std::collections::HashSet::new();
6076        for name in SECCOMP_SYSCALL_ALLOWLIST {
6077            assert!(seen.insert(*name), "{name} appears twice in the allowlist");
6078        }
6079    }
6080
6081    /// The whole design is an allowlist. An empty (or near-empty) array would still compile and
6082    /// still "pass" every other test here, while denying every syscall a shell needs.
6083    #[test]
6084    fn allowlist_covers_the_syscalls_no_process_can_run_without() {
6085        for name in [
6086            "read",
6087            "write",
6088            "openat",
6089            "close",
6090            "mmap",
6091            "munmap",
6092            "brk",
6093            "exit_group",
6094            "futex",
6095            "rt_sigreturn",
6096            "clone",
6097            "wait4",
6098            "getpid",
6099            "getdents64",
6100        ] {
6101            assert!(
6102                SECCOMP_SYSCALL_ALLOWLIST.contains(&name),
6103                "{name} is missing from the allowlist — no process could run under this filter"
6104            );
6105        }
6106    }
6107
6108    #[test]
6109    fn network_ip_allowed_matches_only_the_resolved_allowlist() {
6110        let allow = vec![IpAddr::from([127, 0, 0, 1])];
6111        assert!(network_ip_allowed(IpAddr::from([127, 0, 0, 1]), &allow));
6112        assert!(!network_ip_allowed(IpAddr::from([8, 8, 8, 8]), &allow));
6113        assert!(
6114            !network_ip_allowed(IpAddr::from([127, 0, 0, 1]), &[]),
6115            "an empty resolved allowlist must deny every destination"
6116        );
6117    }
6118
6119    // ---- tier warnings (finding #3: assert behavior, not just "doesn't panic") ----
6120
6121    #[test]
6122    fn tier_warning_kernel_full_warns_when_a_shell_is_declared() {
6123        // The Linux "full" tier must NOT be silent: it is a filesystem and syscall scope, not a
6124        // namespace, and a silent tier would imply it has no documented limits. It warns when a
6125        // shell is declared, and stays silent only when there is no subprocess to enforce on.
6126        assert_eq!(
6127            tier_warning(EnforcementTier::KernelFull, false),
6128            Some((W_SEC_005, KERNEL_ENFORCEMENT_NOTICE))
6129        );
6130        assert_eq!(tier_warning(EnforcementTier::KernelFull, true), None);
6131    }
6132
6133    #[test]
6134    fn tier_warning_all_tiers_warn_only_when_shell_allow_is_nonempty() {
6135        assert_eq!(
6136            tier_warning(EnforcementTier::KernelSeccompOnly, false),
6137            Some((W_SEC_002, SECCOMP_ONLY_WARNING))
6138        );
6139        assert_eq!(
6140            tier_warning(EnforcementTier::EnvironmentOnly, false),
6141            Some((W_SEC_001, ENVIRONMENT_ONLY_WARNING))
6142        );
6143        assert_eq!(tier_warning(EnforcementTier::KernelFull, true), None);
6144        assert_eq!(tier_warning(EnforcementTier::KernelSeccompOnly, true), None);
6145        assert_eq!(tier_warning(EnforcementTier::EnvironmentOnly, true), None);
6146    }
6147
6148    /// The aggregate-bounding gap is warned about exactly where it is real *and* permanent: a
6149    /// non-Linux host running a capsule that can spawn a subprocess. Never on Linux — there the
6150    /// same condition refuses the launch outright, so a warning would describe a session that
6151    /// does not exist — and never for a capsule with no process tree to bound.
6152    #[test]
6153    fn aggregate_bounding_warns_only_off_linux_and_only_with_a_subprocess_route() {
6154        assert_eq!(
6155            aggregate_bounding_warning(false, true, false),
6156            Some((W_SEC_010, NO_AGGREGATE_BOUNDING_WARNING))
6157        );
6158        assert_eq!(
6159            aggregate_bounding_warning(false, false, false),
6160            None,
6161            "a capsule that cannot spawn a subprocess has nothing to bound"
6162        );
6163        assert_eq!(
6164            aggregate_bounding_warning(true, true, false),
6165            None,
6166            "on Linux this case is a refused launch, not a warning"
6167        );
6168        assert_eq!(
6169            aggregate_bounding_warning(true, true, true),
6170            None,
6171            "a scope exists, so there is no gap"
6172        );
6173    }
6174
6175    /// The warning must name the per-uid nature of `RLIMIT_NPROC` explicitly: "rlimits are still
6176    /// applied" reads as reassurance, and the whole point is that the one rlimit an operator
6177    /// would expect to stop a fork bomb does not.
6178    #[test]
6179    fn aggregate_bounding_warning_states_why_rlimit_nproc_is_insufficient() {
6180        let (_, message) = aggregate_bounding_warning(false, true, false).unwrap();
6181        assert!(message.contains("per-uid"), "message was: {message}");
6182        assert!(message.contains("fork bomb"), "message was: {message}");
6183        assert!(message.contains("pids.max"), "message was: {message}");
6184    }
6185
6186    #[test]
6187    fn warn_for_missing_aggregate_bounding_writes_the_code_and_link_to_bootstrap_log() {
6188        let temp = tempfile::tempdir().unwrap();
6189        warn_for_missing_aggregate_bounding(temp.path(), true, false);
6190        let log = bootstrap_log_contents(temp.path());
6191
6192        if cfg!(target_os = "linux") {
6193            assert!(
6194                log.is_empty(),
6195                "Linux refuses the launch instead of warning: {log}"
6196            );
6197        } else {
6198            assert!(log.contains(W_SEC_010), "log was: {log}");
6199            assert!(
6200                log.contains(&security_warning_link(W_SEC_010)),
6201                "log was: {log}"
6202            );
6203        }
6204    }
6205
6206    fn warning_test_policy() -> CapabilityPolicy {
6207        CapabilityPolicy {
6208            shell_allow: vec!["bash".to_string()],
6209            network_allow: vec!["https://api.example.com".to_string()],
6210            ..CapabilityPolicy::default()
6211        }
6212    }
6213
6214    #[test]
6215    fn warn_for_enforcement_tier_kernel_full_logs_scope_when_shell_declared() {
6216        let temp = tempfile::tempdir().unwrap();
6217        warn_for_enforcement_tier(
6218            EnforcementTier::KernelFull,
6219            temp.path(),
6220            &warning_test_policy(),
6221        );
6222        let log = bootstrap_log_contents(temp.path());
6223        assert!(
6224            log.contains(W_SEC_005),
6225            "KernelFull must not be silent — it must state what the tier does and does not cover: {log}"
6226        );
6227        assert!(
6228            log.contains("denied, not absent"),
6229            "must state the scope's documented limit: paths outside the workdir are denied, not \
6230             absent: {log}"
6231        );
6232        assert!(
6233            log.contains("read+execute") && log.contains("outside the workdir"),
6234            "must describe what is now actually granted (narrow, derived read+execute outside \
6235             the workdir), not an unfixed grant bug: {log}"
6236        );
6237        assert!(
6238            log.contains(&security_warning_link(W_SEC_005)),
6239            "must link to the diagnostics doc page: {log}"
6240        );
6241    }
6242
6243    #[test]
6244    fn warn_for_enforcement_tier_kernel_full_silent_without_shell_allow() {
6245        let temp = tempfile::tempdir().unwrap();
6246        warn_for_enforcement_tier(
6247            EnforcementTier::KernelFull,
6248            temp.path(),
6249            &CapabilityPolicy::default(),
6250        );
6251        assert_eq!(
6252            bootstrap_log_contents(temp.path()),
6253            "",
6254            "with no shell declared there is no subprocess to enforce on — stay silent"
6255        );
6256    }
6257
6258    #[test]
6259    fn warn_for_enforcement_tier_seccomp_only_logs_the_landlock_gap() {
6260        let temp = tempfile::tempdir().unwrap();
6261        warn_for_enforcement_tier(
6262            EnforcementTier::KernelSeccompOnly,
6263            temp.path(),
6264            &warning_test_policy(),
6265        );
6266        let log = bootstrap_log_contents(temp.path());
6267        assert!(
6268            log.contains("Landlock"),
6269            "must name the missing primitive: {log}"
6270        );
6271        assert!(
6272            log.contains("filesystem"),
6273            "must name what is not enforced: {log}"
6274        );
6275        assert!(
6276            log.contains(W_SEC_002),
6277            "must carry its warning code: {log}"
6278        );
6279        assert!(
6280            log.contains(&security_warning_link(W_SEC_002)),
6281            "must link to the diagnostics doc page: {log}"
6282        );
6283    }
6284
6285    #[test]
6286    fn warn_for_enforcement_tier_environment_only_logs_permanent_and_bypass_warnings() {
6287        let temp = tempfile::tempdir().unwrap();
6288        warn_for_enforcement_tier(
6289            EnforcementTier::EnvironmentOnly,
6290            temp.path(),
6291            &warning_test_policy(),
6292        );
6293        let log = bootstrap_log_contents(temp.path());
6294        assert!(
6295            log.contains("permanent"),
6296            "must state the tier is permanent, not pending: {log}"
6297        );
6298        assert!(
6299            log.contains("bash"),
6300            "the still-accurate bash/network bypass warning must also fire: {log}"
6301        );
6302        assert!(
6303            log.contains(W_SEC_001),
6304            "must carry the tier warning code: {log}"
6305        );
6306        assert!(
6307            log.contains(W_SEC_003),
6308            "must carry the bash/network bypass warning code: {log}"
6309        );
6310    }
6311
6312    // ---- fail-closed (finding #2: forced setup failure must prevent spawn) ----
6313
6314    struct ForcePrepareFailureGuard;
6315
6316    impl ForcePrepareFailureGuard {
6317        fn new() -> Self {
6318            FORCE_PREPARE_FAILURE.with(|flag| flag.set(true));
6319            Self
6320        }
6321    }
6322
6323    impl Drop for ForcePrepareFailureGuard {
6324        fn drop(&mut self) {
6325            FORCE_PREPARE_FAILURE.with(|flag| flag.set(false));
6326        }
6327    }
6328
6329    #[test]
6330    fn execute_shell_fails_closed_when_enforcement_setup_fails() {
6331        let temp = tempfile::tempdir().unwrap();
6332        let policy = CapabilityPolicy {
6333            shell_allow: vec!["bash".to_string()],
6334            ..CapabilityPolicy::default()
6335        };
6336        let marker = temp.path().join("spawned-anyway.marker");
6337        let script = format!("echo ran > '{}'", marker.display());
6338
6339        {
6340            let _guard = ForcePrepareFailureGuard::new();
6341            let error = crate::shell::execute_shell(
6342                "bash",
6343                &["-c", &script],
6344                &[],
6345                temp.path(),
6346                temp.path(),
6347                &policy,
6348                &ShellEnforcement::environment_only(),
6349            )
6350            .unwrap_err();
6351            assert!(
6352                error.to_string().contains("sandbox"),
6353                "the error must name what failed to initialize: {error}"
6354            );
6355            assert!(
6356                !marker.exists(),
6357                "no subprocess may be spawned at all when enforcement setup fails"
6358            );
6359        }
6360
6361        // Control run without the forced failure: the identical call spawns and writes the
6362        // marker — proving the marker really would have caught a spawn above.
6363        let result = crate::shell::execute_shell(
6364            "bash",
6365            &["-c", &script],
6366            &[],
6367            temp.path(),
6368            temp.path(),
6369            &policy,
6370            &ShellEnforcement::environment_only(),
6371        )
6372        .unwrap();
6373        assert_eq!(result.exit_code, 0);
6374        assert!(marker.exists());
6375    }
6376}
6377
6378#[cfg(target_os = "linux")]
6379#[cfg(test)]
6380mod landlock_probe_isolation {
6381    /// The Landlock probe must leave the calling process exactly as it found it.
6382    ///
6383    /// Stated as "the sealed probe gives the same answer before and after" rather than by
6384    /// inspecting the process's Landlock domain, because there is no API to ask whether a task
6385    /// is landlocked — and because that framing is what actually broke: the probe restricted
6386    /// itself, and every later attempt to build a composed root was refused, on every host, in
6387    /// a way that looked like the host's fault.
6388    ///
6389    /// Host-independent by construction. On a machine that cannot do `sealed` at all, both
6390    /// halves report the same failure and this passes trivially; on a capable one, an
6391    /// in-process `restrict_self` turns the second answer into a mount denial and fails it.
6392    #[test]
6393    fn the_landlock_probe_does_not_restrict_the_calling_process() {
6394        let before = crate::sealed::probe_sealed_support().namespace;
6395        let _ = super::linux_enforce::probe_landlock_full_access();
6396        let after = crate::sealed::probe_sealed_support().namespace;
6397
6398        assert_eq!(
6399            before, after,
6400            "the Landlock probe changed what the sealed probe reports ({before:?} -> {after:?}) — \
6401             it has restricted the calling process instead of a forked child, which permanently \
6402             forbids the mount family to this process and everything it spawns",
6403        );
6404    }
6405}
6406
6407#[cfg(all(test, target_os = "linux"))]
6408mod linux_integration_tests {
6409    use std::path::Path;
6410
6411    use super::*;
6412
6413    /// Spread-base supplying the four *host-bounding* fields (`resource_limits`,
6414    /// `nproc_baseline`, `cgroup_scope`, `workdir_guard`) to the enforcement literals below,
6415    /// which spell out the policy half by hand because they need to pin `tier` explicitly.
6416    ///
6417    /// These tests exercise seccomp, Landlock and the network allowlist — not rlimits or
6418    /// cgroups — so they take exactly what `ShellEnforcement::resolve` produces before
6419    /// `with_host_bounding` attaches a live session's handles: the real default ceilings (not
6420    /// "unbounded" — zeroing them would misrepresent what a real host does, and the rlimit half
6421    /// of the child `pre_exec` runs on every tier), the real uid baseline, and no cgroup scope
6422    /// or workdir guard. The `tier` it carries is always overridden by the literal that spreads
6423    /// it; only the host-bounding tail is ever consumed from here.
6424    fn host_bounding_base() -> ShellEnforcement {
6425        ShellEnforcement::environment_only()
6426    }
6427
6428    /// `<accessible>/.murmur/<session id>/`, the session workdir a `--workdir` launch stages
6429    /// into — the shape that makes the two workdirs different paths, which is the only shape in
6430    /// which putting a staging directory in the wrong one is visible.
6431    fn session_workdir_under(accessible: &Path) -> PathBuf {
6432        let session = accessible.join(".murmur").join("ses_sandbox_tests");
6433        std::fs::create_dir_all(&session).unwrap();
6434        session
6435    }
6436
6437    /// Pure content check on the workdir access-right set: no kernel call, no fork, no spawn.
6438    /// It pins *which* Landlock ABI v1 rights `apply_landlock_scope` hands the workdir, so
6439    /// re-adding device-node creation becomes a test failure instead of a silent regression.
6440    ///
6441    /// It proves **nothing** about whether the kernel enforces that set — that is the manual
6442    /// acceptance procedure in
6443    /// `docs/content/reference/workdir-device-node-manual-verification.md`, not this test.
6444    /// It lives in this `#[cfg(target_os = "linux")]` module rather than the cross-platform
6445    /// `tests` module only because `landlock::AccessFs` is a Linux-only dependency.
6446    #[test]
6447    fn workdir_landlock_grant_withholds_device_and_socket_creation() {
6448        use landlock::{Access, AccessFs, ABI};
6449
6450        let all_v1 = AccessFs::from_all(ABI::V1);
6451        // The `workdir_exec: true` set — the widest the workdir can ever be — so the three
6452        // unconditionally-withheld rights below are checked against the permissive case rather
6453        // than passing trivially because `Execute` happened to be absent too.
6454        let granted = linux_enforce::workdir_access_rights(true);
6455
6456        for withheld in [AccessFs::MakeChar, AccessFs::MakeBlock, AccessFs::MakeSock] {
6457            assert!(
6458                all_v1.contains(withheld),
6459                "{withheld:?} is expected to be part of Landlock ABI v1 — if it is not, this \
6460                 test's premise (and the workdir grant's comment) needs revisiting"
6461            );
6462            assert!(
6463                !granted.contains(withheld),
6464                "the workdir grant must withhold {withheld:?}: with the full ABI v1 set declared \
6465                 by handle_access, withholding it here is what makes it denied rather than merely \
6466                 un-granted"
6467            );
6468        }
6469
6470        assert!(
6471            granted.contains(AccessFs::MakeFifo),
6472            "MakeFifo stays granted — real build tooling creates named pipes in its working tree"
6473        );
6474
6475        let expected = all_v1 & !(AccessFs::MakeChar | AccessFs::MakeBlock | AccessFs::MakeSock);
6476        assert_eq!(
6477            granted, expected,
6478            "the workdir_exec grant must be exactly Landlock ABI v1 minus \
6479             MakeChar/MakeBlock/MakeSock — nothing else may be added or dropped without updating \
6480             this test and the constant's comment together"
6481        );
6482    }
6483
6484    /// The `workdir_exec` bit, pinned in both directions. A *content* check on the right set
6485    /// only: it proves nothing about whether a kernel refuses an exec, which is the manual
6486    /// procedure in
6487    /// `docs/content/reference/workdir-exec-landlock-manual-verification.md`. It catches the one
6488    /// regression that matters here: flipping the default back — which would silently reopen the
6489    /// rename-to-an-allowlisted-basename bypass — cannot happen without this test failing.
6490    #[test]
6491    fn workdir_execute_right_is_granted_only_when_workdir_exec_is_declared() {
6492        use landlock::AccessFs;
6493
6494        assert!(
6495            !linux_enforce::workdir_access_rights(false).contains(AccessFs::Execute),
6496            "the default must withhold Execute from the workdir — that withholding is the whole \
6497             of what enforces capabilities.shell.allow now that the exec supervisor is gone"
6498        );
6499        assert!(
6500            linux_enforce::workdir_access_rights(true).contains(AccessFs::Execute),
6501            "capabilities.filesystem.workdir_exec: true must actually grant Execute, or the \
6502             compile-and-run workflows it exists for silently stop working"
6503        );
6504
6505        // Nothing else moves with the flag: the two sets differ by exactly `Execute`.
6506        assert_eq!(
6507            linux_enforce::workdir_access_rights(true) & !AccessFs::Execute,
6508            linux_enforce::workdir_access_rights(false),
6509            "workdir_exec must be a one-bit axis — no other right may ride along with it"
6510        );
6511    }
6512
6513    /// The tier gate on the workdir-backed `/tmp` fd, in both directions, against a real
6514    /// `tempfile::tempdir()` workdir. Opening an fd is an ordinary `open()` — no Landlock call, no
6515    /// namespace, no privilege — so this runs on any Linux host, unlike the enforcement it feeds.
6516    ///
6517    /// It proves **nothing** about whether the kernel then honors the rule built from that fd; that
6518    /// is the hand-run procedure in
6519    /// `docs/content/reference/sealed-containment-manual-verification.md` (step "3d — writability").
6520    /// It catches two things: that the fd is there to build a rule from at all, and that the
6521    /// directory backing it exists before `build_sealed_root` — which runs *after* this function —
6522    /// binds it.
6523    #[test]
6524    fn the_workdir_backed_tmp_store_is_opened_for_landlock_on_the_sealed_tier_only() {
6525        let accessible = tempfile::tempdir().unwrap();
6526        let session = session_workdir_under(accessible.path());
6527        let fds = linux_enforce::open_landlock_fds(
6528            accessible.path(),
6529            &session,
6530            &[],
6531            &[],
6532            false,
6533            EnforcementTier::KernelSealed,
6534        )
6535        .expect("a real, writable workdir must yield sealed Landlock fds");
6536
6537        assert!(
6538            fds.sealed_tmp_fd().is_some(),
6539            "the composed root binds {} at /tmp read-write on every sealed capsule, so its fd must \
6540             always be opened — a missing rule leaves /tmp mounted but EACCES",
6541            crate::sealed::SEALED_TMP_DIR_NAME,
6542        );
6543        assert!(
6544            session.join(crate::sealed::SEALED_TMP_DIR_NAME).is_dir(),
6545            "the /tmp store must be created here: open_landlock_fds runs before build_sealed_root, \
6546             so nothing else has made this directory yet",
6547        );
6548        assert!(
6549            !accessible
6550                .path()
6551                .join(crate::sealed::SEALED_TMP_DIR_NAME)
6552                .exists(),
6553            "enabling sealed must add nothing to the top level of the accessible workdir — that \
6554             directory is the capsule's deliverable",
6555        );
6556
6557        for tier in [
6558            EnforcementTier::KernelFull,
6559            EnforcementTier::KernelSeccompOnly,
6560            EnforcementTier::EnvironmentOnly,
6561        ] {
6562            let accessible = tempfile::tempdir().unwrap();
6563            let session = session_workdir_under(accessible.path());
6564            let fds = linux_enforce::open_landlock_fds(
6565                accessible.path(),
6566                &session,
6567                &[],
6568                &[],
6569                false,
6570                tier,
6571            )
6572            .expect("a real, writable workdir must yield Landlock fds on any tier");
6573
6574            assert!(
6575                fds.sealed_tmp_fd().is_none(),
6576                "{tier:?} composes no root and binds nothing at /tmp, so granting a workdir-backed \
6577                 /tmp would grant a path this tier's capsule never sees",
6578            );
6579            assert!(
6580                !session.join(crate::sealed::SEALED_TMP_DIR_NAME).exists(),
6581                "{tier:?} must not even create the store — an unbound directory in the session \
6582                 workdir is litter the capsule can see",
6583            );
6584        }
6585    }
6586
6587    /// The synthetic account databases, written and opened by the same parent-side call, against a
6588    /// real `tempfile::tempdir()` workdir.
6589    ///
6590    /// Like the `/tmp` test above it proves nothing about kernel enforcement — that is the hand-run
6591    /// in `docs/content/reference/sealed-containment-manual-verification.md`. It catches three
6592    /// things: that the files exist before `build_sealed_root` binds them, that there is an fd to
6593    /// build each rule from (without one, Landlock matches the *host's* `/etc/passwd` inode and the
6594    /// bound synthetic file is mounted-but-`EACCES`), and that neither is created on a tier that
6595    /// composes no root.
6596    #[test]
6597    fn the_synthetic_etc_files_are_written_and_opened_on_the_sealed_tier_only() {
6598        let accessible = tempfile::tempdir().unwrap();
6599        let session = session_workdir_under(accessible.path());
6600        let fds = linux_enforce::open_landlock_fds(
6601            accessible.path(),
6602            &session,
6603            &[],
6604            &[],
6605            false,
6606            EnforcementTier::KernelSealed,
6607        )
6608        .expect("a real, writable workdir must yield sealed Landlock fds");
6609
6610        let synthetic: Vec<&crate::sealed::SealedEtcPath> = crate::sealed::SEALED_ETC_PATHS
6611            .iter()
6612            .filter(|entry| entry.synthetic.is_some())
6613            .collect();
6614        assert_eq!(
6615            fds.sealed_identity_fd_count(),
6616            synthetic.len(),
6617            "every synthetic /etc entry the composed root binds needs a rule of its own: {synthetic:?}",
6618        );
6619        for entry in &synthetic {
6620            let path = crate::sealed::synthetic_etc_source(&session, entry.synthetic.unwrap());
6621            assert!(
6622                path.is_file(),
6623                "{} must be written here: open_landlock_fds runs before build_sealed_root, so \
6624                 nothing else has written it yet",
6625                entry.path,
6626            );
6627        }
6628        assert!(
6629            !accessible
6630                .path()
6631                .join(crate::sealed::SEALED_ETC_STAGING_DIR_NAME)
6632                .exists(),
6633            "the staging directory belongs to the session, not to the capsule's deliverable",
6634        );
6635
6636        for tier in [
6637            EnforcementTier::KernelFull,
6638            EnforcementTier::KernelSeccompOnly,
6639            EnforcementTier::EnvironmentOnly,
6640        ] {
6641            let accessible = tempfile::tempdir().unwrap();
6642            let session = session_workdir_under(accessible.path());
6643            let fds = linux_enforce::open_landlock_fds(
6644                accessible.path(),
6645                &session,
6646                &[],
6647                &[],
6648                false,
6649                tier,
6650            )
6651            .expect("a real, writable workdir must yield Landlock fds on any tier");
6652
6653            assert_eq!(
6654                fds.sealed_identity_fd_count(),
6655                0,
6656                "{tier:?} composes no root, so its capsule reads the host's real /etc/passwd and \
6657                 these files stand in for nothing",
6658            );
6659            assert!(
6660                !session
6661                    .join(crate::sealed::SEALED_ETC_STAGING_DIR_NAME)
6662                    .exists(),
6663                "{tier:?} must not even create the staging directory — same reason as .mur-tmp",
6664            );
6665        }
6666    }
6667
6668    /// The one field that has to agree across two files: the synthetic `pw_dir` and `$HOME`.
6669    ///
6670    /// Both are derived from `shell::SYNTHETIC_HOME_DIR_NAME`, and this asserts the end result
6671    /// rather than the constant — a capsule sees `pwd.getpwuid(os.getuid()).pw_dir` and
6672    /// `os.environ["HOME"]`, and a disagreement between them is silent until a tool picks the
6673    /// wrong one. The uid/gid are checked against the workdir's own owner, which is where
6674    /// `ensure_sealed_identity_files` reads the capsule's identity from.
6675    #[test]
6676    fn the_synthetic_passwd_entry_carries_exactly_the_home_the_subprocess_env_gets() {
6677        use std::os::unix::fs::MetadataExt;
6678
6679        let accessible = tempfile::tempdir().unwrap();
6680        let session = session_workdir_under(accessible.path());
6681        let written = ensure_sealed_identity_files(&session).unwrap();
6682        let env = crate::shell::build_shell_env(
6683            &crate::types::CapabilityPolicy::default(),
6684            &[],
6685            &session,
6686        )
6687        .unwrap();
6688
6689        let passwd = std::fs::read_to_string(&written[0]).unwrap();
6690        let owner = std::fs::metadata(&session).unwrap();
6691        let entry: Vec<&str> = passwd
6692            .lines()
6693            .last()
6694            .expect("the capsule's own entry is the last line")
6695            .split(':')
6696            .collect();
6697
6698        assert_eq!(entry[2], owner.uid().to_string(), "uid field");
6699        assert_eq!(entry[3], owner.gid().to_string(), "gid field");
6700        assert_eq!(
6701            Some(&entry[5].to_string()),
6702            env.get("HOME"),
6703            "pw_dir and $HOME are the same string or the entry is worse than useless",
6704        );
6705
6706        let group = std::fs::read_to_string(&written[1]).unwrap();
6707        assert_eq!(
6708            group.lines().last().unwrap().split(':').nth(2),
6709            Some(owner.gid().to_string().as_str()),
6710            "gid field of the capsule's own group",
6711        );
6712    }
6713
6714    /// Pure content check on the right-set the composed root's `/tmp` rule carries: no kernel call,
6715    /// no fork, no spawn.
6716    ///
6717    /// `apply_landlock_scope` resolves `workdir_access_rights(fds.workdir_exec)` into a single
6718    /// local and adds it to *both* the workdir rule and the `/tmp` rule, so the two sets are equal
6719    /// by construction; what this test pins is the content of that shared set as `/tmp`'s users
6720    /// need it — a compiler writing intermediates, `mktemp` creating and removing files, a package
6721    /// manager creating build directories — and the `Execute` axis, which must track
6722    /// `workdir_exec` on `/tmp` exactly as it does on the workdir, because both paths resolve to
6723    /// the same storage and a binary staged in one is the same bytes as a binary staged in the
6724    /// other.
6725    #[test]
6726    fn the_composed_root_tmp_rule_carries_exactly_the_workdir_right_set() {
6727        use landlock::AccessFs;
6728
6729        for workdir_exec in [false, true] {
6730            let rights = linux_enforce::workdir_access_rights(workdir_exec);
6731
6732            for needed in [
6733                AccessFs::WriteFile,
6734                AccessFs::ReadFile,
6735                AccessFs::ReadDir,
6736                AccessFs::MakeReg,
6737                AccessFs::MakeDir,
6738                AccessFs::RemoveFile,
6739                AccessFs::RemoveDir,
6740            ] {
6741                assert!(
6742                    rights.contains(needed),
6743                    "/tmp carries the workdir's rights, so it must carry {needed:?}: without it \
6744                     `cc`, `mktemp` and `pip` fail on a mount that is genuinely writable",
6745                );
6746            }
6747
6748            assert_eq!(
6749                rights.contains(AccessFs::Execute),
6750                workdir_exec,
6751                "/tmp is backed by a directory inside the workdir, so Execute there must follow \
6752                 capabilities.filesystem.workdir_exec exactly — granting it unconditionally would \
6753                 make /tmp a hole through which capsule-written bytes run",
6754            );
6755        }
6756
6757        assert_eq!(
6758            linux_enforce::workdir_access_rights(true) & !AccessFs::Execute,
6759            linux_enforce::workdir_access_rights(false),
6760            "the /tmp rule and the workdir rule share one right-set binding in \
6761             apply_landlock_scope; if that set ever grows a second conditional axis, this test and \
6762             that binding must be revisited together",
6763        );
6764    }
6765
6766    #[test]
6767    fn prepare_enforcement_is_noop_for_environment_only_tier_even_on_linux() {
6768        let mut command = std::process::Command::new("true");
6769        let enforcement = ShellEnforcement::environment_only();
6770        let supervisor = prepare_enforcement(
6771            &mut command,
6772            &enforcement,
6773            Path::new("/tmp"),
6774            Path::new("/tmp"),
6775        )
6776        .expect("environment_only must never fail");
6777        supervisor.join_best_effort();
6778    }
6779
6780    // Exec denial outside the allowlist is deliberately not asserted here. Exec is a Landlock
6781    // right, so the claim holds only on `KernelFull`/`KernelSealed`; on any weaker tier such a
6782    // test passes while exercising a path that enforces nothing. The two tests below assert the
6783    // opposite direction — that allowlisted binaries still run — which any tier does evidence.
6784
6785    #[test]
6786    fn kernel_tier_allows_exec_within_shell_allowlist() {
6787        if crate::network_namespace::skip_without_egress_namespace(
6788            "kernel_tier_allows_exec_within_shell_allowlist",
6789        ) {
6790            return;
6791        }
6792        let tier = detect_enforcement_tier();
6793        if tier == EnforcementTier::EnvironmentOnly {
6794            eprintln!(
6795                "skipping kernel_tier_allows_exec_within_shell_allowlist: resolved to \
6796                 EnvironmentOnly on a Linux host — degrading gracefully"
6797            );
6798            return;
6799        }
6800
6801        let temp = tempfile::tempdir().unwrap();
6802        let policy = CapabilityPolicy {
6803            shell_allow: vec!["bash".to_string()],
6804            ..CapabilityPolicy::default()
6805        };
6806        let enforcement = ShellEnforcement {
6807            tier,
6808            network_allow_ips: Vec::new(),
6809            unix_sockets_allowed: policy.unix_sockets_allowed,
6810            landlock_grants: LandlockGrant::non_listable_files(resolve_landlock_grants(
6811                &resolve_exec_allowlist(&policy.shell_allow),
6812            )),
6813            ..host_bounding_base()
6814        };
6815
6816        let result = crate::shell::execute_shell(
6817            "bash",
6818            &["-c", "exit 7"],
6819            &[],
6820            temp.path(),
6821            temp.path(),
6822            &policy,
6823            &enforcement,
6824        )
6825        .unwrap();
6826
6827        assert_eq!(
6828            result.exit_code, 7,
6829            "bash itself is allowlisted, so kernel enforcement must permit its own execve — \
6830             proving the allowlist isn't a blanket deny"
6831        );
6832    }
6833
6834    #[test]
6835    fn kernel_tier_allows_nested_exec_of_second_allowlisted_binary() {
6836        if crate::network_namespace::skip_without_egress_namespace(
6837            "kernel_tier_allows_nested_exec_of_second_allowlisted_binary",
6838        ) {
6839            return;
6840        }
6841        let tier = detect_enforcement_tier();
6842        if tier == EnforcementTier::EnvironmentOnly {
6843            eprintln!(
6844                "skipping kernel_tier_allows_nested_exec_of_second_allowlisted_binary: \
6845                 resolved to EnvironmentOnly on a Linux host — degrading gracefully"
6846            );
6847            return;
6848        }
6849
6850        let temp = tempfile::tempdir().unwrap();
6851        let policy = CapabilityPolicy {
6852            shell_allow: vec!["bash".to_string(), "ls".to_string()],
6853            ..CapabilityPolicy::default()
6854        };
6855        let enforcement = ShellEnforcement {
6856            tier,
6857            network_allow_ips: Vec::new(),
6858            unix_sockets_allowed: policy.unix_sockets_allowed,
6859            landlock_grants: LandlockGrant::non_listable_files(resolve_landlock_grants(
6860                &resolve_exec_allowlist(&policy.shell_allow),
6861            )),
6862            ..host_bounding_base()
6863        };
6864
6865        // Unlike `exit 7` (a builtin), `ls` forces a genuinely *nested* execve from inside
6866        // bash — the case the no-regression scenario ("allowlisted binary still functions")
6867        // actually cares about.
6868        let result = crate::shell::execute_shell(
6869            "bash",
6870            &["-c", "ls"],
6871            &[],
6872            temp.path(),
6873            temp.path(),
6874            &policy,
6875            &enforcement,
6876        )
6877        .unwrap();
6878
6879        assert_eq!(
6880            result.exit_code, 0,
6881            "a second allowlisted binary exec'd from inside allowlisted bash must succeed \
6882             (stderr: {})",
6883            result.stderr
6884        );
6885    }
6886
6887    #[test]
6888    fn kernel_tier_denies_network_connect_outside_allowlist() {
6889        if crate::network_namespace::skip_without_egress_namespace(
6890            "kernel_tier_denies_network_connect_outside_allowlist",
6891        ) {
6892            return;
6893        }
6894        let tier = detect_enforcement_tier();
6895        if tier == EnforcementTier::EnvironmentOnly {
6896            eprintln!(
6897                "skipping kernel_tier_denies_network_connect_outside_allowlist: resolved to \
6898                 EnvironmentOnly on a Linux host — degrading gracefully"
6899            );
6900            return;
6901        }
6902
6903        // A real listener on the *host*, so the destination port is genuinely open. The failure
6904        // below is therefore about reachability, not about a closed port: the subprocess runs in
6905        // its own network namespace, where `127.0.0.1` is that namespace's own loopback and this
6906        // listener does not exist at all.
6907        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
6908        let port = listener.local_addr().unwrap().port();
6909
6910        let temp = tempfile::tempdir().unwrap();
6911        let policy = CapabilityPolicy {
6912            shell_allow: vec!["bash".to_string()],
6913            ..CapabilityPolicy::default()
6914        };
6915        let enforcement = ShellEnforcement {
6916            tier,
6917            // Empty allowlist: nothing is reachable, and the proxy would refuse it even if the
6918            // capsule found its way to the endpoint.
6919            network_allow_rules: Vec::new(),
6920            network_allow_ips: Vec::new(),
6921            unix_sockets_allowed: policy.unix_sockets_allowed,
6922            landlock_grants: LandlockGrant::non_listable_files(resolve_landlock_grants(
6923                &resolve_exec_allowlist(&policy.shell_allow),
6924            )),
6925            ..host_bounding_base()
6926        };
6927
6928        // bash's /dev/tcp is a builtin socket+connect — no extra binary needed, no DNS.
6929        let script = format!("exec 3<>/dev/tcp/127.0.0.1/{port}");
6930        let result = crate::shell::execute_shell(
6931            "bash",
6932            &["-c", &script],
6933            &[],
6934            temp.path(),
6935            temp.path(),
6936            &policy,
6937            &enforcement,
6938        )
6939        .unwrap();
6940
6941        assert_ne!(
6942            result.exit_code, 0,
6943            "a direct connect() to a destination outside capabilities.network.allow must fail \
6944             even though the port is really open on the host — the subprocess is in its own \
6945             network namespace with no route to it"
6946        );
6947    }
6948
6949    /// The no-regression counterpart of the test above: enforcement must add denials for
6950    /// out-of-policy destinations without breaking permitted ones.
6951    ///
6952    /// The allowlist has to be declared rather than only pre-resolved, because it decides two
6953    /// things: which addresses are permitted *and* which ports the namespace binds a listener on.
6954    /// A port no allow entry implies has nothing listening and is refused by the namespace itself.
6955    ///
6956    /// Deliberately *not* a test of the security property — a green suite proves nothing about
6957    /// the kernel-level claim, and the real check is the hand-run procedure in
6958    /// `docs/content/reference/network-namespace-egress-proxy-manual-verification.md`. This
6959    /// asserts only that the permitted path still functions.
6960    #[test]
6961    fn kernel_tier_reaches_an_allowlisted_destination_through_the_egress_proxy() {
6962        if crate::network_namespace::skip_without_egress_namespace(
6963            "kernel_tier_reaches_an_allowlisted_destination_through_the_egress_proxy",
6964        ) {
6965            return;
6966        }
6967        let tier = detect_enforcement_tier();
6968        if tier == EnforcementTier::EnvironmentOnly {
6969            eprintln!(
6970                "skipping kernel_tier_reaches_an_allowlisted_destination_through_the_egress_proxy: \
6971                 resolved to EnvironmentOnly on a Linux host — degrading gracefully"
6972            );
6973            return;
6974        }
6975
6976        // A real listener on the host, answering one connection, so a success below means bytes
6977        // really crossed the namespace boundary through the proxy rather than merely connecting.
6978        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
6979        let port = listener.local_addr().unwrap().port();
6980        let server = std::thread::spawn(move || {
6981            if let Ok((mut stream, _)) = listener.accept() {
6982                use std::io::Write;
6983                let _ = stream.write_all(b"pong\n");
6984            }
6985        });
6986
6987        let temp = tempfile::tempdir().unwrap();
6988        // Naming the port is required, not incidental: it is what puts a listener on that port
6989        // inside the namespace. See `egress_proxy::egress_listen_ports`.
6990        let allow = vec![format!("http://127.0.0.1:{port}")];
6991        let policy = CapabilityPolicy {
6992            shell_allow: vec!["bash".to_string()],
6993            network_allow: allow.clone(),
6994            ..CapabilityPolicy::default()
6995        };
6996        let rules = crate::network_policy::parse_network_allow_rules(&allow).unwrap();
6997        let enforcement = ShellEnforcement {
6998            tier,
6999            egress_tcp_ports: crate::egress_proxy::egress_listen_ports(&rules),
7000            network_allow_rules: rules,
7001            network_allow_ips: resolve_network_allowlist_ips(&allow).unwrap(),
7002            unix_sockets_allowed: policy.unix_sockets_allowed,
7003            landlock_grants: LandlockGrant::non_listable_files(resolve_landlock_grants(
7004                &resolve_exec_allowlist(&policy.shell_allow),
7005            )),
7006            ..host_bounding_base()
7007        };
7008
7009        // Builtins only — `/dev/tcp` and `read` are bash itself — so no second binary is exec'd
7010        // and this measures the network path alone.
7011        let script =
7012            format!("exec 3<>/dev/tcp/127.0.0.1/{port} && read -r reply <&3 && echo \"$reply\"");
7013        let result = crate::shell::execute_shell(
7014            "bash",
7015            &["-c", &script],
7016            &[],
7017            temp.path(),
7018            temp.path(),
7019            &policy,
7020            &enforcement,
7021        )
7022        .unwrap();
7023        let _ = server.join();
7024
7025        assert_eq!(
7026            result.exit_code, 0,
7027            "a destination inside capabilities.network.allow must stay reachable — enforcement \
7028             adds denials for out-of-policy destinations, it does not degrade permitted ones \
7029             (stderr: {})",
7030            result.stderr
7031        );
7032        assert!(
7033            result.stdout.contains("pong"),
7034            "the host listener's bytes must come back through the proxy unmodified \
7035             (stdout: {:?}, stderr: {})",
7036            result.stdout,
7037            result.stderr
7038        );
7039    }
7040
7041    #[test]
7042    fn kernel_full_denies_filesystem_access_outside_workdir() {
7043        if crate::network_namespace::skip_without_egress_namespace(
7044            "kernel_full_denies_filesystem_access_outside_workdir",
7045        ) {
7046            return;
7047        }
7048        let tier = detect_enforcement_tier();
7049        if tier != EnforcementTier::KernelFull {
7050            eprintln!(
7051                "skipping kernel_full_denies_filesystem_access_outside_workdir: requires \
7052                 EnforcementTier::KernelFull (Landlock ABI, kernel 5.13+); detected {tier:?} \
7053                 instead"
7054            );
7055            return;
7056        }
7057
7058        let temp = tempfile::tempdir().unwrap();
7059        let policy = CapabilityPolicy {
7060            shell_allow: vec!["bash".to_string()],
7061            ..CapabilityPolicy::default()
7062        };
7063        let enforcement = ShellEnforcement {
7064            tier,
7065            network_allow_ips: Vec::new(),
7066            unix_sockets_allowed: policy.unix_sockets_allowed,
7067            landlock_grants: LandlockGrant::non_listable_files(resolve_landlock_grants(
7068                &resolve_exec_allowlist(&policy.shell_allow),
7069            )),
7070            ..host_bounding_base()
7071        };
7072
7073        let result = crate::shell::execute_shell(
7074            "bash",
7075            &["-c", "cat /etc/hostname"],
7076            &[],
7077            temp.path(),
7078            temp.path(),
7079            &policy,
7080            &enforcement,
7081        )
7082        .unwrap();
7083
7084        assert_ne!(
7085            result.exit_code, 0,
7086            "reading a file outside the Landlock-scoped workdir must fail under KernelFull"
7087        );
7088    }
7089
7090    // The two tests below exercise the derived Landlock grants. A green run is not evidence they
7091    // work: below `KernelFull` the weaker `KernelSeccompOnly` path runs instead, and on non-Linux
7092    // no Landlock domain is installed at all. Both tests print a skip line and return when the
7093    // host is not `KernelFull`.
7094
7095    #[test]
7096    fn kernel_full_runs_nontrivial_shell_allowlist_but_a_pass_here_does_not_prove_the_landlock_fix()
7097    {
7098        if crate::network_namespace::skip_without_egress_namespace("kernel_full_runs_nontrivial_shell_allowlist_but_a_pass_here_does_not_prove_the_landlock_fix") {
7099            return;
7100        }
7101        let tier = detect_enforcement_tier();
7102        if tier != EnforcementTier::KernelFull {
7103            eprintln!(
7104                "SKIP — PROVES NOTHING ABOUT THE LANDLOCK FIX ON THIS HOST: \
7105                 kernel_full_runs_nontrivial_shell_allowlist_... requires \
7106                 EnforcementTier::KernelFull (Landlock ABI, kernel 5.13+); detected {tier:?}. \
7107                 This run does NOT execute the derived-grant Landlock code path at all, so a \
7108                 green result here is not evidence the workdir-scope exec bug is fixed — only a \
7109                 real KernelFull Linux host can prove that."
7110            );
7111            return;
7112        }
7113
7114        let temp = tempfile::tempdir().unwrap();
7115        // A non-trivial allowlist: an interpreter (`bash`) plus a second, genuinely nested,
7116        // dynamically-linked binary (`cat`). Both are guaranteed present on the target dev/CI
7117        // Linux hosts and both live outside the workdir, so this only succeeds if the derived
7118        // Landlock grants cover each binary, its ELF interpreter, and its shared libraries.
7119        let policy = CapabilityPolicy {
7120            shell_allow: vec!["bash".to_string(), "cat".to_string()],
7121            ..CapabilityPolicy::default()
7122        };
7123        let exec_allow_paths = resolve_exec_allowlist(&policy.shell_allow);
7124        let enforcement = ShellEnforcement {
7125            tier,
7126            network_allow_ips: Vec::new(),
7127            unix_sockets_allowed: policy.unix_sockets_allowed,
7128            landlock_grants: LandlockGrant::non_listable_files(resolve_landlock_grants(
7129                &exec_allow_paths,
7130            )),
7131            ..host_bounding_base()
7132        };
7133
7134        // `echo` is a bash builtin; piping it into `cat` forces bash to fork+exec `cat`, a real
7135        // nested, dynamically-linked exec — the case the whole fix exists for.
7136        let result = crate::shell::execute_shell(
7137            "bash",
7138            &["-c", "echo landlock-grant-ok | cat"],
7139            &[],
7140            temp.path(),
7141            temp.path(),
7142            &policy,
7143            &enforcement,
7144        )
7145        .expect("execute_shell should return Ok, not Err");
7146
7147        assert_eq!(
7148            result.exit_code, 0,
7149            "bash + cat are both allowlisted and dynamically linked; the derived Landlock grants \
7150             must let each exec and dynamic-link outside the workdir (stderr: {})",
7151            result.stderr
7152        );
7153        assert!(
7154            result.stdout.contains("landlock-grant-ok"),
7155            "the nested `cat` must actually run and pass its stdin through (stdout: {}, stderr: {})",
7156            result.stdout,
7157            result.stderr
7158        );
7159    }
7160
7161    #[test]
7162    fn kernel_full_denies_write_outside_workdir_but_a_pass_here_does_not_prove_the_landlock_fix() {
7163        if crate::network_namespace::skip_without_egress_namespace("kernel_full_denies_write_outside_workdir_but_a_pass_here_does_not_prove_the_landlock_fix") {
7164            return;
7165        }
7166        let tier = detect_enforcement_tier();
7167        if tier != EnforcementTier::KernelFull {
7168            eprintln!(
7169                "SKIP — PROVES NOTHING ABOUT THE LANDLOCK FIX ON THIS HOST: \
7170                 kernel_full_denies_write_outside_workdir_... requires \
7171                 EnforcementTier::KernelFull (Landlock ABI, kernel 5.13+); detected {tier:?}. \
7172                 This run does NOT execute the Landlock code path, so a green result here is not \
7173                 evidence writes outside the workdir are actually denied — only a real KernelFull \
7174                 Linux host can prove that."
7175            );
7176            return;
7177        }
7178
7179        let workdir = tempfile::tempdir().unwrap();
7180        // A target OUTSIDE the workdir (a separate temp dir). Its parent exists, so the only
7181        // reason a write can fail is the Landlock scope — not a missing directory.
7182        let outside = tempfile::tempdir().unwrap();
7183        let target = outside.path().join("should-not-be-written.txt");
7184
7185        let policy = CapabilityPolicy {
7186            shell_allow: vec!["bash".to_string()],
7187            ..CapabilityPolicy::default()
7188        };
7189        let exec_allow_paths = resolve_exec_allowlist(&policy.shell_allow);
7190        let enforcement = ShellEnforcement {
7191            tier,
7192            network_allow_ips: Vec::new(),
7193            unix_sockets_allowed: policy.unix_sockets_allowed,
7194            landlock_grants: LandlockGrant::non_listable_files(resolve_landlock_grants(
7195                &exec_allow_paths,
7196            )),
7197            ..host_bounding_base()
7198        };
7199
7200        // `echo >file` uses only a bash builtin + an open-for-write of an outside path — the
7201        // write itself is what Landlock must refuse. The derived read+execute grants never widen
7202        // to write, so nothing outside the workdir (grant paths included) is writable.
7203        let script = format!("echo pwned > '{}'", target.display());
7204        let result = crate::shell::execute_shell(
7205            "bash",
7206            &["-c", &script],
7207            &[],
7208            workdir.path(),
7209            workdir.path(),
7210            &policy,
7211            &enforcement,
7212        )
7213        .expect("execute_shell should return Ok with a nonzero exit code, not Err");
7214
7215        assert!(
7216            !target.exists(),
7217            "a write to a path outside the Landlock-scoped workdir must be denied under KernelFull"
7218        );
7219        assert_ne!(
7220            result.exit_code, 0,
7221            "bash's redirection to an outside path must fail (Landlock denies the open-for-write)"
7222        );
7223    }
7224
7225    /// Builds a KernelFull enforcement for `policy`, combining the derived `DT_NEEDED`-closure
7226    /// file grants with the policy's `interpreter_runtime` directory grants — exactly what
7227    /// `ShellEnforcement::resolve` does, spelled out so the test controls the tier explicitly.
7228    fn kernel_full_enforcement(
7229        tier: EnforcementTier,
7230        policy: &CapabilityPolicy,
7231    ) -> ShellEnforcement {
7232        let exec_allow_paths = resolve_exec_allowlist(&policy.shell_allow);
7233        let mut landlock_grants =
7234            LandlockGrant::non_listable_files(resolve_landlock_grants(&exec_allow_paths));
7235        landlock_grants.extend(resolve_interpreter_runtime_grants(
7236            &policy.shell_interpreter_runtime,
7237        ));
7238        ShellEnforcement {
7239            tier,
7240            network_allow_ips: Vec::new(),
7241            unix_sockets_allowed: policy.unix_sockets_allowed,
7242            landlock_grants,
7243            ..host_bounding_base()
7244        }
7245    }
7246
7247    /// A real sealed run against two different workdirs: the composed root's `/tmp` and its
7248    /// synthetic `/etc/passwd` both have to resolve from the session workdir, and the capsule's
7249    /// own directory has to gain nothing from either.
7250    ///
7251    /// This is the one test that drives a composed root end to end, so it needs a host that can
7252    /// actually reach `KernelSealed` and skips loudly on one that cannot; the parent-side halves
7253    /// are covered unconditionally by the `open_landlock_fds` tests above. `mur doctor` reports
7254    /// the same host answer this checks.
7255    #[test]
7256    fn a_sealed_command_finds_tmp_and_etc_after_they_moved_into_the_session_workdir() {
7257        if crate::network_namespace::skip_without_egress_namespace(
7258            "a_sealed_command_finds_tmp_and_etc_after_they_moved_into_the_session_workdir",
7259        ) {
7260            return;
7261        }
7262        let probe = HostProbe::probe();
7263        if probe.tier() != EnforcementTier::KernelSealed {
7264            eprintln!(
7265                "SKIP — PROVES NOTHING ABOUT THE SEALED ROOT ON THIS HOST: \
7266                 a_sealed_command_finds_tmp_and_etc_... needs a host that reaches KernelSealed \
7267                 (unprivileged user namespaces plus a usable Landlock ABI); detected {:?}. No \
7268                 composed root is built in this run.",
7269                probe.tier()
7270            );
7271            return;
7272        }
7273
7274        let accessible = tempfile::tempdir().unwrap();
7275        let session = accessible.path().join(".murmur").join("ses_sealed_e2e");
7276        std::fs::create_dir_all(&session).unwrap();
7277        let policy = CapabilityPolicy {
7278            shell_allow: vec!["bash".to_string(), "cat".to_string(), "id".to_string()],
7279            ..CapabilityPolicy::default()
7280        };
7281        let enforcement =
7282            ShellEnforcement::resolve(&policy, murmur_artifact::ContainmentClass::Sealed, probe)
7283                .expect("a sealed-capable host resolves sealed enforcement");
7284        assert_eq!(enforcement.tier, EnforcementTier::KernelSealed);
7285
7286        let result = crate::shell::execute_shell(
7287            "bash",
7288            &["-c", "echo t > /tmp/probe && cat /tmp/probe && id -un"],
7289            &[],
7290            accessible.path(),
7291            &session,
7292            &policy,
7293            &enforcement,
7294        )
7295        .expect("execute_shell returns Ok even when the command itself fails");
7296
7297        assert_eq!(
7298            result.exit_code, 0,
7299            "stdout: {} stderr: {}",
7300            result.stdout, result.stderr
7301        );
7302        let mut lines = result.stdout.lines();
7303        assert_eq!(
7304            lines.next(),
7305            Some("t"),
7306            "the capsule's /tmp must be writable"
7307        );
7308        assert!(
7309            lines.next().is_some_and(|name| !name.is_empty()),
7310            "`id -un` resolves only through the synthetic /etc/passwd the composed root binds: \
7311             {}",
7312            result.stdout
7313        );
7314
7315        assert_eq!(
7316            std::fs::read_to_string(
7317                session
7318                    .join(crate::sealed::SEALED_TMP_DIR_NAME)
7319                    .join("probe")
7320            )
7321            .unwrap(),
7322            "t\n",
7323            "the bytes written to /tmp land in the session workdir's own store"
7324        );
7325        assert!(session
7326            .join(crate::sealed::SEALED_ETC_STAGING_DIR_NAME)
7327            .join("passwd")
7328            .is_file());
7329        for name in [
7330            crate::sealed::SEALED_TMP_DIR_NAME,
7331            crate::sealed::SEALED_ETC_STAGING_DIR_NAME,
7332            crate::shell::SYNTHETIC_HOME_DIR_NAME,
7333        ] {
7334            assert!(
7335                !accessible.path().join(name).exists(),
7336                "enabling sealed must add nothing to the top level of the accessible workdir, \
7337                 and it added {name}"
7338            );
7339        }
7340    }
7341
7342    // As above: a green run proves nothing below `KernelFull`. Both tests print a skip line and
7343    // return when the host is not `KernelFull`.
7344
7345    #[test]
7346    fn kernel_full_interpreter_runtime_list_dir_false_opens_file_but_denies_listing() {
7347        if crate::network_namespace::skip_without_egress_namespace(
7348            "kernel_full_interpreter_runtime_list_dir_false_opens_file_but_denies_listing",
7349        ) {
7350            return;
7351        }
7352        let tier = detect_enforcement_tier();
7353        if tier != EnforcementTier::KernelFull {
7354            eprintln!(
7355                "SKIP — PROVES NOTHING ABOUT THE LANDLOCK FIX ON THIS HOST: \
7356                 kernel_full_interpreter_runtime_list_dir_false_... requires \
7357                 EnforcementTier::KernelFull (Landlock ABI, kernel 5.13+); detected {tier:?}. \
7358                 This run does NOT execute the interpreter_runtime Landlock code path, so a green \
7359                 result here is not evidence list_dir:false behaves correctly — only a real \
7360                 KernelFull Linux host can prove that."
7361            );
7362            return;
7363        }
7364
7365        let workdir = tempfile::tempdir().unwrap();
7366        // A "stdlib"-shaped directory OUTSIDE the workdir, holding one known file.
7367        let stdlib = tempfile::tempdir().unwrap();
7368        let module = stdlib.path().join("mod.py");
7369        std::fs::write(&module, "x = 1\n").unwrap();
7370
7371        let policy = CapabilityPolicy {
7372            shell_allow: vec!["bash".to_string(), "cat".to_string(), "ls".to_string()],
7373            shell_interpreter_runtime: vec![InterpreterRuntimeGrant {
7374                binary: "bash".to_string(),
7375                dirs: vec![murmur_artifact::InterpreterRuntimeDir {
7376                    path: stdlib.path().to_string_lossy().into_owned(),
7377                    list_dir: false,
7378                }],
7379            }],
7380            ..CapabilityPolicy::default()
7381        };
7382        let enforcement = kernel_full_enforcement(tier, &policy);
7383
7384        // Opening the file by its exact known name must succeed — Landlock's read rights apply to
7385        // the subtree beneath the granted directory.
7386        let read = crate::shell::execute_shell(
7387            "bash",
7388            &["-c", &format!("cat '{}'", module.display())],
7389            &[],
7390            workdir.path(),
7391            workdir.path(),
7392            &policy,
7393            &enforcement,
7394        )
7395        .expect("execute_shell should return Ok");
7396        assert_eq!(
7397            read.exit_code, 0,
7398            "list_dir:false must still permit opening a known file inside the grant (stderr: {})",
7399            read.stderr
7400        );
7401        assert!(read.stdout.contains("x = 1"), "stdout: {}", read.stdout);
7402
7403        // Listing the directory's own entries must fail — ReadDir was not granted.
7404        let list = crate::shell::execute_shell(
7405            "bash",
7406            &["-c", &format!("ls '{}'", stdlib.path().display())],
7407            &[],
7408            workdir.path(),
7409            workdir.path(),
7410            &policy,
7411            &enforcement,
7412        )
7413        .expect("execute_shell should return Ok with a nonzero exit code");
7414        assert_ne!(
7415            list.exit_code, 0,
7416            "list_dir:false must deny enumerating the granted directory's own entries"
7417        );
7418    }
7419
7420    #[test]
7421    fn kernel_full_interpreter_runtime_list_dir_true_lists_dir_but_not_its_parent() {
7422        if crate::network_namespace::skip_without_egress_namespace(
7423            "kernel_full_interpreter_runtime_list_dir_true_lists_dir_but_not_its_parent",
7424        ) {
7425            return;
7426        }
7427        let tier = detect_enforcement_tier();
7428        if tier != EnforcementTier::KernelFull {
7429            eprintln!(
7430                "SKIP — PROVES NOTHING ABOUT THE LANDLOCK FIX ON THIS HOST: \
7431                 kernel_full_interpreter_runtime_list_dir_true_... requires \
7432                 EnforcementTier::KernelFull (Landlock ABI, kernel 5.13+); detected {tier:?}. \
7433                 This run does NOT execute the interpreter_runtime Landlock code path, so a green \
7434                 result here is not evidence list_dir:true (and its non-widening to the parent) \
7435                 behaves correctly — only a real KernelFull Linux host can prove that."
7436            );
7437            return;
7438        }
7439
7440        let workdir = tempfile::tempdir().unwrap();
7441        // parent/ (NOT granted) contains stdlib/ (granted list_dir:true) contains one file.
7442        let parent = tempfile::tempdir().unwrap();
7443        let stdlib = parent.path().join("stdlib");
7444        std::fs::create_dir(&stdlib).unwrap();
7445        std::fs::write(stdlib.join("mod.py"), "x = 1\n").unwrap();
7446
7447        let policy = CapabilityPolicy {
7448            shell_allow: vec!["bash".to_string(), "ls".to_string()],
7449            shell_interpreter_runtime: vec![InterpreterRuntimeGrant {
7450                binary: "bash".to_string(),
7451                dirs: vec![murmur_artifact::InterpreterRuntimeDir {
7452                    path: stdlib.to_string_lossy().into_owned(),
7453                    list_dir: true,
7454                }],
7455            }],
7456            ..CapabilityPolicy::default()
7457        };
7458        let enforcement = kernel_full_enforcement(tier, &policy);
7459
7460        // Listing the granted directory must succeed.
7461        let list = crate::shell::execute_shell(
7462            "bash",
7463            &["-c", &format!("ls '{}'", stdlib.display())],
7464            &[],
7465            workdir.path(),
7466            workdir.path(),
7467            &policy,
7468            &enforcement,
7469        )
7470        .expect("execute_shell should return Ok");
7471        assert_eq!(
7472            list.exit_code, 0,
7473            "list_dir:true must permit enumerating the granted directory (stderr: {})",
7474            list.stderr
7475        );
7476        assert!(list.stdout.contains("mod.py"), "stdout: {}", list.stdout);
7477
7478        // Listing the PARENT (never named in any grant) must fail — naming one subdirectory does
7479        // not widen enumerability to its ancestors. This is the `/usr/lib` ceiling case.
7480        let list_parent = crate::shell::execute_shell(
7481            "bash",
7482            &["-c", &format!("ls '{}'", parent.path().display())],
7483            &[],
7484            workdir.path(),
7485            workdir.path(),
7486            &policy,
7487            &enforcement,
7488        )
7489        .expect("execute_shell should return Ok with a nonzero exit code");
7490        assert_ne!(
7491            list_parent.exit_code, 0,
7492            "a grant on stdlib/ must not make its (ungranted) parent enumerable"
7493        );
7494    }
7495
7496    /// The `executable` axis, asserted against a real Landlock kernel.
7497    ///
7498    /// This is the property the `sealed` runtime-tree grant depends on: a whole tree can be made
7499    /// readable and enumerable without becoming a place to run programs from. It is asserted here
7500    /// on the plain Landlock path (`KernelFull`) because the access shape is tier-independent —
7501    /// `apply_landlock_scope` builds the same rule either way — and because a `KernelSealed` host
7502    /// would have to be driven through a composed root, which no unit test can reach.
7503    ///
7504    /// Runs on any host with a usable Landlock ABI, `KernelSealed` ones included: the tier is
7505    /// pinned in the enforcement literal, so only the ABI has to be real. Skips loudly elsewhere.
7506    #[test]
7507    fn kernel_full_non_executable_grant_lists_its_tree_but_refuses_to_run_from_it() {
7508        if crate::network_namespace::skip_without_egress_namespace(
7509            "kernel_full_non_executable_grant_lists_its_tree_but_refuses_to_run_from_it",
7510        ) {
7511            return;
7512        }
7513        let host_tier = detect_enforcement_tier();
7514        if !matches!(
7515            host_tier,
7516            EnforcementTier::KernelFull | EnforcementTier::KernelSealed
7517        ) {
7518            eprintln!(
7519                "SKIP — PROVES NOTHING ABOUT THE LANDLOCK FIX ON THIS HOST: \
7520                 kernel_full_non_executable_grant_... needs a usable Landlock ABI (kernel 5.13+); \
7521                 detected {host_tier:?}. This run does NOT install a Landlock domain, so a green \
7522                 result is not evidence that withholding Execute denies execve."
7523            );
7524            return;
7525        }
7526
7527        let workdir = tempfile::tempdir().unwrap();
7528        // A runtime-tree stand-in: one readable file plus one runnable binary, outside the workdir.
7529        let tree = tempfile::tempdir().unwrap();
7530        std::fs::write(tree.path().join("entry.txt"), "x\n").unwrap();
7531        let runme = tree.path().join("runme");
7532        std::fs::copy("/bin/echo", &runme).unwrap();
7533
7534        let policy = CapabilityPolicy {
7535            shell_allow: vec!["bash".to_string(), "ls".to_string()],
7536            ..CapabilityPolicy::default()
7537        };
7538        let with_tree_grant = |executable: bool| {
7539            let mut enforcement = kernel_full_enforcement(EnforcementTier::KernelFull, &policy);
7540            enforcement.landlock_grants.push(LandlockGrant {
7541                path: tree.path().to_path_buf(),
7542                list_dir: true,
7543                executable,
7544            });
7545            enforcement
7546        };
7547        let run = |enforcement: &ShellEnforcement, command: String| {
7548            crate::shell::execute_shell(
7549                "bash",
7550                &["-c", &command],
7551                &[],
7552                workdir.path(),
7553                workdir.path(),
7554                &policy,
7555                enforcement,
7556            )
7557            .expect("execute_shell should return Ok even when the command itself fails")
7558        };
7559
7560        let denied = with_tree_grant(false);
7561        let list = run(&denied, format!("ls '{}'", tree.path().display()));
7562        assert_eq!(
7563            list.exit_code, 0,
7564            "a non-executable grant must still be enumerable — that is its entire purpose \
7565             (stderr: {})",
7566            list.stderr
7567        );
7568        assert!(list.stdout.contains("entry.txt"), "stdout: {}", list.stdout);
7569
7570        let exec_denied = run(&denied, format!("'{}' ran", runme.display()));
7571        assert_ne!(
7572            exec_denied.exit_code, 0,
7573            "withholding Execute must deny execve inside the granted tree; a program ran instead \
7574             (stdout: {})",
7575            exec_denied.stdout
7576        );
7577        assert!(
7578            !exec_denied.stdout.contains("ran"),
7579            "the binary produced output, so it executed: {}",
7580            exec_denied.stdout
7581        );
7582
7583        // The control: the identical grant with `executable: true` does run it. Without this the
7584        // assertion above could be passing for an unrelated reason (a bad path, a missing library).
7585        let allowed = with_tree_grant(true);
7586        let exec_allowed = run(&allowed, format!("'{}' ran", runme.display()));
7587        assert_eq!(
7588            exec_allowed.exit_code, 0,
7589            "the same tree granted Execute must run (stderr: {})",
7590            exec_allowed.stderr
7591        );
7592        assert!(
7593            exec_allowed.stdout.contains("ran"),
7594            "stdout: {}",
7595            exec_allowed.stdout
7596        );
7597    }
7598
7599    /// The access shape most of `SEALED_ETC_PATHS` needs: a non-executable grant on a *regular
7600    /// file* (`/etc/ssl/certs/ca-certificates.crt`'s stand-in) must install and be readable.
7601    ///
7602    /// Two kernel facts are pinned here. First, `ReadFile` alone —
7603    /// `apply_landlock_scope`'s `(false, false)` arm — is enough to `open()` the file. Second,
7604    /// `landlock_append_fs_rule` rejects `ReadDir` on a non-directory with `EINVAL`, and the rule
7605    /// loop is fail-closed, so a `list_dir: true` *claim* on a file would refuse the whole launch
7606    /// if `open_landlock_fds` did not narrow it against the fd it opened. The second half of this
7607    /// test is that narrowing: the same grant asserted `list_dir: true` must still launch and still
7608    /// read, not die in `pre_exec`.
7609    ///
7610    /// Runs on any host with a usable Landlock ABI; skips loudly elsewhere.
7611    #[test]
7612    fn kernel_full_non_executable_file_grant_is_readable_and_survives_a_bad_list_dir_claim() {
7613        if crate::network_namespace::skip_without_egress_namespace(
7614            "kernel_full_non_executable_file_grant_is_readable_and_survives_a_bad_list_dir_claim",
7615        ) {
7616            return;
7617        }
7618        let host_tier = detect_enforcement_tier();
7619        if !matches!(
7620            host_tier,
7621            EnforcementTier::KernelFull | EnforcementTier::KernelSealed
7622        ) {
7623            eprintln!(
7624                "SKIP — PROVES NOTHING ABOUT THE LANDLOCK FIX ON THIS HOST: \
7625                 kernel_full_non_executable_file_grant_... needs a usable Landlock ABI (kernel \
7626                 5.13+); detected {host_tier:?}. This run does NOT install a Landlock domain, so a \
7627                 green result is not evidence that a file grant reads, nor that a ReadDir claim on \
7628                 a file is narrowed instead of refusing the launch."
7629            );
7630            return;
7631        }
7632
7633        let workdir = tempfile::tempdir().unwrap();
7634        // A trust-store stand-in: a regular file outside the workdir, granted on its own.
7635        let store = tempfile::tempdir().unwrap();
7636        let bundle = store.path().join("ca-certificates.crt");
7637        std::fs::write(&bundle, "-----BEGIN CERTIFICATE-----\n").unwrap();
7638
7639        let policy = CapabilityPolicy {
7640            shell_allow: vec!["bash".to_string(), "cat".to_string()],
7641            ..CapabilityPolicy::default()
7642        };
7643        let with_file_grant = |list_dir: bool| {
7644            let mut enforcement = kernel_full_enforcement(EnforcementTier::KernelFull, &policy);
7645            enforcement.landlock_grants.push(LandlockGrant {
7646                path: bundle.clone(),
7647                list_dir,
7648                executable: false,
7649            });
7650            enforcement
7651        };
7652        let read = |enforcement: &ShellEnforcement| {
7653            crate::shell::execute_shell(
7654                "bash",
7655                &["-c", &format!("cat '{}'", bundle.display())],
7656                &[],
7657                workdir.path(),
7658                workdir.path(),
7659                &policy,
7660                enforcement,
7661            )
7662            .expect("execute_shell should return Ok even when the command itself fails")
7663        };
7664
7665        let honest = read(&with_file_grant(false));
7666        assert_eq!(
7667            honest.exit_code, 0,
7668            "ReadFile alone must open a granted regular file — this is what the /etc allowlist's \
7669             file entries rely on (stderr: {})",
7670            honest.stderr
7671        );
7672        assert!(
7673            honest.stdout.contains("BEGIN CERTIFICATE"),
7674            "stdout: {}",
7675            honest.stdout
7676        );
7677
7678        let overclaimed = read(&with_file_grant(true));
7679        assert_eq!(
7680            overclaimed.exit_code, 0,
7681            "a list_dir:true claim on a regular file must be narrowed to ReadFile, not turned \
7682             into an EINVAL that refuses the launch (stderr: {})",
7683            overclaimed.stderr
7684        );
7685        assert!(
7686            overclaimed.stdout.contains("BEGIN CERTIFICATE"),
7687            "stdout: {}",
7688            overclaimed.stdout
7689        );
7690    }
7691
7692    // ---- every distinct pre_exec setup failure is legible + fail-closed ----
7693    //
7694    // These force each of the three distinct sandbox setup failures and assert each produces its
7695    // OWN legible message (not the undifferentiated bare EINVAL), and that the target binary never
7696    // executes. One failure is real (an unresolvable workdir, now caught before fork()); two use
7697    // the child-side (`pre_exec`) test seams below. All are safe on any Linux host: the workdir
7698    // and no_new_privs failures happen before any real kernel enforcement, and the Landlock seam
7699    // short-circuits before any real Landlock syscall.
7700
7701    struct ForceNoNewPrivsFailureGuard;
7702
7703    impl ForceNoNewPrivsFailureGuard {
7704        fn new() -> Self {
7705            FORCE_NO_NEW_PRIVS_FAILURE.with(|flag| flag.set(true));
7706            Self
7707        }
7708    }
7709
7710    impl Drop for ForceNoNewPrivsFailureGuard {
7711        fn drop(&mut self) {
7712            FORCE_NO_NEW_PRIVS_FAILURE.with(|flag| flag.set(false));
7713        }
7714    }
7715
7716    struct ForceLandlockFailureGuard;
7717
7718    impl ForceLandlockFailureGuard {
7719        fn new() -> Self {
7720            FORCE_LANDLOCK_FAILURE.with(|flag| flag.set(true));
7721            Self
7722        }
7723    }
7724
7725    impl Drop for ForceLandlockFailureGuard {
7726        fn drop(&mut self) {
7727            FORCE_LANDLOCK_FAILURE.with(|flag| flag.set(false));
7728        }
7729    }
7730
7731    /// A `KernelFull` enforcement over an empty Landlock grant set. The forced-failure tests do not
7732    /// depend on any specific grant — they force the failure directly — so this exercises the
7733    /// child-side `pre_exec` steps on any Linux host regardless of its real Landlock support.
7734    fn kernel_full_empty_grants() -> ShellEnforcement {
7735        ShellEnforcement {
7736            tier: EnforcementTier::KernelFull,
7737            network_allow_ips: Vec::new(),
7738            unix_sockets_allowed: false,
7739            landlock_grants: Vec::new(),
7740            ..host_bounding_base()
7741        }
7742    }
7743
7744    /// Scenario 1 (real): `prepare_enforcement` with a `KernelFull` tier and a workdir that does
7745    /// not exist. Because the workdir's Landlock fd is opened in the PARENT, this fails
7746    /// synchronously before fork() — `.spawn()` is never called. Returns the error string.
7747    fn workdir_resolution_error() -> String {
7748        let temp = tempfile::tempdir().unwrap();
7749        let missing = temp.path().join("does-not-exist-workdir");
7750        let marker = temp.path().join("never-spawned.marker");
7751        let mut command = std::process::Command::new("bash");
7752        command
7753            .arg("-c")
7754            .arg(format!("echo ran > '{}'", marker.display()));
7755
7756        let error = prepare_enforcement(
7757            &mut command,
7758            &kernel_full_empty_grants(),
7759            &missing,
7760            &missing,
7761        )
7762        .expect_err("an unresolvable workdir must fail before fork()");
7763        assert!(
7764            !marker.exists(),
7765            "prepare_enforcement must never spawn a subprocess: {error}"
7766        );
7767        error
7768    }
7769
7770    /// Runs `execute_shell` for `bash -c 'echo ran > marker'` under `KernelFull` with `arm`'s
7771    /// child-side failure active, asserts the target script never ran (marker absent), and returns
7772    /// the resulting error string. The RAII guard `arm` returns stays alive across `.spawn()`.
7773    fn child_setup_failure_error<G>(arm: impl FnOnce() -> G) -> String {
7774        child_setup_failure_typed(&kernel_full_empty_grants(), arm).to_string()
7775    }
7776
7777    /// [`child_setup_failure_error`] without the lossy `.to_string()`, and over a caller-chosen
7778    /// enforcement. Tests that care which *kind* of failure happened — not merely what it reads
7779    /// like — use this: the whole point of the sealed composed-root failure is that it keeps its
7780    /// identity out to the CLI instead of arriving as one more error string.
7781    fn child_setup_failure_typed<G>(
7782        enforcement: &ShellEnforcement,
7783        arm: impl FnOnce() -> G,
7784    ) -> crate::shell::ShellExecError {
7785        let temp = tempfile::tempdir().unwrap();
7786        let policy = CapabilityPolicy {
7787            shell_allow: vec!["bash".to_string()],
7788            ..CapabilityPolicy::default()
7789        };
7790        let marker = temp.path().join("spawned-anyway.marker");
7791        let script = format!("echo ran > '{}'", marker.display());
7792
7793        let _guard = arm();
7794        let error = crate::shell::execute_shell(
7795            "bash",
7796            &["-c", &script],
7797            &[],
7798            temp.path(),
7799            temp.path(),
7800            &policy,
7801            enforcement,
7802        )
7803        .expect_err("a forced child-side setup failure must make execute_shell return Err");
7804        assert!(
7805            !marker.exists(),
7806            "no subprocess may run when pre_exec setup fails: {error}"
7807        );
7808        error
7809    }
7810
7811    #[test]
7812    fn pre_exec_workdir_resolution_failure_is_caught_before_fork() {
7813        let error = workdir_resolution_error();
7814        assert!(
7815            error.contains("workdir") && error.contains("does-not-exist-workdir"),
7816            "the error must name the workdir path that failed to resolve: {error}"
7817        );
7818        assert!(
7819            !error.contains("os error 22"),
7820            "must not collapse to the bare EINVAL string: {error}"
7821        );
7822    }
7823
7824    #[test]
7825    fn pre_exec_no_new_privs_failure_is_distinct_and_fails_closed() {
7826        if crate::network_namespace::skip_without_egress_namespace(
7827            "pre_exec_no_new_privs_failure_is_distinct_and_fails_closed",
7828        ) {
7829            return;
7830        }
7831        let error = child_setup_failure_error(ForceNoNewPrivsFailureGuard::new);
7832        assert!(
7833            error.contains("no_new_privs"),
7834            "the error must name the no_new_privs step specifically: {error}"
7835        );
7836        assert!(
7837            !error.contains("os error 22"),
7838            "must not collapse to the bare EINVAL string: {error}"
7839        );
7840    }
7841
7842    #[test]
7843    fn pre_exec_landlock_failure_is_distinct_and_fails_closed() {
7844        if crate::network_namespace::skip_without_egress_namespace(
7845            "pre_exec_landlock_failure_is_distinct_and_fails_closed",
7846        ) {
7847            return;
7848        }
7849        let error = child_setup_failure_error(ForceLandlockFailureGuard::new);
7850        assert!(
7851            error.contains("landlock"),
7852            "the error must name the Landlock construction step specifically: {error}"
7853        );
7854        assert!(
7855            !error.contains("os error 22"),
7856            "must not collapse to the bare EINVAL string: {error}"
7857        );
7858    }
7859
7860    #[test]
7861    fn pre_exec_setup_failures_produce_pairwise_distinct_messages() {
7862        if crate::network_namespace::skip_without_egress_namespace(
7863            "pre_exec_setup_failures_produce_pairwise_distinct_messages",
7864        ) {
7865            return;
7866        }
7867        let workdir_msg = workdir_resolution_error();
7868        let no_new_privs_msg = child_setup_failure_error(ForceNoNewPrivsFailureGuard::new);
7869        let landlock_msg = child_setup_failure_error(ForceLandlockFailureGuard::new);
7870
7871        let messages = [
7872            ("workdir", &workdir_msg),
7873            ("no_new_privs", &no_new_privs_msg),
7874            ("landlock", &landlock_msg),
7875        ];
7876        for (i, (left_name, left)) in messages.iter().enumerate() {
7877            for (right_name, right) in &messages[i + 1..] {
7878                assert_ne!(left, right, "{left_name} vs {right_name} must differ");
7879            }
7880        }
7881
7882        for message in [&workdir_msg, &no_new_privs_msg, &landlock_msg] {
7883            assert!(!message.is_empty(), "a distinct message must not be empty");
7884            assert!(
7885                !message.contains("os error 22"),
7886                "no failure may read as a bare EINVAL: {message}"
7887            );
7888        }
7889    }
7890
7891    /// The first half of the composed-root failure path: a `pre_exec`
7892    /// composed-root failure comes back out of `execute_shell` as the *typed*
7893    /// `SealedRootConstructionFailed`, carrying the child's diagnostic, and reports itself as
7894    /// session-fatal. `runtime::tests` covers the second half (what the dispatch layer then
7895    /// does with it) and `murmur-cli`'s error test covers the third (`E-RUN-014`).
7896    #[test]
7897    fn a_composed_root_failure_is_typed_and_session_fatal_not_just_another_message() {
7898        if crate::network_namespace::skip_without_egress_namespace(
7899            "a_composed_root_failure_is_typed_and_session_fatal_not_just_another_message",
7900        ) {
7901            return;
7902        }
7903        let error =
7904            child_setup_failure_typed(&sealed_test_enforcement(), ForceSealedRootFailureGuard::new);
7905
7906        assert!(
7907            matches!(
7908                error,
7909                crate::shell::ShellExecError::SealedRootConstructionFailed { .. }
7910            ),
7911            "a sealed-root diagnostic must survive as its own variant, not collapse into \
7912             ShellExecError::Failed: {error}"
7913        );
7914        let fatal = error
7915            .session_fatal()
7916            .expect("a composed-root failure must end the session, not just the tool call");
7917        assert!(
7918            matches!(
7919                fatal,
7920                crate::errors::RuntimeError::SealedRootConstructionFailed { .. }
7921            ),
7922            "must map to the RuntimeError the CLI renders as E-RUN-014: {fatal}"
7923        );
7924        let rendered = error.to_string();
7925        assert!(
7926            rendered.contains("composed root") && rendered.contains("unshare"),
7927            "the message must name both the mechanism and the step that failed: {rendered}"
7928        );
7929        assert!(
7930            !rendered.contains("os error 22"),
7931            "must not collapse to the bare EINVAL string: {rendered}"
7932        );
7933    }
7934
7935    /// The contrast that makes the assertion above mean something: an equally fatal-looking
7936    /// `pre_exec` failure that is *not* the composed root stays an ordinary failure, so nothing
7937    /// in this path ends a session for a Landlock or `no_new_privs` problem.
7938    #[test]
7939    fn an_ordinary_pre_exec_failure_is_not_session_fatal() {
7940        let landlock =
7941            child_setup_failure_typed(&kernel_full_empty_grants(), ForceLandlockFailureGuard::new);
7942        assert!(
7943            landlock.session_fatal().is_none(),
7944            "a Landlock setup failure is the tool call's problem, not the session's: {landlock}"
7945        );
7946
7947        let no_new_privs = child_setup_failure_typed(
7948            &kernel_full_empty_grants(),
7949            ForceNoNewPrivsFailureGuard::new,
7950        );
7951        assert!(
7952            no_new_privs.session_fatal().is_none(),
7953            "a no_new_privs failure is the tool call's problem, not the session's: {no_new_privs}"
7954        );
7955    }
7956}