diff --git a/Cargo.lock b/Cargo.lock index 47dda154..642adeb8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3694,9 +3694,9 @@ checksum = "d3edd4d5d42c92f0a659926464d4cce56b562761267ecf0f469d85b7de384175" [[package]] name = "redb" -version = "4.5.0" +version = "4.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b317ef681e18f6091efbfab532eaf924a135c492d9d0299d0fbfae07e92a39b" +checksum = "096b1dd5ec053c9c2a5a26a93aafeadf73ebcb710ea54dc3151f17a8e20535ef" dependencies = [ "libc", ] @@ -4320,7 +4320,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.2", "once_cell", "rustix", "windows-sys 0.61.2", diff --git a/Cargo.toml b/Cargo.toml index a2d0159b..001d9684 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -153,7 +153,7 @@ reqwest = { version = "=0.13.5", default-features = false, features = [ ring = { version = "=0.17.14", default-features = false } # Database and storage -redb = "4.2.0" +redb = "4.6.0" regex = "1.13.1" rs_merkle = "1.5.0" # Exact-pinned: the one TLS implementation in the workspace (TLS 1.2 floor, 1.3 diff --git a/daemoneye-lib/src/audit/db.rs b/daemoneye-lib/src/audit/db.rs new file mode 100644 index 00000000..9dd7e059 --- /dev/null +++ b/daemoneye-lib/src/audit/db.rs @@ -0,0 +1,81 @@ +//! Read-only open of an audit ledger file written by another process. + +use std::io::ErrorKind; +use std::path::Path; + +use redb::{DatabaseError, ReadOnlyDatabase, StorageError}; +use thiserror::Error; + +/// Why an audit ledger cannot be read. +#[derive(Debug, Error)] +#[non_exhaustive] +pub enum LedgerReadError { + /// The ledger file does not exist. + #[error("audit ledger file is missing")] + Missing, + /// The OS refused read access to the ledger file. + #[error("permission denied reading the audit ledger")] + PermissionDenied, + /// A crashed writer left the file unclean and no live writer can repair it. + #[error("audit ledger needs recovery by its writer")] + NeedsRecovery, + /// Another handle holds the file in a mode that excludes this reader. + #[error("audit ledger is locked by another handle")] + Locked, + /// This platform cannot share a ledger between processes. + #[error("audit ledger sharing is unsupported on this platform")] + UnsupportedPlatform, + /// Any other storage failure; the redb error stays available as the source. + #[error("audit ledger storage error: {0}")] + Storage(#[source] Box), +} + +impl From for LedgerReadError { + // redb's DatabaseError and io::ErrorKind are #[non_exhaustive], so `if` chains stand in for + // a match: the catch-all is the explicit last line, not a wildcard arm. + fn from(err: DatabaseError) -> Self { + if matches!(err, DatabaseError::DatabaseAlreadyOpen) { + return Self::Locked; + } + if matches!(err, DatabaseError::RepairAborted) { + return Self::NeedsRecovery; + } + if matches!(err, DatabaseError::Storage(StorageError::Unsupported)) { + return Self::UnsupportedPlatform; + } + if let DatabaseError::Storage(StorageError::Io(ref io)) = err { + if io.kind() == ErrorKind::NotFound { + return Self::Missing; + } + if io.kind() == ErrorKind::PermissionDenied { + return Self::PermissionDenied; + } + } + Self::Storage(Box::new(err)) + } +} + +/// Open the ledger at `path` read-only in redb's single-writer mode, so a writer in another +/// process can keep committing and this handle sees each commit in a new read transaction. +/// +/// `cache_bytes` caps the page cache (redb's default is 1 GiB). +#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))] +pub fn open_ledger_read_only( + path: &Path, + cache_bytes: usize, +) -> Result { + redb::Builder::new() + .set_cache_size(cache_bytes) + .set_concurrency_mode(redb::ConcurrencyMode::SingleWriter) + .open_read_only(path) + .map_err(LedgerReadError::from) +} + +/// Other targets have no file locks redb can share across processes; nothing is opened. +#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))] +pub fn open_ledger_read_only( + _path: &Path, + _cache_bytes: usize, +) -> Result { + Err(LedgerReadError::UnsupportedPlatform) +} diff --git a/daemoneye-lib/src/audit/mod.rs b/daemoneye-lib/src/audit/mod.rs new file mode 100644 index 00000000..ef214ef9 --- /dev/null +++ b/daemoneye-lib/src/audit/mod.rs @@ -0,0 +1,5 @@ +//! Audit ledger read access. The writer lives in another crate; this module only reads. + +mod db; + +pub use db::{LedgerReadError, open_ledger_read_only}; diff --git a/daemoneye-lib/src/lib.rs b/daemoneye-lib/src/lib.rs index d77fd3a0..9f02b99c 100644 --- a/daemoneye-lib/src/lib.rs +++ b/daemoneye-lib/src/lib.rs @@ -14,6 +14,7 @@ //! - Cross-platform IPC communication // Core modules (always available) +pub mod audit; pub mod config; pub mod crypto; /// Fixed, non-configurable bounds for the detection rule-load pipeline. diff --git a/daemoneye-lib/tests/audit_two_process.rs b/daemoneye-lib/tests/audit_two_process.rs new file mode 100644 index 00000000..a9808bc7 --- /dev/null +++ b/daemoneye-lib/tests/audit_two_process.rs @@ -0,0 +1,304 @@ +//! Two real OS processes share one redb ledger: a writer child and a reader in this test. +//! +//! The child is this same test binary re-executed with `--exact child_writer --ignored`, which +//! works under both `cargo test` and nextest. Parent and child coordinate through marker files in +//! a temp directory, never through sleeps alone. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +use daemoneye_lib::audit::{LedgerReadError, open_ledger_read_only}; +use redb::{Builder, ConcurrencyMode, ReadOnlyDatabase, ReadableDatabase, TableDefinition}; +use tempfile::TempDir; + +const ROWS: TableDefinition<'static, u64, u64> = TableDefinition::new("rows"); +const CACHE_BYTES: usize = 4 * 1024 * 1024; +const WAIT_LIMIT: Duration = Duration::from_secs(30); +const POLL: Duration = Duration::from_millis(5); +/// Upper bound on the free-running child's commits, so an orphaned child still ends. +const FREE_MAX_COMMITS: u64 = 200_000; +static SPAWNS: AtomicU64 = AtomicU64::new(0); +const ENV_DB: &str = "AUDIT_CHILD_DB"; +const ENV_COORD: &str = "AUDIT_CHILD_COORD"; +const ENV_MODE: &str = "AUDIT_CHILD_MODE"; +const MODE_STEP: &str = "step"; +const MODE_FREE: &str = "free"; + +fn wait_for(path: &Path, what: &str) { + let start = Instant::now(); + while !path.exists() { + assert!( + start.elapsed() < WAIT_LIMIT, + "timed out after {WAIT_LIMIT:?} waiting for {what} ({})", + path.display() + ); + std::thread::sleep(POLL); + } +} + +fn touch(path: &Path) { + fs::write(path, b"").unwrap(); +} + +/// Child entry point; only runs when the parent re-executes this binary with `--ignored`. +#[test] +#[ignore = "writer child process, spawned by the two-process tests"] +fn child_writer() { + let db_path = PathBuf::from(std::env::var(ENV_DB).expect("AUDIT_CHILD_DB not set")); + let coord = PathBuf::from(std::env::var(ENV_COORD).expect("AUDIT_CHILD_COORD not set")); + let mode = std::env::var(ENV_MODE).expect("AUDIT_CHILD_MODE not set"); + + let db = Builder::new() + .set_cache_size(CACHE_BYTES) + .set_concurrency_mode(ConcurrencyMode::SingleWriter) + .create(&db_path) + .unwrap(); + let commit = |key: u64| { + let txn = db.begin_write().unwrap(); + txn.open_table(ROWS).unwrap().insert(key, key * 10).unwrap(); + txn.commit().unwrap(); + }; + commit(0); + touch(&coord.join("ready")); + + if mode == MODE_FREE { + for key in 1..=FREE_MAX_COMMITS { + commit(key); + } + // Hold the ledger open until the parent kills this process; the marker is never written. + let never = coord.join("never"); + let start = Instant::now(); + while !never.exists() { + assert!( + start.elapsed() < WAIT_LIMIT, + "free-running child was not killed in time" + ); + std::thread::sleep(POLL); + } + return; + } + assert_eq!(mode, MODE_STEP, "unknown child mode"); + for key in 1_u64.. { + let go = coord.join(format!("go-{key}")); + let quit = coord.join("quit"); + let start = Instant::now(); + while !go.exists() && !quit.exists() { + assert!( + start.elapsed() < WAIT_LIMIT, + "child timed out waiting for go-{key}" + ); + std::thread::sleep(POLL); + } + if !go.exists() { + return; + } + commit(key); + touch(&coord.join(format!("done-{key}"))); + } +} + +/// A live writer child; killed and reaped on drop. +struct Writer { + child: Child, + coord: PathBuf, +} + +impl Writer { + fn spawn(dir: &TempDir, mode: &str) -> (Self, PathBuf) { + let db_path = dir.path().join("ledger.redb"); + let seq = SPAWNS.fetch_add(1, Ordering::Relaxed); + let coord = dir.path().join(format!("coord-{seq}")); + fs::create_dir_all(&coord).unwrap(); + let child = Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "child_writer", "--ignored", "--nocapture"]) + .env(ENV_DB, &db_path) + .env(ENV_COORD, &coord) + .env(ENV_MODE, mode) + .stdin(Stdio::null()) + .spawn() + .unwrap(); + let writer = Self { child, coord }; + wait_for(&writer.coord.join("ready"), "writer child ready"); + (writer, db_path) + } + + /// Have the step-mode child commit `key` and wait until it has. + fn commit(&self, key: u64) { + touch(&self.coord.join(format!("go-{key}"))); + wait_for( + &self.coord.join(format!("done-{key}")), + "writer child commit", + ); + } + + /// Ask the child to exit cleanly and wait for it. + fn quit_clean(mut self) { + touch(&self.coord.join("quit")); + let status = self.child.wait().unwrap(); + assert!(status.success(), "writer child failed: {status}"); + } + + fn kill(&mut self) { + self.child.kill().unwrap(); + self.child.wait().unwrap(); + } +} + +impl Drop for Writer { + fn drop(&mut self) { + // Already-exited children make kill fail; nothing to do then. + drop(self.child.kill()); + drop(self.child.wait()); + } +} + +fn row(db: &ReadOnlyDatabase, key: u64) -> Option { + let txn = db.begin_read().unwrap(); + let table = txn.open_table(ROWS).unwrap(); + table.get(key).unwrap().map(|guard| guard.value()) +} + +fn open(path: &Path) -> Result { + open_ledger_read_only(path, CACHE_BYTES) +} + +#[test] +fn reader_sees_commit_made_after_it_opened() { + let dir = TempDir::new().unwrap(); + let (writer, path) = Writer::spawn(&dir, MODE_STEP); + let reader = open(&path).unwrap(); + assert_eq!(row(&reader, 0), Some(0)); + assert_eq!(row(&reader, 1), None); + + writer.commit(1); + assert_eq!(row(&reader, 1), Some(10)); + writer.commit(2); + assert_eq!(row(&reader, 2), Some(20)); +} + +#[test] +fn default_mode_reader_is_locked_out_by_live_writer() { + let dir = TempDir::new().unwrap(); + let (writer, path) = Writer::spawn(&dir, MODE_STEP); + let reader = open(&path).unwrap(); + let err = ReadOnlyDatabase::open(&path) + .err() + .expect("default-mode open must fail"); + assert!( + matches!(err, redb::DatabaseError::DatabaseAlreadyOpen), + "redb said: {err:?}" + ); + assert!(matches!( + LedgerReadError::from(err), + LedgerReadError::Locked + )); + + // The refused open must not disturb the live handles or leave the file needing repair. + writer.commit(1); + assert_eq!(row(&reader, 1), Some(10)); + writer.quit_clean(); + drop(reader); + let fresh = open(&path).unwrap(); + assert_eq!(row(&fresh, 1), Some(10)); +} + +#[test] +fn missing_file_is_missing() { + let dir = TempDir::new().unwrap(); + let err = open(&dir.path().join("absent.redb")).err().unwrap(); + assert!(matches!(err, LedgerReadError::Missing), "got {err:?}"); +} + +#[test] +fn killed_writer_leaves_ledger_needing_recovery() { + let dir = TempDir::new().unwrap(); + let (mut writer, path) = Writer::spawn(&dir, MODE_FREE); + writer.kill(); + let err = open(&path) + .err() + .expect("expected a failure, got an open reader"); + assert!(matches!(err, LedgerReadError::NeedsRecovery), "got {err:?}"); +} + +#[cfg(unix)] +mod unix_only { + use super::*; + use std::os::unix::fs::PermissionsExt; + + fn set_mode(path: &Path, mode: u32) { + fs::set_permissions(path, fs::Permissions::from_mode(mode)).unwrap(); + } + + /// Restores writable modes on drop so the temp dir can be removed on every path. + struct RestoreModes { + dir: PathBuf, + file: PathBuf, + } + + impl Drop for RestoreModes { + fn drop(&mut self) { + drop(fs::set_permissions( + &self.dir, + fs::Permissions::from_mode(0o750), + )); + drop(fs::set_permissions( + &self.file, + fs::Permissions::from_mode(0o640), + )); + } + } + + #[test] + fn unreadable_file_is_permission_denied() { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("locked.redb"); + fs::write(&path, b"x").unwrap(); + set_mode(&path, 0o000); + if fs::File::open(&path).is_ok() { + eprintln!("skipping: permission bits do not apply (running as root)"); + return; + } + let err = open(&path).err().unwrap(); + assert!( + matches!(err, LedgerReadError::PermissionDenied), + "got {err:?}" + ); + } + + #[test] + fn read_only_file_and_dir_open_with_no_live_writer() { + let dir = TempDir::new().unwrap(); + let (writer, path) = Writer::spawn(&dir, MODE_STEP); + writer.commit(1); + writer.quit_clean(); + + let _restore = RestoreModes { + dir: dir.path().to_path_buf(), + file: path.clone(), + }; + set_mode(&path, 0o440); + set_mode(dir.path(), 0o550); + let reader = open(&path).unwrap(); + assert_eq!(row(&reader, 1), Some(10)); + } + + #[test] + fn read_only_file_and_dir_open_with_live_writer() { + let dir = TempDir::new().unwrap(); + let (writer, path) = Writer::spawn(&dir, MODE_STEP); + let _restore = RestoreModes { + dir: dir.path().to_path_buf(), + file: path.clone(), + }; + set_mode(&path, 0o440); + set_mode(dir.path(), 0o550); + let reader = open(&path).unwrap(); + // The writer keeps committing through the descriptor it already holds. + writer.commit(1); + assert_eq!(row(&reader, 1), Some(10)); + } +}