diff --git a/docs/spec.md b/docs/spec.md index 2fbb0e3..9c5c59c 100644 --- a/docs/spec.md +++ b/docs/spec.md @@ -664,7 +664,11 @@ The floor is **one object with per-platform contents**. On macOS it must include `rc=134` and empty stderr. It must also include `file-read*` on the literal `/System/Volumes/Data`: libSystem stats that mount point at startup, and when the stat is denied it reports the denial over the syslog socket, which the process then holds for its lifetime. On -Linux it includes `/proc`, `/dev`, the loader and its cache. How the floor is spelled never appears in a test; the loader canary and the fd negative must pass on +Linux it includes `/proc`, `/dev`, the loader and its cache, and `/etc/hosts`: `NO_PROXY` names +`localhost`, and a client that honours it resolves that name itself, through glibc reading +`/etc/hosts`; denied, the lookup falls through to a nameserver an FHS host does not run +([#86](https://github.com/firefly-engineering/playpen/issues/86)). The rest of the resolver's +configuration is not in the floor. How the floor is spelled never appears in a test; the loader canary and the fd negative must pass on both platforms. ### 8.3 Toolchain @@ -1312,7 +1316,11 @@ in `--json`, beside the record's own fields): - **macOS**: `/usr/bin/log show --start '' --end '' --predicate 'sender == "Sandbox" AND eventMessage CONTAINS "playpen-run-"'`, the window widened to whole - seconds and given in UTC, and `--end` omitted for a run with no end. The backend attaches the + seconds and by five more either side, and given in UTC, and `--end` omitted for a run with no + end. The margin is for the unified log's own clock, which stamps a denial from a different time + base from the wall clock the record reads, and on a CI runner logged a descendant's denial + before the record's launch time + ([#142](https://github.com/firefly-engineering/playpen/issues/142)). The backend attaches the run's **denial tag**, `playpen-run-`, to the profile's default deny, and the kernel logs it with every denial in the confined tree, whatever the denied process's pid ([#124](https://github.com/firefly-engineering/playpen/issues/124)); the record holds the tag diff --git a/src/explain.rs b/src/explain.rs index ff10eeb..0abbee2 100644 --- a/src/explain.rs +++ b/src/explain.rs @@ -483,11 +483,23 @@ fn render_run(replay: &Replay, out: &mut impl Write) -> io::Result<()> { Ok(()) } +/// How far the denials window reaches past the record's own times, in seconds. The unified log +/// stamps an entry from its own clock, not the wall clock the record reads, and the two disagree: +/// on a `macos-15` CI runner a descendant's denial, made after the record's launch time, was +/// logged at least 52ms before it, outside a window cut at that second +/// ([#142](https://github.com/firefly-engineering/playpen/issues/142)). One sample bounds the skew +/// from below only, so the margin is generous rather than measured. A tagged run's predicate +/// matches that run alone, so it costs `log show` only a little more to read; a pre-tag record's +/// pid filter admits ten more seconds in which another process could have held that pid. +#[cfg(target_os = "macos")] +const LOG_CLOCK_MARGIN_S: u64 = 5; + /// The exact platform command that pulls the denials of the run `record` holds, or `None` for a run /// that never launched ([spec ยง14.2]). /// -/// On macOS the query is the run's window, widened to the whole seconds `log show` takes, filtered -/// to the run's denial tag, which the kernel logs with every denial in the confined tree +/// On macOS the query is the run's window, widened to the whole seconds `log show` takes and by +/// [`LOG_CLOCK_MARGIN_S`] either side, filtered to the run's denial tag, which the kernel logs +/// with every denial in the confined tree /// ([`crate::backend::denial_tag`]). A record written before runs were tagged holds none, and is /// filtered to the child's pid instead, which misses its descendants' denials /// ([#124](https://github.com/firefly-engineering/playpen/issues/124)). `/usr/bin/log` by path, @@ -498,9 +510,11 @@ fn render_run(replay: &Replay, out: &mut impl Write) -> io::Result<()> { fn denials(record: &Record) -> Option { let pid = record.pid?; let launched = record.launched_at_unix_ms?; - let mut command = format!("/usr/bin/log show --start '{}'", log_time(launched / 1000)); + let start = (launched / 1000).saturating_sub(LOG_CLOCK_MARGIN_S); + let mut command = format!("/usr/bin/log show --start '{}'", log_time(start)); if let Some(ended) = record.ended_at_unix_ms { - command += &format!(" --end '{}'", log_time(ended.div_ceil(1000))); + let end = ended.div_ceil(1000) + LOG_CLOCK_MARGIN_S; + command += &format!(" --end '{}'", log_time(end)); } // A tagged run is found by its tag, which its whole tree logs; an older one by the child's pid. // The stored tag is printed into a shell command, so it is used only when it is the one this @@ -629,8 +643,8 @@ mod tests { assert_eq!( denials(&record).as_deref(), Some( - "/usr/bin/log show --start '2026-10-05 07:51:33+0000' \ - --end '2026-10-05 07:51:34+0000' \ + "/usr/bin/log show --start '2026-10-05 07:51:28+0000' \ + --end '2026-10-05 07:51:39+0000' \ --predicate 'sender == \"Sandbox\" AND \ eventMessage CONTAINS \"playpen-run-01M45GQTY3RF111ZQ8WPJ5SKTY\"'" ) @@ -654,8 +668,9 @@ mod tests { } /// A record written before denials were tagged is queried by the child's pid, the best it - /// holds. The window is widened to whole seconds, the precision `log show` takes, and given in - /// UTC so that it means the same instant wherever the command is pasted. + /// holds. The window is widened to whole seconds, the precision `log show` takes, and by + /// [`LOG_CLOCK_MARGIN_S`] either side, and given in UTC so that it means the same instant + /// wherever the command is pasted. #[test] #[cfg(target_os = "macos")] fn the_denials_command_names_the_runs_window_and_pid() { @@ -667,8 +682,8 @@ mod tests { assert_eq!( denials(&record).as_deref(), Some( - "/usr/bin/log show --start '2026-10-05 07:51:33+0000' \ - --end '2026-10-05 07:51:34+0000' \ + "/usr/bin/log show --start '2026-10-05 07:51:28+0000' \ + --end '2026-10-05 07:51:39+0000' \ --predicate 'sender == \"Sandbox\" AND eventMessage CONTAINS \"(82276)\"'" ) ); diff --git a/src/floor.rs b/src/floor.rs index 04743c4..323f28a 100644 --- a/src/floor.rs +++ b/src/floor.rs @@ -68,6 +68,12 @@ const PATHS: &[(&str, Scope)] = &[ ("/etc/ld.so.cache", Scope::Subtree), ("/etc/ld.so.conf", Scope::Subtree), ("/etc/ld.so.conf.d", Scope::Subtree), + // How glibc resolves `localhost`, which `NO_PROXY` names, so a client honouring it can reach + // what it bypasses the proxy for. Denied, the lookup falls through to a nameserver on + // `127.0.0.1:53` that an FHS host does not run, and fails + // ([#86](https://github.com/firefly-engineering/playpen/issues/86)). The rest of the + // resolver's configuration is not granted: nothing in the suite would assert it. + ("/etc/hosts", Scope::Subtree), ("/proc", Scope::Subtree), ("/dev", Scope::Subtree), ]; diff --git a/tests/enforcement/main.rs b/tests/enforcement/main.rs index f5489fe..f7c56e2 100644 --- a/tests/enforcement/main.rs +++ b/tests/enforcement/main.rs @@ -97,6 +97,10 @@ fn main() { "no_upstream_leg_needs_the_request_to_have_been_refused", no_upstream_leg_needs_the_request_to_have_been_refused, ), + ( + "a_command_that_fails_is_an_error_not_empty_output", + a_command_that_fails_is_an_error_not_empty_output, + ), ( "a_row_scoped_to_the_other_platform_is_na_and_never_runs", a_row_scoped_to_the_other_platform_is_na_and_never_runs, @@ -204,6 +208,20 @@ fn a_negative_passes_only_on_a_denial_errno() { } } +/// A command `P-denial-tree` runs that fails has said nothing about the log: read as empty output, +/// a `log show` that cannot run would be polled to its deadline and reported as a denial the log +/// never showed ([#142](https://github.com/firefly-engineering/playpen/issues/142)). +fn a_command_that_fails_is_an_error_not_empty_output() { + // Spelled so the command's own text holds neither the stderr word nor the status the error + // must carry, nor anything of stdout. + let failed = + run::shell("echo p''artial; echo w''hy >&2; exit 7").expect_err("exit 7 is an error"); + assert!(failed.contains("why"), "{failed}"); + assert!(failed.contains("exit status: 7"), "{failed}"); + assert!(!failed.contains("partial"), "{failed}"); + assert_eq!(run::shell("echo said").as_deref(), Ok("said\n")); +} + /// A sandbox denies a lookup as not privileged; an unknown service is what absence reads as, so /// it fails the row as `ENOENT` does. On Linux no lookup is a denial. fn a_mach_negative_passes_only_when_the_lookup_is_not_privileged() { diff --git a/tests/enforcement/run.rs b/tests/enforcement/run.rs index c53e7c0..3c06aff 100644 --- a/tests/enforcement/run.rs +++ b/tests/enforcement/run.rs @@ -1276,11 +1276,19 @@ fn descendant_denied(row: &Row) -> Verdict { #[cfg(target_os = "macos")] const LOG_DEADLINE: std::time::Duration = std::time::Duration::from_secs(30); +/// How far back the outside half looks for the decoy's denial, as `log show --last` takes it. Its +/// own reach, never the window `explain` printed: a window cut too narrow is the command's defect +/// and must fail the row, where a window shared with the outside half reads as a host that never +/// logged the denial ([#142](https://github.com/firefly-engineering/playpen/issues/142)). The +/// decoy's path is unique to this run, so reaching back further admits nothing else. +#[cfg(target_os = "macos")] +const LOG_LOOKBACK: &str = "5m"; + /// A confined shell forks the probe, which is denied a read of a decoy outside every grant. The -/// outside half is the platform's log showing that denial at all, found by the decoy's path; the -/// inside half is the command `explain --run` prints returning it, from a process that is not the -/// child ([#124](https://github.com/firefly-engineering/playpen/issues/124)). An error is a -/// fixture that could not be made, before either half could be observed. +/// outside half is the platform's log showing that denial at all, found by the decoy's path over +/// [`LOG_LOOKBACK`]; the inside half is the command `explain --run` prints returning it, from a +/// process that is not the child ([#124](https://github.com/firefly-engineering/playpen/issues/124)). +/// An error is a fixture that could not be made, before either half could be observed. #[cfg(target_os = "macos")] fn pull_denials() -> Result<(Seen, Seen), String> { let failed = |detail: String| Seen::Failed { @@ -1298,6 +1306,11 @@ fn pull_denials() -> Result<(Seen, Seen), String> { .path() .canonicalize() .map_err(|e| format!("the decoy's path: {e}"))?; + let name = path + .file_name() + .and_then(|name| name.to_str()) + .ok_or_else(|| format!("the decoy's name: {path:?}"))? + .to_owned(); let path = utf8(&path)?; let denied = format!("deny(1) file-read-data {path}"); @@ -1305,11 +1318,14 @@ fn pull_denials() -> Result<(Seen, Seen), String> { let probe = fixture.probe(); // `; true` keeps the shell from replacing itself with the probe, so the probe is forked. let script = format!("'{}' read '{path}'; true", probe.display()); + // The shell's `; true` makes any other exit playpen's own: a launch that never ran the probe + // denied nothing, and the log would be polled for a denial that cannot come. let ran = fixture .run(&[&common::os_bin("sh"), "-c", &script]) .stdin(Stdio::null()) .output() - .map_err(|e| format!("run playpen: {e}"))?; + .map_err(|e| format!("run playpen: {e}")) + .and_then(|ran| succeeded(ran, "playpen running the probe"))?; let run = fixture .run_ids() .pop() @@ -1324,30 +1340,48 @@ fn pull_denials() -> Result<(Seen, Seen), String> { return Err(format!("no denials command or pid: {replay}")); }; - // Outside: the same window, found by the decoy's path rather than by anything the run set. - let (window, _) = command - .split_once(" --predicate ") - .ok_or_else(|| format!("no predicate in {command}"))?; - let by_path = format!( - "{window} --predicate 'sender == \"Sandbox\" AND eventMessage CONTAINS \"{path}\"'" - ); + // Outside: found by the decoy's path over the harness's own reach, nothing the run set. + let sandbox = |needle: &str| { + format!( + "/usr/bin/log show --last {LOG_LOOKBACK} --predicate 'sender == \"Sandbox\" AND \ + eventMessage CONTAINS \"{needle}\"'" + ) + }; + let by_path = sandbox(&path); let deadline = std::time::Instant::now() + LOG_DEADLINE; - while !shell(&by_path)?.contains(&denied) { + loop { + // A `log show` that fails is polled again, not taken as the answer: the deadline decides. + let shown = shell(&by_path); + if shown.as_ref().is_ok_and(|shown| shown.contains(&denied)) { + break; + } if std::time::Instant::now() > deadline { - let never = format!("the log never showed `{denied}` within {LOG_DEADLINE:?}"); + // What the probe itself reported tells a read that was never denied from a denial + // never logged; the decoy's name alone tells one logged under another path or + // operation from none. + let by_name = sandbox(&name); + let never = format!( + "the log never showed `{denied}` within {LOG_DEADLINE:?}; the probe reported \ + {:?}; `{by_path}` last showed {shown:?}; `{by_name}` shows {:?}", + String::from_utf8_lossy(&ran.stdout).trim_end(), + shell(&by_name) + ); return Ok((failed(never), failed(String::new()))); } std::thread::sleep(std::time::Duration::from_secs(1)); } - // Inside: the command as printed, and the line it returns is a descendant's. - let pulled = shell(command)?; - let inside = match pulled.lines().find(|line| line.contains(&denied)) { - Some(line) if !line.contains(&format!("({child})")) => Seen::Succeeded, - Some(line) => failed(format!( - "the denial is the child's own, not a descendant's: {line}" - )), - None => failed(format!("`{command}` does not return `{denied}`")), + // Inside: the command as printed, and the line it returns is a descendant's. A command that + // fails is the command `explain` printed failing, which is the row's to fail, not the fixture's. + let inside = match shell(command) { + Err(why) => failed(why), + Ok(pulled) => match pulled.lines().find(|line| line.contains(&denied)) { + Some(line) if !line.contains(&format!("({child})")) => Seen::Succeeded, + Some(line) => failed(format!( + "the denial is the child's own, not a descendant's: {line}" + )), + None => failed(format!("`{command}` does not return `{denied}`")), + }, }; Ok((Seen::Succeeded, inside)) } @@ -1359,17 +1393,30 @@ fn pull_denials() -> Result<(Seen, Seen), String> { unreachable!("P-denial-tree is n/a on Linux") } -/// `command`'s stdout, run by the shell as a user pasting it would. -#[cfg(target_os = "macos")] -fn shell(command: &str) -> Result { +/// `command`'s stdout, run by the shell as a user pasting it would. A command that fails is an +/// error carrying its stderr, never the empty output it happened to print. +pub fn shell(command: &str) -> Result { let output = Command::new(common::os_bin("sh")) .args(["-c", command]) .stdin(Stdio::null()) .output() .map_err(|e| format!("run the shell: {e}"))?; + let output = succeeded(output, &format!("`{command}`"))?; Ok(String::from_utf8_lossy(&output.stdout).into_owned()) } +/// `output`, if `what` exited successfully; otherwise an error naming its status and stderr. +fn succeeded(output: Output, what: &str) -> Result { + if output.status.success() { + return Ok(output); + } + Err(format!( + "{what} failed, {}: {}", + output.status, + String::from_utf8_lossy(&output.stderr).trim_end() + )) +} + /// A refusal row, under a fixture of its own so its state directory holds this run alone. fn refusal(row: &Row) -> Verdict { match row.action { diff --git a/tests/environment.rs b/tests/environment.rs index a49e50b..5d86b08 100644 --- a/tests/environment.rs +++ b/tests/environment.rs @@ -27,8 +27,22 @@ fn with_env(fx: &Fixture, env: Value) -> std::path::PathBuf { /// The confined child's environment, as `env` prints it. fn environ(fx: &Fixture, policy: &Path, host: &[(&str, &str)]) -> BTreeMap { + environ_without(fx, policy, host, &[]) +} + +/// [`environ`], on a host that lacks every name in `absent`: removed here rather than assumed +/// missing from the test's own environment, which a CI runner's toolchain setup fills in. +fn environ_without( + fx: &Fixture, + policy: &Path, + host: &[(&str, &str)], + absent: &[&str], +) -> BTreeMap { let mut command = fx.run_under(policy, &[&os_bin("env")]); command.envs(host.iter().copied()); + for name in absent { + command.env_remove(name); + } let output = command.output().expect("playpen"); assert!(output.status.success(), "{output:?}"); String::from_utf8(output.stdout) @@ -126,7 +140,7 @@ fn allowed_and_fragment_names_pass_through_and_set_values_win_over_the_floor() { "set": {"TERM": "dumb", "GIT_AUTHOR_NAME": "playpen agent"}, }), ); - let env = environ( + let env = environ_without( &fx, &policy, &[ @@ -134,6 +148,7 @@ fn allowed_and_fragment_names_pass_through_and_set_values_win_over_the_floor() { ("CARGO_HOME", "/c"), ("TERM", "xterm"), ], + &["RUSTUP_HOME"], ); assert_eq!(env["COLORTERM"], "truecolor"); assert_eq!(env["CARGO_HOME"], "/c");