diff --git a/Cargo.lock b/Cargo.lock index 420fdbe795..d59eb15b6c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4750,9 +4750,9 @@ checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" name = "openshell-binary-identity" version = "0.0.0" dependencies = [ + "libc", "openshell-crypto", "openshell-isolation-interface", - "rustix 1.1.6", ] [[package]] diff --git a/crates/openshell-binary-identity/Cargo.toml b/crates/openshell-binary-identity/Cargo.toml index de2f336107..2cd53cf919 100644 --- a/crates/openshell-binary-identity/Cargo.toml +++ b/crates/openshell-binary-identity/Cargo.toml @@ -15,7 +15,7 @@ openshell-isolation-interface = { path = "../openshell-isolation-interface" } openshell-crypto = { workspace = true } [target.'cfg(target_os = "linux")'.dependencies] -rustix = { workspace = true, features = ["param"] } +libc = "0.2" [lints] workspace = true diff --git a/crates/openshell-binary-identity/src/lib.rs b/crates/openshell-binary-identity/src/lib.rs index 7096d3641d..a82dda55c9 100644 --- a/crates/openshell-binary-identity/src/lib.rs +++ b/crates/openshell-binary-identity/src/lib.rs @@ -199,11 +199,38 @@ fn start_time_ms(ticks: u64) -> Option { .parse() .ok() }))?; - let ticks_per_sec = rustix::param::clock_ticks_per_second(); + let ticks_per_sec = clock_ticks_per_second(); let since_boot_ms = ticks.checked_mul(1_000)?.checked_div(ticks_per_sec)?; i64::try_from(boot_secs.checked_mul(1_000)?.checked_add(since_boot_ms)?).ok() } +/// The `/proc` clock tick rate defined by the Linux ABI. +/// +/// Every Linux architecture reports `/proc` stat fields in `USER_HZ` units, +/// fixed at 100 regardless of the kernel's internal `CONFIG_HZ`. +#[cfg(target_os = "linux")] +const PROCFS_CLOCK_TICKS_PER_SECOND: u64 = 100; + +/// Clock ticks per second for `/proc` stat fields, resolved without auxv. +/// +/// `rustix::param::clock_ticks_per_second` initialises the auxv and panics +/// when the kernel lacks `PR_GET_AUXV` (added in Linux 6.4) and +/// `/proc/self/auxv` cannot be opened, which is the case for the sandbox +/// network broker on RHEL 9 nodes (#6069). `sysconf(_SC_CLK_TCK)` is the +/// conversion `/proc//stat` documents its fields against and cannot +/// fail on Linux, but degrade to the ABI constant anyway rather than risk a +/// panic on an identity path. +#[cfg(target_os = "linux")] +#[allow(unsafe_code)] +fn clock_ticks_per_second() -> u64 { + // SAFETY: `sysconf` takes a read-only selector and returns a scalar. + let ticks = unsafe { libc::sysconf(libc::_SC_CLK_TCK) }; + match u64::try_from(ticks) { + Ok(ticks) if ticks > 0 => ticks, + _ => PROCFS_CLOCK_TICKS_PER_SECOND, + } +} + #[cfg(target_os = "linux")] fn resolve_open_executable( snapshot: &ProcessSnapshot, @@ -1000,4 +1027,346 @@ mod tests { ]; assert_eq!(paths, expected); } + + #[test] + fn clock_ticks_per_second_matches_linux_abi() { + // `USER_HZ` is 100 on every Linux ABI, which is also the fallback + // value, so sysconf and the constant must agree. + assert_eq!(clock_ticks_per_second(), PROCFS_CLOCK_TICKS_PER_SECOND); + assert_eq!(clock_ticks_per_second(), 100); + } + + #[test] + fn start_time_ms_survives_unavailable_auxv() { + // Regression test for #6069: with `PR_GET_AUXV` unavailable and + // `/proc/self/auxv` unreadable, the old rustix-based tick lookup + // panicked on the broker thread and every mediated connect() was + // answered EIO. The child must resolve a start time instead. + let mut child = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--ignored", + "--exact", + "tests::auxv_denied_child", + "--nocapture", + ]) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .expect("spawn auxv-denied child"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while child.try_wait().expect("poll auxv-denied child").is_none() { + if std::time::Instant::now() >= deadline { + let _ = child.kill(); + let result = child.wait_with_output().expect("reap child after deadline"); + panic!( + "auxv-denied child exceeded the 10-second deadline\n{}\n{}", + String::from_utf8_lossy(&result.stdout), + String::from_utf8_lossy(&result.stderr) + ); + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } + let result = child.wait_with_output().expect("reap auxv-denied child"); + let stdout = String::from_utf8_lossy(&result.stdout); + let stderr = String::from_utf8_lossy(&result.stderr); + assert!( + result.status.success(), + "auxv-denied child failed\n{stdout}\n{stderr}" + ); + // The child reports whether it exercised the denial or skipped on an + // unavailable control, so a vacuous pass cannot hide as a green test. + // The marker is matched anywhere in a line because single-threaded + // libtest output prefixes it with the test name. + let sentinel = stdout + .lines() + .find(|line| line.contains("auxv-fixture:")) + .unwrap_or_default(); + assert!( + !sentinel.is_empty(), + "auxv-denied child printed no fixture outcome\n{stdout}\n{stderr}" + ); + eprintln!("{sentinel}"); + } + + /// Child half of [`start_time_ms_survives_unavailable_auxv`]. + /// + /// Installs a Landlock ruleset that only leaves `/proc/stat` readable and + /// a seccomp filter that answers `prctl(PR_GET_AUXV)` with `ENOSYS`, + /// reproducing the kernel < 6.4 sandbox conditions from #6069, then + /// resolves a start time. Landlock is the only way to make + /// `/proc/self/auxv` unreadable while keeping `/proc/stat` readable, and + /// seccomp is the only way to hide `PR_GET_AUXV` from a kernel >= 6.4, + /// so the test is skipped when a control is unavailable (RHEL 9 kernels, + /// for instance, ship without the Landlock LSM) and fails when a control + /// is rejected or does not engage. The seccomp half is redundant on + /// kernels < 6.4, which fail `PR_GET_AUXV` natively, so the test still + /// runs there when only the filter is unavailable. + #[test] + #[ignore = "subprocess fixture for the auxv regression test"] + fn auxv_denied_child() { + if !auxv_denied::landlock_restrict_proc_reads_to_proc_stat().expect("enforce Landlock") { + println!("auxv-fixture: skipped: Landlock unavailable"); + return; + } + // The denial must actually be established, or the fixture silently + // degrades the regression test to a vacuous pass. + assert!( + std::fs::read("/proc/self/auxv").is_err(), + "/proc/self/auxv stayed readable; the Landlock fixture did not engage" + ); + if !auxv_denied::install_prctl_get_auxv_enosys().expect("install prctl ENOSYS filter") + && auxv_denied::pr_get_auxv_is_served_natively() + { + println!("auxv-fixture: skipped: cannot hide PR_GET_AUXV on this kernel"); + return; + } + println!("auxv-fixture: exercised"); + let start = start_time_ms(100).expect("resolve start time without auxv"); + assert!(start > 0); + } + + mod auxv_denied { + //! Raw syscall fixtures for `auxv_denied_child`, local to the test + //! binary so this crate keeps its small dependency surface. + + #![allow(unsafe_code)] + + use std::io; + use std::mem::size_of; + + /// `PR_GET_AUXV`, `include/uapi/linux/prctl.h`, added in Linux 6.4 + /// (the option word spells `AUXV` in ASCII). Older kernels (RHEL 9 + /// runs 5.14) answer it with `EINVAL`. + pub const PR_GET_AUXV: libc::c_int = 0x4155_5856; + + const SECCOMP_SET_MODE_FILTER: libc::c_uint = 1; + const SECCOMP_RET_ERRNO: u32 = 0x0005_0000; + const SECCOMP_RET_ALLOW: u32 = 0x7fff_0000; + const BPF_LD_W_ABS: u16 = 0x20; + const BPF_JMP_JEQ_K: u16 = 0x15; + const BPF_RET_K: u16 = 0x06; + const SECCOMP_DATA_NR_OFFSET: u32 = 0; + const SECCOMP_DATA_ARGS_OFFSET: u32 = 16; + + const LANDLOCK_RULE_PATH_BENEATH: libc::c_int = 1; + const LANDLOCK_ACCESS_FS_READ_FILE: u64 = 1 << 2; + + #[repr(C)] + struct LandlockRulesetAttr { + handled_access_fs: u64, + } + + #[repr(C)] + struct LandlockPathBeneathAttr { + allowed_access: u64, + parent_fd: libc::c_int, + } + + const fn stmt(code: u16, value: u32) -> libc::sock_filter { + libc::sock_filter { + code, + jt: 0, + jf: 0, + k: value, + } + } + + const fn jump(code: u16, value: u32, jt: u8, jf: u8) -> libc::sock_filter { + libc::sock_filter { + code, + jt, + jf, + k: value, + } + } + + const fn errno(value: i32) -> libc::sock_filter { + stmt(BPF_RET_K, SECCOMP_RET_ERRNO | value.cast_unsigned()) + } + + /// Answer `prctl(PR_GET_AUXV)` with `ENOSYS`, like a pre-6.4 kernel, + /// and allow every other `prctl` use. + /// + /// Returns `Ok(false)`, like the Landlock fixture, when seccomp + /// filtering itself is unavailable (`ENOSYS`), blocked by an outer + /// profile (`EPERM`), or no-new-privileges cannot be set, so the + /// caller can skip instead of fail. Any other error means the filter + /// was rejected and is propagated. + pub fn install_prctl_get_auxv_enosys() -> io::Result { + if set_no_new_privileges().is_err() { + eprintln!("skipping: cannot set no_new_privs for the seccomp filter"); + return Ok(false); + } + let prctl = u32::try_from(libc::SYS_prctl) + .map_err(|_| io::Error::other("negative prctl syscall number"))?; + // The option value fits in 32 bits, so matching either half of + // the first argument covers both byte orders: the low word sits + // at offset 16 on little-endian targets and at offset 20 on + // big-endian ones. + let instructions = [ + stmt(BPF_LD_W_ABS, SECCOMP_DATA_NR_OFFSET), + jump(BPF_JMP_JEQ_K, prctl, 0, 5), + stmt(BPF_LD_W_ABS, SECCOMP_DATA_ARGS_OFFSET), + jump(BPF_JMP_JEQ_K, PR_GET_AUXV.cast_unsigned(), 2, 0), + stmt(BPF_LD_W_ABS, SECCOMP_DATA_ARGS_OFFSET + 4), + jump(BPF_JMP_JEQ_K, PR_GET_AUXV.cast_unsigned(), 0, 1), + errno(libc::ENOSYS), + stmt(BPF_RET_K, SECCOMP_RET_ALLOW), + ]; + let mut program = libc::sock_fprog { + len: u16::try_from(instructions.len()).expect("seccomp filter fits"), + filter: instructions.as_ptr().cast_mut(), + }; + // SAFETY: `program` references the instruction array for the + // complete syscall; no TSYNC flag is used. + let result = unsafe { + libc::syscall( + libc::SYS_seccomp, + SECCOMP_SET_MODE_FILTER, + 0, + std::ptr::addr_of_mut!(program), + ) + }; + if result < 0 { + let error = io::Error::last_os_error(); + match error.raw_os_error() { + Some(libc::ENOSYS | libc::EPERM) => { + eprintln!("skipping: seccomp filtering is unavailable ({error})"); + Ok(false) + } + _ => Err(error), + } + } else { + Ok(true) + } + } + + /// Whether the running kernel serves `PR_GET_AUXV` natively, which + /// only Linux >= 6.4 does. On older kernels `prctl(PR_GET_AUXV)` + /// fails on its own, so the seccomp half of the fixture is + /// redundant there. + pub fn pr_get_auxv_is_served_natively() -> bool { + let mut buffer = [0_u8; 1024]; + // SAFETY: `prctl` writes at most `buffer.len()` bytes into the + // stack buffer passed as the second argument. + let result = unsafe { + libc::prctl( + PR_GET_AUXV, + buffer.as_mut_ptr().cast::(), + buffer.len(), + 0, + 0, + ) + }; + result >= 0 + } + + fn set_no_new_privileges() -> io::Result<()> { + // SAFETY: `PR_SET_NO_NEW_PRIVS` with a nonzero third argument + // only affects privilege escalation on later exec. + let result = unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) }; + if result < 0 { + Err(io::Error::last_os_error()) + } else { + Ok(()) + } + } + + /// Restrict file reads to `/proc/stat` (the `btime` source + /// `start_time_ms` needs). + /// + /// Returns `Ok(false)` when Landlock is unavailable, so the caller + /// can skip instead of fail: `ENOSYS` (kernel without Landlock), + /// `EOPNOTSUPP` (built but not enabled), or `EPERM` (blocked by an + /// outer seccomp profile). Any other error, including a rejected + /// rule, is an enforcement failure and is propagated so the caller + /// fails rather than passing vacuously. + pub fn landlock_restrict_proc_reads_to_proc_stat() -> io::Result { + if set_no_new_privileges().is_err() { + eprintln!("skipping: cannot set no_new_privs for Landlock"); + return Ok(false); + } + let attr = LandlockRulesetAttr { + handled_access_fs: LANDLOCK_ACCESS_FS_READ_FILE, + }; + // SAFETY: `attr` is referenced for the syscall only; flags are + // zero, so a ruleset fd is created instead of probing the ABI. + let ruleset_fd = unsafe { + libc::syscall( + libc::SYS_landlock_create_ruleset, + std::ptr::addr_of!(attr), + size_of::(), + 0, + ) + }; + if ruleset_fd < 0 { + let error = io::Error::last_os_error(); + return match error.raw_os_error() { + Some(libc::ENOSYS | libc::EOPNOTSUPP | libc::EPERM) => { + eprintln!("skipping: Landlock is unavailable ({error})"); + Ok(false) + } + _ => Err(error), + }; + } + let ruleset_fd = libc::c_int::try_from(ruleset_fd).expect("ruleset fd fits in c_int"); + // SAFETY: the fd stays open for the lifetime of the child. + let proc_stat = + unsafe { libc::open(c"/proc/stat".as_ptr(), libc::O_PATH | libc::O_CLOEXEC) }; + if proc_stat < 0 { + let error = io::Error::last_os_error(); + // SAFETY: `ruleset_fd` is an open descriptor or -1 here; + // closing a ruleset fd only detaches the ruleset. + unsafe { libc::close(ruleset_fd) }; + // An outer sandbox that already denies `/proc/stat` cannot + // host this fixture (and `start_time_ms` needs the file + // anyway), so treat that like any other unavailability. + if let Some(libc::EACCES | libc::EPERM | libc::ENOSYS) = error.raw_os_error() { + eprintln!("skipping: /proc/stat is unreadable ({error})"); + return Ok(false); + } + eprintln!("cannot open /proc/stat for the Landlock rule: {error}"); + return Err(error); + } + let rule = LandlockPathBeneathAttr { + allowed_access: LANDLOCK_ACCESS_FS_READ_FILE, + parent_fd: proc_stat, + }; + // SAFETY: `rule` is referenced for the syscall only. The + // trailing flags argument must be zero and is passed explicitly: + // a variadic syscall leaves unpassed argument registers + // uninitialized, so the kernel would read garbage flags and + // reject the rule with EINVAL. + let added = unsafe { + libc::syscall( + libc::SYS_landlock_add_rule, + libc::c_long::from(ruleset_fd), + libc::c_long::from(LANDLOCK_RULE_PATH_BENEATH), + std::ptr::addr_of!(rule), + 0, + ) + }; + // Snapshot the error before any other libc call can overwrite it. + let added_error = (added < 0).then(io::Error::last_os_error); + // SAFETY: closing a ruleset fd only detaches the already + // enforced ruleset. + let restricted = unsafe { + libc::syscall( + libc::SYS_landlock_restrict_self, + libc::c_long::from(ruleset_fd), + 0, + ) + }; + let restricted_error = (restricted < 0).then(io::Error::last_os_error); + // SAFETY: `ruleset_fd` is a valid open descriptor; closing it + // after enforcement only detaches the ruleset. + unsafe { libc::close(ruleset_fd) }; + if let Some(error) = added_error.or(restricted_error) { + eprintln!("cannot enforce the Landlock ruleset: {error}"); + return Err(error); + } + Ok(true) + } + } }