diff --git a/.github/SECURITY.md b/.github/SECURITY.md index 98815a81..33db5e06 100644 --- a/.github/SECURITY.md +++ b/.github/SECURITY.md @@ -37,7 +37,7 @@ DaemonEye implements a **three-component security architecture** with strict pri - **SQL Injection Prevention**: AST validation with sqlparser, prepared statements only - **Credential Management**: Environment variables or OS keychain, never hardcode secrets - **Attack Surface Minimization**: No network listening, outbound-only connections -- **Audit Trail**: Certificate Transparency-style audit ledger with BLAKE3 and Merkle trees +- **Audit Trail**: RFC 6962 Merkle audit ledger over BLAKE3 with Ed25519-signed checkpoints (local evidence of alteration) ### Advanced Security Features (Enterprise Tier) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index f3a965ce..96ab2a0c 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -534,8 +534,8 @@ fn validate_query_complexity(statement: &Statement) -> Result<(), ValidationErro ## Key Dependencies & Patterns - **Database**: redb pure Rust embedded database for event storage -- **Audit Ledger**: Certificate Transparency-style Merkle tree with BLAKE3 hashing for tamper-evident logging -- **Cryptographic Integrity**: `rs-merkle` for efficient inclusion proofs, Ed25519 for optional signatures +- **Audit Ledger**: Certificate Transparency-style Merkle tree with BLAKE3 hashing for local tamper evidence (not proof of integrity) +- **Cryptographic Integrity**: hand-rolled RFC 6962 Merkle tree (`rs_merkle` is a test oracle only), Ed25519-signed checkpoints - **CLI**: clap v4 with derive macros, support `--json` output + `NO_COLOR` - **Async**: Tokio runtime with structured logging via `tracing` - **Process enumeration**: `sysinfo` crate with platform-specific optimizations diff --git a/.kiro/specs/daemoneye-core-monitoring/design.md b/.kiro/specs/daemoneye-core-monitoring/design.md index 25d83c53..29cb3c64 100644 --- a/.kiro/specs/daemoneye-core-monitoring/design.md +++ b/.kiro/specs/daemoneye-core-monitoring/design.md @@ -149,7 +149,7 @@ sequenceDiagram 04. **EventBus Communication**: Tasks published to control topics, events published to event topics 05. **Topic-Based Routing**: DaemonEye EventBus routes messages based on topic patterns and subscriptions 06. **Overcollection Strategy**: procmond may overcollect data due to granularity limitations -07. **Audit Logging**: procmond writes to tamper-evident audit ledger (write-only; redb + rs-merkle Merkle tree) +07. **Audit Logging**: procmond writes to tamper-evident audit ledger (write-only; redb + RFC 6962 Merkle tree) 08. **Event Aggregation**: daemoneye-agent subscribes to event topics for multi-collector coordination 09. **Detection Phase**: daemoneye-agent executes original SQL rules against collected/stored data 10. **Alert Generation**: Structured alerts with deduplication and context @@ -1228,136 +1228,27 @@ The system uses redb (pure Rust embedded database) for optimal performance and s - `alerts`: Generated alerts with execution context - `alert_deliveries`: Delivery tracking with retry information -**Audit Ledger** (redb + rs-merkle, CT-style Merkle log): +**Audit Ledger** (redb, RFC 6962 Merkle log over BLAKE3; see [ADR-0016](../../../docs/adr/0016-the-ledger-commits-what-procmond-records.md)): -The audit ledger is an append-only Merkle tree backed by `redb` rather than a relational schema. It provides tamper-evident logging with inclusion proofs and periodic signed checkpoints. +The ledger is an append-only, hash-chained Merkle log in its own redb file, written only by procmond. It is local evidence of alteration, not proof of integrity. -Key Concepts: +What it commits: -- Append-only sequence of canonical JSON leaf entries. -- BLAKE3 used for leaf hashing (uniform algorithm per lineage). -- Incremental Merkle root updated each append (`O(log n)` path). -- Inclusion proofs (sibling hash list) generated on demand; optionally cached. -- Periodic checkpoints `(tree_size, root_hash[, signature])` persisted for rapid recovery & external audit. -- Optional Ed25519 signatures over `(tree_size || root_hash)` for auditor trust anchoring. -- Air‑gap export: Signed checkpoints + sampled proofs can be exported for offline verification. +- One batch entry per collection cycle: first and last WAL sequence, event count and a Merkle root over each sanitised event's canonical hash (the hashed projection includes the executable hash, its algorithm and the collection time). +- procmond's own actions: start, privileges detected, config update received, executable-hash drift, clean stop, signing key created or failed. +- A gap entry when commits were missed. -redb Logical Layout (conceptual): +Structure: -- `AUDIT_LEDGER (u64 -> AuditEntry)` -- `AUDIT_CHECKPOINTS (u64 tree_size -> Checkpoint)` +- Tables `AUDIT_LEDGER`, `AUDIT_CHECKPOINTS`, `AUDIT_FRONTIER` and a metadata table. Each entry carries sequence, millisecond timestamp, kind, payload hash, previous entry hash and its own hash (BLAKE3). +- The tree is RFC 6962 (leaf `H(0x00 || data)`, node `H(0x01 || l || r)`), with a persisted frontier so the writer holds `O(log n)` hashes. Each append is one redb write transaction. +- A checkpoint every 64 entries and at clean stop records tree size, root, time, signing state and public key; it is Ed25519-signed by default. The key sits beside the ledger as `.key` (`0400`), is created only for an empty ledger and is never regenerated. +- Inclusion proof: `(root, index, total, leaf_hash, siblings[])`, verifiable offline. A proof binds a leaf to a root; a changed stated total is not always detected. +- Start-up recovery checks the persisted frontier against the entries after the latest checkpoint. On disagreement the writer refuses to append and health reports degraded. -Simplified Data Structures (illustrative): +Read side: `verify`, `prove` and `export_checkpoint` in `daemoneye-lib::audit::verify` over a read-only handle. Verification names the first failing sequence and check, lists every signing key id, and flags key changes and signed-to-unsigned transitions. Success means internally consistent only: someone with root who holds the signing key can rebuild the whole ledger. Same key id, so only a checkpoint kept off the host (`export_checkpoint`) detects it, and only for the history it covers; a trusted key id detects a different key or signing off, and a ledger with no checkpoint. Entries after the last checkpoint are not signed. Anchoring checkpoints off the host belongs to commercial tiers, which extend this foundation, are sold separately and are not in this repo. -```rust,ignore -#[derive(Serialize, Deserialize, Clone)] -struct AuditEntry { - id: u64, // monotonic - ts_ms: i64, // epoch millis - actor: String, - action: String, - payload: serde_json::Value, - leaf_hash: [u8; 32], // BLAKE3(canonical_leaf) - tree_size: u64, // size AFTER insertion - root_hash: [u8; 32], // Merkle root at tree_size - inclusion_proof: Option>, // optional cached siblings - checkpoint_sig: Option>, // optional signature at this state -} - -#[derive(Serialize, Deserialize, Clone)] -struct Checkpoint { - tree_size: u64, - root_hash: [u8; 32], - created_at_ms: i64, - signature: Option>, // Ed25519(tree_size || root_hash) -} -``` - -rs-merkle Integration (minimal sketch): - -```rust,ignore -use blake3; -use rs_merkle::{Hasher, MerkleProof, MerkleTree}; - -#[derive(Clone, Debug)] -struct Blake3Hasher; -impl Hasher for Blake3Hasher { - type Hash = [u8; 32]; - fn hash(data: &[u8]) -> Self::Hash { - *blake3::hash(data).as_bytes() - } -} - -fn canonical_leaf(actor: &str, action: &str, payload: &serde_json::Value, ts_ms: i64) -> Vec { - // Fixed key order for stability; if stronger guarantees needed adopt RFC 8785 canonical JSON. - serde_json::to_vec(&serde_json::json!({"a": actor, "ac": action, "p": payload, "ts": ts_ms})) - .unwrap() -} - -fn append( - tree: &mut MerkleTree, - leaves: &mut Vec<[u8; 32]>, - actor: &str, - action: &str, - payload: &serde_json::Value, - ts_ms: i64, -) -> (u64, [u8; 32], Vec<[u8; 32]>) { - let leaf_bytes = canonical_leaf(actor, action, payload, ts_ms); - let leaf_hash = Blake3Hasher::hash(&leaf_bytes); - tree.insert(leaf_hash).commit(); - leaves.push(leaf_hash); - let size = leaves.len() as u64; - let root = tree.root().expect("root present after append"); - let proof = tree.proof(&[(size - 1) as usize]); - (size, root, proof.proof_hashes().to_vec()) -} - -fn verify( - root: [u8; 32], - index: u64, - total: u64, - leaf_hash: [u8; 32], - siblings: &[[u8; 32]], -) -> bool { - let proof = MerkleProof::::new(siblings.to_vec()); - proof.verify(root, &[index as usize], &[leaf_hash], total as usize) -} -``` - -Operational Flow: - -- Append Path: canonicalize → hash → insert → commit → record root → (optional) store proof. -- Checkpoint: every N appends or T seconds persist `(tree_size, root_hash[, signature])`. -- Recovery: load max checkpoint, replay subsequent entries, validate root; enter safe mode if mismatch. -- Proof Serving: regenerate on demand if not cached (logarithmic complexity). -- Pruning: logical tombstone retains leaf hash; full physical pruning requires rebuild under maintenance. - -Security Invariants: - -1. Canonical serialization stability; change requires full tree rebuild + lineage reset. -2. Single monotonic root sequence; no forks outside controlled offline maintenance. -3. Uniform hash algorithm (BLAKE3) per lineage. -4. Signed checkpoints (if enabled) anchor external trust. -5. Inclusion verification inputs: `(root, leaf_index, total_leaves_at_checkpoint, leaf_hash, siblings[])`. - -Key Management: - -- The checkpoint-signing Ed25519 keypair is generated at first run and stored `0400`, owned by the procmond UID, under the data directory. The public key is exported for verifiers; key rotation starts a new lineage version (old lineage remains verifiable with the old public key). In-memory handling uses the `secrecy`/`zeroize` crates so the private key is never logged and is zeroed on drop. - -OS-Level Isolation: - -- The ledger file is owned by procmond's UID with `0640` permissions (`daemoneye` group). daemoneye-agent and daemoneye-cli open read-only descriptors; only procmond holds a writable handle, enforcing the write-only/read-only split at the filesystem level in addition to the application layer. - -Recovery and Memory Bounds: - -- Checkpoints persist a Merkle frontier (MMR-style peak hashes) alongside `(tree_size, root_hash)`. Recovery loads the latest checkpoint's frontier and replays only post-checkpoint entries instead of rehashing every leaf, and steady-state append memory is `O(log n)` peak hashes rather than retaining all leaf hashes in memory. - -Future Enhancements: - -- Domain separation tags for leaf vs internal nodes (e.g., `BLAKE3("SD_LEAF" || data)`). -- Multi-proof batching for range forensic queries. -- RFC 8785 canonical JSON implementation for cross-implementation determinism. -- Streaming proof generation API for bulk verification. +Concurrency: redb single-writer mode (one writer process, read-only readers) on Linux, macOS and Windows. On platforms without byte-range locks (for example FreeBSD) procmond writes in redb's default mode and the read-only handle reports the platform as unsupported. Only broker-connected (actor) mode keeps a ledger. ## Error Handling @@ -1634,15 +1525,15 @@ impl PrivilegeManager { ### Cryptographic Integrity -Refer to the earlier **Audit Ledger (redb + rs-merkle, CT-style Merkle log)** section for full data structures and code sketch. This subsection summarizes cryptographic guarantees without duplicating implementation details: +Refer to the earlier **Audit Ledger** section and [ADR-0016](../../../docs/adr/0016-the-ledger-commits-what-procmond-records.md) for full data structures and code sketch. This subsection summarizes cryptographic guarantees without duplicating implementation details: Core Guarantees: - Append-only sequencing with monotonic `tree_size` mapped to Merkle roots. -- Canonical JSON leaf serialization → BLAKE3 leaf hash → rs-merkle insertion. +- Canonical entry encoding → BLAKE3 entry hash → RFC 6962 tree leaf. - Inclusion proofs (logarithmic sibling path) verifiable offline using `(root, index, total, leaf_hash, siblings[])`. - Periodic checkpoints (root + tree_size [+ signature]) enable rapid recovery & external attestation. -- Optional Ed25519 signatures provide trust anchor continuity across exports / air‑gapped validation. +- Ed25519 signatures (on by default) provide trust anchor continuity across exports / air‑gapped validation. Security Invariants: @@ -2148,6 +2039,6 @@ This comprehensive testing strategy ensures DaemonEye works reliably across ente ### From 2026-06-09 design review - **Cascade chaining policy:** the orchestration rule says triggerable collectors never trigger other triggerable collectors, yet the canonical workflow chains binmond → memmond → netanalymond. Decide: permit chains with an agent-enforced max cascade depth (tracked via parent_correlation_id chain length), or forbid chains and rewrite the example. -- **Audit-entry granularity:** one entry per scan cycle vs per process record changes Merkle tree growth by orders of magnitude and determines whether memory/recovery budgets hold. Needs an explicit decision. +- **Audit-entry granularity:** decided in ADR-0016: one batch entry per collection cycle, with a Merkle root over the cycle's event hashes, plus one entry per procmond action. Per-event leaves are not stored. - **SQL-to-task translation limits:** **Resolved (2026-06-09):** rules that cannot be lowered into collection tasks plus derived DataFusion SQL are rejected at load time with a clear, actionable error — there is no silent fallback to scheduled full enumeration. Overcollection is bounded by pushdown conformance vectors (R18 AC4) and per-rule budgets. The pipeline and construct-to-task mapping are specified in the [Detection Engine (SQL-to-IPC, ADR-0006)](#detection-engine-sql-to-ipc-adr-0006) section. - **procmond privilege lifecycle:** **Resolved (2026-06-09):** procmond is the only elevated component and retains only the minimum platform-specific capability set required for steady-state collection (e.g., CAP_DAC_READ_SEARCH / CAP_SYS_PTRACE on Linux when enhanced access is configured; SeDebugPrivilege on Windows), dropping everything else after init; the retained set is expected to evolve as collection features are added and is logged at startup. daemoneye-agent and daemoneye-cli run as dedicated non-root users (see requirements.md R6 AC3/AC4). Remaining follow-up: author the per-platform privilege lifecycle table here against this model. diff --git a/.kiro/specs/daemoneye-core-monitoring/requirements.md b/.kiro/specs/daemoneye-core-monitoring/requirements.md index c6af02c8..1684878d 100644 --- a/.kiro/specs/daemoneye-core-monitoring/requirements.md +++ b/.kiro/specs/daemoneye-core-monitoring/requirements.md @@ -103,8 +103,8 @@ Decided 2026-06-09 to sequence solo-maintainer effort toward OSS v1.0.0: #### Acceptance Criteria -1. WHEN security events occur THEN the system SHALL record them in an append-only audit ledger with monotonic sequence numbers -2. WHEN creating audit entries THEN the system SHALL include timestamp, actor, action, payload hash, previous hash, and entry hash +1. WHEN a collection cycle ends or procmond takes a security-relevant action THEN the system SHALL record each cycle's recorded events (one batch entry holding the WAL sequence range, count and a Merkle root over the events' hashes) and each action in an append-only audit ledger with monotonic sequence numbers +2. WHEN creating audit entries THEN the system SHALL include timestamp, kind, payload hash, previous hash, and entry hash 3. WHEN computing hashes THEN the system SHALL use BLAKE3 for fast, cryptographically secure hash computation 4. WHEN verifying integrity THEN the system SHALL provide chain verification function to detect tampering 5. WHEN audit events are recorded THEN the system SHALL maintain proper ordering and millisecond-precision timestamps diff --git a/.kiro/steering/structure.md b/.kiro/steering/structure.md index 328870cf..90125214 100644 --- a/.kiro/steering/structure.md +++ b/.kiro/steering/structure.md @@ -125,7 +125,7 @@ Hierarchical configuration with clear precedence: - **alerts**: Generated alerts with execution context - **system_info**: System-level information records - **alert_deliveries**: Delivery tracking with retry information [Planned — not yet in storage.rs] -- **audit_ledger**: Tamper-evident cryptographic chain [Planned — not yet in storage.rs] +- **audit_ledger**: Tamper-evident Merkle chain in its own redb file, written by procmond (`procmond/src/audit_writer/`, `daemoneye-lib/src/audit/`) [Implemented] ### Access Patterns diff --git a/AGENTS.md b/AGENTS.md index f431119b..9c24a479 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,13 +34,13 @@ Every architectural decision in this repo — privilege separation, protobuf IPC ### Principles -| Principle | Description | -| ------------------------ | ----------------------------------------------------------------------------- | -| **Customer sovereignty** | All telemetry owned by the customer; no automatic egress to external services | -| **Silent observation** | Default mode is passive; rules and traces generate no host-visible artifacts | -| **Auditable forensics** | All events Ed25519-signed, recorded in write-only audit ledger | -| **Air-gap friendly** | Fully functional offline; signed bundles for rule and update distribution | -| **Privacy defaults** | Command args masked by default; RBAC for trace initiation | +| Principle | Description | +| ------------------------ | ------------------------------------------------------------------------------------- | +| **Customer sovereignty** | All telemetry owned by the customer; no automatic egress to external services | +| **Silent observation** | Default mode is passive; rules and traces generate no host-visible artifacts | +| **Auditable forensics** | Collection cycles and procmond actions committed to a signed, write-only audit ledger | +| **Air-gap friendly** | Fully functional offline; signed bundles for rule and update distribution | +| **Privacy defaults** | Command args masked by default; RBAC for trace initiation | **Source of Truth**: Technical requirements for the Community tier live in `spec/` and `.kiro/specs/daemoneye-core-monitoring/`. Higher-tier designs are maintained privately and are not part of this repo. @@ -166,20 +166,20 @@ The dashed line to "External tiers" indicates that `daemoneye-agent`'s outbound ### Dependencies -| Category | Crate | Version | -| ------------- | --------- | ------- | -| Runtime | tokio | 1.0+ | -| Serialization | serde | 1.0+ | -| CLI | clap | 4.0+ | -| Database | redb | 4.2+ | -| Process | sysinfo | 0.37+ | -| Logging | tracing | 0.1+ | -| Errors | thiserror | 2.0+ | -| Errors | anyhow | 1.0+ | -| Crypto | blake3 | 1.8+ | -| Crypto | rs-merkle | 1.5+ | -| Testing | insta | 1.0+ | -| Benchmarks | criterion | 0.7+ | +| Category | Crate | Version | +| ------------- | ------------- | ------- | +| Runtime | tokio | 1.0+ | +| Serialization | serde | 1.0+ | +| CLI | clap | 4.0+ | +| Database | redb | 4.6+ | +| Process | sysinfo | 0.37+ | +| Logging | tracing | 0.1+ | +| Errors | thiserror | 2.0+ | +| Errors | anyhow | 1.0+ | +| Crypto | blake3 | 1.8+ | +| Crypto | ed25519-dalek | 3.0+ | +| Testing | insta | 1.0+ | +| Benchmarks | criterion | 0.7+ | ### OS Support @@ -229,12 +229,11 @@ The dashed line to "External tiers" indicates that `daemoneye-agent`'s outbound - SQL injection prevention: AST validation at rule load time [Implemented]; SQL-based rule execution \[Implemented: `RuleExecutor` over DataFusion, see `detection/execution/`\]. Pipeline is two-phase: sqlparser lowers the custom dialect (spec §4.10) at rule-compile time into (a) protobuf collection tasks and (b) derived standard SQL; the runtime executor only sees the derived SQL, never the original dialect. - Credentials: Environment variables or OS keychain, never hardcoded - No inbound network: Outbound-only for alerts -- Audit trail: BLAKE3 hash-chained audit ledger [Implemented]; Merkle tree inclusion proofs \[In Progress — `generate_inclusion_proof()` returns empty vec, see `crypto.rs`\] +- Audit trail: BLAKE3 hash-chained, RFC 6962 Merkle audit ledger written only by procmond \[Implemented, ADR-0016\]: one batch entry per collection cycle, one entry per procmond action, Ed25519-signed checkpoints, offline inclusion proofs (`daemoneye-lib/src/audit/`). Limit: it is local evidence of alteration. Someone with root who holds the signing key can rewrite the whole ledger consistently, keeping the same key id. Only a checkpoint kept off the host detects that, and only for the history it covers; a trusted key id detects only a different key or signing turned off. Entries after the last checkpoint are not signed. Commercial tiers extend this foundation, are sold separately and are not in this repo. Only broker-connected (actor) mode keeps a ledger ### Planned Hardening (Community) - SLSA Level 3 provenance, Cosign signatures [Planned] -- Merkle tree with inclusion proofs \[In Progress — chain hashing implemented; inclusion proof generation stubbed in `crypto.rs`\] - Sandboxed detection engine (read-only DB) [Planned] - Query whitelist (SELECT only with approved functions) \[Implemented: the load-time allowlist refuses any other function call, and the executor registers only those seven functions (`hex`, `instr`, `length`, `like`, `match`, `regexp`, `unhex`), replacing DataFusion's defaults. Function-like syntax that parses to its own AST node (`SUBSTR`, `TRIM`, `POSITION`, ...) is refused at load by variant, so nothing loads that the executor cannot run\] diff --git a/CONCEPTS.md b/CONCEPTS.md index a6ba2cef..bc9c6c37 100644 --- a/CONCEPTS.md +++ b/CONCEPTS.md @@ -36,7 +36,7 @@ The agent-managed redb database of collected telemetry — `processes.events` an ### Audit ledger -The write-once, hash-chained record of what a privileged collector observed and did. procmond is its only writer; the agent and the operator CLI read it. That asymmetry is the point — a component that cannot write the chain cannot forge history in it, so the ledger stays trustworthy even if everything above it is compromised. Distinct from the Event store, which holds collected telemetry and which the agent does write. +The write-once, hash-chained Merkle record of what procmond recorded and did: one batch entry per collection cycle (a root over that cycle's event hashes) and one entry per procmond action, with signed checkpoints. procmond is its only writer; any other process reads it through the read-only handle in the shared library (agent requests and CLI commands for that are planned, not built). Local evidence of alteration, not proof of integrity: someone with root who holds the signing key can rebuild it under the same key id; only a checkpoint kept off the host detects that, and only for the history it covers. Only broker-connected mode keeps one. A cycle whose ledger commit fails has no batch entry: collection continues, and the next entry written records how many commits were missed. That asymmetry is the point — a component that cannot write the chain cannot forge history in it, so compromising those components gives no way to write to the chain. Distinct from the Event store, which holds collected telemetry and which the agent does write. ### Time bucket diff --git a/Cargo.lock b/Cargo.lock index 642adeb8..b88eff97 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -994,6 +994,33 @@ dependencies = [ "memchr", ] +[[package]] +name = "curve25519-dalek" +version = "5.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94c1aa5a9b7626ed65ac0cf5ea9d4f1547af89017fbac20bd4de40022fff516f" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "curve25519-dalek-derive", + "digest 0.11.3", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "daemoneye-agent" version = "0.1.0" @@ -1079,10 +1106,12 @@ dependencies = [ "criterion", "datafusion", "dirs", + "ed25519-dalek", "figment", "futures", "futures-util", "fuzzyhash", + "getrandom 0.4.2", "insta", "interprocess", "lru", @@ -1113,6 +1142,7 @@ dependencies = [ "tracing-test", "unidirs", "uuid", + "zeroize", ] [[package]] @@ -1865,6 +1895,28 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2db04e74f0a9a93103b50e90b96024c9b2bdca8bce6a632ec71b88736d3d359" +[[package]] +name = "ed25519" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a" +dependencies = [ + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de" +dependencies = [ + "curve25519-dalek", + "ed25519", + "sha2 0.11.1", + "subtle", + "zeroize", +] + [[package]] name = "either" version = "1.16.0" @@ -1927,6 +1979,12 @@ version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" +[[package]] +name = "fiat-crypto" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24" + [[package]] name = "figment" version = "0.10.19" @@ -3422,6 +3480,7 @@ dependencies = [ "anyhow", "assert_cmd", "async-trait", + "blake3", "chrono", "clap", "collector-core", @@ -3435,6 +3494,7 @@ dependencies = [ "postcard", "predicates", "proptest", + "redb", "serde", "serde_json", "sysinfo", @@ -4138,6 +4198,12 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" + [[package]] name = "simd_cesu8" version = "1.2.0" diff --git a/Cargo.toml b/Cargo.toml index 001d9684..137b467f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -87,6 +87,9 @@ datafusion = { version = "55.1.0", default-features = false, features = [ "string_expressions", ] } dirs = "7.0.0" +# Exact-pinned: Ed25519 checkpoint signatures; a version bump must be reviewed, +# not absorbed. See AGENTS.md "Dependency Security". +ed25519-dalek = { version = "=3.0.0", default-features = false, features = ["zeroize"] } figment = { version = "0.10.19", features = ["toml", "json", "env"] } futures = "0.3.34" futures-util = "0.3.34" @@ -95,6 +98,9 @@ futures-util = "0.3.34" # integrity-adjacent data. See AGENTS.md "Dependency Security". fuzzyhash = "=0.2.2" +# Exact-pinned: OS RNG for the checkpoint signing seed. See AGENTS.md "Dependency Security". +getrandom = "=0.4.2" + # System information and IPC hostname-validator = "1.1.1" insta = { version = "1.48.0", features = ["filters"] } @@ -229,6 +235,8 @@ windows = { version = "0.62.2", features = [ ] } windows-service = "0.8.1" winreg = "0.56.0" +# Exact-pinned: wipes the signing seed on drop. See AGENTS.md "Dependency Security". +zeroize = "=1.9.1" # Workspace lint configuration [workspace.lints.rust] diff --git a/GOTCHAS.md b/GOTCHAS.md index f03dd932..c362b879 100644 --- a/GOTCHAS.md +++ b/GOTCHAS.md @@ -36,6 +36,14 @@ The workspace denies `clippy::expect_used`, `unwrap_used`, and `panic` outside t To call a trait method on a type from another crate, the trait must be imported even if you never name it directly — e.g. `use daemoneye_eventbus::rpc::RegistrationProvider;`. Without it the method "doesn't exist" with a confusing error. Common in tests exercising cross-crate behavior. +### 1.5 Run `git commit` Directly With `PROTOC` Exported, Never Under `mise exec` + +The pre-commit hooks build the workspace and run `cargo-audit`, so a commit needs `PROTOC` in the environment: `export PROTOC="$(mise which protoc)"`, then plain `git commit`. Do not run it as `mise exec -- git commit`: the `cargo-audit` pre-commit hook fails against git's temporary index when git runs under `mise exec`. + +### 1.6 A Lockfile Change and Its Manifest Change Go in the Same Commit + +A path-limited commit that leaves a `Cargo.toml` change out while including `Cargo.lock` gets its lockfile rewritten by the clippy hook: pre-commit stashes the manifest change that is not in the commit, cargo then re-resolves the lockfile without it, and the commit aborts with "files were modified by this hook". Commit a dependency edit and the `Cargo.lock` change it causes together. + ## 2. Toolchain (mise) ### 2.1 mise pipx Tools Need `uv` Installed diff --git a/SECURITY.md b/SECURITY.md index 6794da4b..0fe2fb84 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -27,7 +27,7 @@ DaemonEye is split into three binaries with strict privilege separation, plus th - **Least privilege**: Components run with the minimum permissions they need. procmond is the only component that ever runs elevated, and it drops privileges after collection setup. - **Privilege separation**: procmond writes only to the audit ledger; daemoneye-agent reads the audit ledger and reads/writes the event store; daemoneye-cli is read-only. - **Validated IPC**: Inter-process messages use protobuf with CRC32 framing checks. There are no inbound network listeners; alert delivery is outbound-only. -- **Audit trail**: Events are recorded in a BLAKE3 hash-chained ledger. A Certificate Transparency-style Merkle tree with inclusion proofs is in progress. +- **Audit trail**: Events are recorded in a BLAKE3 hash-chained ledger. Entries are committed to an RFC 6962 Merkle tree with Ed25519-signed checkpoints and offline inclusion proofs. This is local evidence of alteration; Commercial tiers extend this foundation, are sold separately and are not in this repo. ## Security Features @@ -38,11 +38,10 @@ DaemonEye is split into three binaries with strict privilege separation, plus th - **SQL injection prevention**: AST validation via sqlparser at rule load time [Implemented]. Execution-time enforcement of the SELECT-only/whitelist policy is [Planned]; the current engine uses category-based pattern matching. - **Credential handling**: Secrets come from environment variables or the OS keychain. Nothing is hardcoded. - **Attack surface**: No inbound network listeners. Alert delivery is outbound-only. -- **Audit trail**: BLAKE3 hash-chained audit ledger [Implemented]. Certificate Transparency-style Merkle tree inclusion proofs are [In Progress]; the generator currently returns an empty vec in `crypto.rs`. +- **Audit trail**: BLAKE3 hash-chained, Merkle-tree audit ledger with signed checkpoints and inclusion proofs [Implemented, broker-connected mode only; standalone mode keeps no ledger]. Someone with root who holds the signing key can rewrite the whole ledger consistently, keeping the same key id. Only a checkpoint kept off the host detects that, and only for the history it covers; a trusted key id detects only a different key or signing turned off. Entries after the last checkpoint are not signed. ### Planned Hardening (Community Tier) -- **Cryptographic integrity**: Merkle tree with inclusion proofs and periodic checkpoints. [In Progress]; chain hashing is implemented, inclusion proof generation is stubbed. - **Code signing**: SLSA Level 3 provenance and Cosign signatures on releases. [Planned] - **Sandboxed execution**: read-only database connections for the detection engine. [Planned] - **Query whitelist**: SELECT-only with an approved-function list. [Implemented at rule load time; not yet enforced at execution time] diff --git a/daemoneye-agent/src/collector_registry.rs b/daemoneye-agent/src/collector_registry.rs index 5de72159..511f508c 100644 --- a/daemoneye-agent/src/collector_registry.rs +++ b/daemoneye-agent/src/collector_registry.rs @@ -26,7 +26,7 @@ pub struct CollectorRegistry { records: RwLock>, default_heartbeat: Duration, /// Agent-side chain of refused registrations (R8). Kept behind a synchronous lock that is - /// never held across an `.await`; the `audit_ledger` table is procmond's to write. + /// never held across an `.await`; the audit ledger is procmond's to write. rejections: Mutex, /// Whether, and how, a registration is authenticated (R8, R10). admission: AdmissionPolicy, diff --git a/daemoneye-lib/Cargo.toml b/daemoneye-lib/Cargo.toml index fd4dacc1..b2bf7361 100644 --- a/daemoneye-lib/Cargo.toml +++ b/daemoneye-lib/Cargo.toml @@ -79,6 +79,8 @@ datafusion = { workspace = true, optional = true } # Configuration management dirs = { workspace = true } +# Audit checkpoint signatures +ed25519-dalek = { workspace = true } figment = { workspace = true } # Futures utilities @@ -88,6 +90,9 @@ futures-util = { workspace = true } # Optional: non-cryptographic fuzzy (ssdeep/CTPH) hashing for binary-change detection fuzzyhash = { workspace = true, optional = true } +# OS RNG for the checkpoint signing seed +getrandom = { workspace = true } + # IPC communication interprocess = { workspace = true } @@ -142,6 +147,8 @@ unidirs = { workspace = true } # UUID support uuid = { workspace = true } +# Wipe the signing seed on drop +zeroize = { workspace = true } [build-dependencies] prost-build = { workspace = true } diff --git a/daemoneye-lib/src/audit/checkpoint.rs b/daemoneye-lib/src/audit/checkpoint.rs new file mode 100644 index 00000000..77eab1e5 --- /dev/null +++ b/daemoneye-lib/src/audit/checkpoint.rs @@ -0,0 +1,441 @@ +//! Ledger checkpoints: the tree root at a given size, with its signing state. + +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use super::merkle::{Frontier, Hash}; +use super::signing::{KeyId, SigningMode, SigningState, key_id, verify_signature}; + +/// Format version of a stored checkpoint and of its signed message. +pub const CHECKPOINT_VERSION_V1: u8 = 1; +/// Format version of an export blob. +pub const EXPORT_VERSION_V1: u8 = 1; +/// Entries between checkpoints. Fixed: verification and recovery read checkpoints at multiples of +/// it, so changing it needs a new format version. +pub const CHECKPOINT_INTERVAL: u64 = 64; + +/// Domain tag so a checkpoint signature cannot be replayed as any other signed message. +const SIGNED_MESSAGE_TAG: &[u8] = b"daemoneye.audit.checkpoint"; + +/// Whether a checkpoint is due once the tree holds `tree_size` entries. +#[must_use] +pub const fn is_checkpoint_due(tree_size: u64) -> bool { + tree_size != 0 && tree_size.is_multiple_of(CHECKPOINT_INTERVAL) +} + +/// Why a checkpoint or export blob could not be encoded or decoded. +#[derive(Debug, Error)] +#[non_exhaustive] +pub enum CheckpointError { + #[error("unknown checkpoint format version {0}")] + UnknownVersion(u8), + #[error("checkpoint bytes are empty")] + Empty, + #[error("checkpoint encoding failed: {0}")] + Codec(#[from] postcard::Error), +} + +/// A checkpoint with the frontier needed to resume the tree from it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Checkpoint { + /// Format version byte, covered by the signature. + pub version: u8, + /// Entries the checkpoint covers, covered by the signature. + pub tree_size: u64, + /// Merkle root at `tree_size`, covered by the signature. + pub root: Hash, + /// Creation time in milliseconds since the Unix epoch, covered by the signature. + pub created_ms: i64, + /// The tree frontier at `tree_size`, to resume appending from. + pub frontier: Frontier, + /// The signature state of this checkpoint. + pub signing: SigningState, +} + +/// The outcome of checking a signing state against its message. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[allow( + clippy::exhaustive_enums, + reason = "closed set: every match must decide each case" +)] +pub enum SignatureVerdict { + /// A valid signature from this key. + ValidSigned { key_id: KeyId }, + /// Signing was off. Not a valid signature. + UnsignedByConfig, + /// Signing was on but the key failed to load. Not a valid signature. + UnsignedKeyFailed, + /// A signature is present and does not verify. + BadSignature, +} + +/// The outcome of verifying a stored checkpoint. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[allow( + clippy::exhaustive_enums, + reason = "closed set: every match must decide each case" +)] +pub enum CheckpointVerdict { + /// The checkpoint is self-consistent; this is its signature outcome. + Signature(SignatureVerdict), + /// The stored root or size disagrees with the stored frontier. + Inconsistent, +} + +/// What an export blob carries: enough to check the signature offline, without the frontier. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ExportBlob { + /// Format version byte, covered by the signature. + pub version: u8, + /// Entries the checkpoint covers, covered by the signature. + pub tree_size: u64, + /// Merkle root at `tree_size`, covered by the signature. + pub root: Hash, + /// Creation time in milliseconds since the Unix epoch, covered by the signature. + pub created_ms: i64, + /// The signature state of this checkpoint. + pub signing: SigningState, +} + +/// Length-prefix a field so adjacent fields cannot be shifted into one another. +fn push_field(out: &mut Vec, field: &[u8]) { + let length = u32::try_from(field.len()).unwrap_or(u32::MAX); + out.extend_from_slice(&length.to_be_bytes()); + out.extend_from_slice(field); +} + +fn signed_message(version: u8, tree_size: u64, root: &Hash, created_ms: i64) -> Vec { + let mut out = vec![version]; + push_field(&mut out, SIGNED_MESSAGE_TAG); + push_field(&mut out, &tree_size.to_be_bytes()); + push_field(&mut out, root); + push_field(&mut out, &created_ms.to_be_bytes()); + out +} + +fn check_signing(state: &SigningState, message: &[u8]) -> SignatureVerdict { + match *state { + SigningState::Signed { + ref public_key, + ref signature, + } => { + if verify_signature(public_key, message, signature) { + SignatureVerdict::ValidSigned { + key_id: key_id(public_key), + } + } else { + SignatureVerdict::BadSignature + } + } + SigningState::UnsignedByConfig => SignatureVerdict::UnsignedByConfig, + SigningState::UnsignedKeyFailed => SignatureVerdict::UnsignedKeyFailed, + } +} + +/// Prefix `payload` with the version byte, mirroring the event store's value layout. +fn with_version_byte(version: u8, value: &T) -> Result, CheckpointError> { + let payload = postcard::to_allocvec(value)?; + let mut out = Vec::with_capacity(payload.len().saturating_add(1)); + out.push(version); + out.extend_from_slice(&payload); + Ok(out) +} + +fn split_version(bytes: &[u8], expected: u8) -> Result<&[u8], CheckpointError> { + let (version, payload) = bytes.split_first().ok_or(CheckpointError::Empty)?; + if *version == expected { + Ok(payload) + } else { + Err(CheckpointError::UnknownVersion(*version)) + } +} + +impl Checkpoint { + /// Build a checkpoint at the frontier's size, signing it when `signing` carries a signer. + #[must_use] + pub fn build(frontier: &Frontier, created_ms: i64, signing: SigningMode<'_>) -> Self { + let tree_size = frontier.leaf_count(); + let root = frontier.root(); + let state = match signing { + SigningMode::Signed(signer) => signer.sign(&signed_message( + CHECKPOINT_VERSION_V1, + tree_size, + &root, + created_ms, + )), + SigningMode::UnsignedByConfig => SigningState::UnsignedByConfig, + SigningMode::UnsignedKeyFailed => SigningState::UnsignedKeyFailed, + }; + Self { + version: CHECKPOINT_VERSION_V1, + tree_size, + root, + created_ms, + frontier: frontier.clone(), + signing: state, + } + } + + /// Check the signature, then that the root and size agree with the frontier. A forged field + /// is reported as a bad signature before any consistency question arises. + #[must_use] + pub fn verify(&self) -> CheckpointVerdict { + let message = signed_message(self.version, self.tree_size, &self.root, self.created_ms); + let verdict = check_signing(&self.signing, &message); + if verdict == SignatureVerdict::BadSignature { + return CheckpointVerdict::Signature(verdict); + } + if self.root != self.frontier.root() || self.tree_size != self.frontier.leaf_count() { + return CheckpointVerdict::Inconsistent; + } + CheckpointVerdict::Signature(verdict) + } + + /// Encode for storage: a version byte, then postcard. + /// + /// # Errors + /// + /// Returns [`CheckpointError::Codec`] if serialisation fails. + pub fn encode(&self) -> Result, CheckpointError> { + with_version_byte(CHECKPOINT_VERSION_V1, self) + } + + /// Decode bytes written by [`Checkpoint::encode`]. + /// + /// # Errors + /// + /// Returns [`CheckpointError::UnknownVersion`] for any other leading version byte or inner + /// version, [`CheckpointError::Codec`] for malformed bytes. + pub fn decode(bytes: &[u8]) -> Result { + let decoded: Self = postcard::from_bytes(split_version(bytes, CHECKPOINT_VERSION_V1)?)?; + if decoded.version == CHECKPOINT_VERSION_V1 { + Ok(decoded) + } else { + Err(CheckpointError::UnknownVersion(decoded.version)) + } + } + + /// The offline-verifiable form, without the frontier. + #[must_use] + pub fn export(&self) -> ExportBlob { + ExportBlob { + version: EXPORT_VERSION_V1, + tree_size: self.tree_size, + root: self.root, + created_ms: self.created_ms, + signing: self.signing.clone(), + } + } +} + +impl ExportBlob { + /// Check the signature from the blob alone. The signed message uses the checkpoint format + /// version, which is the only one this blob version can carry. + #[must_use] + pub fn verify(&self) -> SignatureVerdict { + let message = signed_message( + CHECKPOINT_VERSION_V1, + self.tree_size, + &self.root, + self.created_ms, + ); + check_signing(&self.signing, &message) + } + + /// Encode as one self-contained value: a version byte, then postcard. + /// + /// # Errors + /// + /// Returns [`CheckpointError::Codec`] if serialisation fails. + pub fn encode(&self) -> Result, CheckpointError> { + with_version_byte(EXPORT_VERSION_V1, self) + } + + /// Decode bytes written by [`ExportBlob::encode`]. + /// + /// # Errors + /// + /// Returns [`CheckpointError::UnknownVersion`] for any other leading version byte or inner + /// version, [`CheckpointError::Codec`] for malformed bytes. + pub fn decode(bytes: &[u8]) -> Result { + let decoded: Self = postcard::from_bytes(split_version(bytes, EXPORT_VERSION_V1)?)?; + if decoded.version == EXPORT_VERSION_V1 { + Ok(decoded) + } else { + Err(CheckpointError::UnknownVersion(decoded.version)) + } + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use super::*; + use crate::audit::merkle::leaf_hash; + use crate::audit::signing::{CheckpointSigner, KeyOutcome, resolve_key}; + + fn frontier(count: u8) -> Frontier { + let mut frontier = Frontier::new(); + for index in 0..count { + frontier.append(leaf_hash(&[index])).unwrap(); + } + frontier + } + + fn signer(dir: &tempfile::TempDir) -> CheckpointSigner { + match resolve_key(true, &dir.path().join("k"), true) { + KeyOutcome::Signer { signer, .. } => signer, + KeyOutcome::UnsignedByConfig | KeyOutcome::KeyFailed(_) => panic!("no signer"), + } + } + + fn signed(dir: &tempfile::TempDir) -> Checkpoint { + let signer = signer(dir); + Checkpoint::build(&frontier(5), 1_000, SigningMode::Signed(&signer)) + } + + #[test] + fn signed_checkpoint_verifies_with_its_key_id() { + let dir = tempfile::tempdir().unwrap(); + let signer = signer(&dir); + let checkpoint = Checkpoint::build(&frontier(5), 1_000, SigningMode::Signed(&signer)); + + assert_eq!( + checkpoint.verify(), + CheckpointVerdict::Signature(SignatureVerdict::ValidSigned { + key_id: signer.key_id() + }) + ); + } + + #[test] + fn changing_size_root_or_time_is_a_bad_signature() { + let dir = tempfile::tempdir().unwrap(); + let original = signed(&dir); + let bad = CheckpointVerdict::Signature(SignatureVerdict::BadSignature); + + let mut size = original.clone(); + size.tree_size += 1; + assert_eq!(size.verify(), bad); + + let mut root = original.clone(); + *root.root.first_mut().unwrap() ^= 1; + assert_eq!(root.verify(), bad); + + let mut time = original; + time.created_ms += 1; + assert_eq!(time.verify(), bad); + } + + #[test] + fn changing_one_signature_byte_is_a_bad_signature() { + let dir = tempfile::tempdir().unwrap(); + let mut checkpoint = signed(&dir); + let SigningState::Signed { + ref mut signature, .. + } = checkpoint.signing + else { + panic!("expected signed"); + }; + *signature.first_mut().unwrap() ^= 1; + + assert_eq!( + checkpoint.verify(), + CheckpointVerdict::Signature(SignatureVerdict::BadSignature) + ); + } + + #[test] + fn root_disagreeing_with_the_frontier_is_inconsistent() { + let dir = tempfile::tempdir().unwrap(); + let signer = signer(&dir); + let mut checkpoint = Checkpoint::build(&frontier(5), 1, SigningMode::Signed(&signer)); + // Same size, different content: the signed root is the original, the frontier is not. + checkpoint.frontier = { + let mut other = Frontier::new(); + for index in 10..15_u8 { + other.append(leaf_hash(&[index])).unwrap(); + } + other + }; + + assert_eq!(checkpoint.verify(), CheckpointVerdict::Inconsistent); + } + + #[test] + fn unsigned_states_are_reported_and_still_checked_for_consistency() { + let unsigned = Checkpoint::build(&frontier(3), 1, SigningMode::UnsignedByConfig); + assert_eq!( + unsigned.verify(), + CheckpointVerdict::Signature(SignatureVerdict::UnsignedByConfig) + ); + let mut failed = Checkpoint::build(&frontier(3), 1, SigningMode::UnsignedKeyFailed); + assert_eq!( + failed.verify(), + CheckpointVerdict::Signature(SignatureVerdict::UnsignedKeyFailed) + ); + failed.tree_size = 99; + assert_eq!(failed.verify(), CheckpointVerdict::Inconsistent); + } + + #[test] + fn stored_checkpoint_round_trips_and_rejects_unknown_versions() { + let dir = tempfile::tempdir().unwrap(); + let checkpoint = signed(&dir); + let bytes = checkpoint.encode().unwrap(); + + assert_eq!(bytes.first(), Some(&CHECKPOINT_VERSION_V1)); + assert_eq!(Checkpoint::decode(&bytes).unwrap(), checkpoint); + + let mut unknown = bytes; + unknown.splice(0..1, [9]); + assert!(matches!( + Checkpoint::decode(&unknown), + Err(CheckpointError::UnknownVersion(9)) + )); + assert!(matches!( + Checkpoint::decode(&[]), + Err(CheckpointError::Empty) + )); + } + + #[test] + fn export_blob_round_trips_and_verifies_alone() { + let dir = tempfile::tempdir().unwrap(); + let checkpoint = signed(&dir); + let bytes = checkpoint.export().encode().unwrap(); + + let blob = ExportBlob::decode(&bytes).unwrap(); + + assert!(matches!( + blob.verify(), + SignatureVerdict::ValidSigned { .. } + )); + + let mut tampered = blob; + tampered.tree_size += 1; + assert_eq!(tampered.verify(), SignatureVerdict::BadSignature); + } + + #[test] + fn export_blob_with_unknown_version_is_a_typed_error() { + let dir = tempfile::tempdir().unwrap(); + let mut bytes = signed(&dir).export().encode().unwrap(); + bytes.splice(0..1, [2]); + + assert!(matches!( + ExportBlob::decode(&bytes), + Err(CheckpointError::UnknownVersion(2)) + )); + } + + #[test] + fn checkpoint_is_due_exactly_at_multiples_of_the_interval() { + assert!(!is_checkpoint_due(0)); + assert!(!is_checkpoint_due(1)); + assert!(!is_checkpoint_due(CHECKPOINT_INTERVAL - 1)); + assert!(is_checkpoint_due(CHECKPOINT_INTERVAL)); + assert!(!is_checkpoint_due(CHECKPOINT_INTERVAL + 1)); + assert!(is_checkpoint_due(CHECKPOINT_INTERVAL * 3)); + } +} diff --git a/daemoneye-lib/src/audit/entry.rs b/daemoneye-lib/src/audit/entry.rs new file mode 100644 index 00000000..c674982c --- /dev/null +++ b/daemoneye-lib/src/audit/entry.rs @@ -0,0 +1,361 @@ +//! Ledger entries, their canonical encoding and their hash chain. + +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use super::event_hash::put_len_prefixed; +use super::merkle::{self, Frontier, Hash, MerkleError}; + +/// Format version of the entry and of its hash input; also the leading byte on disk. +pub const ENTRY_VERSION: u8 = 1; + +/// The `prev_hash` of the first entry. +pub const GENESIS_PREV_HASH: Hash = [0; 32]; + +/// Most privilege names one action may carry. +pub const MAX_PRIVILEGES: usize = 16; +/// Longest privilege name, in bytes. +pub const MAX_PRIVILEGE_LEN: usize = 32; + +const ENTRY_MAGIC: &[u8; 4] = b"DEAL"; + +/// Failures building, checking, encoding or decoding an entry. +#[derive(Debug, Error, PartialEq, Eq)] +#[non_exhaustive] +pub enum EntryError { + #[error("unsupported entry version {0}")] + UnsupportedVersion(u8), + #[error("entry bytes are empty")] + Empty, + #[error("{0} unread bytes follow the entry")] + TrailingBytes(usize), + #[error("entry codec failure: {0}")] + Codec(postcard::Error), + #[error("the entry sequence number overflowed")] + SequenceOverflow, + #[error("the tree holds {found} leaves but entry {expected} follows {expected} entries")] + TreeSizeMismatch { expected: u64, found: u64 }, + #[error("a privilege name is {len} bytes, over the {MAX_PRIVILEGE_LEN} byte limit")] + PrivilegeTooLong { len: usize }, + #[error("{count} privilege names, over the limit of {MAX_PRIVILEGES}")] + TooManyPrivileges { count: usize }, + #[error("entry {sequence} does not hash to its recorded hash")] + HashMismatch { sequence: u64 }, + #[error("entry {sequence} does not match its recorded payload hash")] + PayloadHashMismatch { sequence: u64 }, + #[error(transparent)] + Merkle(#[from] MerkleError), +} + +/// The detected privilege set: short names, bounded in count and length. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Privileges(Vec); + +impl Privileges { + /// Rejects more than [`MAX_PRIVILEGES`] names or any name over [`MAX_PRIVILEGE_LEN`] bytes. + pub fn new(names: Vec) -> Result { + let candidate = Self(names); + candidate.validate()?; + Ok(candidate) + } + + #[must_use] + pub fn names(&self) -> &[String] { + &self.0 + } + + fn validate(&self) -> Result<(), EntryError> { + if self.0.len() > MAX_PRIVILEGES { + return Err(EntryError::TooManyPrivileges { + count: self.0.len(), + }); + } + self.0 + .iter() + .find(|name| name.len() > MAX_PRIVILEGE_LEN) + .map_or(Ok(()), |name| { + Err(EntryError::PrivilegeTooLong { len: name.len() }) + }) + } +} + +/// A security-relevant action of procmond. Identifiers and hashes only; never rule text or +/// configuration values. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[allow( + clippy::exhaustive_enums, + reason = "closed set: a new variant needs a new version, and every match must decide" +)] +pub enum Action { + ProcessStart { pid: u32 }, + CleanStop { pid: u32 }, + PrivilegesDetected { privileges: Privileges }, + ConfigUpdateReceived { config_hash: Hash }, + IntegrityDriftReported { subject: Hash, observed: Hash }, + SigningKeyCreated { key_id: Hash }, + SigningKeyFailed, +} + +/// Why commits were missed. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[allow( + clippy::exhaustive_enums, + reason = "closed set: a new variant needs a new version, and every match must decide" +)] +pub enum GapReason { + CommitFailed, + LedgerUnavailable, +} + +/// What an entry records. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[allow( + clippy::exhaustive_enums, + reason = "closed set: a new variant needs a new version, and every match must decide" +)] +pub enum Kind { + /// The events one collection cycle wrote to the WAL. + Batch { + first_seq: u64, + last_seq: u64, + count: u64, + batch_root: Hash, + recovered: bool, + }, + Action(Action), + /// Commits that were never made. + Gap { + missed: u64, + reason: GapReason, + }, +} + +impl Action { + fn put_canonical(&self, buf: &mut Vec) { + match *self { + Self::ProcessStart { pid } => { + buf.push(1); + buf.extend_from_slice(&pid.to_be_bytes()); + } + Self::CleanStop { pid } => { + buf.push(2); + buf.extend_from_slice(&pid.to_be_bytes()); + } + Self::PrivilegesDetected { ref privileges } => { + buf.push(3); + buf.extend_from_slice( + &u64::try_from(privileges.0.len()) + .unwrap_or(u64::MAX) + .to_be_bytes(), + ); + for name in &privileges.0 { + put_len_prefixed(buf, name.as_bytes()); + } + } + Self::ConfigUpdateReceived { config_hash } => { + buf.push(4); + buf.extend_from_slice(&config_hash); + } + Self::IntegrityDriftReported { subject, observed } => { + buf.push(5); + buf.extend_from_slice(&subject); + buf.extend_from_slice(&observed); + } + Self::SigningKeyCreated { key_id } => { + buf.push(6); + buf.extend_from_slice(&key_id); + } + Self::SigningKeyFailed => buf.push(7), + } + } +} + +impl Kind { + /// Tag byte then fixed-width fields, strings length-prefixed. The payload hash is the BLAKE3 + /// of this encoding, so it covers, per kind: a batch's first and last sequence, count, root + /// and recovered flag; an action's tag and every identifier, hash and privilege name; a + /// gap's missed count and reason. + #[must_use] + pub fn canonical_bytes(&self) -> Vec { + let mut buf = Vec::with_capacity(64); + match *self { + Self::Batch { + first_seq, + last_seq, + count, + batch_root, + recovered, + } => { + buf.push(1); + for value in [first_seq, last_seq, count] { + buf.extend_from_slice(&value.to_be_bytes()); + } + buf.extend_from_slice(&batch_root); + buf.push(u8::from(recovered)); + } + Self::Action(ref action) => { + buf.push(2); + action.put_canonical(&mut buf); + } + Self::Gap { missed, reason } => { + buf.push(3); + buf.extend_from_slice(&missed.to_be_bytes()); + buf.push(match reason { + GapReason::CommitFailed => 1, + GapReason::LedgerUnavailable => 2, + }); + } + } + buf + } + + #[must_use] + pub fn payload_hash(&self) -> Hash { + blake3::hash(&self.canonical_bytes()).into() + } + + fn validate(&self) -> Result<(), EntryError> { + match *self { + Self::Action(Action::PrivilegesDetected { ref privileges }) => privileges.validate(), + Self::Batch { .. } | Self::Action(_) | Self::Gap { .. } => Ok(()), + } + } +} + +/// One ledger entry. `tree_size` and `root` describe the ledger tree after this entry and are +/// derived from `entry_hash`, so they are not part of it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Entry { + pub version: u8, + pub seq: u64, + pub ts_ms: i64, + pub kind: Kind, + pub payload_hash: Hash, + pub prev_hash: Hash, + pub entry_hash: Hash, + pub tree_size: u64, + pub root: Hash, +} + +/// BLAKE3 over: magic, version, sequence, timestamp, the length-prefixed kind encoding, payload +/// hash and previous hash. +fn compute_entry_hash( + version: u8, + seq: u64, + ts_ms: i64, + kind: &Kind, + payload: &Hash, + prev: &Hash, +) -> Hash { + let mut buf = Vec::with_capacity(160); + buf.extend_from_slice(ENTRY_MAGIC); + buf.push(version); + buf.extend_from_slice(&seq.to_be_bytes()); + buf.extend_from_slice(&ts_ms.to_be_bytes()); + put_len_prefixed(&mut buf, &kind.canonical_bytes()); + buf.extend_from_slice(payload); + buf.extend_from_slice(prev); + blake3::hash(&buf).into() +} + +impl Entry { + /// Builds the entry after `prev` (`None` for the first) and returns it with the tree that + /// includes it. `tree` is the ledger tree before this entry. + pub fn next( + prev: Option<&Self>, + kind: Kind, + ts_ms: i64, + tree: &Frontier, + ) -> Result<(Self, Frontier), EntryError> { + kind.validate()?; + let (seq, prev_hash) = match prev { + None => (0, GENESIS_PREV_HASH), + Some(last) => ( + last.seq + .checked_add(1) + .ok_or(EntryError::SequenceOverflow)?, + last.entry_hash, + ), + }; + if tree.leaf_count() != seq { + return Err(EntryError::TreeSizeMismatch { + expected: seq, + found: tree.leaf_count(), + }); + } + let payload_hash = kind.payload_hash(); + let entry_hash = + compute_entry_hash(ENTRY_VERSION, seq, ts_ms, &kind, &payload_hash, &prev_hash); + let mut after = tree.clone(); + after.append(merkle::leaf_hash(&entry_hash))?; + let entry = Self { + version: ENTRY_VERSION, + seq, + ts_ms, + kind, + payload_hash, + prev_hash, + entry_hash, + tree_size: after.leaf_count(), + root: after.root(), + }; + Ok((entry, after)) + } + + /// The ledger tree leaf for this entry; the writer and the verifier both use it. + #[must_use] + pub fn ledger_leaf(&self) -> Hash { + merkle::leaf_hash(&self.entry_hash) + } + + /// Recomputes the payload hash and entry hash from the entry's fields. + pub fn verify_self(&self) -> Result<(), EntryError> { + if self.version != ENTRY_VERSION { + return Err(EntryError::UnsupportedVersion(self.version)); + } + self.kind.validate()?; + if self.kind.payload_hash() != self.payload_hash { + return Err(EntryError::PayloadHashMismatch { sequence: self.seq }); + } + let expected = compute_entry_hash( + self.version, + self.seq, + self.ts_ms, + &self.kind, + &self.payload_hash, + &self.prev_hash, + ); + if expected == self.entry_hash { + Ok(()) + } else { + Err(EntryError::HashMismatch { sequence: self.seq }) + } + } + + /// `[version byte][postcard payload]`. + pub fn encode(&self) -> Result, EntryError> { + let payload = postcard::to_allocvec(self).map_err(EntryError::Codec)?; + let mut out = Vec::with_capacity(payload.len().saturating_add(1)); + out.push(ENTRY_VERSION); + out.extend_from_slice(&payload); + Ok(out) + } + + /// Decodes bytes written by [`Self::encode`]; an unknown version byte is an error. + pub fn decode(bytes: &[u8]) -> Result { + let (version, payload) = bytes.split_first().ok_or(EntryError::Empty)?; + if *version != ENTRY_VERSION { + return Err(EntryError::UnsupportedVersion(*version)); + } + let (entry, rest) = + postcard::take_from_bytes::(payload).map_err(EntryError::Codec)?; + if !rest.is_empty() { + return Err(EntryError::TrailingBytes(rest.len())); + } + if entry.version != ENTRY_VERSION { + return Err(EntryError::UnsupportedVersion(entry.version)); + } + entry.kind.validate()?; + Ok(entry) + } +} diff --git a/daemoneye-lib/src/audit/event_hash.rs b/daemoneye-lib/src/audit/event_hash.rs new file mode 100644 index 00000000..efdc763f --- /dev/null +++ b/daemoneye-lib/src/audit/event_hash.rs @@ -0,0 +1,192 @@ +//! The canonical hash of a recorded process event, and the check of a batch against it. + +use std::borrow::Borrow; + +use thiserror::Error; + +use super::merkle::{self, Frontier, Hash, MerkleError}; + +/// Bumped whenever a field is added to, removed from or reordered in the hashed encoding. +pub const EVENT_HASH_VERSION: u8 = 1; + +const EVENT_MAGIC: &[u8; 4] = b"DEEV"; + +/// Failures while building a batch root. +#[derive(Debug, Error, PartialEq, Eq)] +#[non_exhaustive] +pub enum EventHashError { + #[error("WAL sequence {0} appears more than once in one batch")] + DuplicateSequence(u64), + #[error(transparent)] + Merkle(#[from] MerkleError), +} + +/// The three event types procmond publishes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[allow( + clippy::exhaustive_enums, + reason = "closed set: a new variant needs a new version, and every match must decide" +)] +pub enum EventType { + Start, + Stop, + Modify, +} + +impl EventType { + const fn tag(self) -> u8 { + match self { + Self::Start => 1, + Self::Stop => 2, + Self::Modify => 3, + } + } +} + +/// The fields of one recorded event that the ledger commits to, after command-line sanitisation. +/// Times are integer nanoseconds since the Unix epoch. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EventProjection { + pub wal_sequence: u64, + pub event_type: EventType, + pub pid: u32, + pub ppid: Option, + pub name: String, + pub executable_path: Option, + pub command_line: Option, + pub start_time_ns: Option, + pub executable_hash: Option, + pub hash_algorithm: Option, + pub collection_time_ns: i64, +} + +/// Appends `bytes` behind a fixed-width length, so no two field sequences share an encoding. +pub(super) fn put_len_prefixed(buf: &mut Vec, bytes: &[u8]) { + let len = u64::try_from(bytes.len()).unwrap_or(u64::MAX); + buf.extend_from_slice(&len.to_be_bytes()); + buf.extend_from_slice(bytes); +} + +fn put_opt_fixed(buf: &mut Vec, value: Option<[u8; N]>) { + match value { + None => buf.push(0), + Some(bytes) => { + buf.push(1); + buf.extend_from_slice(&bytes); + } + } +} + +impl EventProjection { + /// Versioned, length-prefixed encoding; every optional field carries a presence byte. + #[must_use] + pub fn canonical_bytes(&self) -> Vec { + let mut buf = Vec::with_capacity(128); + buf.extend_from_slice(EVENT_MAGIC); + buf.push(EVENT_HASH_VERSION); + buf.extend_from_slice(&self.wal_sequence.to_be_bytes()); + buf.push(self.event_type.tag()); + buf.extend_from_slice(&self.pid.to_be_bytes()); + put_opt_fixed(&mut buf, self.ppid.map(u32::to_be_bytes)); + put_len_prefixed(&mut buf, self.name.as_bytes()); + for text in [&self.executable_path, &self.command_line] { + put_opt_text(&mut buf, text.as_deref()); + } + put_opt_fixed(&mut buf, self.start_time_ns.map(i64::to_be_bytes)); + for text in [&self.executable_hash, &self.hash_algorithm] { + put_opt_text(&mut buf, text.as_deref()); + } + buf.extend_from_slice(&self.collection_time_ns.to_be_bytes()); + buf + } + + /// The event's data hash: BLAKE3 of [`Self::canonical_bytes`]. + #[must_use] + pub fn data_hash(&self) -> Hash { + blake3::hash(&self.canonical_bytes()).into() + } + + /// The batch tree leaf for this event. + #[must_use] + pub fn leaf(&self) -> Hash { + merkle::leaf_hash(&self.data_hash()) + } +} + +fn put_opt_text(buf: &mut Vec, text: Option<&str>) { + match text { + None => buf.push(0), + Some(value) => { + buf.push(1); + put_len_prefixed(buf, value.as_bytes()); + } + } +} + +/// The event count and Merkle root of one batch. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct BatchRoot { + pub count: u64, + pub root: Hash, +} + +/// Orders events by WAL sequence and returns their count and Merkle root; no events gives the +/// empty root. +pub fn batch_root(events: I) -> Result +where + I: IntoIterator, + I::Item: Borrow, +{ + let mut leaves: Vec<(u64, Hash)> = events + .into_iter() + .map(|event| (event.borrow().wal_sequence, event.borrow().leaf())) + .collect(); + leaves.sort_unstable_by_key(|&(sequence, _)| sequence); + for pair in leaves.windows(2) { + if let &[(first, _), (second, _)] = pair + && first == second + { + return Err(EventHashError::DuplicateSequence(first)); + } + } + let mut tree = Frontier::new(); + for &(_, leaf) in &leaves { + tree.append(leaf)?; + } + Ok(BatchRoot { + count: tree.leaf_count(), + root: tree.root(), + }) +} + +/// Outcome of checking recorded events against a batch entry. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[allow( + clippy::exhaustive_enums, + reason = "closed set: a new variant needs a new version, and every match must decide" +)] +pub enum BatchCheck { + Match, + Mismatch, + CountMismatch, +} + +/// Compares `events` with the count and root a batch entry holds; input order does not matter. +pub fn check_batch( + expected_count: u64, + expected_root: &Hash, + events: I, +) -> Result +where + I: IntoIterator, + I::Item: Borrow, +{ + let actual = batch_root(events)?; + Ok(if actual.count != expected_count { + BatchCheck::CountMismatch + } else if actual.root == *expected_root { + BatchCheck::Match + } else { + BatchCheck::Mismatch + }) +} diff --git a/daemoneye-lib/src/audit/merkle.rs b/daemoneye-lib/src/audit/merkle.rs new file mode 100644 index 00000000..1b5f2f0c --- /dev/null +++ b/daemoneye-lib/src/audit/merkle.rs @@ -0,0 +1,527 @@ +//! RFC 6962 Merkle tree over BLAKE3 with logarithmic append state. +//! +//! A leaf hashes as `H(0x00 || data)` and an interior node as `H(0x01 || left || right)`, so a +//! leaf can never be passed off as a node. The tree over `n` leaves splits at the largest power +//! of two strictly below `n`, which makes the root a fold over the peaks of a [`Frontier`]. + +use std::cmp::Reverse; + +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +/// A 32-byte BLAKE3 digest. +pub type Hash = [u8; 32]; + +const LEAF_PREFIX: u8 = 0x00; +const NODE_PREFIX: u8 = 0x01; + +/// Failures from frontier handling and proof generation. +#[derive(Debug, Error, PartialEq, Eq)] +#[non_exhaustive] +pub enum MerkleError { + #[error("the tree has no leaves")] + EmptyTree, + #[error("leaf index {index} is outside a tree of {total} leaves")] + IndexOutOfRange { index: u64, total: u64 }, + #[error("leaf source ended before the {total} leaves the tree holds")] + ShortLeafSource { total: u64 }, + #[error("{peaks} peaks cannot describe a frontier of {leaf_count} leaves")] + InvalidFrontier { leaf_count: u64, peaks: usize }, + #[error("the frontier already holds the maximum number of leaves")] + LeafCountOverflow, +} + +fn digest(prefix: u8, parts: &[&[u8]]) -> Hash { + let mut hasher = blake3::Hasher::new(); + hasher.update(&[prefix]); + for part in parts { + hasher.update(part); + } + hasher.finalize().into() +} + +/// Hash of a leaf's data: `H(0x00 || data)`. +#[must_use] +pub fn leaf_hash(data: &[u8]) -> Hash { + digest(LEAF_PREFIX, &[data]) +} + +/// Hash of an interior node: `H(0x01 || left || right)`. +#[must_use] +pub fn node_hash(left: &Hash, right: &Hash) -> Hash { + digest(NODE_PREFIX, &[left, right]) +} + +/// Root of a tree with no leaves: the BLAKE3 hash of empty input. +#[must_use] +pub fn empty_root() -> Hash { + blake3::hash(&[]).into() +} + +/// Largest power of two strictly below `n`, for `n >= 2`. +fn split_point(n: u64) -> u64 { + let bits = n.saturating_sub(1).checked_ilog2().unwrap_or(0); + 1_u64.checked_shl(bits).unwrap_or(1) +} + +/// The complete-subtree roots of a tree, largest first, plus the leaf count. +/// +/// The heights of the peaks are the set bits of the leaf count, so only the hashes are kept. +#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(try_from = "RawFrontier")] +pub struct Frontier { + leaf_count: u64, + peaks: Vec, +} + +#[derive(Deserialize)] +struct RawFrontier { + leaf_count: u64, + peaks: Vec, +} + +impl TryFrom for Frontier { + type Error = MerkleError; + + fn try_from(raw: RawFrontier) -> Result { + Self::from_parts(raw.leaf_count, raw.peaks) + } +} + +impl Frontier { + /// An empty frontier. + #[must_use] + pub const fn new() -> Self { + Self { + leaf_count: 0, + peaks: Vec::new(), + } + } + + /// Rebuild a frontier from persisted parts, rejecting a peak list that does not have one + /// peak per set bit of `leaf_count`. + pub fn from_parts(leaf_count: u64, peaks: Vec) -> Result { + let expected = usize::try_from(leaf_count.count_ones()).ok(); + if expected != Some(peaks.len()) { + return Err(MerkleError::InvalidFrontier { + leaf_count, + peaks: peaks.len(), + }); + } + Ok(Self { leaf_count, peaks }) + } + + /// Number of leaves appended so far. + #[must_use] + pub const fn leaf_count(&self) -> u64 { + self.leaf_count + } + + /// The peaks, largest subtree first. + #[must_use] + pub fn peaks(&self) -> &[Hash] { + &self.peaks + } + + /// Append an already-hashed leaf, merging peaks of equal height. + pub fn append(&mut self, leaf: Hash) -> Result<(), MerkleError> { + let new_count = self + .leaf_count + .checked_add(1) + .ok_or(MerkleError::LeafCountOverflow)?; + self.peaks.push(leaf); + for _ in 0..new_count.trailing_zeros() { + if let (Some(right), Some(left)) = (self.peaks.pop(), self.peaks.pop()) { + self.peaks.push(node_hash(&left, &right)); + } + } + self.leaf_count = new_count; + Ok(()) + } + + /// The tree root: the peaks folded right to left. + #[must_use] + pub fn root(&self) -> Hash { + let mut peaks = self.peaks.iter().rev(); + let Some(last) = peaks.next() else { + return empty_root(); + }; + peaks.fold(*last, |acc, peak| node_hash(peak, &acc)) + } +} + +/// The audit path for leaf `index` of `total`, in RFC 6962 order (deepest sibling first). +/// +/// Reads `leaves` once and holds O(log n) hashes, never the leaves themselves. +pub fn inclusion_path(index: u64, total: u64, leaves: I) -> Result, MerkleError> +where + I: IntoIterator, +{ + if total == 0 { + return Err(MerkleError::EmptyTree); + } + if index >= total { + return Err(MerkleError::IndexOutOfRange { index, total }); + } + + // Sibling ranges as (start, len), top-down; together with `index` they tile [0, total). + let mut ranges: Vec<(u64, u64)> = Vec::new(); + let (mut lo, mut n) = (0_u64, total); + while n > 1 { + let k = split_point(n); + if index.saturating_sub(lo) < k { + ranges.push((lo.saturating_add(k), n.saturating_sub(k))); + n = k; + } else { + ranges.push((lo, k)); + lo = lo.saturating_add(k); + n = n.saturating_sub(k); + } + } + + let mut order: Vec<(usize, (u64, u64))> = ranges.into_iter().enumerate().collect(); + order.sort_by_key(|&(_, (start, _))| start); + + let mut source = leaves.into_iter(); + let mut cursor = 0_u64; + let mut hashed: Vec<(usize, Hash)> = Vec::with_capacity(order.len()); + for (slot, (start, len)) in order { + for _ in 0..start.saturating_sub(cursor) { + source + .next() + .ok_or(MerkleError::ShortLeafSource { total })?; + } + let mut subtree = Frontier::new(); + for _ in 0..len { + let leaf = source + .next() + .ok_or(MerkleError::ShortLeafSource { total })?; + subtree.append(leaf)?; + } + cursor = start.saturating_add(len); + hashed.push((slot, subtree.root())); + } + + hashed.sort_by_key(|&(slot, _)| Reverse(slot)); + Ok(hashed.into_iter().map(|(_, hash)| hash).collect()) +} + +/// An inclusion proof that carries everything needed to check it offline. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Proof { + pub root: Hash, + pub index: u64, + pub total: u64, + pub leaf_hash: Hash, + pub siblings: Vec, +} + +impl Proof { + /// True when the siblings fold the leaf up to `root` along the path `(index, total)` fixes. + /// A sibling count that does not match the path, or `index >= total`, fails. + #[must_use] + pub fn verify(&self) -> bool { + if self.index >= self.total { + return false; + } + let mut node = self.index; + let mut last = self.total.saturating_sub(1); + let mut acc = self.leaf_hash; + for sibling in &self.siblings { + if last == 0 { + return false; + } + if node & 1 == 1 || node == last { + acc = node_hash(sibling, &acc); + while node & 1 == 0 && node != 0 { + node >>= 1; + last >>= 1; + } + } else { + acc = node_hash(&acc, sibling); + } + node >>= 1; + last >>= 1; + } + last == 0 && acc == self.root + } +} + +#[cfg(test)] +#[allow( + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::as_conversions, + clippy::indexing_slicing, + clippy::pattern_type_mismatch, + clippy::shadow_unrelated, + clippy::shadow_reuse, + clippy::redundant_clone, + clippy::arithmetic_side_effects +)] +mod tests { + use proptest::prelude::*; + use rs_merkle::{Hasher, MerkleTree}; + + use super::*; + + fn leaves(n: u64) -> Vec { + (0..n).map(|i| leaf_hash(&i.to_le_bytes())).collect() + } + + fn frontier_of(hashes: &[Hash]) -> Frontier { + let mut frontier = Frontier::new(); + for hash in hashes { + frontier.append(*hash).unwrap(); + } + frontier + } + + /// RFC 6962 MTH, straight from the definition. + fn reference_root(hashes: &[Hash]) -> Hash { + match hashes { + [] => empty_root(), + [only] => *only, + _ => { + let (left, right) = + hashes.split_at(usize::try_from(split_point(hashes.len() as u64)).unwrap()); + node_hash(&reference_root(left), &reference_root(right)) + } + } + } + + #[derive(Clone)] + struct Oracle; + + impl Hasher for Oracle { + type Hash = Hash; + + fn hash(data: &[u8]) -> Hash { + blake3::hash(data).into() + } + + fn concat_and_hash(left: &Hash, right: Option<&Hash>) -> Hash { + right.map_or(*left, |right| node_hash(left, right)) + } + } + + fn proof_for(hashes: &[Hash], index: u64) -> Proof { + let total = hashes.len() as u64; + Proof { + root: frontier_of(hashes).root(), + index, + total, + leaf_hash: hashes[usize::try_from(index).unwrap()], + siblings: inclusion_path(index, total, hashes.iter().copied()).unwrap(), + } + } + + #[test] + fn frontier_root_matches_rfc_6962_definition_for_1_to_65_leaves() { + for n in 1..=65 { + let hashes = leaves(n); + assert_eq!( + frontier_of(&hashes).root(), + reference_root(&hashes), + "n={n}" + ); + } + } + + #[test] + fn root_matches_rs_merkle_oracle_for_1_to_65_leaves() { + for n in 1..=65 { + let hashes = leaves(n); + let oracle = MerkleTree::::from_leaves(&hashes).root().unwrap(); + assert_eq!(frontier_of(&hashes).root(), oracle, "n={n}"); + } + } + + #[test] + fn every_proof_verifies_and_every_single_mutation_fails() { + for n in 1..=33_u64 { + let hashes = leaves(n); + for index in 0..n { + let proof = proof_for(&hashes, index); + assert!(proof.verify(), "n={n} index={index}"); + + for byte in 0..32 { + let mut bad = proof.clone(); + bad.leaf_hash[byte] ^= 1; + assert!(!bad.verify(), "leaf byte {byte} n={n} i={index}"); + let mut bad = proof.clone(); + bad.root[byte] ^= 1; + assert!(!bad.verify(), "root byte {byte} n={n} i={index}"); + for s in 0..proof.siblings.len() { + let mut bad = proof.clone(); + bad.siblings[s][byte] ^= 1; + assert!(!bad.verify(), "sibling {s} byte {byte} n={n} i={index}"); + } + } + let mut bad = proof.clone(); + bad.index = index + 1; + assert!(!bad.verify(), "index+1 n={n} i={index}"); + // A total with the same path length for this index is indistinguishable from + // the real one (the sibling just names a subtree), so only a different path + // length must fail. + for total in [n + 1, n - 1] { + if total <= index { + continue; + } + let dummy = std::iter::repeat_n([0_u8; 32], usize::try_from(total).unwrap()); + let len = inclusion_path(index, total, dummy).unwrap().len(); + if len != proof.siblings.len() { + let bad = Proof { + total, + ..proof.clone() + }; + assert!(!bad.verify(), "total {total} n={n} i={index}"); + } + } + let mut bad = proof.clone(); + bad.siblings.push([0; 32]); + assert!(!bad.verify(), "extra sibling n={n} i={index}"); + if !proof.siblings.is_empty() { + let mut bad = proof.clone(); + bad.siblings.pop(); + assert!(!bad.verify(), "missing sibling n={n} i={index}"); + } + } + } + } + + #[test] + fn proof_for_index_3_of_8_does_not_verify_as_index_3_of_9() { + let proof = proof_for(&leaves(8), 3); + assert!(proof.verify()); + let as_nine = Proof { total: 9, ..proof }; + assert!(!as_nine.verify()); + } + + #[test] + fn index_at_or_past_total_never_verifies() { + let proof = proof_for(&leaves(4), 3); + assert!( + !Proof { + index: 4, + ..proof.clone() + } + .verify() + ); + assert!( + !Proof { + index: u64::MAX, + total: u64::MAX, + ..proof + } + .verify() + ); + } + + #[test] + fn leaf_data_shaped_like_two_nodes_does_not_hash_to_their_parent() { + let (a, b) = (leaf_hash(b"a"), leaf_hash(b"b")); + let parent = node_hash(&a, &b); + let forged = leaf_hash(&[a.as_slice(), b.as_slice()].concat()); + assert_ne!(forged, parent); + } + + #[test] + fn million_appends_keep_at_most_20_peaks() { + let mut frontier = Frontier::new(); + let leaf = leaf_hash(b"x"); + for _ in 0..1_000_000 { + frontier.append(leaf).unwrap(); + } + assert_eq!(frontier.leaf_count(), 1_000_000); + assert!( + frontier.peaks().len() <= 20, + "peaks={}", + frontier.peaks().len() + ); + } + + #[test] + fn frontier_with_mismatched_peak_list_is_rejected() { + let built = frontier_of(&leaves(6)); + let mut extra = built.peaks().to_vec(); + extra.push([0; 32]); + assert_eq!( + Frontier::from_parts(6, extra), + Err(MerkleError::InvalidFrontier { + leaf_count: 6, + peaks: 3 + }) + ); + assert_eq!( + Frontier::from_parts(6, Vec::new()), + Err(MerkleError::InvalidFrontier { + leaf_count: 6, + peaks: 0 + }) + ); + assert_eq!( + Frontier::from_parts(0, vec![[0; 32]]), + Err(MerkleError::InvalidFrontier { + leaf_count: 0, + peaks: 1 + }) + ); + let json = r#"{"leaf_count":3,"peaks":[]}"#; + assert!(serde_json::from_str::(json).is_err()); + } + + #[test] + fn serde_round_trip_preserves_frontier_and_proof() { + let frontier = frontier_of(&leaves(11)); + let json = serde_json::to_string(&frontier).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), frontier); + + let proof = proof_for(&leaves(11), 6); + let json = serde_json::to_string(&proof).unwrap(); + let back: Proof = serde_json::from_str(&json).unwrap(); + assert_eq!(back, proof); + assert!(back.verify()); + } + + #[test] + fn empty_tree_root_is_blake3_of_empty_input_and_has_no_proofs() { + assert_eq!(Frontier::new().root(), <[u8; 32]>::from(blake3::hash(b""))); + for index in [0, 1, u64::MAX] { + assert_eq!( + inclusion_path(index, 0, std::iter::empty()), + Err(MerkleError::EmptyTree) + ); + } + } + + #[test] + fn proof_generation_rejects_bad_index_and_short_source() { + assert_eq!( + inclusion_path(5, 5, leaves(5)), + Err(MerkleError::IndexOutOfRange { index: 5, total: 5 }) + ); + assert_eq!( + inclusion_path(2, 5, leaves(4)), + Err(MerkleError::ShortLeafSource { total: 5 }) + ); + } + + proptest! { + #[test] + fn rebuilt_frontier_equals_appended_and_streamed_proof_verifies( + n in 1_u64..200, + pick in any::(), + ) { + let hashes = leaves(n); + let built = frontier_of(&hashes); + let rebuilt = Frontier::from_parts(built.leaf_count(), built.peaks().to_vec()).unwrap(); + prop_assert_eq!(&built, &rebuilt); + + let proof = proof_for(&hashes, pick % n); + prop_assert!(proof.verify()); + prop_assert_eq!(proof.root, rebuilt.root()); + } + } +} diff --git a/daemoneye-lib/src/audit/mod.rs b/daemoneye-lib/src/audit/mod.rs index ef214ef9..0f5c30dd 100644 --- a/daemoneye-lib/src/audit/mod.rs +++ b/daemoneye-lib/src/audit/mod.rs @@ -1,5 +1,13 @@ -//! Audit ledger read access. The writer lives in another crate; this module only reads. +//! Audit ledger types, hashing and read access. The writer lives in procmond; nothing here opens the ledger for writing. +pub mod checkpoint; mod db; +pub mod entry; +pub mod event_hash; +pub mod merkle; +pub mod reader; +pub mod signing; +pub mod tables; +pub mod verify; pub use db::{LedgerReadError, open_ledger_read_only}; diff --git a/daemoneye-lib/src/audit/reader.rs b/daemoneye-lib/src/audit/reader.rs new file mode 100644 index 00000000..95f6041a --- /dev/null +++ b/daemoneye-lib/src/audit/reader.rs @@ -0,0 +1,263 @@ +//! Read-only access to a ledger file: entries, checkpoints and the format version. +//! +//! Every call opens one short read transaction and closes it before returning. Nothing here +//! writes, and every row is treated as untrusted bytes. + +use std::error::Error as StdError; +use std::path::Path; + +use redb::{ + Key, ReadOnlyDatabase, ReadOnlyTable, ReadTransaction, ReadableDatabase, ReadableTable, + TableDefinition, TableError, Value, +}; +use thiserror::Error; + +use super::LedgerReadError; +use super::checkpoint::{Checkpoint, CheckpointError}; +use super::db::open_ledger_read_only; +use super::entry::{Entry, EntryError}; +use super::tables::{ + AUDIT_CHECKPOINTS, AUDIT_LEDGER, AUDIT_META, LEDGER_FORMAT_VERSION, META_FORMAT_VERSION, +}; + +/// Page cache for a reading handle; redb's default is 1 GiB. +const READER_CACHE_BYTES: usize = 4 * 1024 * 1024; +/// Rows copied out of one read transaction when streaming entries. +const PAGE_ROWS: usize = 256; + +/// Why a ledger could not be read. +#[derive(Debug, Error)] +#[non_exhaustive] +pub enum ReaderError { + /// The file could not be opened. + #[error(transparent)] + Open(#[from] LedgerReadError), + /// The file's format version is not the one this build reads. + #[error( + "ledger file format version {found} is not supported (this build reads {LEDGER_FORMAT_VERSION})" + )] + UnsupportedFormat { found: u64 }, + /// The file has rows but no format version row. + #[error("ledger holds rows but no format version")] + MissingFormatVersion, + /// The storage engine failed a read. + #[error("ledger storage read failed: {0}")] + Storage(#[source] Box), + /// An entry row's bytes do not decode. + #[error("entry row {seq} cannot be decoded: {source}")] + CorruptEntry { + seq: u64, + #[source] + source: EntryError, + }, + /// A checkpoint row's bytes do not decode. + #[error("checkpoint row {tree_size} cannot be decoded: {source}")] + CorruptCheckpoint { + tree_size: u64, + #[source] + source: CheckpointError, + }, +} + +fn storage(error: E) -> ReaderError { + ReaderError::Storage(Box::new(error)) +} + +/// A table that has not been created yet reads as empty. +fn open_table( + txn: &ReadTransaction, + definition: TableDefinition<'static, K, V>, +) -> Result>, ReaderError> { + match txn.open_table(definition) { + Ok(table) => Ok(Some(table)), + Err(TableError::TableDoesNotExist(_name)) => Ok(None), + Err(other) => Err(storage(other)), + } +} + +/// A read-only handle on a ledger file. +pub struct LedgerReader { + db: ReadOnlyDatabase, +} + +impl std::fmt::Debug for LedgerReader { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("LedgerReader").finish_non_exhaustive() + } +} + +impl LedgerReader { + /// Open the ledger at `path` and check its format version. A freshly created file with no + /// rows has no version row yet and opens fine. + pub fn open(path: &Path) -> Result { + let reader = Self { + db: open_ledger_read_only(path, READER_CACHE_BYTES)?, + }; + reader.check_format()?; + Ok(reader) + } + + fn begin(&self) -> Result { + self.db.begin_read().map_err(storage) + } + + fn check_format(&self) -> Result<(), ReaderError> { + let txn = self.begin()?; + let version = match open_table(&txn, AUDIT_META)? { + Some(table) => table + .get(META_FORMAT_VERSION) + .map_err(storage)? + .map(|guard| guard.value()), + None => None, + }; + match version { + Some(found) if found == LEDGER_FORMAT_VERSION => Ok(()), + Some(found) => Err(ReaderError::UnsupportedFormat { found }), + None => { + let has_entries = match open_table(&txn, AUDIT_LEDGER)? { + Some(table) => table.first().map_err(storage)?.is_some(), + None => false, + }; + let has_checkpoints = match open_table(&txn, AUDIT_CHECKPOINTS)? { + Some(table) => table.first().map_err(storage)?.is_some(), + None => false, + }; + if has_entries || has_checkpoints { + Err(ReaderError::MissingFormatVersion) + } else { + Ok(()) + } + } + } + } + + /// One more than the highest stored sequence; 0 for an empty ledger. A ledger with holes + /// still reports its high end, so the holes show up as verification failures. + pub fn entry_count(&self) -> Result { + let txn = self.begin()?; + let Some(table) = open_table(&txn, AUDIT_LEDGER)? else { + return Ok(0); + }; + let last = table.last().map_err(storage)?; + Ok(last.map_or(0, |(key, _value)| key.value().saturating_add(1))) + } + + /// The decoded entry stored under `seq`. + pub fn entry(&self, seq: u64) -> Result, ReaderError> { + let txn = self.begin()?; + let Some(table) = open_table(&txn, AUDIT_LEDGER)? else { + return Ok(None); + }; + let Some(row) = table.get(seq).map_err(storage)? else { + return Ok(None); + }; + Entry::decode(row.value()) + .map(Some) + .map_err(|source| ReaderError::CorruptEntry { seq, source }) + } + + /// Raw entry rows with keys at or above `from`, in key order, read a page per transaction. + /// Memory is one page: `PAGE_ROWS` rows, however long the ledger. + #[must_use] + pub fn entries(&self, from: u64) -> EntryRows<'_> { + EntryRows { + reader: self, + next_key: from, + page: Vec::new().into_iter(), + exhausted: false, + } + } + + /// The smallest checkpoint tree size at or above `from`. + pub fn next_checkpoint_size(&self, from: u64) -> Result, ReaderError> { + let txn = self.begin()?; + let Some(table) = open_table(&txn, AUDIT_CHECKPOINTS)? else { + return Ok(None); + }; + let mut range = table.range(from..).map_err(storage)?; + match range.next() { + Some(row) => Ok(Some(row.map_err(storage)?.0.value())), + None => Ok(None), + } + } + + /// The checkpoint stored for `tree_size`. + pub fn checkpoint(&self, tree_size: u64) -> Result, ReaderError> { + let txn = self.begin()?; + let Some(table) = open_table(&txn, AUDIT_CHECKPOINTS)? else { + return Ok(None); + }; + let Some(row) = table.get(tree_size).map_err(storage)? else { + return Ok(None); + }; + Checkpoint::decode(row.value()) + .map(Some) + .map_err(|source| ReaderError::CorruptCheckpoint { tree_size, source }) + } + + /// The checkpoint with the largest tree size. + pub fn latest_checkpoint(&self) -> Result, ReaderError> { + let size = { + let txn = self.begin()?; + let Some(table) = open_table(&txn, AUDIT_CHECKPOINTS)? else { + return Ok(None); + }; + let last = table.last().map_err(storage)?; + last.map(|(key, _value)| key.value()) + }; + size.map_or(Ok(None), |tree_size| self.checkpoint(tree_size)) + } +} + +/// Raw `(sequence, bytes)` entry rows, loaded one page at a time. +pub struct EntryRows<'a> { + reader: &'a LedgerReader, + next_key: u64, + page: std::vec::IntoIter<(u64, Vec)>, + exhausted: bool, +} + +impl EntryRows<'_> { + fn load_page(&self) -> Result)>, ReaderError> { + let txn = self.reader.begin()?; + let Some(table) = open_table(&txn, AUDIT_LEDGER)? else { + return Ok(Vec::new()); + }; + let mut rows = Vec::with_capacity(PAGE_ROWS); + for row in table + .range(self.next_key..) + .map_err(storage)? + .take(PAGE_ROWS) + { + let (key, value) = row.map_err(storage)?; + rows.push((key.value(), value.value().to_vec())); + } + Ok(rows) + } +} + +impl Iterator for EntryRows<'_> { + type Item = Result<(u64, Vec), ReaderError>; + + fn next(&mut self) -> Option { + if let Some(row) = self.page.next() { + return Some(Ok(row)); + } + if self.exhausted { + return None; + } + let rows = match self.load_page() { + Ok(rows) => rows, + Err(error) => { + self.exhausted = true; + return Some(Err(error)); + } + }; + self.exhausted = rows.len() < PAGE_ROWS; + self.next_key = rows + .last() + .map_or(self.next_key, |&(key, _)| key.saturating_add(1)); + self.page = rows.into_iter(); + self.page.next().map(Ok) + } +} diff --git a/daemoneye-lib/src/audit/signing.rs b/daemoneye-lib/src/audit/signing.rs new file mode 100644 index 00000000..0f118eb0 --- /dev/null +++ b/daemoneye-lib/src/audit/signing.rs @@ -0,0 +1,487 @@ +//! The checkpoint signing key and the signing state it yields. +//! +//! The key is a 32-byte Ed25519 seed in a file beside the ledger. It is created once, when the +//! ledger is empty, and never regenerated or re-permissioned: a key that is missing from a +//! non-empty ledger, unreadable, too permissive or the wrong length leaves checkpoints unsigned, +//! so a deleted key cannot be silently replaced by one the ledger's history never saw. + +use std::fs::{self, File, OpenOptions}; +use std::io::{Read as _, Write as _}; +use std::path::Path; + +use ed25519_dalek::{Signature, Signer as _, SigningKey, VerifyingKey}; +use secrecy::{ExposeSecret as _, SecretBox}; +use serde::{Deserialize, Serialize}; +use zeroize::Zeroize as _; + +use super::merkle::Hash; + +/// Seed length in bytes. +pub const SEED_LEN: usize = 32; +/// Public key length in bytes. +pub const PUBLIC_KEY_LEN: usize = 32; +/// Signature length in bytes. +pub const SIGNATURE_LEN: usize = 64; + +/// Mode bits a key file must not carry: everything except owner read. +#[cfg(unix)] +const FORBIDDEN_MODE_BITS: u32 = 0o377; +#[cfg(unix)] +const KEY_FILE_MODE: u32 = 0o400; + +/// The BLAKE3 hash of a public key; names a signing key without carrying it. +pub type KeyId = Hash; + +/// How a checkpoint was signed, recorded inside the checkpoint. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[allow( + clippy::exhaustive_enums, + reason = "closed set: every match must decide each case" +)] +pub enum SigningState { + /// Signed; carries the public key that verifies the signature. + Signed { + public_key: [u8; PUBLIC_KEY_LEN], + #[serde(with = "signature_bytes")] + signature: [u8; SIGNATURE_LEN], + }, + /// Signing is switched off in configuration. + UnsignedByConfig, + /// Signing is on but the key could not be used. + UnsignedKeyFailed, +} + +/// Why the key could not be used. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[allow( + clippy::exhaustive_enums, + reason = "closed set: every match must decide each case" +)] +pub enum KeyFailure { + /// No key file, and the ledger already holds entries. + Missing, + /// The key file exists but could not be opened or read. + Unreadable, + /// The key file allows more than owner read. + ModeTooWide, + /// The key file is not exactly one seed long. + WrongLength, + /// A new key file could not be created. + CreateFailed, +} + +/// What the writer gets at start. +#[derive(Debug)] +#[allow( + clippy::exhaustive_enums, + reason = "closed set: every match must decide each case" +)] +pub enum KeyOutcome { + /// A usable signer. `created` is true when this call generated the key. + Signer { + signer: CheckpointSigner, + created: bool, + }, + UnsignedByConfig, + KeyFailed(KeyFailure), +} + +/// What a checkpoint is built with. +#[derive(Debug, Clone, Copy)] +#[allow( + clippy::exhaustive_enums, + reason = "closed set: every match must decide each case" +)] +pub enum SigningMode<'a> { + Signed(&'a CheckpointSigner), + UnsignedByConfig, + UnsignedKeyFailed, +} + +/// An Ed25519 signer. The seed lives in a [`SecretBox`] and the signing key is derived only +/// while signing. +#[derive(Debug)] +pub struct CheckpointSigner { + seed: SecretBox<[u8; SEED_LEN]>, + public_key: [u8; PUBLIC_KEY_LEN], +} + +impl CheckpointSigner { + fn from_seed(seed: Box<[u8; SEED_LEN]>) -> Self { + let public_key = SigningKey::from_bytes(&seed).verifying_key().to_bytes(); + Self { + seed: SecretBox::new(seed), + public_key, + } + } + + /// The public key that verifies this signer's signatures. + #[must_use] + pub const fn public_key(&self) -> &[u8; PUBLIC_KEY_LEN] { + &self.public_key + } + + /// The id of this signer's public key. + #[must_use] + pub fn key_id(&self) -> KeyId { + key_id(&self.public_key) + } + + /// Sign `message` and return the resulting signing state. + #[must_use] + pub fn sign(&self, message: &[u8]) -> SigningState { + let key = SigningKey::from_bytes(self.seed.expose_secret()); + SigningState::Signed { + public_key: self.public_key, + signature: key.sign(message).to_bytes(), + } + } +} + +/// The id of a public key. +#[must_use] +pub fn key_id(public_key: &[u8; PUBLIC_KEY_LEN]) -> KeyId { + blake3::hash(public_key).into() +} + +/// Check a signature with `verify_strict`. A malformed public key is a failed check. +#[must_use] +pub fn verify_signature( + public_key: &[u8; PUBLIC_KEY_LEN], + message: &[u8], + signature: &[u8; SIGNATURE_LEN], +) -> bool { + VerifyingKey::from_bytes(public_key).is_ok_and(|key| { + key.verify_strict(message, &Signature::from_bytes(signature)) + .is_ok() + }) +} + +/// Decide the signing state at start. +/// +/// With signing off the key file is not read. With signing on, a key is created only when no key +/// file exists and the ledger is empty; every other failure leaves the filesystem untouched. +#[must_use] +pub fn resolve_key(signing_enabled: bool, key_path: &Path, ledger_is_empty: bool) -> KeyOutcome { + if !signing_enabled { + return KeyOutcome::UnsignedByConfig; + } + match File::open(key_path) { + Ok(file) => match load_seed(file) { + Ok(seed) => KeyOutcome::Signer { + signer: CheckpointSigner::from_seed(seed), + created: false, + }, + Err(failure) => KeyOutcome::KeyFailed(failure), + }, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + if ledger_is_empty { + create_key(key_path) + } else { + KeyOutcome::KeyFailed(KeyFailure::Missing) + } + } + Err(_error) => KeyOutcome::KeyFailed(KeyFailure::Unreadable), + } +} + +/// Check the mode of the open file, then read exactly one seed. +fn load_seed(mut file: File) -> Result, KeyFailure> { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + let metadata = file.metadata().map_err(|_error| KeyFailure::Unreadable)?; + if metadata.permissions().mode() & FORBIDDEN_MODE_BITS != 0 { + return Err(KeyFailure::ModeTooWide); + } + } + let mut bytes = Vec::with_capacity(SEED_LEN); + // One byte past the seed length detects an over-long file without reading it all. + let limit = u64::try_from(SEED_LEN) + .unwrap_or(u64::MAX) + .saturating_add(1); + let read = (&mut file).take(limit).read_to_end(&mut bytes); + let seed = match read { + Ok(_count) => <[u8; SEED_LEN]>::try_from(bytes.as_slice()) + .map(Box::new) + .map_err(|_error| KeyFailure::WrongLength), + Err(_error) => Err(KeyFailure::Unreadable), + }; + bytes.zeroize(); + seed +} + +fn create_key(key_path: &Path) -> KeyOutcome { + let mut seed = Box::new([0_u8; SEED_LEN]); + if getrandom::fill(seed.as_mut_slice()).is_err() { + return KeyOutcome::KeyFailed(KeyFailure::CreateFailed); + } + if write_new_key_file(key_path, seed.as_slice()).is_err() { + seed.zeroize(); + return KeyOutcome::KeyFailed(KeyFailure::CreateFailed); + } + KeyOutcome::Signer { + signer: CheckpointSigner::from_seed(seed), + created: true, + } +} + +#[cfg(unix)] +fn restrict_mode(options: &mut OpenOptions) { + use std::os::unix::fs::OpenOptionsExt as _; + options.mode(KEY_FILE_MODE); +} + +/// Non-Unix targets rely on the directory's inherited ACL. +#[cfg(not(unix))] +const fn restrict_mode(_options: &mut OpenOptions) {} + +/// Create the file exclusively with its final mode in the same `open`, so it is never observable +/// at a wider mode. A partial file left by a failed write is removed so it cannot pose as a key. +fn write_new_key_file(path: &Path, seed: &[u8]) -> std::io::Result<()> { + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + restrict_mode(&mut options); + let mut file = options.open(path)?; + let written = file.write_all(seed).and_then(|()| file.sync_all()); + if let Err(error) = written { + drop(file); + if let Err(remove_error) = fs::remove_file(path) { + tracing::warn!(%remove_error, "could not remove a partially written audit key file"); + } + return Err(error); + } + Ok(()) +} + +/// Serde for a 64-byte array, which serde does not implement natively. +mod signature_bytes { + use std::fmt; + + use serde::de::{Error as _, SeqAccess, Visitor}; + use serde::ser::SerializeTuple as _; + use serde::{Deserializer, Serializer}; + + use super::SIGNATURE_LEN; + + pub(super) fn serialize( + bytes: &[u8; SIGNATURE_LEN], + serializer: S, + ) -> Result { + let mut tuple = serializer.serialize_tuple(SIGNATURE_LEN)?; + for byte in bytes { + tuple.serialize_element(byte)?; + } + tuple.end() + } + + pub(super) fn deserialize<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result<[u8; SIGNATURE_LEN], D::Error> { + struct ArrayVisitor; + + impl<'de> Visitor<'de> for ArrayVisitor { + type Value = [u8; SIGNATURE_LEN]; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "{SIGNATURE_LEN} bytes") + } + + fn visit_seq>(self, mut seq: A) -> Result { + let mut out = [0_u8; SIGNATURE_LEN]; + for slot in &mut out { + *slot = seq + .next_element()? + .ok_or_else(|| A::Error::custom("signature too short"))?; + } + Ok(out) + } + } + + deserializer.deserialize_tuple(SIGNATURE_LEN, ArrayVisitor) + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use std::fmt::Write as _; + + use super::*; + + fn key_path(dir: &tempfile::TempDir) -> std::path::PathBuf { + dir.path().join("audit.key") + } + + #[cfg(unix)] + fn mode_of(path: &Path) -> u32 { + use std::os::unix::fs::PermissionsExt as _; + fs::metadata(path).unwrap().permissions().mode() & 0o777 + } + + #[cfg(unix)] + fn set_mode(path: &Path, mode: u32) { + use std::os::unix::fs::PermissionsExt as _; + fs::set_permissions(path, fs::Permissions::from_mode(mode)).unwrap(); + } + + fn expect_signer(outcome: KeyOutcome) -> (CheckpointSigner, bool) { + match outcome { + KeyOutcome::Signer { signer, created } => (signer, created), + KeyOutcome::UnsignedByConfig => panic!("unexpected UnsignedByConfig"), + KeyOutcome::KeyFailed(failure) => panic!("unexpected key failure {failure:?}"), + } + } + + #[test] + fn creates_a_key_on_an_empty_ledger_then_reloads_the_same_one() { + let dir = tempfile::tempdir().unwrap(); + let path = key_path(&dir); + + let (first, created) = expect_signer(resolve_key(true, &path, true)); + assert!(created, "first call must report the key as created"); + assert_eq!(fs::read(&path).unwrap().len(), SEED_LEN); + #[cfg(unix)] + assert_eq!(mode_of(&path), 0o400); + + let (second, created_again) = expect_signer(resolve_key(true, &path, false)); + assert!(!created_again, "second call must load, not create"); + assert_eq!(first.key_id(), second.key_id()); + } + + #[test] + fn missing_key_on_a_non_empty_ledger_fails_and_creates_nothing() { + let dir = tempfile::tempdir().unwrap(); + let path = key_path(&dir); + + let outcome = resolve_key(true, &path, false); + + assert!(matches!( + outcome, + KeyOutcome::KeyFailed(KeyFailure::Missing) + )); + assert!(!path.exists(), "a missing key must not be regenerated"); + } + + #[test] + fn signing_off_does_not_read_the_key_file() { + let dir = tempfile::tempdir().unwrap(); + let path = key_path(&dir); + fs::write(&path, b"not a key, and not 32 bytes").unwrap(); + + assert!(matches!( + resolve_key(false, &path, true), + KeyOutcome::UnsignedByConfig + )); + assert!(matches!( + resolve_key(false, &path, false), + KeyOutcome::UnsignedByConfig + )); + } + + #[test] + fn signing_off_with_a_valid_key_is_still_unsigned_by_config() { + let dir = tempfile::tempdir().unwrap(); + let path = key_path(&dir); + expect_signer(resolve_key(true, &path, true)); + + assert!(matches!( + resolve_key(false, &path, false), + KeyOutcome::UnsignedByConfig + )); + } + + #[test] + fn wrong_length_key_file_fails_for_short_and_long() { + let dir = tempfile::tempdir().unwrap(); + let path = key_path(&dir); + for len in [0_usize, 31, 33, 64] { + fs::remove_file(&path).ok(); + fs::write(&path, vec![7_u8; len]).unwrap(); + #[cfg(unix)] + set_mode(&path, 0o400); + for empty in [true, false] { + assert!( + matches!( + resolve_key(true, &path, empty), + KeyOutcome::KeyFailed(KeyFailure::WrongLength) + ), + "length {len}, empty ledger {empty}" + ); + } + } + } + + #[cfg(unix)] + #[test] + fn key_file_wider_than_owner_read_fails_and_keeps_its_mode() { + let dir = tempfile::tempdir().unwrap(); + let path = key_path(&dir); + for mode in [0o440, 0o404, 0o600, 0o644] { + fs::remove_file(&path).ok(); + fs::write(&path, [9_u8; SEED_LEN]).unwrap(); + set_mode(&path, mode); + for empty in [true, false] { + assert!( + matches!( + resolve_key(true, &path, empty), + KeyOutcome::KeyFailed(KeyFailure::ModeTooWide) + ), + "mode {mode:o}, empty ledger {empty}" + ); + assert_eq!(mode_of(&path), mode); + } + } + } + + #[test] + fn signature_verifies_and_a_changed_message_or_byte_does_not() { + let dir = tempfile::tempdir().unwrap(); + let (signer, _created) = expect_signer(resolve_key(true, &key_path(&dir), true)); + let SigningState::Signed { + public_key, + signature, + } = signer.sign(b"message") + else { + panic!("a signer must produce Signed"); + }; + + assert!(verify_signature(&public_key, b"message", &signature)); + assert!(!verify_signature(&public_key, b"messagE", &signature)); + let mut flipped = signature; + *flipped.last_mut().unwrap() ^= 1; + assert!(!verify_signature(&public_key, b"message", &flipped)); + assert_eq!(signer.key_id(), key_id(&public_key)); + } + + #[test] + fn debug_output_reveals_no_seed_bytes() { + let seed = [0xA7_u8, 0x3C, 0x91, 0x5E, 0x02, 0xD8, 0x4B, 0xF6] + .into_iter() + .cycle() + .take(SEED_LEN) + .collect::>(); + let boxed: Box<[u8; SEED_LEN]> = Box::new(seed.as_slice().try_into().unwrap()); + let signer = CheckpointSigner::from_seed(boxed); + + let shown = format!("{signer:?} {:#?}", signer.seed); + + let hex = seed.iter().fold(String::new(), |mut out, byte| { + write!(out, "{byte:02x}").unwrap(); + out + }); + let decimal = seed + .iter() + .map(u8::to_string) + .collect::>() + .join(", "); + let hex_head: String = hex.chars().take(16).collect(); + let decimal_head: String = decimal.chars().take(20).collect(); + assert!( + !shown.to_lowercase().contains(&hex_head), + "hex leaked: {shown}" + ); + assert!(!shown.contains(&decimal_head), "decimal leaked: {shown}"); + assert!(shown.contains("REDACTED"), "{shown}"); + } +} diff --git a/daemoneye-lib/src/audit/tables.rs b/daemoneye-lib/src/audit/tables.rs new file mode 100644 index 00000000..a2ae7a40 --- /dev/null +++ b/daemoneye-lib/src/audit/tables.rs @@ -0,0 +1,28 @@ +//! The ledger file's table layout, shared by the writer in procmond and the readers here. +//! +//! Values are the versioned byte encodings produced by `Entry::encode`, `Checkpoint::encode` +//! and the serialised `Frontier`; redb never sees the record types. + +use redb::TableDefinition; + +/// Ledger entries, keyed by sequence number. +pub const AUDIT_LEDGER: TableDefinition<'static, u64, &'static [u8]> = + TableDefinition::new("audit_ledger"); + +/// Checkpoints, keyed by the tree size they cover. +pub const AUDIT_CHECKPOINTS: TableDefinition<'static, u64, &'static [u8]> = + TableDefinition::new("audit_checkpoints"); + +/// The current frontier of the ledger tree: one row. +pub const AUDIT_FRONTIER: TableDefinition<'static, (), &'static [u8]> = + TableDefinition::new("audit_frontier"); + +/// Ledger file metadata: one row per key in [`META_FORMAT_VERSION`]. +pub const AUDIT_META: TableDefinition<'static, &'static str, u64> = + TableDefinition::new("audit_meta"); + +/// Key of the ledger file format version in [`AUDIT_META`]. +pub const META_FORMAT_VERSION: &str = "format_version"; + +/// The ledger file format this build reads and writes. +pub const LEDGER_FORMAT_VERSION: u64 = 1; diff --git a/daemoneye-lib/src/audit/verify.rs b/daemoneye-lib/src/audit/verify.rs new file mode 100644 index 00000000..341847cc --- /dev/null +++ b/daemoneye-lib/src/audit/verify.rs @@ -0,0 +1,591 @@ +//! Verification of a ledger: the hash chain, the Merkle roots, checkpoints and their signatures. +//! +//! A `Consistent` result means the ledger agrees with itself. It is not proof of integrity: see +//! [`CAVEAT`]. + +use std::fmt; + +use thiserror::Error; + +use super::checkpoint::CheckpointVerdict; +use super::checkpoint::{ExportBlob, SignatureVerdict}; +use super::entry::{Entry, GENESIS_PREV_HASH}; +use super::merkle::{self, Frontier, Hash, MerkleError, Proof}; +use super::reader::{LedgerReader, ReaderError}; +use super::signing::KeyId; + +/// Timestamp regressions listed individually; further ones are only counted. +pub const MAX_TIMESTAMP_NOTES: usize = 1024; + +/// What a consistent result does and does not show. +pub const CAVEAT: &str = "The ledger agrees with itself. Anyone able to write both the ledger \ +file and the signing key file could have rebuilt every entry, root, checkpoint and signature under \ +the same key id. A trusted key id detects a ledger rebuilt under a different key or with signing \ +off; it does not detect a same-key rewrite or a cut back to an earlier checkpoint. Only a \ +checkpoint kept off the host does, and only for the history it covers. Entries after the last \ +checkpoint are not signed."; + +/// The seven internal checks, in the order they are applied. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[allow( + clippy::exhaustive_enums, + reason = "closed set: every match must decide each case" +)] +pub enum Check { + /// Sequences are not consecutive from 0, or a row's key differs from its sequence. + SequenceGap, + /// An entry cannot be decoded or its hash does not match its content. + EntryHash, + /// An entry's `prev_hash` is not the previous entry's hash. + ChainLink, + /// An entry's recorded tree size or root differs from the recomputed one. + MerkleRoot, + /// A checkpoint is missing, undecodable, or disagrees with the recomputed tree. + CheckpointRoot, + /// A checkpoint's signature does not verify. + CheckpointSignature, + /// A checkpoint is not signed by the trusted key id. + CheckpointKey, +} + +impl Check { + #[must_use] + pub const fn name(self) -> &'static str { + match self { + Self::SequenceGap => "sequence gap", + Self::EntryHash => "entry hash", + Self::ChainLink => "chain link", + Self::MerkleRoot => "Merkle root", + Self::CheckpointRoot => "checkpoint root", + Self::CheckpointSignature => "checkpoint signature", + Self::CheckpointKey => "checkpoint key", + } + } +} + +impl fmt::Display for Check { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.name()) + } +} + +/// The first check that failed. `at` is the entry sequence, or the tree size of the checkpoint +/// for the three checkpoint checks. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub struct Failure { + /// Entry sequence, or checkpoint tree size. + pub at: u64, + /// The check that failed. + pub check: Check, +} + +/// How a checkpoint was signed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[allow( + clippy::exhaustive_enums, + reason = "closed set: every match must decide each case" +)] +pub enum CheckpointSigning { + /// Carries a valid signature from this key. + Signed { key_id: KeyId }, + /// Signing was off; the checkpoint carries no signature. + UnsignedByConfig, + /// Signing was on but the key failed to load; the checkpoint carries no signature. + UnsignedKeyFailed, +} + +/// One checkpoint that passed every check. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub struct CheckpointSummary { + /// Entries covered by the checkpoint. + pub tree_size: u64, + /// How the checkpoint was signed. + pub signing: CheckpointSigning, +} + +/// What a ledger that agrees with itself looks like. [`Report::caveat`] says what that is +/// worth; show it with the result. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Report { + /// Entries read. Those after the last checkpoint are covered by no signature. + pub entry_count: u64, + /// The root recomputed from every entry; the empty-tree root for an empty ledger. + pub final_root: Hash, + /// Every checkpoint in tree-size order; signed only up to the last one. + pub checkpoints: Vec, + /// Tree sizes of checkpoints signed by a different key than the previous signed one. + pub key_changes: Vec, + /// Tree sizes of the first unsigned checkpoint after a signed one. + pub signing_downgrades: Vec, + /// Sequences whose timestamp is below their predecessor's; at most [`MAX_TIMESTAMP_NOTES`]. + pub timestamp_regressions: Vec, + /// How many regressions there were in all. + pub timestamp_regression_count: u64, +} + +impl Report { + /// What a consistent result does and does not show. + #[must_use] + pub const fn caveat(&self) -> &'static str { + CAVEAT + } + + /// The checkpoint with the largest tree size. + #[must_use] + pub fn latest_checkpoint(&self) -> Option<&CheckpointSummary> { + self.checkpoints.last() + } +} + +/// How a ledger that agrees with itself disagrees with what the caller brought. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[allow( + clippy::exhaustive_enums, + reason = "closed set: every match must decide each case" +)] +pub enum TrustedDisagreement { + /// The ledger holds fewer entries than the trusted checkpoint covers: truncation. + LedgerShorter { + ledger_entries: u64, + trusted_tree_size: u64, + }, + /// The root recomputed at the trusted checkpoint's size is not the trusted root. + RootMismatch { tree_size: u64 }, + /// A key id was trusted but the ledger holds no checkpoint, so nothing in it is signed by + /// that key: emptied, rebuilt short, or never checkpointed. + NoCheckpointForTrustedKey { ledger_entries: u64 }, +} + +/// The outcome of [`verify`]. +#[derive(Debug, Clone, PartialEq, Eq)] +#[allow( + clippy::exhaustive_enums, + reason = "closed set: every match must decide each case" +)] +pub enum Verification { + /// The ledger agrees with itself and with anything the caller trusted. + Consistent(Report), + /// The ledger disagrees with itself. + Failed(Failure), + /// The ledger agrees with itself but not with the trusted checkpoint. + TrustedDisagreement { + report: Report, + disagreement: TrustedDisagreement, + }, +} + +/// What the caller brings from outside the ledger. +#[derive(Debug, Clone, Copy, Default)] +#[non_exhaustive] +pub struct VerifyOptions<'a> { + trusted_checkpoint: Option<&'a ExportBlob>, + trusted_key_id: Option, +} + +impl<'a> VerifyOptions<'a> { + /// Options that trust nothing outside the ledger. + #[must_use] + pub const fn new() -> Self { + Self { + trusted_checkpoint: None, + trusted_key_id: None, + } + } + + /// Compare the ledger with a checkpoint exported earlier. + #[must_use] + pub const fn with_trusted_checkpoint(mut self, blob: &'a ExportBlob) -> Self { + self.trusted_checkpoint = Some(blob); + self + } + + /// Require every checkpoint to be signed by this key id. This pins the signer, not the + /// history: a same-key rewrite still passes. + #[must_use] + pub const fn with_trusted_key_id(mut self, key_id: KeyId) -> Self { + self.trusted_key_id = Some(key_id); + self + } +} + +/// Where [`prove`] anchors the proof. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[allow( + clippy::exhaustive_enums, + reason = "closed set: every match must decide each case" +)] +pub enum ProofAnchor { + /// The root of the whole ledger as it stands. + CurrentRoot, + /// The root at the checkpoint stored for this tree size. + Checkpoint(u64), +} + +/// Operational failures; a ledger that is wrong is a [`Verification`], not an error. +#[derive(Debug, Error)] +#[non_exhaustive] +pub enum VerifyError { + /// The ledger file could not be read. + #[error(transparent)] + Read(#[from] ReaderError), + /// The supplied trusted checkpoint carries a bad signature. + #[error("the trusted checkpoint's signature does not verify")] + TrustedCheckpointInvalid, + /// The requested sequence is not in the tree. + #[error("sequence {seq} is outside a tree of {total} entries")] + SequenceOutOfRange { seq: u64, total: u64 }, + /// No checkpoint is stored at the requested size. + #[error("no checkpoint is stored for tree size {tree_size}")] + NoCheckpoint { tree_size: u64 }, + /// Entries around `seq` are not consecutive. + #[error("entries are not consecutive near sequence {seq}; run verify")] + NotSequential { seq: u64 }, + /// A Merkle computation failed. + #[error(transparent)] + Merkle(#[from] MerkleError), +} + +/// Why the walk stopped early. +enum Stop { + Fail(Failure), + Error(VerifyError), +} + +impl From for Stop { + fn from(error: ReaderError) -> Self { + Self::Error(VerifyError::Read(error)) + } +} + +const fn fail(at: u64, check: Check) -> Stop { + Stop::Fail(Failure { at, check }) +} + +/// The walk's state: a frontier, the previous entry hash and the next checkpoint to meet. +struct Walk<'a> { + reader: &'a LedgerReader, + options: &'a VerifyOptions<'a>, + frontier: Frontier, + expected_seq: u64, + prev_hash: Hash, + prev_ts: Option, + next_checkpoint: Option, + last_signed_key: Option, + previous_was_signed: bool, + trusted: Option, + report: Report, +} + +impl<'a> Walk<'a> { + fn new(reader: &'a LedgerReader, options: &'a VerifyOptions<'a>) -> Result { + Ok(Self { + reader, + options, + frontier: Frontier::new(), + expected_seq: 0, + prev_hash: GENESIS_PREV_HASH, + prev_ts: None, + next_checkpoint: reader.next_checkpoint_size(0)?, + last_signed_key: None, + previous_was_signed: false, + trusted: None, + report: Report { + entry_count: 0, + final_root: merkle::empty_root(), + checkpoints: Vec::new(), + key_changes: Vec::new(), + signing_downgrades: Vec::new(), + timestamp_regressions: Vec::new(), + timestamp_regression_count: 0, + }, + }) + } + + fn run(&mut self) -> Result<(), Stop> { + self.at_size(0)?; + let reader = self.reader; + // Entry pages and checkpoint lookups are separate read transactions, so a checkpoint + // can name a size committed after the last page. Re-read from where the walk stopped + // while that makes progress; only a checkpoint still past the end is a failure. + loop { + let before = self.expected_seq; + for row in reader.entries(before) { + let (key, bytes) = row?; + self.entry(key, &bytes)?; + } + if self.next_checkpoint.is_none() || self.expected_seq == before { + break; + } + } + if let Some(size) = self.next_checkpoint { + return Err(fail(size, Check::CheckpointRoot)); + } + if let Some(blob) = self.options.trusted_checkpoint + && blob.tree_size > self.frontier.leaf_count() + { + self.trusted = Some(TrustedDisagreement::LedgerShorter { + ledger_entries: self.frontier.leaf_count(), + trusted_tree_size: blob.tree_size, + }); + } + Ok(()) + } + + /// The checks of one entry, in their fixed order. + fn entry(&mut self, key: u64, bytes: &[u8]) -> Result<(), Stop> { + if key != self.expected_seq { + return Err(fail(key, Check::SequenceGap)); + } + // A row that cannot be decoded is reported as a bad entry hash: its bytes do not + // describe a hashable entry. + let entry = Entry::decode(bytes).map_err(|_error| fail(key, Check::EntryHash))?; + if entry.seq != key { + return Err(fail(key, Check::SequenceGap)); + } + entry + .verify_self() + .map_err(|_error| fail(key, Check::EntryHash))?; + if entry.prev_hash != self.prev_hash { + return Err(fail(key, Check::ChainLink)); + } + self.frontier + .append(entry.ledger_leaf()) + .map_err(|_error| fail(key, Check::MerkleRoot))?; + if entry.tree_size != self.frontier.leaf_count() || entry.root != self.frontier.root() { + return Err(fail(key, Check::MerkleRoot)); + } + self.note_timestamp(key, entry.ts_ms); + self.prev_hash = entry.entry_hash; + self.expected_seq = key.saturating_add(1); + self.at_size(self.frontier.leaf_count()) + } + + fn note_timestamp(&mut self, seq: u64, ts_ms: i64) { + if self.prev_ts.is_some_and(|previous| ts_ms < previous) { + self.report.timestamp_regression_count = + self.report.timestamp_regression_count.saturating_add(1); + if self.report.timestamp_regressions.len() < MAX_TIMESTAMP_NOTES { + self.report.timestamp_regressions.push(seq); + } + } + self.prev_ts = Some(ts_ms); + } + + /// What applies once the tree holds `size` entries: the trusted root, then the checkpoint. + fn at_size(&mut self, size: u64) -> Result<(), Stop> { + if let Some(blob) = self.options.trusted_checkpoint + && blob.tree_size == size + && blob.root != self.frontier.root() + { + self.trusted = Some(TrustedDisagreement::RootMismatch { tree_size: size }); + } + if self.next_checkpoint == Some(size) { + self.check_checkpoint(size)?; + self.next_checkpoint = match size.checked_add(1) { + Some(after) => self.reader.next_checkpoint_size(after)?, + None => None, + }; + } + Ok(()) + } + + fn check_checkpoint(&mut self, size: u64) -> Result<(), Stop> { + // A row that cannot be decoded, or that vanished, fails as a checkpoint root. + let checkpoint = match self.reader.checkpoint(size) { + Ok(Some(checkpoint)) => checkpoint, + Ok(None) => return Err(fail(size, Check::CheckpointRoot)), + Err(ReaderError::CorruptCheckpoint { .. }) => { + return Err(fail(size, Check::CheckpointRoot)); + } + Err(other) => return Err(other.into()), + }; + if checkpoint.tree_size != size + || checkpoint.root != self.frontier.root() + || checkpoint.frontier != self.frontier + { + return Err(fail(size, Check::CheckpointRoot)); + } + let verdict = match checkpoint.verify() { + CheckpointVerdict::Inconsistent => return Err(fail(size, Check::CheckpointRoot)), + CheckpointVerdict::Signature(verdict) => verdict, + }; + let signing = match verdict { + SignatureVerdict::BadSignature => { + return Err(fail(size, Check::CheckpointSignature)); + } + SignatureVerdict::ValidSigned { key_id } => CheckpointSigning::Signed { key_id }, + SignatureVerdict::UnsignedByConfig => CheckpointSigning::UnsignedByConfig, + SignatureVerdict::UnsignedKeyFailed => CheckpointSigning::UnsignedKeyFailed, + }; + // An unsigned checkpoint is not signed by the trusted key either: a ledger rebuilt + // with signing off must not pass for someone who brought a key. + if let Some(trusted) = self.options.trusted_key_id + && signing != (CheckpointSigning::Signed { key_id: trusted }) + { + return Err(fail(size, Check::CheckpointKey)); + } + self.record_signing(size, signing); + Ok(()) + } + + fn record_signing(&mut self, size: u64, signing: CheckpointSigning) { + match signing { + CheckpointSigning::Signed { key_id } => { + if self + .last_signed_key + .is_some_and(|previous| previous != key_id) + { + self.report.key_changes.push(size); + } + self.last_signed_key = Some(key_id); + self.previous_was_signed = true; + } + CheckpointSigning::UnsignedByConfig | CheckpointSigning::UnsignedKeyFailed => { + if self.previous_was_signed { + self.report.signing_downgrades.push(size); + } + self.previous_was_signed = false; + } + } + self.report.checkpoints.push(CheckpointSummary { + tree_size: size, + signing, + }); + } + + fn finish(mut self) -> Verification { + self.report.entry_count = self.frontier.leaf_count(); + self.report.final_root = self.frontier.root(); + let unsigned_by_trusted_key = (self.options.trusted_key_id.is_some() + && self.report.checkpoints.is_empty()) + .then_some(TrustedDisagreement::NoCheckpointForTrustedKey { + ledger_entries: self.report.entry_count, + }); + match self.trusted.or(unsigned_by_trusted_key) { + None => Verification::Consistent(self.report), + Some(disagreement) => Verification::TrustedDisagreement { + report: self.report, + disagreement, + }, + } + } +} + +/// Walk every entry in order and apply the checks, stopping at the first failure. +/// +/// Memory is O(log n): a frontier, the previous entry hash, the next checkpoint size and one +/// page of raw rows from the reader. The report grows with the number of checkpoints (one per +/// 64 entries) and is capped for timestamp notes. +/// +/// # Errors +/// +/// [`VerifyError::TrustedCheckpointInvalid`] when the trusted checkpoint's own signature is bad, +/// and [`VerifyError::Read`] when the file cannot be read. Content that is wrong is a +/// [`Verification`], never an error. +pub fn verify( + reader: &LedgerReader, + options: &VerifyOptions<'_>, +) -> Result { + if let Some(blob) = options.trusted_checkpoint + && blob.verify() == SignatureVerdict::BadSignature + { + return Err(VerifyError::TrustedCheckpointInvalid); + } + let mut walk = Walk::new(reader, options)?; + match walk.run() { + Ok(()) => Ok(walk.finish()), + Err(Stop::Fail(failure)) => Ok(Verification::Failed(failure)), + Err(Stop::Error(error)) => Err(error), + } +} + +/// An inclusion proof for entry `seq`, against the current root or a checkpoint's root. +/// +/// Entry leaves are streamed through [`merkle::inclusion_path`], so memory is O(log n). The +/// proof is built from the stored entries and is not itself a verification of the ledger: +/// `Proof::verify` fails when the stored entries do not hash to the anchor root. +/// +/// # Errors +/// +/// [`VerifyError::SequenceOutOfRange`] when `seq` is not below the anchor's size and +/// [`VerifyError::NoCheckpoint`] when a named checkpoint is not stored. +pub fn prove(reader: &LedgerReader, seq: u64, anchor: ProofAnchor) -> Result { + let (total, root) = match anchor { + ProofAnchor::CurrentRoot => current_anchor(reader, seq)?, + ProofAnchor::Checkpoint(tree_size) => { + let checkpoint = reader + .checkpoint(tree_size)? + .ok_or(VerifyError::NoCheckpoint { tree_size })?; + (tree_size, checkpoint.root) + } + }; + if seq >= total { + return Err(VerifyError::SequenceOutOfRange { seq, total }); + } + let leaf_hash = reader + .entry(seq)? + .ok_or(VerifyError::NotSequential { seq })? + .ledger_leaf(); + let siblings = streamed_path(reader, seq, total)?; + Ok(Proof { + root, + index: seq, + total, + leaf_hash, + siblings, + }) +} + +fn current_anchor(reader: &LedgerReader, seq: u64) -> Result<(u64, Hash), VerifyError> { + let total = reader.entry_count()?; + let last = total + .checked_sub(1) + .ok_or(VerifyError::SequenceOutOfRange { seq, total })?; + let root = reader + .entry(last)? + .ok_or(VerifyError::NotSequential { seq: last })? + .root; + Ok((total, root)) +} + +/// The inclusion path over the first `total` entries, reading them once. +fn streamed_path(reader: &LedgerReader, seq: u64, total: u64) -> Result, VerifyError> { + let mut problem: Option = None; + let leaves = (0..total) + .zip(reader.entries(0)) + .map_while(|(expected, row)| { + let outcome = row + .map_err(VerifyError::Read) + .and_then(|(key, bytes)| leaf_of(key, expected, &bytes)); + outcome.map_err(|error| problem = Some(error)).ok() + }); + let path = merkle::inclusion_path(seq, total, leaves); + match problem { + Some(error) => Err(error), + None => Ok(path?), + } +} + +fn leaf_of(key: u64, expected: u64, bytes: &[u8]) -> Result { + if key != expected { + return Err(VerifyError::NotSequential { seq: key }); + } + let entry = + Entry::decode(bytes).map_err(|source| ReaderError::CorruptEntry { seq: key, source })?; + Ok(entry.ledger_leaf()) +} + +/// The export blob of the checkpoint stored for `tree_size`. +/// +/// # Errors +/// +/// [`VerifyError::NoCheckpoint`] when none is stored. +pub fn export_checkpoint(reader: &LedgerReader, tree_size: u64) -> Result { + reader + .checkpoint(tree_size)? + .map(|checkpoint| checkpoint.export()) + .ok_or(VerifyError::NoCheckpoint { tree_size }) +} diff --git a/daemoneye-lib/src/config.rs b/daemoneye-lib/src/config.rs index 1f99d808..348e4fbf 100644 --- a/daemoneye-lib/src/config.rs +++ b/daemoneye-lib/src/config.rs @@ -55,6 +55,9 @@ pub struct Config { /// Detection rule-load configuration #[serde(default)] pub detection: DetectionConfig, + /// Audit ledger configuration + #[serde(default)] + pub audit: AuditConfig, } /// Application-specific configuration. @@ -132,6 +135,30 @@ impl DatabaseConfig { } } +/// Audit ledger configuration. The signing key sits beside the ledger file. +/// +/// Both are opened by path, so keep their directory writable only by the account procmond runs +/// as: anyone who can write there can replace either file. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(default)] +pub struct AuditConfig { + /// Ledger file path + pub ledger_path: PathBuf, + /// Sign checkpoints with Ed25519. An existing key file is always used. A missing one is + /// created only for an empty ledger: with no key file and entries already in the ledger, + /// checkpoints stay unsigned. + pub signing_enabled: bool, +} + +impl Default for AuditConfig { + fn default() -> Self { + Self { + ledger_path: PathBuf::from("/var/lib/daemoneye/audit.redb"), + signing_enabled: true, + } + } +} + /// Alerting configuration. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct AlertingConfig { @@ -1234,6 +1261,7 @@ impl Config { // --- Path traversal validation --- ConfigLoader::validate_path_no_traversal(&config.database.path, "database.path")?; + ConfigLoader::validate_path_no_traversal(&config.audit.ledger_path, "audit.ledger_path")?; ConfigLoader::validate_path_no_traversal( &config.broker.config_directory, "broker.config_directory", @@ -2494,4 +2522,33 @@ enabled = true config.database.page_cache_mb = 0; assert!(config.validate().is_err()); } + + #[test] + fn audit_defaults_to_signing_on() { + assert!(Config::default().audit.signing_enabled); + } + + #[test] + fn audit_section_round_trips_through_toml() { + let mut config = Config::default(); + config.audit.signing_enabled = false; + config.audit.ledger_path = PathBuf::from("/srv/audit.redb"); + let text = toml::to_string(&config).expect("serialise"); + let back: Config = toml::from_str(&text).expect("parse"); + assert_eq!(back.audit, config.audit); + } + + #[test] + fn audit_section_absent_loads_defaults() { + let back: AuditConfig = toml::from_str("").expect("parse"); + assert_eq!(back, AuditConfig::default()); + } + + #[test] + fn audit_ledger_path_traversal_is_rejected() { + let mut config = Config::default(); + config.audit.ledger_path = PathBuf::from("/var/../audit.redb"); + let msg = format!("{}", config.validate().expect_err("traversal")); + assert!(msg.contains("audit.ledger_path"), "{msg}"); + } } diff --git a/daemoneye-lib/src/crypto.rs b/daemoneye-lib/src/crypto.rs index 0186499a..c8694ad8 100644 --- a/daemoneye-lib/src/crypto.rs +++ b/daemoneye-lib/src/crypto.rs @@ -1,7 +1,7 @@ //! Cryptographic utilities for audit trails and integrity verification. //! -//! This module provides cryptographic functions for creating Certificate Transparency-style -//! audit ledgers with Merkle tree structure for efficient verification and tamper detection. +//! BLAKE3 hashing and the hash-chained audit entry encoding. The Merkle tree lives in +//! [`crate::audit::merkle`]. use serde::{Deserialize, Serialize}; use thiserror::Error; @@ -106,32 +106,6 @@ impl AuditEntry { ) } - /// Compute the legacy (v1) hash-input string for backward-compatible verification. - /// - /// The v1 format was a colon-delimited string using Unix epoch-seconds timestamps. - /// It is ambiguous when `actor` or `action` contain `:` but is retained here - /// solely to verify entries that were written before the v2 format was introduced. - // Used by verify_integrity for backward-compatible ledger verification. - #[allow(dead_code)] - fn compute_entry_hash_input_v1( - sequence: u64, - timestamp: &chrono::DateTime, - actor: &str, - action: &str, - payload_hash: &str, - previous_hash: Option<&str>, - ) -> String { - format!( - "{}:{}:{}:{}:{}:{}", - sequence, - timestamp.timestamp(), - actor, - action, - payload_hash, - previous_hash.unwrap_or("") - ) - } - /// Create a new audit entry. pub fn new( sequence: u64, @@ -165,111 +139,6 @@ impl AuditEntry { } } -/// Certificate Transparency-style audit ledger for maintaining tamper-evident log integrity. -/// -/// This structure provides Merkle tree-based verification with logarithmic proof sizes -/// and support for efficient inclusion/exclusion proofs and periodic checkpoints. -pub struct AuditLedger { - entries: Vec, - tree_size: usize, -} - -impl AuditLedger { - /// Create a new audit ledger. - pub const fn new() -> Self { - Self { - entries: Vec::new(), - tree_size: 0, - } - } - - /// Add an entry to the audit ledger with Merkle tree structure. - pub fn add_entry(&mut self, actor: String, action: String, payload: &[u8]) -> AuditEntry { - let sequence = u64::try_from(self.tree_size).unwrap_or(0); - let previous_hash = self.entries.last().map(|entry| entry.entry_hash.clone()); - - let entry = AuditEntry::new(sequence, actor, action, payload, previous_hash); - self.entries.push(entry.clone()); - self.tree_size = self.tree_size.saturating_add(1); - entry - } - - /// Generate inclusion proof for entry verification (placeholder for future Merkle tree implementation). - pub const fn generate_inclusion_proof(_index: usize) -> Vec { - // TODO: Implement Merkle tree inclusion proof generation - // This would use rs-merkle crate for efficient proof generation - vec![] - } - - /// Verify the integrity of the audit ledger. - /// - /// First attempts verification using the current v2 (length-prefixed) hash format. - /// If that fails, falls back to the legacy v1 (colon-delimited, epoch-seconds) - /// format so that ledgers written before the v2 format was introduced can still - /// be verified. - pub fn verify_integrity(&self) -> Result<(), CryptoError> { - for (i, entry) in self.entries.iter().enumerate() { - // Try current v2 format first. - let entry_data_v2 = AuditEntry::compute_entry_hash_input( - entry.sequence, - &entry.timestamp, - &entry.actor, - &entry.action, - &entry.payload_hash, - entry.previous_hash.as_deref(), - ); - let expected_v2 = Blake3Hasher::hash_string(&entry_data_v2); - - if entry.entry_hash != expected_v2 { - // Fall back to legacy v1 format before declaring a mismatch. - let entry_data_v1 = AuditEntry::compute_entry_hash_input_v1( - entry.sequence, - &entry.timestamp, - &entry.actor, - &entry.action, - &entry.payload_hash, - entry.previous_hash.as_deref(), - ); - let expected_v1 = Blake3Hasher::hash_string(&entry_data_v1); - if entry.entry_hash != expected_v1 { - return Err(CryptoError::Hash(format!("Hash mismatch at entry {i}"))); - } - } - - // Verify chain continuity - if i > 0 { - let prev_entry = self - .entries - .get(i.saturating_sub(1)) - .ok_or_else(|| CryptoError::Hash("Missing previous entry".to_owned()))?; - if entry.previous_hash != Some(prev_entry.entry_hash.clone()) { - return Err(CryptoError::Hash(format!( - "Chain discontinuity at entry {i}" - ))); - } - } - } - - Ok(()) - } - - /// Get all entries in the chain. - pub fn get_entries(&self) -> &[AuditEntry] { - &self.entries - } - - /// Get the latest entry hash. - pub fn get_latest_hash(&self) -> Option<&String> { - self.entries.last().map(|entry| &entry.entry_hash) - } -} - -impl Default for AuditLedger { - fn default() -> Self { - Self::new() - } -} - #[cfg(test)] #[allow( clippy::unwrap_used, @@ -333,30 +202,6 @@ mod tests { assert_eq!(entry.action, "test-action"); } - #[test] - fn test_audit_ledger_integrity() { - let mut ledger = AuditLedger::new(); - - ledger.add_entry("actor1".to_owned(), "action1".to_owned(), b"payload1"); - ledger.add_entry("actor2".to_owned(), "action2".to_owned(), b"payload2"); - - assert!(ledger.verify_integrity().is_ok()); - assert_eq!(ledger.get_entries().len(), 2); - } - - #[test] - fn test_audit_ledger_tamper_detection() { - let mut ledger = AuditLedger::new(); - ledger.add_entry("actor1".to_owned(), "action1".to_owned(), b"payload1"); - - // Tamper with the entry - if let Some(entry) = ledger.entries.get_mut(0) { - entry.actor = "tampered".to_owned(); - } - - assert!(ledger.verify_integrity().is_err()); - } - #[test] fn test_compute_entry_hash_input_uses_rfc3339() { // Use a fixed timestamp with nanosecond sub-second precision. @@ -415,44 +260,4 @@ mod tests { let b = AuditEntry::compute_entry_hash_input(5, &ts, "actor", "action", "ph", None); assert_eq!(a, b); } - - #[test] - fn test_verify_integrity_accepts_legacy_v1_entries() { - // Build an entry whose hash was computed with the old v1 colon-delimited - // format so we can confirm backward-compatible verification still works. - let actor = "legacy-actor".to_owned(); - let action = "legacy-action".to_owned(); - let payload = b"legacy payload"; - let payload_hash = Blake3Hasher::hash(payload); - let timestamp = - chrono::DateTime::from_timestamp(1_700_000_000, 0).expect("valid timestamp"); - - let v1_input = format!( - "{}:{}:{}:{}:{}:{}", - 0_u64, - timestamp.timestamp(), - actor, - action, - payload_hash, - "" - ); - let v1_hash = Blake3Hasher::hash_string(&v1_input); - - let legacy_entry = AuditEntry { - sequence: 0, - timestamp, - actor, - action, - payload_hash, - previous_hash: None, - entry_hash: v1_hash, - }; - - let mut ledger = AuditLedger::new(); - ledger.entries.push(legacy_entry); - assert!( - ledger.verify_integrity().is_ok(), - "legacy v1 entries must still pass integrity verification" - ); - } } diff --git a/daemoneye-lib/src/detection/mod.rs b/daemoneye-lib/src/detection/mod.rs index a0a4694d..14de7f17 100644 --- a/daemoneye-lib/src/detection/mod.rs +++ b/daemoneye-lib/src/detection/mod.rs @@ -357,7 +357,7 @@ impl DetectionEngine { /// The rejections this engine has recorded, oldest first. /// - /// The chain is in-memory and agent-side: the `audit_ledger` table is procmond's to write. + /// The chain is in-memory and agent-side: the audit ledger is procmond's to write. pub const fn rejection_log(&self) -> &RejectionLog { &self.rejections } diff --git a/daemoneye-lib/src/rejection_log.rs b/daemoneye-lib/src/rejection_log.rs index 370aa877..1feeaf51 100644 --- a/daemoneye-lib/src/rejection_log.rs +++ b/daemoneye-lib/src/rejection_log.rs @@ -1,10 +1,10 @@ //! Agent-side hash-chained record of rule-load and registration rejections (R4, R8). //! -//! Rejections happen in `daemoneye-agent`, and the `audit_ledger` table is procmond-write / +//! Rejections happen in `daemoneye-agent`, and the audit ledger is procmond-write / //! others-read. Routing agent-observed rejections through procmond would invert that boundary for //! no forensic gain, so the agent keeps its own chain here. This store is a **bounded in-memory -//! window**, not durable retention: persistence and Merkle inclusion proofs belong to the -//! audit-ledger work and are deliberately absent. +//! window**, not durable retention: it is not committed to the audit ledger, which records only +//! what procmond observes and does. //! //! The chain reuses [`crate::crypto::AuditEntry::compute_entry_hash_input`] so there is exactly one //! canonical hash-input format in the workspace for a later persistence layer to adopt. @@ -200,8 +200,8 @@ impl RejectionRecord { /// Hash-chained store of the agent's own rejections, bounded to a fixed window. /// -/// In-memory only. Nothing here opens the `audit_ledger` table, for reading or for writing — the -/// durable, forensically complete record is the audit ledger, which is T8's work. This is the +/// In-memory only. Nothing here opens the audit ledger, for reading or for writing, and these +/// records are not in it. This is the /// agent's live view of its own refusals, and it is **lossy by design**: registration is reachable /// over IPC, so an unbounded chain would let a collector retrying with a stale token exhaust the /// agent's memory budget. At [`MAX_REJECTION_RECORDS`] the oldest record is evicted to make room diff --git a/daemoneye-lib/tests/audit_golden.rs b/daemoneye-lib/tests/audit_golden.rs new file mode 100644 index 00000000..57f6ba9e --- /dev/null +++ b/daemoneye-lib/tests/audit_golden.rs @@ -0,0 +1,544 @@ +//! Golden bytes and hashes for ledger entries and recorded events, and the batch check. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +#![allow( + clippy::indexing_slicing, + clippy::arithmetic_side_effects, + clippy::string_slice, + reason = "fixtures index vectors and hex strings of known length" +)] + +use std::fmt::Write as _; + +use daemoneye_lib::audit::entry::{ + Action, Entry, EntryError, GENESIS_PREV_HASH, GapReason, Kind, MAX_PRIVILEGE_LEN, + MAX_PRIVILEGES, Privileges, +}; +use daemoneye_lib::audit::event_hash::{ + BatchCheck, EventProjection, EventType, batch_root, check_batch, +}; +use daemoneye_lib::audit::merkle::{Frontier, Hash, empty_root}; + +fn hex(bytes: &[u8]) -> String { + bytes.iter().fold(String::new(), |mut out, byte| { + write!(out, "{byte:02x}").unwrap(); + out + }) +} + +fn full_event() -> EventProjection { + EventProjection { + wal_sequence: 7, + event_type: EventType::Start, + pid: 4242, + ppid: Some(1), + name: "bash".to_owned(), + executable_path: Some("/bin/bash".to_owned()), + command_line: Some("bash -c id".to_owned()), + start_time_ns: Some(1_700_000_000_123_456_789), + executable_hash: Some("ab".repeat(32)), + hash_algorithm: Some("sha256".to_owned()), + collection_time_ns: 1_700_000_001_000_000_000, + } +} + +const fn bare_event() -> EventProjection { + EventProjection { + wal_sequence: 0, + event_type: EventType::Stop, + pid: 1, + ppid: None, + name: String::new(), + executable_path: None, + command_line: None, + start_time_ns: None, + executable_hash: None, + hash_algorithm: None, + collection_time_ns: 0, + } +} + +fn kinds() -> Vec { + vec![ + Kind::Batch { + first_seq: 10, + last_seq: 19, + count: 10, + batch_root: [0x11; 32], + recovered: false, + }, + Kind::Batch { + first_seq: 20, + last_seq: 20, + count: 1, + batch_root: [0x22; 32], + recovered: true, + }, + Kind::Action(Action::ProcessStart { pid: 4242 }), + Kind::Action(Action::CleanStop { pid: 4242 }), + Kind::Action(Action::PrivilegesDetected { + privileges: Privileges::new(vec!["root".to_owned(), "cap_sys_ptrace".to_owned()]) + .unwrap(), + }), + Kind::Action(Action::ConfigUpdateReceived { + config_hash: [0x33; 32], + }), + Kind::Action(Action::IntegrityDriftReported { + subject: [0x44; 32], + observed: [0x55; 32], + }), + Kind::Action(Action::SigningKeyCreated { key_id: [0x66; 32] }), + Kind::Action(Action::SigningKeyFailed), + Kind::Gap { + missed: 3, + reason: GapReason::CommitFailed, + }, + Kind::Gap { + missed: 1, + reason: GapReason::LedgerUnavailable, + }, + ] +} + +/// Builds a chain with one entry per kind, at fixed timestamps. +fn chain(kinds: Vec) -> Vec { + let mut entries: Vec = Vec::new(); + let mut tree = Frontier::new(); + for (index, kind) in kinds.into_iter().enumerate() { + let ts = 1_700_000_000_000 + i64::try_from(index).unwrap(); + let (entry, after) = Entry::next(entries.last(), kind, ts, &tree).unwrap(); + tree = after; + entries.push(entry); + } + entries +} + +#[test] +fn entries_encode_to_the_committed_bytes_and_decode_back() { + let entries = chain(kinds()); + let actual: Vec = entries.iter().map(|e| hex(&e.encode().unwrap())).collect(); + assert_eq!( + actual, + GOLDEN_ENTRIES + .iter() + .map(|s| (*s).to_owned()) + .collect::>() + ); + for (entry, golden) in entries.iter().zip(GOLDEN_ENTRIES) { + let bytes: Vec = (0..golden.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&golden[i..i + 2], 16).unwrap()) + .collect(); + assert_eq!(&Entry::decode(&bytes).unwrap(), entry); + } +} + +#[test] +fn event_hashes_match_the_committed_values() { + assert_eq!(hex(&full_event().data_hash()), GOLDEN_FULL_EVENT); + assert_eq!(hex(&bare_event().data_hash()), GOLDEN_BARE_EVENT); +} + +#[test] +fn any_single_field_change_changes_the_event_hash() { + let base = full_event(); + let variants: Vec<(&str, EventProjection)> = vec![ + ( + "wal_sequence", + EventProjection { + wal_sequence: 8, + ..base.clone() + }, + ), + ( + "event_type", + EventProjection { + event_type: EventType::Modify, + ..base.clone() + }, + ), + ( + "pid", + EventProjection { + pid: 4243, + ..base.clone() + }, + ), + ( + "ppid", + EventProjection { + ppid: Some(2), + ..base.clone() + }, + ), + ( + "name", + EventProjection { + name: "bashx".to_owned(), + ..base.clone() + }, + ), + ( + "executable_path", + EventProjection { + executable_path: Some("/bin/sh".to_owned()), + ..base.clone() + }, + ), + ( + "command_line", + EventProjection { + command_line: Some("bash".to_owned()), + ..base.clone() + }, + ), + ( + "start_time_ns", + EventProjection { + start_time_ns: Some(1), + ..base.clone() + }, + ), + ( + "executable_hash", + EventProjection { + executable_hash: Some("cd".repeat(32)), + ..base.clone() + }, + ), + ( + "hash_algorithm", + EventProjection { + hash_algorithm: Some("blake3".to_owned()), + ..base.clone() + }, + ), + ( + "collection_time_ns", + EventProjection { + collection_time_ns: 1, + ..base.clone() + }, + ), + ]; + for (field, variant) in variants { + assert_ne!( + variant.data_hash(), + base.data_hash(), + "{field} did not affect the hash" + ); + } +} + +#[test] +fn an_absent_optional_field_hashes_differently_from_a_present_empty_one() { + let base = bare_event(); + let variants: Vec<(&str, EventProjection)> = vec![ + ( + "ppid", + EventProjection { + ppid: Some(0), + ..base.clone() + }, + ), + ( + "executable_path", + EventProjection { + executable_path: Some(String::new()), + ..base.clone() + }, + ), + ( + "command_line", + EventProjection { + command_line: Some(String::new()), + ..base.clone() + }, + ), + ( + "start_time_ns", + EventProjection { + start_time_ns: Some(0), + ..base.clone() + }, + ), + ( + "executable_hash", + EventProjection { + executable_hash: Some(String::new()), + ..base.clone() + }, + ), + ( + "hash_algorithm", + EventProjection { + hash_algorithm: Some(String::new()), + ..base.clone() + }, + ), + ]; + for (field, variant) in variants { + assert_ne!( + variant.data_hash(), + base.data_hash(), + "{field}: present-empty equals absent" + ); + } +} + +#[test] +fn field_boundaries_cannot_be_shifted_between_events() { + let first = EventProjection { + name: "a".to_owned(), + command_line: Some("bc".to_owned()), + ..bare_event() + }; + let second = EventProjection { + name: "ab".to_owned(), + command_line: Some("c".to_owned()), + ..bare_event() + }; + let colon = EventProjection { + name: "a:1".to_owned(), + executable_path: Some("2:b".to_owned()), + ..bare_event() + }; + let digits = EventProjection { + name: "a:12".to_owned(), + executable_path: Some(":b".to_owned()), + ..bare_event() + }; + // A name that spells out a length prefix and the next field's presence byte. + let forged = EventProjection { + name: "a".to_owned(), + ..bare_event() + }; + let spoof_name = "a\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{1}".to_owned(); + let spoofed = EventProjection { + name: spoof_name, + ..bare_event() + }; + assert_ne!(first.data_hash(), second.data_hash()); + assert_ne!(colon.data_hash(), digits.data_hash()); + assert_ne!(forged.data_hash(), spoofed.data_hash()); +} + +#[test] +fn privilege_names_cannot_be_regrouped_into_the_same_entry_hash() { + let hash_for = |names: &[&str]| { + let privileges = Privileges::new(names.iter().map(|n| (*n).to_owned()).collect()).unwrap(); + chain(vec![Kind::Action(Action::PrivilegesDetected { + privileges, + })])[0] + .entry_hash + }; + let hashes = [ + hash_for(&["a", "bc"]), + hash_for(&["ab", "c"]), + hash_for(&["abc"]), + hash_for(&["1:a", "2"]), + hash_for(&["1", ":a2"]), + hash_for(&["a", "b", "c"]), + ]; + for (i, left) in hashes.iter().enumerate() { + for right in hashes.iter().skip(i + 1) { + assert_ne!(left, right); + } + } +} + +#[test] +fn privilege_bounds_are_enforced_at_construction() { + let long = "x".repeat(MAX_PRIVILEGE_LEN + 1); + assert_eq!( + Privileges::new(vec![long]), + Err(EntryError::PrivilegeTooLong { + len: MAX_PRIVILEGE_LEN + 1 + }) + ); + let many = vec!["p".to_owned(); MAX_PRIVILEGES + 1]; + assert_eq!( + Privileges::new(many), + Err(EntryError::TooManyPrivileges { + count: MAX_PRIVILEGES + 1 + }) + ); + assert!(Privileges::new(vec!["x".repeat(MAX_PRIVILEGE_LEN); MAX_PRIVILEGES]).is_ok()); +} + +#[test] +fn an_unknown_version_byte_is_a_typed_decode_error() { + let mut bytes = chain(kinds())[0].encode().unwrap(); + bytes[0] = 2; + assert_eq!( + Entry::decode(&bytes), + Err(EntryError::UnsupportedVersion(2)) + ); + assert_eq!(Entry::decode(&[]), Err(EntryError::Empty)); +} + +#[test] +fn trailing_bytes_after_an_entry_are_rejected() { + let mut bytes = chain(kinds())[0].encode().unwrap(); + bytes.push(0); + assert_eq!(Entry::decode(&bytes), Err(EntryError::TrailingBytes(1))); +} + +fn ten_events() -> Vec { + (0..10) + .map(|i| EventProjection { + wal_sequence: 100 + i, + pid: u32::try_from(i).unwrap() + 10, + name: format!("proc{i}"), + ..full_event() + }) + .collect() +} + +#[test] +fn a_batch_checks_against_its_own_entry() { + let events = ten_events(); + let summary = batch_root(&events).unwrap(); + assert_eq!(summary.count, 10); + assert_eq!( + check_batch(summary.count, &summary.root, &events), + Ok(BatchCheck::Match) + ); + + let mut renamed = events.clone(); + renamed[4].name = "other".to_owned(); + assert_eq!( + check_batch(summary.count, &summary.root, &renamed), + Ok(BatchCheck::Mismatch) + ); + + let mut missing = events.clone(); + missing.remove(3); + assert_eq!( + check_batch(summary.count, &summary.root, &missing), + Ok(BatchCheck::CountMismatch) + ); + + let reversed: Vec = events.iter().rev().cloned().collect(); + assert_eq!( + check_batch(summary.count, &summary.root, &reversed), + Ok(BatchCheck::Match) + ); +} + +#[test] +fn a_batch_of_zero_events_has_the_empty_root() { + let none: Vec = Vec::new(); + let summary = batch_root(&none).unwrap(); + assert_eq!(summary.count, 0); + assert_eq!(summary.root, empty_root()); + assert_eq!(check_batch(0, &empty_root(), &none), Ok(BatchCheck::Match)); +} + +#[test] +fn duplicate_wal_sequences_in_one_batch_are_an_error() { + let mut events = ten_events(); + events[5].wal_sequence = 100; + assert!(matches!( + batch_root(&events), + Err(daemoneye_lib::audit::event_hash::EventHashError::DuplicateSequence(100)) + )); +} + +#[test] +fn a_chain_links_by_previous_hash_and_detects_any_field_change() { + let entries = chain(kinds().into_iter().take(3).collect()); + let sequences: Vec = entries.iter().map(|e| e.seq).collect(); + assert_eq!(sequences, vec![0, 1, 2]); + assert_eq!(entries[0].prev_hash, GENESIS_PREV_HASH); + assert_eq!(entries[1].prev_hash, entries[0].entry_hash); + assert_eq!(entries[2].prev_hash, entries[1].entry_hash); + for entry in &entries { + assert_eq!(entry.verify_self(), Ok(())); + } + assert_eq!(entries[2].tree_size, 3); + + let middle = &entries[1]; + let other_hash: Hash = [0xee; 32]; + let tampered = [ + Entry { + seq: middle.seq + 1, + ..middle.clone() + }, + Entry { + ts_ms: middle.ts_ms + 1, + ..middle.clone() + }, + Entry { + kind: Kind::Gap { + missed: 9, + reason: GapReason::CommitFailed, + }, + ..middle.clone() + }, + Entry { + payload_hash: other_hash, + ..middle.clone() + }, + Entry { + prev_hash: other_hash, + ..middle.clone() + }, + Entry { + entry_hash: other_hash, + ..middle.clone() + }, + Entry { + version: 9, + ..middle.clone() + }, + ]; + for entry in tampered { + assert!(entry.verify_self().is_err()); + } +} + +#[test] +fn the_ledger_leaf_and_tree_fields_follow_the_frontier() { + let entries = chain(kinds()); + let mut tree = Frontier::new(); + for entry in &entries { + tree.append(entry.ledger_leaf()).unwrap(); + assert_eq!(entry.tree_size, tree.leaf_count()); + assert_eq!(entry.root, tree.root()); + } +} + +#[test] +fn building_against_the_wrong_tree_is_a_typed_error() { + let entries = chain(kinds().into_iter().take(2).collect()); + let result = Entry::next( + Some(&entries[1]), + Kind::Action(Action::SigningKeyFailed), + 0, + &Frontier::new(), + ); + assert_eq!( + result.unwrap_err(), + EntryError::TreeSizeMismatch { + expected: 2, + found: 0 + } + ); +} + +const GOLDEN_FULL_EVENT: &str = "92fe0e4d0d9f3b1712fd718e3f5e023f4ef87916afe42e5c699988d818b2d3c0"; +const GOLDEN_BARE_EVENT: &str = "2629ae9d098fbcb0f361d4dc1529bb0129ecbc6c5458fb389053d4bbcded393a"; +const GOLDEN_ENTRIES: [&str; 11] = [ + "01010080a0abfef962000a130a111111111111111111111111111111111111111111111111111111111111111100fbbd340ce81bfc36e095b5250e59673762fb1bffe19a3a89b46540d567f0378f00000000000000000000000000000000000000000000000000000000000000004db31f802446070e035d610763b3ce4ecdb2addfc831b80bb74026fffb7881b5013bbdadf9bd5ce788f3664eb9c0e4aec0190e57b9fe5a996bd06cf717eb187b4a", + "01010182a0abfef9620014140122222222222222222222222222222222222222222222222222222222222222220184fd4261aad79006763dffec2644411126889082191f58f62fa43efe405dd55d4db31f802446070e035d610763b3ce4ecdb2addfc831b80bb74026fffb7881b51a5177861d6175002583d693125468c3112646a8b6a5661d666d296efb564460021cc857460b00c79cafa3799ff69f6d0cd342bf2e67e4abc7920ce3b9fe70a830", + "01010284a0abfef962010092219842a4263e4f275a24fe8519d099e870c4a61d3f5ace1e89cdaa8daeea730b8f1a5177861d6175002583d693125468c3112646a8b6a5661d666d296efb564460c2b35d85b6b953fc254d62c7f1bd67430947bf101afc767e0df500bad565acd8036cea6e1733fa850a7bd438281fcfc80737ce8ff0e8f3e657852891a3978e6471", + "01010386a0abfef962010192219059a317f3e1c6ae6cdae4f078a7dc3c0c9c2db152cad0ae80f623c7531b404cc2b35d85b6b953fc254d62c7f1bd67430947bf101afc767e0df500bad565acd871adfe665ce96121e527db3d90a72624e025122eb26ec8673fe177ae46ff4753041bba5740415107397a02281361ac07dbcc1ae916b77d3633f61b7774ee7eaa09", + "01010488a0abfef96201020204726f6f740e6361705f7379735f707472616365e1d84fe07eeb9a32cdfaa9f850e8dd5134cac94c27d1f44786e41a2def1f39de71adfe665ce96121e527db3d90a72624e025122eb26ec8673fe177ae46ff4753cc7397fed6a910cd200a6ce0871b09a980bba19c439351093789901025494afe055d8a0f70e0ea3751cfa098dad55a72a5c5230befca89b1986a263594d9aa8e70", + "0101058aa0abfef96201033333333333333333333333333333333333333333333333333333333333333333bb5c1c29041126fbb942d47db0142b65fb68a0ca364bc5f5a87f5396ede1fbe7cc7397fed6a910cd200a6ce0871b09a980bba19c439351093789901025494afe783b36142f5f0d13c56b5d778dae0e9dc807c982ef8576a43c7c1e6fff67a1a706eceba4e955fb49045d179a6d6c9f6ff112be47d1fa52be153c1bc53f3b29f91d", + "0101068ca0abfef96201044444444444444444444444444444444444444444444444444444444444444444555555555555555555555555555555555555555555555555555555555555555552f35dc4084f54006eb4dba37d7a05f35bd3297eb0d7198cf2d6794d023888ba783b36142f5f0d13c56b5d778dae0e9dc807c982ef8576a43c7c1e6fff67a1a788d7b7d738f19d612b2219ee0c11457d9407a4ea4d076b7f4ef952aa1f2f989f076cb39efd11bac1d2c8bddfe6aa2e6c57687fdab695a42a47cdcfbc54e1920a82", + "0101078ea0abfef962010566666666666666666666666666666666666666666666666666666666666666668ea235bb7659f23def8d6f95da0cd0d01868cd46d4c3c7d7e5d21d3997818cb988d7b7d738f19d612b2219ee0c11457d9407a4ea4d076b7f4ef952aa1f2f989ffb75df825812a8658045f7d9478e093f5eb94d05aeb40869109af44e297d0ce008cd2fd05d5bf161838a207212ed66a315a0013d2c40519160b3d2ae2c17bebdde", + "01010890a0abfef962010607901d74955dc1f9dd5d8ae31aef8a2d455f98f3046e6822339d5051fcc6284dfb75df825812a8658045f7d9478e093f5eb94d05aeb40869109af44e297d0ce075c9c6b65316885ff857653d1a134e61fdeb5bddcab88d3d7920da456410014a092360bd1f2d62f9625686c7e5b93f3e5bdbd8e04b25de5a52133697d7718aceb8", + "01010992a0abfef962020300f056660b26a79440c34d60cb3f425ab8859ed2624a13414ef4cb3b63df37cb9b75c9c6b65316885ff857653d1a134e61fdeb5bddcab88d3d7920da456410014ac6d72fdb489a99aca0725f245c835224169de7c02f1689560b8a776ee885b1380ae47f298f84fb4600388bfa58381525b67e87ba4018b04058c4bebe57fbe39998", + "01010a94a0abfef9620201010098d3779f857600145c123db8a42c298a261cfa3c468a5ba4dbca9e70998af6c6d72fdb489a99aca0725f245c835224169de7c02f1689560b8a776ee885b138292a7822e00d5533a15c171dd4236127167f05d562dbf958843b2cea4d8ea0f20bbf8a65bcadf8be992cf9c62229e1edbe40cb28a2ce38ee15ded892492fb92f0e", +]; diff --git a/daemoneye-lib/tests/audit_verify.rs b/daemoneye-lib/tests/audit_verify.rs new file mode 100644 index 00000000..da6c3087 --- /dev/null +++ b/daemoneye-lib/tests/audit_verify.rs @@ -0,0 +1,518 @@ +//! Verification of real ledger files: untouched, tampered, rebuilt and truncated. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +#![allow( + clippy::indexing_slicing, + clippy::arithmetic_side_effects, + clippy::missing_const_for_fn, + clippy::unused_self, + clippy::semicolon_outside_block, + clippy::integer_division, + clippy::wildcard_enum_match_arm, + reason = "fixtures index and count fixed-size vectors" +)] + +mod audit_verify_support; + +use std::collections::BTreeSet; + +use redb::ReadableTable; + +use audit_verify_support::{ + Choice, Spec, Workspace, change_entry, consistent, create_bare, edit, failure, interval, + reader, run, write_rows, +}; +use daemoneye_lib::audit::LedgerReadError; +use daemoneye_lib::audit::checkpoint::{Checkpoint, SignatureVerdict}; +use daemoneye_lib::audit::entry::{Entry, GapReason, Kind}; +use daemoneye_lib::audit::merkle::Frontier; +use daemoneye_lib::audit::reader::{LedgerReader, ReaderError}; +use daemoneye_lib::audit::signing::SigningState; +use daemoneye_lib::audit::verify::{ + CAVEAT, Check, CheckpointSigning, ProofAnchor, TrustedDisagreement, Verification, VerifyError, + VerifyOptions, export_checkpoint, prove, +}; + +const SHORT: u64 = 50; +const ENTRY: u64 = 20; + +fn long() -> u64 { + 2 * interval() + 10 +} + +#[test] +fn payload_hash_altered_fails_as_entry_hash() { + let ws = Workspace::new(); + let path = ws.ledger("a.redb", Spec::signed(SHORT)); + consistent(&path); + change_entry(&path, ENTRY, |entry| entry.payload_hash[0] ^= 1); + assert_eq!( + failure(run(&path, &VerifyOptions::new())), + (ENTRY, Check::EntryHash) + ); +} + +#[test] +fn entry_rewritten_with_fresh_hashes_fails_at_the_next_chain_link() { + let ws = Workspace::new(); + let rows = ws.build_rows(Spec::signed(SHORT)); + let path = ws.path("a.redb"); + write_rows(&path, &rows); + consistent(&path); + let mut before = Frontier::new(); + for entry in rows.entries.iter().take(20) { + before.append(entry.ledger_leaf()).unwrap(); + } + let kind = Kind::Gap { + missed: 9_999, + reason: GapReason::LedgerUnavailable, + }; + let (rewritten, _after) = Entry::next(rows.entries.get(19), kind, 1_000, &before).unwrap(); + rewritten.verify_self().unwrap(); + edit(&path, |ledger, _checkpoints| { + ledger + .insert(ENTRY, rewritten.encode().unwrap().as_slice()) + .unwrap(); + }); + assert_eq!( + failure(run(&path, &VerifyOptions::new())), + (ENTRY + 1, Check::ChainLink) + ); +} + +#[test] +fn entries_rebuilt_under_an_old_checkpoint_fail_at_that_checkpoint() { + let ws = Workspace::new(); + let original = ws.build_rows(Spec::signed(long())); + let mut rebuilt = ws.build_rows(Spec { + salt_from: interval() / 2, + ..Spec::signed(long()) + }); + let path = ws.path("a.redb"); + write_rows(&path, &original); + consistent(&path); + // Entries from half an interval on are rebuilt with correct hashes, links and roots, but + // the checkpoints are the originals. + rebuilt.checkpoints = original.checkpoints; + let tampered = ws.path("b.redb"); + write_rows(&tampered, &rebuilt); + assert_eq!( + failure(run(&tampered, &VerifyOptions::new())), + (interval(), Check::CheckpointRoot) + ); +} + +#[test] +fn removed_entry_fails_as_sequence_gap_at_the_next_one() { + let ws = Workspace::new(); + let path = ws.ledger("a.redb", Spec::signed(SHORT)); + consistent(&path); + edit(&path, |ledger, _checkpoints| { + ledger.remove(ENTRY).unwrap(); + }); + assert_eq!( + failure(run(&path, &VerifyOptions::new())), + (ENTRY + 1, Check::SequenceGap) + ); +} + +#[test] +fn recorded_root_altered_fails_as_merkle_root() { + let ws = Workspace::new(); + let path = ws.ledger("a.redb", Spec::signed(SHORT)); + consistent(&path); + change_entry(&path, ENTRY, |entry| entry.root[0] ^= 1); + assert_eq!( + failure(run(&path, &VerifyOptions::new())), + (ENTRY, Check::MerkleRoot) + ); +} + +#[test] +fn checkpoint_signature_altered_fails_as_checkpoint_signature() { + let ws = Workspace::new(); + let path = ws.ledger("a.redb", Spec::signed(long())); + consistent(&path); + edit(&path, |_ledger, checkpoints| { + let mut checkpoint = + Checkpoint::decode(checkpoints.get(interval()).unwrap().unwrap().value()).unwrap(); + let SigningState::Signed { + ref mut signature, .. + } = checkpoint.signing + else { + panic!("checkpoint is not signed"); + }; + signature[0] ^= 1; + checkpoints + .insert(interval(), checkpoint.encode().unwrap().as_slice()) + .unwrap(); + }); + assert_eq!( + failure(run(&path, &VerifyOptions::new())), + (interval(), Check::CheckpointSignature) + ); +} + +#[test] +fn garbage_entry_row_fails_as_entry_hash() { + let ws = Workspace::new(); + let path = ws.ledger("a.redb", Spec::signed(SHORT)); + consistent(&path); + edit(&path, |ledger, _checkpoints| { + ledger.insert(ENTRY, [0xff_u8; 12].as_slice()).unwrap(); + }); + assert_eq!( + failure(run(&path, &VerifyOptions::new())), + (ENTRY, Check::EntryHash) + ); +} + +#[test] +fn garbage_checkpoint_row_fails_as_checkpoint_root() { + let ws = Workspace::new(); + let path = ws.ledger("a.redb", Spec::signed(long())); + consistent(&path); + edit(&path, |_ledger, checkpoints| { + checkpoints + .insert(interval(), [0xff_u8; 5].as_slice()) + .unwrap(); + }); + assert_eq!( + failure(run(&path, &VerifyOptions::new())), + (interval(), Check::CheckpointRoot) + ); +} + +#[test] +fn checkpoint_beyond_the_last_entry_fails_as_checkpoint_root() { + let ws = Workspace::new(); + let path = ws.ledger("a.redb", Spec::signed(long())); + let last = long(); + let extra = ws.build_rows(Spec::signed(3 * interval())); + let stray = extra.checkpoints.last().unwrap().clone(); + consistent(&path); + edit(&path, |_ledger, checkpoints| { + checkpoints + .insert(stray.tree_size, stray.encode().unwrap().as_slice()) + .unwrap(); + }); + assert!(stray.tree_size > last); + assert_eq!( + failure(run(&path, &VerifyOptions::new())), + (stray.tree_size, Check::CheckpointRoot) + ); +} + +#[test] +fn untouched_ledger_is_consistent_and_reports_the_caveat() { + let ws = Workspace::new(); + let path = ws.ledger("a.redb", Spec::signed(long())); + let report = consistent(&path); + assert_eq!(report.entry_count, long()); + assert_ne!(report.caveat(), ""); + assert_eq!(report.caveat(), CAVEAT); + let latest = report.latest_checkpoint().unwrap(); + assert_eq!(latest.tree_size, 2 * interval()); + assert_eq!( + latest.signing, + CheckpointSigning::Signed { + key_id: ws.key_id(0) + } + ); + assert_eq!(report.key_changes, Vec::::new()); + assert_eq!(report.signing_downgrades, Vec::::new()); +} + +#[test] +fn trusted_checkpoint_from_the_same_ledger_stays_consistent() { + let ws = Workspace::new(); + let path = ws.ledger("a.redb", Spec::signed(long())); + let blob = export_checkpoint(&reader(&path), interval()).unwrap(); + let verdict = run(&path, &VerifyOptions::new().with_trusted_checkpoint(&blob)); + assert!( + matches!(verdict, Verification::Consistent(_)), + "got {verdict:?}" + ); +} + +#[test] +fn trusted_checkpoint_with_a_foreign_root_is_a_mismatch() { + let ws = Workspace::new(); + let path = ws.ledger("a.redb", Spec::signed(long())); + let other = ws.ledger( + "other.redb", + Spec { + salt_from: 0, + ..Spec::signed(long()) + }, + ); + let blob = export_checkpoint(&reader(&other), interval()).unwrap(); + let verdict = run(&path, &VerifyOptions::new().with_trusted_checkpoint(&blob)); + let Verification::TrustedDisagreement { disagreement, .. } = verdict else { + panic!("expected a trusted disagreement, got {verdict:?}"); + }; + assert_eq!( + disagreement, + TrustedDisagreement::RootMismatch { + tree_size: interval() + } + ); +} + +#[test] +fn trusted_checkpoint_with_a_bad_signature_is_an_error_not_a_ledger_failure() { + let ws = Workspace::new(); + let path = ws.ledger("a.redb", Spec::signed(long())); + let mut blob = export_checkpoint(&reader(&path), interval()).unwrap(); + let SigningState::Signed { + ref mut signature, .. + } = blob.signing + else { + panic!("blob is not signed"); + }; + signature[0] ^= 1; + assert_eq!(blob.verify(), SignatureVerdict::BadSignature); + let outcome = daemoneye_lib::audit::verify::verify( + &reader(&path), + &VerifyOptions::new().with_trusted_checkpoint(&blob), + ); + assert!( + matches!(outcome, Err(VerifyError::TrustedCheckpointInvalid)), + "got {outcome:?}" + ); +} + +#[test] +fn ledger_rebuilt_under_a_new_key_is_consistent_until_the_old_key_is_trusted() { + let ws = Workspace::new(); + let original = ws.ledger("a.redb", Spec::signed(long())); + let trusted = VerifyOptions::new().with_trusted_key_id(ws.key_id(0)); + assert!(matches!( + run(&original, &trusted), + Verification::Consistent(_) + )); + let rebuilt = ws.ledger( + "b.redb", + Spec { + choose: |_size| Choice::Key(1), + ..Spec::signed(long()) + }, + ); + let report = consistent(&rebuilt); + let keys: BTreeSet<_> = report + .checkpoints + .iter() + .map(|summary| format!("{:?}", summary.signing)) + .collect(); + assert_eq!(keys.len(), 1); + assert_eq!( + failure(run(&rebuilt, &trusted)), + (interval(), Check::CheckpointKey) + ); +} + +#[test] +fn key_change_part_way_is_reported_at_the_first_checkpoint_of_the_new_key() { + let ws = Workspace::new(); + let path = ws.ledger( + "a.redb", + Spec { + choose: |size| { + if size <= 64 { + Choice::Key(0) + } else { + Choice::Key(1) + } + }, + ..Spec::signed(3 * interval() + 5) + }, + ); + let report = consistent(&path); + assert_eq!(report.key_changes, vec![2 * interval()]); + assert_eq!(report.signing_downgrades, Vec::::new()); +} + +#[test] +fn signing_turned_off_part_way_is_reported_once_at_the_first_unsigned_checkpoint() { + let ws = Workspace::new(); + let path = ws.ledger( + "a.redb", + Spec { + choose: |size| { + if size <= 64 { + Choice::Key(0) + } else { + Choice::Config + } + }, + ..Spec::signed(3 * interval() + 5) + }, + ); + let report = consistent(&path); + assert_eq!(report.signing_downgrades, vec![2 * interval()]); + assert_eq!(report.key_changes, Vec::::new()); +} + +#[test] +fn ledger_unsigned_by_configuration_throughout_has_no_downgrade() { + let ws = Workspace::new(); + let path = ws.ledger( + "a.redb", + Spec { + choose: |_size| Choice::Config, + ..Spec::signed(long()) + }, + ); + let report = consistent(&path); + assert_eq!(report.signing_downgrades, Vec::::new()); + assert_eq!( + report.latest_checkpoint().unwrap().signing, + CheckpointSigning::UnsignedByConfig + ); + // Someone who brought a key must not be told an unsigned ledger is signed by it. + let trusted = VerifyOptions::new().with_trusted_key_id(ws.key_id(0)); + assert_eq!( + failure(run(&path, &trusted)), + (interval(), Check::CheckpointKey) + ); +} + +#[test] +fn trusted_key_with_no_checkpoint_in_the_ledger_is_a_disagreement() { + let ws = Workspace::new(); + // Short of the first checkpoint: no row in the ledger is signed by anyone. + let short = ws.ledger("short.redb", Spec::signed(interval() - 1)); + assert_eq!(consistent(&short).checkpoints.len(), 0); + + let trusted = VerifyOptions::new().with_trusted_key_id(ws.key_id(0)); + let Verification::TrustedDisagreement { disagreement, .. } = run(&short, &trusted) else { + panic!("a key-pinned run that met no checkpoint must not be consistent"); + }; + assert_eq!( + disagreement, + TrustedDisagreement::NoCheckpointForTrustedKey { + ledger_entries: interval() - 1 + } + ); + + // With a checkpoint signed by that key, the same options are consistent. + let long_enough = ws.ledger("long.redb", Spec::signed(interval())); + assert!(matches!( + run(&long_enough, &trusted), + Verification::Consistent(_) + )); +} + +#[test] +fn truncated_ledger_is_consistent_alone_but_shorter_than_a_trusted_checkpoint() { + let ws = Workspace::new(); + let original = ws.ledger("a.redb", Spec::signed(long())); + let blob = export_checkpoint(&reader(&original), 2 * interval()).unwrap(); + let cut = ws.ledger("cut.redb", Spec::signed(interval() + 10)); + consistent(&cut); + let verdict = run(&cut, &VerifyOptions::new().with_trusted_checkpoint(&blob)); + let Verification::TrustedDisagreement { disagreement, .. } = verdict else { + panic!("expected a trusted disagreement, got {verdict:?}"); + }; + assert_eq!( + disagreement, + TrustedDisagreement::LedgerShorter { + ledger_entries: interval() + 10, + trusted_tree_size: 2 * interval(), + } + ); +} + +#[test] +fn earlier_timestamp_is_noted_but_consistent() { + let ws = Workspace::new(); + let path = ws.ledger( + "a.redb", + Spec { + regress_at: Some(30), + ..Spec::signed(SHORT) + }, + ); + let report = consistent(&path); + assert_eq!(report.timestamp_regressions, vec![30]); + assert_eq!(report.timestamp_regression_count, 1); +} + +#[test] +fn proofs_verify_against_the_current_root_and_against_a_checkpoint() { + let ws = Workspace::new(); + let path = ws.ledger("a.redb", Spec::signed(long())); + let report = consistent(&path); + let handle = reader(&path); + for seq in 0..long() { + let proof = prove(&handle, seq, ProofAnchor::CurrentRoot).unwrap(); + assert!(proof.verify(), "proof for {seq} does not verify"); + assert_eq!(proof.root, report.final_root); + } + let checkpoint_root = handle.checkpoint(interval()).unwrap().unwrap().root; + for seq in 0..interval() { + let proof = prove(&handle, seq, ProofAnchor::Checkpoint(interval())).unwrap(); + assert!(proof.verify(), "checkpoint proof for {seq} does not verify"); + assert_eq!(proof.root, checkpoint_root); + } + let beyond = prove(&handle, interval(), ProofAnchor::Checkpoint(interval())); + assert!( + matches!(beyond, Err(VerifyError::SequenceOutOfRange { .. })), + "got {beyond:?}" + ); + let missing = prove(&handle, 0, ProofAnchor::Checkpoint(interval() + 1)); + assert!( + matches!(missing, Err(VerifyError::NoCheckpoint { .. })), + "got {missing:?}" + ); + let past_end = prove(&handle, long(), ProofAnchor::CurrentRoot); + assert!( + matches!(past_end, Err(VerifyError::SequenceOutOfRange { .. })), + "got {past_end:?}" + ); +} + +#[test] +fn exported_checkpoint_verifies_alone_and_matches_the_stored_one() { + let ws = Workspace::new(); + let path = ws.ledger("a.redb", Spec::signed(long())); + let handle = reader(&path); + let blob = export_checkpoint(&handle, interval()).unwrap(); + assert_eq!( + blob.verify(), + SignatureVerdict::ValidSigned { + key_id: ws.key_id(0) + } + ); + assert_eq!( + blob, + handle.checkpoint(interval()).unwrap().unwrap().export() + ); + let missing = export_checkpoint(&handle, interval() + 1); + assert!( + matches!(missing, Err(VerifyError::NoCheckpoint { .. })), + "got {missing:?}" + ); +} + +#[test] +fn empty_ledgers_verify_with_zero_entries() { + let ws = Workspace::new(); + let written = ws.ledger("empty.redb", Spec::signed(0)); + let bare = ws.path("bare.redb"); + create_bare(&bare); + for path in [written, bare] { + let report = consistent(&path); + assert_eq!(report.entry_count, 0); + assert_eq!(report.checkpoints, Vec::new()); + } +} + +#[test] +fn missing_file_surfaces_as_missing() { + let ws = Workspace::new(); + let outcome = LedgerReader::open(&ws.path("absent.redb")); + assert!( + matches!(outcome, Err(ReaderError::Open(LedgerReadError::Missing))), + "got {outcome:?}" + ); +} diff --git a/daemoneye-lib/tests/audit_verify_support/mod.rs b/daemoneye-lib/tests/audit_verify_support/mod.rs new file mode 100644 index 00000000..7b7809aa --- /dev/null +++ b/daemoneye-lib/tests/audit_verify_support/mod.rs @@ -0,0 +1,243 @@ +//! Builds real ledger files the way the writer lays them out, and tampers with them. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +#![allow( + clippy::indexing_slicing, + clippy::arithmetic_side_effects, + clippy::missing_const_for_fn, + clippy::unused_self, + clippy::semicolon_outside_block, + clippy::integer_division, + clippy::wildcard_enum_match_arm, + reason = "fixtures index and count fixed-size vectors" +)] + +use std::path::{Path, PathBuf}; + +use daemoneye_lib::audit::checkpoint::{CHECKPOINT_INTERVAL, Checkpoint}; +use daemoneye_lib::audit::entry::{Entry, GapReason, Kind}; +use daemoneye_lib::audit::merkle::Frontier; +use daemoneye_lib::audit::reader::LedgerReader; +use daemoneye_lib::audit::signing::{CheckpointSigner, KeyOutcome, SigningMode, resolve_key}; +use daemoneye_lib::audit::tables::{ + AUDIT_CHECKPOINTS, AUDIT_FRONTIER, AUDIT_LEDGER, AUDIT_META, LEDGER_FORMAT_VERSION, + META_FORMAT_VERSION, +}; +use daemoneye_lib::audit::verify::{Check, Failure, Report, Verification, VerifyOptions, verify}; +use redb::{Builder, ConcurrencyMode, ReadableTable, Table}; +use tempfile::TempDir; + +const CACHE_BYTES: usize = 4 * 1024 * 1024; +const TS_STEP_MS: i64 = 10; + +/// How one checkpoint is signed. +#[derive(Clone, Copy)] +pub enum Choice { + Key(usize), + Config, +} + +/// What a built ledger contains. +#[derive(Clone, Copy)] +pub struct Spec { + pub count: u64, + /// Entries from this sequence on carry different payloads. + pub salt_from: u64, + /// This sequence gets a timestamp below its predecessor's. + pub regress_at: Option, + /// Signing choice for the checkpoint at the given tree size. + pub choose: fn(u64) -> Choice, +} + +impl Spec { + pub fn signed(count: u64) -> Self { + Self { + count, + salt_from: u64::MAX, + regress_at: None, + choose: |_size| Choice::Key(0), + } + } +} + +/// Everything the writer would store. +pub struct Rows { + pub entries: Vec, + pub checkpoints: Vec, + pub frontier: Frontier, +} + +/// A temp dir, two signing keys and a place for ledger files. +pub struct Workspace { + dir: TempDir, + signers: Vec, +} + +pub fn interval() -> u64 { + CHECKPOINT_INTERVAL +} + +impl Workspace { + pub fn new() -> Self { + let dir = TempDir::new().unwrap(); + let signers = (0..2) + .map( + |n| match resolve_key(true, &dir.path().join(format!("key-{n}")), true) { + KeyOutcome::Signer { signer, .. } => signer, + other => panic!("key {n} not created: {other:?}"), + }, + ) + .collect(); + Self { dir, signers } + } + + pub fn key_id(&self, index: usize) -> [u8; 32] { + self.signers.get(index).unwrap().key_id() + } + + pub fn path(&self, name: &str) -> PathBuf { + self.dir.path().join(name) + } + + pub fn build_rows(&self, spec: Spec) -> Rows { + let mut entries: Vec = Vec::new(); + let mut checkpoints = Vec::new(); + let mut frontier = Frontier::new(); + for seq in 0..spec.count { + let salt = if seq >= spec.salt_from { 1000 } else { 0 }; + let kind = Kind::Gap { + missed: seq + salt, + reason: GapReason::CommitFailed, + }; + let (entry, after) = + Entry::next(entries.last(), kind, self.ts(spec, seq), &frontier).unwrap(); + entries.push(entry); + frontier = after; + let size = frontier.leaf_count(); + if size.is_multiple_of(CHECKPOINT_INTERVAL) { + checkpoints.push(self.checkpoint(&frontier, (spec.choose)(size))); + } + } + Rows { + entries, + checkpoints, + frontier, + } + } + + fn ts(&self, spec: Spec, seq: u64) -> i64 { + let base = i64::try_from(seq).unwrap() * TS_STEP_MS; + if spec.regress_at == Some(seq) { + 0 + } else { + base + 1_000 + } + } + + fn checkpoint(&self, frontier: &Frontier, choice: Choice) -> Checkpoint { + let mode = match choice { + Choice::Key(index) => SigningMode::Signed(self.signers.get(index).unwrap()), + Choice::Config => SigningMode::UnsignedByConfig, + }; + Checkpoint::build(frontier, 5_000, mode) + } + + /// Build and write a ledger file, closing the writer before returning. + pub fn ledger(&self, name: &str, spec: Spec) -> PathBuf { + let path = self.path(name); + write_rows(&path, &self.build_rows(spec)); + path + } +} + +fn open_rw(path: &Path) -> redb::Database { + Builder::new() + .set_cache_size(CACHE_BYTES) + .set_concurrency_mode(ConcurrencyMode::SingleWriter) + .create(path) + .unwrap() +} + +pub fn write_rows(path: &Path, rows: &Rows) { + let db = open_rw(path); + let txn = db.begin_write().unwrap(); + { + let mut ledger = txn.open_table(AUDIT_LEDGER).unwrap(); + for entry in &rows.entries { + ledger + .insert(entry.seq, entry.encode().unwrap().as_slice()) + .unwrap(); + } + let mut checkpoints = txn.open_table(AUDIT_CHECKPOINTS).unwrap(); + for checkpoint in &rows.checkpoints { + checkpoints + .insert( + checkpoint.tree_size, + checkpoint.encode().unwrap().as_slice(), + ) + .unwrap(); + } + let frontier = postcard::to_allocvec(&rows.frontier).unwrap(); + txn.open_table(AUDIT_FRONTIER) + .unwrap() + .insert((), frontier.as_slice()) + .unwrap(); + txn.open_table(AUDIT_META) + .unwrap() + .insert(META_FORMAT_VERSION, LEDGER_FORMAT_VERSION) + .unwrap(); + } + txn.commit().unwrap(); +} + +/// A file redb created and nothing else: no tables at all. +pub fn create_bare(path: &Path) { + drop(open_rw(path)); +} + +/// Reopen the ledger for writing, apply `edit` to the entry and checkpoint tables, and close. +pub fn edit( + path: &Path, + edit: impl FnOnce(&mut Table<'_, u64, &[u8]>, &mut Table<'_, u64, &[u8]>), +) { + let db = open_rw(path); + let txn = db.begin_write().unwrap(); + { + let mut ledger = txn.open_table(AUDIT_LEDGER).unwrap(); + let mut checkpoints = txn.open_table(AUDIT_CHECKPOINTS).unwrap(); + edit(&mut ledger, &mut checkpoints); + } + txn.commit().unwrap(); +} + +/// Replace entry `seq` with the result of `change` applied to its decoded form. +pub fn change_entry(path: &Path, seq: u64, change: impl FnOnce(&mut Entry)) { + edit(path, |ledger, _checkpoints| { + let mut entry = Entry::decode(ledger.get(seq).unwrap().unwrap().value()).unwrap(); + change(&mut entry); + ledger + .insert(seq, entry.encode().unwrap().as_slice()) + .unwrap(); + }); +} + +pub fn run(path: &Path, options: &VerifyOptions<'_>) -> Verification { + verify(&LedgerReader::open(path).unwrap(), options).unwrap() +} + +pub fn consistent(path: &Path) -> Report { + match run(path, &VerifyOptions::new()) { + Verification::Consistent(report) => report, + other => panic!("expected a consistent ledger, got {other:?}"), + } +} + +pub fn failure(verification: Verification) -> (u64, Check) { + match verification { + Verification::Failed(Failure { at, check, .. }) => (at, check), + other => panic!("expected a failure, got {other:?}"), + } +} + +pub fn reader(path: &Path) -> LedgerReader { + LedgerReader::open(path).unwrap() +} diff --git a/docs/adr/0016-the-ledger-commits-what-procmond-records.md b/docs/adr/0016-the-ledger-commits-what-procmond-records.md new file mode 100644 index 00000000..9546cfe9 --- /dev/null +++ b/docs/adr/0016-the-ledger-commits-what-procmond-records.md @@ -0,0 +1,79 @@ +# ADR-0016: The ledger commits what procmond records + +**Date**: 2026-11-28 **Status**: accepted **Deciders**: UncleSp1d3r + +## Context + +DaemonEye observes an adversary who alters logs, and the docs promise that what a collector saw is kept in alter-evident form. Before this decision nothing delivered it: the ledger type was an in-memory list that no production code wrote to, and its inclusion-proof function returned an empty list. procmond's first record of an observation is its write-ahead log (WAL), whose entries carry a CRC32. A CRC catches corruption, not alteration, because whoever edits an entry can recompute it. + +The upstream documents disagreed on coverage: "all events", "security-relevant events", and a log file rather than a database table. Process records also do not reach the agent's event store from procmond yet, so a ledger anchored in the agent would commit nothing real. + +## Decision + +procmond writes a hash-chained RFC 6962 Merkle ledger in its own redb file. Each entry commits one collection cycle's recorded events (first and last WAL sequence, count and a Merkle root over each sanitised event's hash) or one action procmond took. Checkpoints every 64 entries are signed with an Ed25519 key that sits beside the ledger. The ledger is local evidence of alteration; it does not claim to prove integrity against someone who can write both files. + +## Alternatives Considered + +### Alternative 1: Commit only security-relevant actions + +- **Pros**: tiny ledger; matches the original requirement wording. +- **Cons**: the observations themselves stay in a log whose only protection is a CRC. +- **Why not**: the point of the tree is to make the first record of what procmond observed alter-evident. + +### Alternative 2: One ledger leaf per event + +- **Pros**: an alteration localises to one event. +- **Cons**: ledger growth proportional to event volume. +- **Why not**: a batch root localises an alteration to one collection cycle, which is enough. Per-event leaves can be added if examiners need them. + +### Alternative 3: Commit when the agent receives or stores the record + +- **Pros**: ties the ledger to what the agent holds. +- **Cons**: the enumeration RPC returns no records today and the agent stores nothing procmond publishes, so the ledger would be empty. +- **Why not**: committing where procmond observes works whichever transport delivers records later. Events are committed whether or not the broker accepted them: the ledger records what was observed, not what was delivered. + +### Alternative 4: `rs_merkle` as the production tree + +- **Pros**: no tree code to own. +- **Cons**: it keeps every leaf and a clone of every commit in memory, cannot save or restore its state, and applies no leaf or node prefix. +- **Why not**: the writer must hold memory proportional to the logarithm of the entry count and survive a restart from a persisted frontier. The tree is hand-rolled to RFC 6962 over BLAKE3 and `rs_merkle` is a dev-dependency used as a test oracle. + +### Alternative 5: Any process may write the ledger + +- **Pros**: the agent could record its own actions. +- **Cons**: the agent holds more privilege and a compromised agent could forge history. +- **Why not**: only procmond opens the file for writing, and the function that does so lives in the procmond crate. The library offers a read-only open. + +### Alternative 6: Pin the first key or latest checkpoint in the agent + +- **Pros**: would expose a ledger rebuilt under a new key. +- **Cons**: new stored state, and no help if the attacker also holds the agent's store. +- **Why not**: verification reports every key id and every signed-to-unsigned or key change, and accepts a trusted key id, which pins the signer, or a trusted checkpoint kept off the host, which pins the history. + +### Alternative 7: Stop collecting when the ledger fails + +- **Pros**: no unrecorded observations. +- **Cons**: losing visibility is worse than a recorded gap. +- **Why not**: collection continues, health reports degraded and names the ledger, and the next entry written records how many commits were missed. + +## Consequences + +### Positive + +- An alteration to a committed entry, a root or a checkpoint is detected from the ledger alone, and a set of event records can be checked against the batch entry that committed it. +- One writer and any number of read-only readers share the file; CI proves this on Linux, macOS and Windows. +- No per-event growth: the ledger grows with cycles and actions. + +### Negative + +- Someone with root on the host who holds the signing key can rewrite the whole ledger consistently. The rewrite keeps the same key id, so only a checkpoint taken with `export_checkpoint` and kept off the host detects it, and only for the history it covers. A trusted key id detects a ledger rebuilt under a different key, with signing off, or with no checkpoint. Entries after the last checkpoint are not signed. Off-box anchoring belongs to the commercial tiers, which extend this foundation, are sold separately and are not in this repo. +- The signing key is created only for an empty ledger and never regenerated. A missing or too-wide key file on a non-empty ledger yields unsigned checkpoints. +- An inclusion proof binds a leaf to a root. A changed stated total is not always detected: index 0 of 3 and index 0 of 4 can both verify. +- Only broker-connected (actor) mode keeps a ledger. Standalone mode has no WAL to commit from and records nothing. +- redb's single-writer mode needs byte-range locks. On platforms without them (for example FreeBSD) procmond still writes the ledger, in redb's default mode, but the read-only handle reports the platform as unsupported, so verification is not available there. That path has no CI coverage. +- Deliveries can remove a rotated WAL file before its cycle's batch commits. A crash in that window, in a cycle that also rotated the WAL, leaves events the ledger never committed and no gap entry for them. Recovery covers only what the WAL still holds. + +### Risks + +- The batch check needs every field of the hashed projection. The projection includes the executable hash, its algorithm and the collection time, which the wire event to the agent does not carry today; the end-to-end integration work must extend the wire event or it cannot recompute batch roots. +- A ledger that refuses to open stays refused until an operator moves the ledger and key files aside and restarts procmond; see [security](../src/security.md). The files are moved, never deleted, so the evidence survives. diff --git a/docs/adr/README.md b/docs/adr/README.md index 27d3908d..95181529 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ This directory continues that sequence rather than restarting it, so an ADR numb | [0013](0013-the-provider-reports-inexact-filter-pushdown.md) | The provider reports Inexact filter pushdown, never Exact | accepted | 2026-10-10 | | [0014](0014-a-cycle-evaluates-its-own-window.md) | A detection cycle evaluates the rows its own window covers | accepted | 2026-10-10 | | [0015](0015-delivery-state-is-independent-of-the-detection-cursor.md) | Delivery state is independent of the detection cursor | accepted | 2026-10-12 | +| [0016](0016-the-ledger-commits-what-procmond-records.md) | The ledger commits what procmond records | accepted | 2026-11-28 | diff --git a/docs/src/architecture.md b/docs/src/architecture.md index 4965c631..ce7d23a9 100644 --- a/docs/src/architecture.md +++ b/docs/src/architecture.md @@ -88,7 +88,7 @@ graph TB - **Process Enumeration**: Cross-platform process data collection using sysinfo crate - **Executable Hashing**: SHA-256 hash computation for integrity verification -- **Audit Logging**: BLAKE3 hash-chained audit ledger (Merkle inclusion proofs In Progress) +- **Audit Logging**: BLAKE3 hash-chained audit ledger (RFC 6962 Merkle tree, Ed25519-signed checkpoints, offline inclusion proofs) - **EventBus Communication**: Publishes process events through the embedded daemoneye-eventbus broker hosted by daemoneye-agent **Security Boundaries**: @@ -303,8 +303,10 @@ message DetectionResult { - **Purpose**: Tamper-evident audit trail using a BLAKE3 hash-chained ledger - **Access**: procmond write-only -- **Features**: Per-entry BLAKE3 hash chaining with optional Ed25519 signatures -- **Implementation**: rs-merkle scaffolding present; Merkle inclusion proofs are In Progress +- **Features**: Per-entry BLAKE3 hash chaining, RFC 6962 Merkle tree, Ed25519-signed checkpoints, offline inclusion proofs +- **Implementation**: `daemoneye-lib/src/audit/` (tree, entries, verification) and `procmond/src/audit_writer/` (the only writer); see [ADR-0016](../adr/0016-the-ledger-commits-what-procmond-records.md) +- **Limit**: The ledger is local evidence of alteration, not proof of integrity: someone with root on the host who holds the signing key can rewrite the whole ledger consistently under the same key id. Only a checkpoint the operator kept off the host detects that, and only for the history it covers; a trusted key id detects only a ledger rebuilt under a different key or with signing off. Entries after the last checkpoint are not signed. Commercial tiers extend this foundation, are sold separately and are not in this repo. +- **Scope**: only broker-connected (actor) mode keeps a ledger ## Security Architecture diff --git a/docs/src/architecture/system-architecture.md b/docs/src/architecture/system-architecture.md index f80b165e..01950c69 100644 --- a/docs/src/architecture/system-architecture.md +++ b/docs/src/architecture/system-architecture.md @@ -703,69 +703,27 @@ pub struct Alert { } ``` -### Audit Ledger (Hash-chained) +### Audit Ledger (Merkle, hash-chained) -**Purpose**: Tamper-evident audit trail with cryptographic integrity using hash-chained log file. +**Purpose**: Alter-evident record of what procmond recorded and did. Design record: [ADR-0016](../../adr/0016-the-ledger-commits-what-procmond-records.md). -**Implementation**: +**Implementation**: a redb database in its own file (default `/var/lib/daemoneye/audit.redb`), written only by procmond and opened read-only by everyone else. Each entry carries a sequence number, a millisecond UTC timestamp, its kind, a payload hash, the previous entry's hash and its own BLAKE3 hash. Entries are the leaves of an RFC 6962 Merkle tree whose frontier is persisted, so the writer holds `O(log n)` hashes. -The audit ledger is implemented as a hash-chained log file, not a database table. Each entry contains a cryptographic hash of the previous entry, creating an immutable chain. - -**Hash Chain Implementation**: - -```rust,ignore -pub struct AuditChain { - hasher: blake3::Hasher, - signer: Option, - previous_hash: Option, -} - -impl AuditChain { - pub fn append_entry(&mut self, entry: &AuditEntry) -> Result { - let entry_data = serde_json::to_vec(entry)?; - let entry_hash = blake3::hash(&entry_data); - - let record = AuditRecord { - sequence: self.next_sequence(), - timestamp: SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis() as i64, - actor: entry.actor.clone(), - action: entry.action.clone(), - payload_hash: entry_hash, - previous_hash: self.previous_hash, - entry_hash: self.compute_entry_hash(&entry_hash)?, - signature: self.sign_entry(&entry_hash)?, - }; - - self.previous_hash = Some(record.entry_hash); - Ok(record) - } - - pub fn verify_chain(&self, records: &[AuditRecord]) -> Result { - // Verify hash chain integrity and signatures - for (i, record) in records.iter().enumerate() { - if i > 0 { - let prev_record = &records[i - 1]; - if record.previous_hash != Some(prev_record.entry_hash) { - return Err(VerificationError::ChainBroken(i)); - } - } +```mermaid +flowchart LR + W[procmond WAL] -->|each cycle| B[Batch entry
sequence range, count,
Merkle root of event hashes] + A[procmond actions] --> E[Action entry] + B --> L[(Ledger file)] + E --> L + L -->|every 64 entries| C[Signed checkpoint] + L -->|read-only| R[Verify / prove / export] +``` - // Verify entry hash - let computed_hash = self.compute_entry_hash(&record.payload_hash)?; - if record.entry_hash != computed_hash { - return Err(VerificationError::HashMismatch(i)); - } +**What is committed**: one batch entry per collection cycle and one entry per procmond action (start, privileges detected, config update received, executable-hash drift, clean stop, signing key created or failed). Individual event rows are not stored; the batch root lets a set of event records be checked against the entry that committed them. - // Verify signature if present - if let Some(signature) = &record.signature { - self.verify_signature(&record.payload_hash, signature)?; - } - } +**Scope**: only broker-connected (actor) mode keeps a ledger; standalone mode has no WAL to commit from and records nothing. A ledger that refuses to open or fails to commit never stops collection: health reports degraded and names the ledger. - Ok(VerificationResult::Valid) - } -} -``` +**Limit**: The ledger is local evidence of alteration, not proof of integrity: someone with root on the host who holds the signing key can rewrite the whole ledger consistently under the same key id. Only a checkpoint the operator kept off the host detects that, and only for the history it covers; a trusted key id detects only a ledger rebuilt under a different key or with signing off. Entries after the last checkpoint are not signed. Commercial tiers extend this foundation, are sold separately and are not in this repo. ## Security Architecture diff --git a/docs/src/introduction.md b/docs/src/introduction.md index 09552314..994e7965 100644 --- a/docs/src/introduction.md +++ b/docs/src/introduction.md @@ -11,7 +11,7 @@ DaemonEye is an agent-centric system monitoring tool designed for cybersecurity - **Real-time Process Monitoring**: Continuous monitoring of system processes with minimal performance impact - **SQL-Based Detection**: Detection rules expressed in a SQL-like DSL with AST validation - **Cross-Platform Support**: Linux and Windows primary; macOS and FreeBSD secondary -- **Audit-Grade Integrity**: BLAKE3 hash-chained audit ledger with Merkle-proof support (Ed25519 event signing is planned, not yet implemented) +- **Audit-Grade Integrity**: BLAKE3 hash-chained audit ledger with a Merkle tree, Ed25519-signed checkpoints and offline inclusion proofs (local evidence of alteration) - **Air-Gap Friendly**: Fully functional offline; no automatic egress - **Security-Focused**: Built with security best practices and minimal attack surface diff --git a/docs/src/project-overview.md b/docs/src/project-overview.md index 27d15b18..0468b2a1 100644 --- a/docs/src/project-overview.md +++ b/docs/src/project-overview.md @@ -14,9 +14,9 @@ Detect and alert on suspicious system activity through continuous process monito ### **Audit-Grade Integrity** -- Certificate Transparency-style Merkle tree with inclusion proofs (In Progress) suitable for compliance and forensics +- Certificate Transparency-style (RFC 6962) Merkle tree with offline inclusion proofs, local evidence of alteration; detecting a rewrite by someone holding the signing key needs a checkpoint kept off the host - BLAKE3 hashing for fast, cryptographically secure hash computation -- Optional Ed25519 signatures for enhanced integrity verification +- Ed25519-signed checkpoints, on by default - Append-only audit ledger with monotonic sequence numbers ### **Offline-First Operation** @@ -149,8 +149,8 @@ This repository ships the agent-side Community tier. It is appropriate for indiv #### Certificate Transparency Audit Logging - Cryptographic integrity for forensic analysis -- Certificate Transparency-style Merkle tree with rs-merkle -- Ed25519 digital signatures and inclusion proofs (In Progress) +- RFC 6962 Merkle tree over BLAKE3, persisted in its own redb file +- Ed25519-signed checkpoints and offline inclusion proofs - Millisecond-precision timestamps #### Resource-Bounded Operation diff --git a/docs/src/security.md b/docs/src/security.md index 83e9326d..3f599be9 100644 --- a/docs/src/security.md +++ b/docs/src/security.md @@ -150,6 +150,22 @@ impl IntegrityChecker { } ``` +### Audit Ledger + +procmond writes a hash-chained Merkle ledger to its own file (`audit.ledger_path`, default `/var/lib/daemoneye/audit.redb`, mode `0640`). Each collection cycle's recorded events and each procmond action (start, privileges detected, config update received, executable-hash drift, clean stop, signing key created or failed) is one entry. Every 64 entries, and at clean stop, a checkpoint records the tree root and is Ed25519-signed (`audit.signing_enabled`, default `true`). The key is `.key` beside the ledger, mode `0400`, created only for an empty ledger and never regenerated. Design record: [ADR-0016](../adr/0016-the-ledger-commits-what-procmond-records.md). + +**What a verified ledger means.** Verification reports the first sequence and the check that fails (entry hash, chain link, sequence gap, Merkle root, checkpoint root, checkpoint signature or checkpoint key), and lists every signing key id with any key change or signed-to-unsigned transition. A clean result means internally consistent, not proof of integrity: someone with root on the host who holds the signing key can rewrite the whole ledger consistently under the same key id. Detecting that needs a checkpoint you kept off the host: export one with `export_checkpoint`, store it elsewhere, and pass it to verification as trusted; it covers only the history up to its tree size. A trusted key id detects a ledger rebuilt under a different key or with signing off (and a ledger with no checkpoint), not a same-key rewrite or a rollback. Entries after the last checkpoint are not signed. An inclusion proof binds a leaf to a root; a changed stated total is not always detected. Commercial tiers extend this foundation, are sold separately and are not in this repo. + +**Scope.** Only broker-connected (actor) mode keeps a ledger; standalone mode has no WAL to commit from and records nothing. Reading the ledger while procmond writes it needs byte-range file locks. On platforms without them (for example FreeBSD) procmond still writes the ledger, but the read-only handle reports the platform as unsupported and verification is not available there. + +**A ledger that refuses or fails.** A ledger that cannot be opened, fails its start-up consistency check or fails to commit never stops collection. procmond's health check and heartbeat report degraded, and the health check names the ledger. A failed or missing signing key yields unsigned checkpoints and a key-failure entry. To recover: + +1. Stop procmond. +2. Move the ledger file and its `.key` file aside to a safe location. Never delete them: they are the evidence. +3. Start procmond. It creates a fresh ledger and a new key. + +Keep the moved files; verification of the old ledger still works against them, and the new ledger starts a new key history. + ### SQL Injection Prevention Multiple layers of SQL injection prevention: @@ -404,7 +420,7 @@ DaemonEye helps meet various security standards: 1. **Audit Logging**: - Comprehensive event logging - - BLAKE3 hash-chained audit ledger [Implemented]; Merkle tree inclusion proofs \[In Progress — `generate_inclusion_proof()` is stubbed\] + - BLAKE3 hash-chained, Merkle-tree audit ledger with signed checkpoints and inclusion proofs [Implemented] - Long-term retention 2. **Access Controls**: diff --git a/docs/src/technical.md b/docs/src/technical.md index 7a7ad3e5..1a24750c 100644 --- a/docs/src/technical.md +++ b/docs/src/technical.md @@ -57,7 +57,7 @@ graph LR - **Language**: Rust 2024 Edition - **Runtime**: Tokio async runtime - **Event Store**: redb (pure Rust embedded database) -- **Audit Ledger**: Certificate Transparency-style Merkle tree +- **Audit Ledger**: Certificate Transparency-style (RFC 6962) Merkle tree over BLAKE3 - **IPC**: Custom Protobuf over Unix Sockets - **CLI**: clap v4 with derive macros - **Configuration**: figment with hierarchical loading diff --git a/docs/src/technical/security_design_overview.md b/docs/src/technical/security_design_overview.md index 5d34dc3d..652420d9 100644 --- a/docs/src/technical/security_design_overview.md +++ b/docs/src/technical/security_design_overview.md @@ -134,7 +134,7 @@ graph TB - BLAKE3 hashing for all audit entries - Merkle tree integrity verification -- Optional Ed25519 signatures for external verification +- Ed25519-signed checkpoints (on by default) ## Component Security Design @@ -284,44 +284,15 @@ impl SqlValidator { - **Tamper Evidence**: Any modification to historical entries invalidates the entire chain[^26] - **Inclusion Proofs**: Cryptographic proof that specific entries exist in the ledger[^26] -- **Checkpoint Signatures**: Optional Ed25519 signatures for external verification +- **Checkpoint Signatures**: Ed25519 signatures on by default; the signing state is recorded in every checkpoint - **Forward Security**: New entries don't compromise historical integrity - **Append-Only**: Monotonic sequence numbers for all entries[^27] - **BLAKE3 Hashing**: Fast, cryptographically secure hash computation[^25] - **Millisecond Precision**: Proper ordering and millisecond-precision timestamps[^5] -**Implementation Details**: +**Implementation Details**: an RFC 6962 Merkle tree over BLAKE3 with a persisted frontier, in `daemoneye-lib/src/audit/`; procmond is the only writer (`procmond/src/audit_writer/`). Each collection cycle commits one batch entry and each procmond action one entry; checkpoints every 64 entries are Ed25519-signed by default. See [ADR-0016](../../adr/0016-the-ledger-commits-what-procmond-records.md). -```rust,ignore -pub struct AuditLedger { - merkle_tree: MerkleTree, - checkpoints: Vec, - signature_key: Option, -} - -impl AuditLedger { - pub fn append_entry(&mut self, entry: AuditEntry) -> Result { - // Canonicalize entry for consistent hashing - let canonical = self.canonicalize_entry(&entry)?; - let leaf_hash = Blake3Hasher::hash(&canonical); - - // Insert into Merkle tree - self.merkle_tree.insert(leaf_hash).commit(); - - // Generate inclusion proof - let proof = self - .merkle_tree - .proof(&[self.merkle_tree.leaves().len() - 1]); - - // Optional: Sign checkpoint if threshold reached - if self.should_create_checkpoint() { - self.create_signed_checkpoint()?; - } - - Ok(proof) - } -} -``` +**Limit**: The ledger is local evidence of alteration, not proof of integrity: someone with root on the host who holds the signing key can rewrite the whole ledger consistently under the same key id. Only a checkpoint the operator kept off the host detects that, and only for the history it covers; a trusted key id detects only a ledger rebuilt under a different key or with signing off. Entries after the last checkpoint are not signed. Commercial tiers extend this foundation, are sold separately and are not in this repo. ### Key Management @@ -728,7 +699,7 @@ This section explains how DaemonEye addresses specific concerns and requirements **Audit-Grade Evidence Collection**: -DaemonEye's Merkle tree audit ledger provides cryptographically verifiable evidence that ISSOs can use for compliance reporting and forensic investigations. The system generates inclusion proofs for every audit event, enabling ISSOs to demonstrate data integrity and non-repudiation to auditors and investigators. +In broker-connected mode, DaemonEye's Merkle tree audit ledger provides cryptographically verifiable evidence that ISSOs can use for compliance reporting and forensic investigations. Standalone mode keeps no ledger, so none of the following is available there. A cycle whose ledger commit fails has no batch entry: collection continues, and the next entry written records how many commits were missed. The system generates offline-verifiable inclusion proofs for ledger entries (one per collection cycle and per procmond action); a proof shows that one entry belongs under a given root and nothing more. Detecting alteration of the recorded history is a separate step: verifying the ledger against a checkpoint retained off the host, which covers the history up to that checkpoint. Verification reports internal consistency, not proof of integrity: someone with root who holds the signing key can rebuild the ledger under the same key id, so keep an exported checkpoint off the host. A trusted key id detects only a different key or signing turned off. **Minimal Attack Surface for High-Risk Environments**: @@ -745,8 +716,8 @@ DaemonEye operates entirely offline, making it suitable for classified environme DaemonEye directly implements several NIST SP 800-53 controls that ISSOs must verify: - **AU-2 (Audit Events)**: Comprehensive logging of all security-relevant events with structured JSON format -- **AU-9 (Protection of Audit Information)**: Cryptographic integrity protection using BLAKE3 hashing -- **AU-10 (Non-Repudiation)**: Merkle tree audit ledger provides cryptographic proof of data integrity +- **AU-9 (Protection of Audit Information)**: Local tamper evidence using BLAKE3 hashing and signed checkpoints; detecting a rewrite by a key holder needs a checkpoint kept off the host +- **AU-10 (Non-Repudiation)**: Merkle tree audit ledger gives evidence of alteration; it does not prove who signed (see the ledger limit above) - **SI-4 (Information System Monitoring)**: Continuous process monitoring with real-time threat detection - **SC-7 (Boundary Protection)**: Outbound-only network connections with no listening ports - **AC-6 (Least Privilege)**: Minimal privilege implementation with immediate privilege dropping diff --git a/procmond/Cargo.toml b/procmond/Cargo.toml index 64985338..782cab7c 100644 --- a/procmond/Cargo.toml +++ b/procmond/Cargo.toml @@ -32,6 +32,7 @@ path = "src/main.rs" # Core dependencies anyhow = { workspace = true } async-trait = { workspace = true } +blake3 = { workspace = true } chrono = { workspace = true } clap = { workspace = true } @@ -43,6 +44,7 @@ daemoneye-lib = { workspace = true } futures = { workspace = true } postcard = { workspace = true } +redb = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/procmond/src/audit_writer/mod.rs b/procmond/src/audit_writer/mod.rs new file mode 100644 index 00000000..b57c6fac --- /dev/null +++ b/procmond/src/audit_writer/mod.rs @@ -0,0 +1,352 @@ +//! The audit ledger writer. procmond is the only process that opens the ledger file for writing. +//! +//! Synchronous and blocking by design: the caller runs it under `spawn_blocking`. Every append is +//! one redb write transaction holding the entry, the new frontier, any checkpoint that falls due +//! and the last committed WAL sequence, so a crash leaves the whole append or none of it. A +//! ledger that fails its start-up consistency check is never written: the writer refuses. +//! +//! The signing key sits beside the ledger as `.key`. + +mod open; +pub mod projection; +#[cfg(test)] +mod tests; + +use std::path::Path; + +use chrono::Utc; +use daemoneye_lib::audit::checkpoint::{Checkpoint, CheckpointError, is_checkpoint_due}; +use daemoneye_lib::audit::entry::{Action, Entry, EntryError, GapReason, Kind}; +use daemoneye_lib::audit::merkle::{Frontier, Hash}; +use daemoneye_lib::audit::signing::{CheckpointSigner, SigningMode}; +use daemoneye_lib::audit::tables::{AUDIT_CHECKPOINTS, AUDIT_FRONTIER, AUDIT_LEDGER, AUDIT_META}; +use redb::{Database, ReadableDatabase as _}; +use thiserror::Error; + +pub use open::RefuseReason; + +/// Page cache for the ledger; redb's default is 1 GiB. +const LEDGER_CACHE_BYTES: usize = 4 * 1024 * 1024; + +/// Key of the last committed WAL sequence in the metadata table. +const META_LAST_WAL_SEQ: &str = "last_wal_seq"; + +/// What the writer is doing, for health reporting. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[allow( + clippy::exhaustive_enums, + reason = "closed set: every match must decide each case" +)] +pub enum WriterState { + /// Appends commit normally. + Committing, + /// Appends are failing; `missed` of them have not been committed since the last success. + Failing { missed: u64 }, + /// The ledger failed its start-up check and is never written. + Refusing(RefuseReason), +} + +/// Why one append did not commit. +#[derive(Debug, Error)] +#[non_exhaustive] +pub enum CommitError { + #[error("building the ledger entry failed: {0}")] + Entry(#[from] EntryError), + #[error("encoding a checkpoint failed: {0}")] + Checkpoint(#[from] CheckpointError), + #[error("encoding the frontier failed: {0}")] + Frontier(postcard::Error), + #[error("ledger row {0} already exists")] + RowExists(u64), + #[error("ledger storage failed: {0}")] + Storage(Box), + #[cfg(test)] + #[error("injected commit failure")] + Injected, +} + +fn storage>(error: E) -> CommitError { + CommitError::Storage(Box::new(error.into())) +} + +/// Why an append or checkpoint call returned no success. +#[derive(Debug, Error)] +#[non_exhaustive] +pub enum AppendError { + /// The ledger is refusing; nothing was attempted. + #[error("audit ledger is refusing writes: {0}")] + Refusing(RefuseReason), + /// The commit failed and was counted as missed. + #[error("audit ledger commit failed: {0}")] + Failed(#[source] CommitError), +} + +enum Signing { + Signer(CheckpointSigner), + ByConfig, + KeyFailed, +} + +impl Signing { + const fn mode(&self) -> SigningMode<'_> { + match *self { + Self::Signer(ref signer) => SigningMode::Signed(signer), + Self::ByConfig => SigningMode::UnsignedByConfig, + Self::KeyFailed => SigningMode::UnsignedKeyFailed, + } + } +} + +/// Entries and checkpoints built for one transaction, and the tree after them. +struct Pending { + entries: Vec, + checkpoints: Vec, + tree: Frontier, +} + +struct Live { + db: Database, + last: Option, + tree: Frontier, + last_wal_seq: Option, + missed: u64, + signing: Signing, + #[cfg(test)] + inject_failures: std::sync::atomic::AtomicU32, +} + +enum Mode { + Live(Box), + Refusing(RefuseReason), +} + +/// The single writer of one ledger file. Nothing here edits, removes or reorders an entry. +pub struct AuditWriter { + mode: Mode, +} + +impl AuditWriter { + /// Open the ledger at `ledger_path`, creating it when no file exists. Never fails: a ledger + /// that cannot be used yields a writer in the refusing state, and the file is left as found. + #[must_use] + pub fn open(ledger_path: &Path, signing_enabled: bool) -> Self { + match open::open_live(ledger_path, signing_enabled) { + Ok((live, startup)) => { + let mut writer = Self { + mode: Mode::Live(Box::new(live)), + }; + if let Some(action) = startup { + // A failure here is already counted and reported through `state`. + let _outcome = writer.append_action(action); + } + writer + } + Err(reason) => Self { + mode: Mode::Refusing(reason), + }, + } + } + + /// Commit one collection cycle's batch together with the last WAL sequence it covers. + pub fn append_batch( + &mut self, + first_seq: u64, + last_seq: u64, + count: u64, + batch_root: Hash, + recovered: bool, + ) -> Result<(), AppendError> { + let kind = Kind::Batch { + first_seq, + last_seq, + count, + batch_root, + recovered, + }; + self.append(kind, Some(last_seq)) + } + + /// Commit one action procmond took. + pub fn append_action(&mut self, action: Action) -> Result<(), AppendError> { + self.append(Kind::Action(action), None) + } + + /// Write a checkpoint at the current tree size unless one already exists there. + pub fn checkpoint_now(&mut self) -> Result<(), AppendError> { + let live = match self.mode { + Mode::Live(ref mut live) => live, + Mode::Refusing(reason) => return Err(AppendError::Refusing(reason)), + }; + live.checkpoint_now().map_err(AppendError::Failed) + } + + fn append(&mut self, kind: Kind, wal_seq: Option) -> Result<(), AppendError> { + match self.mode { + Mode::Live(ref mut live) => live.append(kind, wal_seq).map_err(AppendError::Failed), + Mode::Refusing(reason) => Err(AppendError::Refusing(reason)), + } + } + + /// Makes the next `count` commits fail. + #[cfg(test)] + pub(crate) fn fail_next_commits(&self, count: u32) { + if let Mode::Live(ref live) = self.mode { + live.inject_failures + .store(count, std::sync::atomic::Ordering::Relaxed); + } + } + + #[must_use] + pub const fn state(&self) -> WriterState { + match self.mode { + Mode::Live(ref live) if live.missed > 0 => WriterState::Failing { + missed: live.missed, + }, + Mode::Live(_) => WriterState::Committing, + Mode::Refusing(reason) => WriterState::Refusing(reason), + } + } + + /// The highest WAL sequence a committed batch covers; survives restart. + #[must_use] + pub const fn last_wal_seq(&self) -> Option { + match self.mode { + Mode::Live(ref live) => live.last_wal_seq, + Mode::Refusing(_) => None, + } + } + + /// Entries committed so far; `None` while refusing. + #[must_use] + pub const fn tree_size(&self) -> Option { + match self.mode { + Mode::Live(ref live) => Some(live.tree.leaf_count()), + Mode::Refusing(_) => None, + } + } + + /// The ledger tree root; `None` while refusing. + #[must_use] + pub fn root(&self) -> Option { + match self.mode { + Mode::Live(ref live) => Some(live.tree.root()), + Mode::Refusing(_) => None, + } + } +} + +impl Live { + fn append(&mut self, kind: Kind, wal_seq: Option) -> Result<(), CommitError> { + let mut kinds = Vec::with_capacity(2); + if self.missed > 0 { + kinds.push(Kind::Gap { + missed: self.missed, + reason: GapReason::CommitFailed, + }); + } + kinds.push(kind); + match self.plan(kinds).and_then(|pending| { + self.commit(&pending, wal_seq)?; + Ok(pending) + }) { + Ok(pending) => { + self.last = pending.entries.last().cloned().or_else(|| self.last.take()); + self.tree = pending.tree; + self.last_wal_seq = wal_seq.or(self.last_wal_seq); + self.missed = 0; + Ok(()) + } + Err(error) => { + self.missed = self.missed.saturating_add(1); + Err(error) + } + } + } + + fn plan(&self, kinds: Vec) -> Result { + let now = Utc::now().timestamp_millis(); + let mut tree = self.tree.clone(); + let mut prev = self.last.clone(); + let mut entries = Vec::with_capacity(kinds.len()); + let mut checkpoints = Vec::new(); + for kind in kinds { + let (entry, after) = Entry::next(prev.as_ref(), kind, now, &tree)?; + if is_checkpoint_due(entry.tree_size) { + checkpoints.push(Checkpoint::build(&after, now, self.signing.mode())); + } + tree = after; + prev = Some(entry.clone()); + entries.push(entry); + } + Ok(Pending { + entries, + checkpoints, + tree, + }) + } + + fn commit(&self, pending: &Pending, wal_seq: Option) -> Result<(), CommitError> { + let txn = self.db.begin_write().map_err(storage)?; + { + let mut ledger = txn.open_table(AUDIT_LEDGER).map_err(storage)?; + for entry in &pending.entries { + let bytes = entry.encode()?; + if ledger + .insert(entry.seq, bytes.as_slice()) + .map_err(storage)? + .is_some() + { + return Err(CommitError::RowExists(entry.seq)); + } + } + let mut checkpoints = txn.open_table(AUDIT_CHECKPOINTS).map_err(storage)?; + for checkpoint in &pending.checkpoints { + let bytes = checkpoint.encode()?; + checkpoints + .insert(checkpoint.tree_size, bytes.as_slice()) + .map_err(storage)?; + } + let frontier = postcard::to_allocvec(&pending.tree).map_err(CommitError::Frontier)?; + txn.open_table(AUDIT_FRONTIER) + .map_err(storage)? + .insert((), frontier.as_slice()) + .map_err(storage)?; + if let Some(seq) = wal_seq { + txn.open_table(AUDIT_META) + .map_err(storage)? + .insert(META_LAST_WAL_SEQ, seq) + .map_err(storage)?; + } + } + #[cfg(test)] + { + use std::sync::atomic::Ordering::Relaxed; + let left = self.inject_failures.load(Relaxed); + if left > 0 { + self.inject_failures.store(left.saturating_sub(1), Relaxed); + return Err(CommitError::Injected); + } + } + txn.commit().map_err(storage) + } + + fn checkpoint_now(&self) -> Result<(), CommitError> { + let size = self.tree.leaf_count(); + if size == 0 || self.has_checkpoint(size)? { + return Ok(()); + } + let now = Utc::now().timestamp_millis(); + let pending = Pending { + entries: Vec::new(), + checkpoints: vec![Checkpoint::build(&self.tree, now, self.signing.mode())], + tree: self.tree.clone(), + }; + self.commit(&pending, None) + } + + fn has_checkpoint(&self, size: u64) -> Result { + let read = self.db.begin_read().map_err(storage)?; + let table = read.open_table(AUDIT_CHECKPOINTS).map_err(storage)?; + Ok(table.get(size).map_err(storage)?.is_some()) + } +} diff --git a/procmond/src/audit_writer/open.rs b/procmond/src/audit_writer/open.rs new file mode 100644 index 00000000..eb115b3e --- /dev/null +++ b/procmond/src/audit_writer/open.rs @@ -0,0 +1,328 @@ +//! Opening the ledger file: creation, the format check and the start-up consistency check. + +use std::fs::{self, File, OpenOptions}; +use std::io::ErrorKind; +use std::path::{Path, PathBuf}; + +use daemoneye_lib::audit::checkpoint::{Checkpoint, CheckpointVerdict, SignatureVerdict}; +use daemoneye_lib::audit::entry::{Action, Entry, GENESIS_PREV_HASH}; +use daemoneye_lib::audit::merkle::Frontier; +use daemoneye_lib::audit::signing::{KeyOutcome, resolve_key}; +use daemoneye_lib::audit::tables::{ + AUDIT_CHECKPOINTS, AUDIT_FRONTIER, AUDIT_LEDGER, AUDIT_META, LEDGER_FORMAT_VERSION, + META_FORMAT_VERSION, +}; +use redb::backends::FileBackend; +use redb::{ + Builder, Database, DatabaseError, ReadableDatabase, ReadableTable as _, + ReadableTableMetadata as _, StorageError, +}; +use thiserror::Error; + +use super::{LEDGER_CACHE_BYTES, Live, META_LAST_WAL_SEQ, Signing}; + +/// Why the writer will not touch the ledger file. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)] +#[allow( + clippy::exhaustive_enums, + reason = "closed set: every match must decide each case" +)] +pub enum RefuseReason { + #[error("the ledger file is locked by another handle")] + Locked, + #[error("permission denied opening the ledger file")] + PermissionDenied, + #[error("the file is not an audit ledger")] + NotALedger, + #[error("the ledger file format version is not supported")] + UnsupportedFormat, + #[error("the ledger's entries, checkpoints and frontier disagree")] + Inconsistent, + #[error("this platform cannot share a ledger between processes")] + UnsupportedPlatform, + #[error("the ledger could not be created or read")] + Storage, +} + +impl From<&DatabaseError> for RefuseReason { + // redb's error enums are #[non_exhaustive], so `if` chains end in the explicit catch-all. + fn from(err: &DatabaseError) -> Self { + if matches!(err, DatabaseError::DatabaseAlreadyOpen) { + return Self::Locked; + } + if matches!(err, DatabaseError::UpgradeRequired(_)) { + return Self::UnsupportedFormat; + } + if matches!(err, DatabaseError::Storage(StorageError::Unsupported)) { + return Self::UnsupportedPlatform; + } + if matches!(err, DatabaseError::Storage(StorageError::Corrupted(_))) { + return Self::NotALedger; + } + if let DatabaseError::Storage(StorageError::Io(ref io)) = *err { + if io.kind() == ErrorKind::PermissionDenied { + return Self::PermissionDenied; + } + if io.kind() == ErrorKind::InvalidData { + return Self::NotALedger; + } + } + Self::Storage + } +} + +/// The key file's path: the ledger file name plus `.key`, in the same directory. +pub(super) fn key_path(ledger_path: &Path) -> PathBuf { + let mut name = ledger_path.as_os_str().to_os_string(); + name.push(".key"); + PathBuf::from(name) +} + +fn builder() -> Builder { + let mut builder = Builder::new(); + builder.set_cache_size(LEDGER_CACHE_BYTES); + #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))] + builder.set_concurrency_mode(redb::ConcurrencyMode::SingleWriter); + builder +} + +/// Create the empty ledger file; it is never observable wider than `0640`, whatever the umask. +/// On non-Unix the directory's inherited ACL applies. +fn create_new_file(path: &Path) -> std::io::Result { + let mut options = OpenOptions::new(); + options.read(true).write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt as _; + options.mode(0o600) + }; + let file = options.open(path)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + file.set_permissions(fs::Permissions::from_mode(0o640))? + }; + Ok(file) +} + +/// Create and initialise a new ledger, or open the one that exists. A file already at the path +/// is never created over, truncated or replaced, and an empty one is refused like any other +/// non-ledger. +fn open_database(path: &Path) -> Result { + match create_new_file(path) { + Ok(file) => { + let created = FileBackend::new(file) + .and_then(|backend| builder().create_with_backend(backend)) + .map_err(|err| RefuseReason::from(&err)) + .and_then(|db| init_tables(&db).map(|()| db)); + if created.is_err() { + // Our own file, created a moment ago: an empty husk would refuse forever. + let _removed = fs::remove_file(path); + } + created + } + Err(create) if create.kind() == ErrorKind::AlreadyExists => { + preflight(path)?; + builder() + .open(path) + .map_err(|open| RefuseReason::from(&open)) + } + Err(err) if err.kind() == ErrorKind::PermissionDenied => { + Err(RefuseReason::PermissionDenied) + } + Err(_err) => Err(RefuseReason::Storage), + } +} + +/// Check an existing file through a read-only handle first: opening it for writing makes redb +/// write to it, and a refused ledger must stay byte-identical. A file left unclean by a crash +/// cannot be read this way; redb repairs it on the writable open and the replay there decides. +fn preflight(path: &Path) -> Result<(), RefuseReason> { + match builder().open_read_only(path) { + Ok(db) => replay(&db).map(|_replayed| ()), + Err(DatabaseError::RepairAborted) => Ok(()), + Err(err) => Err(RefuseReason::from(&err)), + } +} + +fn init_tables(db: &Database) -> Result<(), RefuseReason> { + let storage = |_err: redb::Error| RefuseReason::Storage; + let txn = db.begin_write().map_err(|e| storage(e.into()))?; + txn.open_table(AUDIT_LEDGER) + .map_err(|e| storage(e.into()))?; + txn.open_table(AUDIT_CHECKPOINTS) + .map_err(|e| storage(e.into()))?; + txn.open_table(AUDIT_FRONTIER) + .map_err(|e| storage(e.into()))?; + txn.open_table(AUDIT_META) + .map_err(|e| storage(e.into()))? + .insert(META_FORMAT_VERSION, LEDGER_FORMAT_VERSION) + .map_err(|e| storage(e.into()))?; + txn.commit().map_err(|e| storage(e.into())) +} + +/// What the replay learned. +struct Replayed { + last: Option, + tree: Frontier, + last_wal_seq: Option, +} + +/// Open the ledger and run the start-up checks. Returns the live writer and the action to +/// record first (a key was created, or the key failed), if any. +pub(super) fn open_live( + path: &Path, + signing_enabled: bool, +) -> Result<(Live, Option), RefuseReason> { + let db = open_database(path)?; + let replayed = replay(&db)?; + let (signing, startup) = match resolve_key( + signing_enabled, + &key_path(path), + replayed.tree.leaf_count() == 0, + ) { + KeyOutcome::Signer { signer, created } => { + let action = created.then(|| Action::SigningKeyCreated { + key_id: signer.key_id(), + }); + (Signing::Signer(signer), action) + } + KeyOutcome::UnsignedByConfig => (Signing::ByConfig, None), + KeyOutcome::KeyFailed(failure) => { + tracing::warn!(reason = ?failure, "Audit signing key unusable; checkpoints are unsigned"); + (Signing::KeyFailed, Some(Action::SigningKeyFailed)) + } + }; + let live = Live { + db, + last: replayed.last, + tree: replayed.tree, + last_wal_seq: replayed.last_wal_seq, + missed: 0, + signing, + #[cfg(test)] + inject_failures: std::sync::atomic::AtomicU32::new(0), + }; + Ok((live, startup)) +} + +/// Format check, then the replay of every entry after the latest checkpoint. +fn replay(db: &D) -> Result { + let unreadable = |_err: redb::Error| RefuseReason::Storage; + let read = db.begin_read().map_err(|e| unreadable(e.into()))?; + let meta = read + .open_table(AUDIT_META) + .map_err(|_err| RefuseReason::NotALedger)?; + let version = meta + .get(META_FORMAT_VERSION) + .map_err(|e| unreadable(e.into()))? + .map(|guard| guard.value()); + if version != Some(LEDGER_FORMAT_VERSION) { + return Err(RefuseReason::UnsupportedFormat); + } + let last_wal_seq = meta + .get(META_LAST_WAL_SEQ) + .map_err(|e| unreadable(e.into()))? + .map(|guard| guard.value()); + let ledger = read + .open_table(AUDIT_LEDGER) + .map_err(|_err| RefuseReason::Inconsistent)?; + let checkpoints = read + .open_table(AUDIT_CHECKPOINTS) + .map_err(|_err| RefuseReason::Inconsistent)?; + let frontier_table = read + .open_table(AUDIT_FRONTIER) + .map_err(|_err| RefuseReason::Inconsistent)?; + + let (mut tree, mut prev, start) = match checkpoints.last().map_err(|e| unreadable(e.into()))? { + None => (Frontier::new(), None, 0), + Some((key, value)) => { + let checkpoint = + Checkpoint::decode(value.value()).map_err(|_err| RefuseReason::Inconsistent)?; + check_checkpoint(&checkpoint, key.value())?; + let anchor = checkpoint + .tree_size + .checked_sub(1) + .ok_or(RefuseReason::Inconsistent)?; + let entry = ledger + .get(anchor) + .map_err(|e| unreadable(e.into()))? + .ok_or(RefuseReason::Inconsistent) + .and_then(|row| decode_entry(row.value()))?; + if entry.seq != anchor + || entry.tree_size != checkpoint.tree_size + || entry.root != checkpoint.root + { + return Err(RefuseReason::Inconsistent); + } + (checkpoint.frontier, Some(entry), checkpoint.tree_size) + } + }; + + for row in ledger.range(start..).map_err(|e| unreadable(e.into()))? { + let (key, value) = row.map_err(|e| unreadable(e.into()))?; + let entry = decode_entry(value.value())?; + let (expected_seq, expected_prev) = prev + .as_ref() + .map_or(Some((0, GENESIS_PREV_HASH)), |last| { + last.seq.checked_add(1).map(|seq| (seq, last.entry_hash)) + }) + .ok_or(RefuseReason::Inconsistent)?; + if key.value() != expected_seq + || entry.seq != expected_seq + || entry.prev_hash != expected_prev + { + return Err(RefuseReason::Inconsistent); + } + tree.append(entry.ledger_leaf()) + .map_err(|_err| RefuseReason::Inconsistent)?; + if entry.tree_size != tree.leaf_count() || entry.root != tree.root() { + return Err(RefuseReason::Inconsistent); + } + prev = Some(entry); + } + + let stored = frontier_table + .get(()) + .map_err(|e| unreadable(e.into()))? + .map(|row| postcard::from_bytes::(row.value())) + .transpose() + .map_err(|_err| RefuseReason::Inconsistent)?; + let frontier_agrees = stored + .as_ref() + .map_or_else(|| tree.leaf_count() == 0, |persisted| *persisted == tree); + let rows = ledger.len().map_err(|e| unreadable(e.into()))?; + if !frontier_agrees || rows != tree.leaf_count() { + return Err(RefuseReason::Inconsistent); + } + Ok(Replayed { + last: prev, + tree, + last_wal_seq, + }) +} + +fn decode_entry(bytes: &[u8]) -> Result { + let entry = Entry::decode(bytes).map_err(|_err| RefuseReason::Inconsistent)?; + entry + .verify_self() + .map_err(|_err| RefuseReason::Inconsistent)?; + Ok(entry) +} + +fn check_checkpoint(checkpoint: &Checkpoint, key: u64) -> Result<(), RefuseReason> { + let verdict = checkpoint.verify(); + let sound = matches!( + verdict, + CheckpointVerdict::Signature( + SignatureVerdict::ValidSigned { .. } + | SignatureVerdict::UnsignedByConfig + | SignatureVerdict::UnsignedKeyFailed + ) + ); + if sound && key == checkpoint.tree_size { + Ok(()) + } else { + Err(RefuseReason::Inconsistent) + } +} diff --git a/procmond/src/audit_writer/projection.rs b/procmond/src/audit_writer/projection.rs new file mode 100644 index 00000000..974b88f4 --- /dev/null +++ b/procmond/src/audit_writer/projection.rs @@ -0,0 +1,48 @@ +//! The hashed projection of an event procmond wrote to its WAL. + +use std::time::{SystemTime, UNIX_EPOCH}; + +use collector_core::event::ProcessEvent; +use daemoneye_lib::audit::event_hash::{EventProjection, EventType}; + +use crate::event_bus_connector::ProcessEventType; + +fn unix_ns(time: SystemTime) -> i64 { + match time.duration_since(UNIX_EPOCH) { + Ok(after) => i64::try_from(after.as_nanos()).unwrap_or(i64::MAX), + Err(before) => { + i64::try_from(before.duration().as_nanos()).map_or(i64::MIN, i64::saturating_neg) + } + } +} + +/// The WAL's event type string; `None` for one procmond never writes. +#[must_use] +pub fn event_type(wal_type: &str) -> Option { + ProcessEventType::from_type_string(wal_type) + .ok() + .map(ProcessEventType::audit_type) +} + +/// Projects an already sanitised event. The command line is joined as it is on the wire, so a +/// reader holding the delivered event computes the same hash. +#[must_use] +pub fn projection( + wal_sequence: u64, + event: &ProcessEvent, + event_type: EventType, +) -> EventProjection { + EventProjection { + wal_sequence, + event_type, + pid: event.pid, + ppid: event.ppid, + name: event.name.clone(), + executable_path: event.executable_path.clone(), + command_line: Some(event.command_line.join(" ")), + start_time_ns: event.start_time.map(unix_ns), + executable_hash: event.executable_hash.clone(), + hash_algorithm: event.hash_algorithm.clone(), + collection_time_ns: unix_ns(event.timestamp), + } +} diff --git a/procmond/src/audit_writer/tests.rs b/procmond/src/audit_writer/tests.rs new file mode 100644 index 00000000..8a0119c8 --- /dev/null +++ b/procmond/src/audit_writer/tests.rs @@ -0,0 +1,408 @@ +#![allow( + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::arithmetic_side_effects, + clippy::indexing_slicing, + clippy::as_conversions +)] + +use std::fs; +use std::path::{Path, PathBuf}; + +use daemoneye_lib::audit::checkpoint::{ + CHECKPOINT_INTERVAL, Checkpoint, CheckpointVerdict, SignatureVerdict, +}; +use daemoneye_lib::audit::entry::{Action, Entry, GENESIS_PREV_HASH, GapReason, Kind}; +use daemoneye_lib::audit::merkle::Frontier; +use daemoneye_lib::audit::open_ledger_read_only; +use daemoneye_lib::audit::reader::LedgerReader; +use daemoneye_lib::audit::signing::SigningState; +use daemoneye_lib::audit::tables::{AUDIT_CHECKPOINTS, AUDIT_FRONTIER, AUDIT_LEDGER, AUDIT_META}; +use daemoneye_lib::audit::verify::{ProofAnchor, Verification, VerifyOptions, prove, verify}; +use redb::{ReadableDatabase as _, ReadableTable as _}; +use tempfile::TempDir; + +use super::{AppendError, AuditWriter, META_LAST_WAL_SEQ, RefuseReason, WriterState}; + +const READ_CACHE: usize = 1024 * 1024; + +fn ledger_path(dir: &TempDir) -> PathBuf { + dir.path().join("audit.redb") +} + +fn key_file(path: &Path) -> PathBuf { + super::open::key_path(path) +} + +fn start(pid: u32) -> Action { + Action::ProcessStart { pid } +} + +fn entries(path: &Path) -> Vec { + let db = open_ledger_read_only(path, READ_CACHE).unwrap(); + let table = db.begin_read().unwrap().open_table(AUDIT_LEDGER).unwrap(); + table + .iter() + .unwrap() + .map(|row| Entry::decode(row.unwrap().1.value()).unwrap()) + .collect() +} + +fn checkpoints(path: &Path) -> Vec { + let db = open_ledger_read_only(path, READ_CACHE).unwrap(); + let table = db + .begin_read() + .unwrap() + .open_table(AUDIT_CHECKPOINTS) + .unwrap(); + table + .iter() + .unwrap() + .map(|row| Checkpoint::decode(row.unwrap().1.value()).unwrap()) + .collect() +} + +fn append_n(writer: &mut AuditWriter, count: u32) { + for pid in 0..count { + writer.append_action(start(pid)).unwrap(); + } +} + +#[test] +fn hundred_entries_chain_and_roots_agree() { + let dir = TempDir::new().unwrap(); + let path = ledger_path(&dir); + let mut writer = AuditWriter::open(&path, true); + // Seq 0 is the key-created entry the open wrote; the other 99 are appended here. + append_n(&mut writer, 99); + let all = entries(&path); + assert_eq!(all.len(), 100); + assert!(matches!( + all[0].kind, + Kind::Action(Action::SigningKeyCreated { .. }) + )); + let mut tree = Frontier::new(); + let mut prev = GENESIS_PREV_HASH; + for (index, entry) in all.iter().enumerate() { + assert_eq!(entry.seq, index as u64, "sequence layout"); + assert_eq!(entry.prev_hash, prev, "prev hash at {index}"); + entry.verify_self().unwrap(); + tree.append(entry.ledger_leaf()).unwrap(); + assert_eq!(entry.root, tree.root(), "root at {index}"); + prev = entry.entry_hash; + } + assert_eq!(writer.tree_size(), Some(100)); + assert_eq!(writer.root(), Some(tree.root())); +} + +/// The writer and the verifier live in different crates; this is where they must agree. +#[test] +fn verifier_accepts_what_the_writer_wrote_and_proves_an_entry() { + let dir = TempDir::new().unwrap(); + let path = ledger_path(&dir); + let mut writer = AuditWriter::open(&path, true); + append_n(&mut writer, 149); + writer.append_batch(10, 19, 10, [7; 32], false).unwrap(); + writer.checkpoint_now().unwrap(); + // Read while the writer is still live, as the agent will. + let reader = LedgerReader::open(&path).unwrap(); + let Verification::Consistent(report) = verify(&reader, &VerifyOptions::new()).unwrap() else { + panic!("writer output did not verify"); + }; + assert_eq!(report.entry_count, 151); + assert_eq!(Some(report.final_root), writer.root()); + assert_eq!(report.checkpoints.len(), 3); + assert_eq!(report.key_changes, Vec::::new()); + let proof = prove(&reader, 70, ProofAnchor::CurrentRoot).unwrap(); + assert!(proof.verify()); + assert_eq!(proof.root, report.final_root); +} + +#[test] +fn checkpoints_at_interval_and_shutdown_are_signed_by_one_key() { + let dir = TempDir::new().unwrap(); + let path = ledger_path(&dir); + let mut writer = AuditWriter::open(&path, true); + append_n(&mut writer, 149); + writer.checkpoint_now().unwrap(); + writer.checkpoint_now().unwrap(); + let sizes: Vec = checkpoints(&path).iter().map(|c| c.tree_size).collect(); + assert_eq!( + sizes, + vec![CHECKPOINT_INTERVAL, CHECKPOINT_INTERVAL * 2, 150] + ); + let mut key_ids = Vec::new(); + for checkpoint in checkpoints(&path) { + let CheckpointVerdict::Signature(SignatureVerdict::ValidSigned { key_id }) = + checkpoint.verify() + else { + panic!("checkpoint not signed"); + }; + key_ids.push(key_id); + } + key_ids.dedup(); + assert_eq!(key_ids.len(), 1); +} + +#[test] +fn clean_reopen_continues_with_same_root_and_wal_sequence() { + let dir = TempDir::new().unwrap(); + let path = ledger_path(&dir); + let mut writer = AuditWriter::open(&path, false); + append_n(&mut writer, 3); + writer.append_batch(10, 19, 10, [7; 32], false).unwrap(); + writer.checkpoint_now().unwrap(); + let (root, size) = (writer.root(), writer.tree_size()); + drop(writer); + + let mut reopened = AuditWriter::open(&path, false); + assert_eq!(reopened.state(), WriterState::Committing); + assert_eq!((reopened.root(), reopened.tree_size()), (root, size)); + assert_eq!(reopened.last_wal_seq(), Some(19)); + reopened.append_action(start(9)).unwrap(); + assert_eq!(entries(&path).last().unwrap().seq, 4); +} + +#[test] +fn writer_dropped_without_shutdown_checkpoint_reopens_and_continues() { + let dir = TempDir::new().unwrap(); + let path = ledger_path(&dir); + let mut writer = AuditWriter::open(&path, true); + append_n(&mut writer, 70); + drop(writer); + let mut reopened = AuditWriter::open(&path, true); + assert_eq!(reopened.state(), WriterState::Committing); + assert_eq!(reopened.tree_size(), Some(71)); + reopened.append_action(start(1)).unwrap(); + assert_eq!(entries(&path).len(), 72); +} + +fn rewrite_frontier(path: &Path, frontier: &Frontier) { + let db = redb::Database::open(path).unwrap(); + let txn = db.begin_write().unwrap(); + let bytes = postcard::to_allocvec(frontier).unwrap(); + txn.open_table(AUDIT_FRONTIER) + .unwrap() + .insert((), bytes.as_slice()) + .unwrap(); + txn.commit().unwrap(); +} + +#[test] +fn altered_frontier_refuses_and_leaves_file_untouched() { + let dir = TempDir::new().unwrap(); + let path = ledger_path(&dir); + let mut writer = AuditWriter::open(&path, false); + append_n(&mut writer, 5); + drop(writer); + let mut forged = Frontier::new(); + forged.append([9; 32]).unwrap(); + rewrite_frontier(&path, &forged); + + let before = fs::read(&path).unwrap(); + let mut refused = AuditWriter::open(&path, false); + assert_eq!( + refused.state(), + WriterState::Refusing(RefuseReason::Inconsistent) + ); + assert!(matches!( + refused.append_action(start(1)), + Err(AppendError::Refusing(RefuseReason::Inconsistent)) + )); + assert!(matches!( + refused.checkpoint_now(), + Err(AppendError::Refusing(RefuseReason::Inconsistent)) + )); + assert_eq!( + refused.state(), + WriterState::Refusing(RefuseReason::Inconsistent) + ); + drop(refused); + assert_eq!(fs::read(&path).unwrap(), before); +} + +#[test] +fn file_that_is_not_a_database_refuses_and_is_untouched() { + let dir = TempDir::new().unwrap(); + let path = ledger_path(&dir); + fs::write(&path, vec![0x5a_u8; 4096]).unwrap(); + let writer = AuditWriter::open(&path, true); + assert!(matches!(writer.state(), WriterState::Refusing(_))); + assert_eq!(fs::read(&path).unwrap(), vec![0x5a_u8; 4096]); + assert!(!key_file(&path).exists()); +} + +#[test] +fn empty_existing_file_refuses_and_is_untouched() { + let dir = TempDir::new().unwrap(); + let path = ledger_path(&dir); + fs::write(&path, b"").unwrap(); + let writer = AuditWriter::open(&path, true); + assert!(matches!(writer.state(), WriterState::Refusing(_))); + assert_eq!(fs::read(&path).unwrap(), Vec::::new()); +} + +fn tamper_entry(path: &Path, seq: u64) { + let db = redb::Database::open(path).unwrap(); + let txn = db.begin_write().unwrap(); + let mut table = txn.open_table(AUDIT_LEDGER).unwrap(); + let mut entry = Entry::decode(table.get(seq).unwrap().unwrap().value()).unwrap(); + entry.ts_ms += 1; + let bytes = entry.encode().unwrap(); + table.insert(seq, bytes.as_slice()).unwrap(); + drop(table); + txn.commit().unwrap(); +} + +#[test] +fn altered_entry_after_latest_checkpoint_refuses() { + let dir = TempDir::new().unwrap(); + let path = ledger_path(&dir); + let mut writer = AuditWriter::open(&path, false); + append_n(&mut writer, 70); + drop(writer); + tamper_entry(&path, 66); + let tampered = AuditWriter::open(&path, false); + assert_eq!( + tampered.state(), + WriterState::Refusing(RefuseReason::Inconsistent) + ); +} + +#[test] +fn injected_failures_are_counted_then_a_gap_entry_precedes_the_next_append() { + let dir = TempDir::new().unwrap(); + let path = ledger_path(&dir); + let mut writer = AuditWriter::open(&path, false); + append_n(&mut writer, 2); + writer.fail_next_commits(2); + + assert!(matches!( + writer.append_action(start(1)), + Err(AppendError::Failed(_)) + )); + assert_eq!(writer.state(), WriterState::Failing { missed: 1 }); + assert!(writer.append_action(start(2)).is_err()); + assert_eq!(writer.state(), WriterState::Failing { missed: 2 }); + assert_eq!(entries(&path).len(), 2, "failed commits leave no rows"); + + writer.append_action(start(3)).unwrap(); + assert_eq!(writer.state(), WriterState::Committing); + let all = entries(&path); + assert_eq!(all.len(), 4); + assert_eq!( + all[2].kind, + Kind::Gap { + missed: 2, + reason: GapReason::CommitFailed + } + ); + assert_eq!(all[3].kind, Kind::Action(start(3))); +} + +#[test] +fn deleted_key_on_non_empty_ledger_records_failure_and_signs_unsigned() { + let dir = TempDir::new().unwrap(); + let path = ledger_path(&dir); + let mut writer = AuditWriter::open(&path, true); + append_n(&mut writer, 9); + drop(writer); + fs::remove_file(key_file(&path)).unwrap(); + + let mut reopened = AuditWriter::open(&path, true); + assert_eq!(reopened.state(), WriterState::Committing); + assert!(!key_file(&path).exists()); + let all = entries(&path); + assert_eq!(all.len(), 11); + assert_eq!(all[10].kind, Kind::Action(Action::SigningKeyFailed)); + reopened.checkpoint_now().unwrap(); + let last = checkpoints(&path).pop().unwrap(); + assert_eq!(last.signing, SigningState::UnsignedKeyFailed); +} + +#[test] +fn signing_disabled_writes_unsigned_by_config_and_no_key() { + let dir = TempDir::new().unwrap(); + let path = ledger_path(&dir); + let mut writer = AuditWriter::open(&path, false); + append_n(&mut writer, 3); + writer.checkpoint_now().unwrap(); + assert!(!key_file(&path).exists()); + assert_eq!( + checkpoints(&path).pop().unwrap().signing, + SigningState::UnsignedByConfig + ); + assert_eq!(entries(&path).len(), 3); +} + +#[test] +fn second_writer_is_refused_as_locked_and_first_keeps_working() { + let dir = TempDir::new().unwrap(); + let path = ledger_path(&dir); + let mut first = AuditWriter::open(&path, false); + first.append_action(start(1)).unwrap(); + let second = AuditWriter::open(&path, false); + assert_eq!(second.state(), WriterState::Refusing(RefuseReason::Locked)); + first.append_action(start(2)).unwrap(); + assert_eq!(first.state(), WriterState::Committing); + assert_eq!(first.tree_size(), Some(2)); + let meta_ok = open_ledger_read_only(&path, READ_CACHE) + .unwrap() + .begin_read() + .unwrap() + .open_table(AUDIT_META) + .unwrap() + .get(META_LAST_WAL_SEQ) + .unwrap() + .is_none(); + assert!( + meta_ok, + "no batch was committed, so no WAL sequence is stored" + ); +} + +#[cfg(unix)] +mod unix_mode { + use std::os::unix::fs::PermissionsExt as _; + use std::process::Command; + + use super::*; + + const CHILD_PATH_ENV: &str = "AUDIT_WRITER_UMASK_CHILD_PATH"; + + /// Re-executed by the umask tests under a different process umask; never runs on its own. + #[test] + #[ignore = "child process of the umask tests"] + fn umask_child() { + let path = PathBuf::from(std::env::var(CHILD_PATH_ENV).unwrap()); + let writer = AuditWriter::open(&path, false); + assert_eq!(writer.state(), WriterState::Committing); + } + + fn mode_after_create_under_umask(umask: &str) -> u32 { + let dir = TempDir::new().unwrap(); + let path = ledger_path(&dir); + let status = Command::new("sh") + .arg("-c") + .arg(r#"umask "$1" && exec "$2" --exact audit_writer::tests::unix_mode::umask_child --ignored"#) + .arg("sh") + .arg(umask) + .arg(std::env::current_exe().unwrap()) + .env(CHILD_PATH_ENV, &path) + .status() + .unwrap(); + assert!(status.success(), "child under umask {umask} failed"); + fs::metadata(&path).unwrap().permissions().mode() & 0o777 + } + + #[test] + fn ledger_is_0640_under_a_strict_umask() { + assert_eq!(mode_after_create_under_umask("077"), 0o640); + } + + #[test] + fn ledger_is_0640_under_a_zero_umask() { + assert_eq!(mode_after_create_under_umask("000"), 0o640); + } +} diff --git a/procmond/src/collector_audit.rs b/procmond/src/collector_audit.rs new file mode 100644 index 00000000..baed29cf --- /dev/null +++ b/procmond/src/collector_audit.rs @@ -0,0 +1,341 @@ +//! The collector's side of the audit ledger: what it records, and when. + +use daemoneye_lib::audit::entry::{Action, Privileges}; +use daemoneye_lib::audit::event_hash::EventType; +use daemoneye_lib::audit::merkle::{Frontier, Hash}; +use tracing::{error, warn}; + +use crate::audit_writer::projection::{event_type, projection}; +use crate::audit_writer::{AuditWriter, WriterState}; +use crate::lifecycle::ProcessLifecycleEvent; +use crate::wal::WalEntry; + +/// The events one collection cycle wrote to the WAL, in sequence order. +#[derive(Debug, Default)] +pub struct CycleBatch { + first_seq: u64, + last_seq: u64, + tree: Frontier, +} + +impl CycleBatch { + /// Adds the next event. Sequences must arrive in increasing order, as the WAL assigns them. + pub fn push(&mut self, sequence: u64, leaf: Hash) { + if let Err(e) = self.tree.append(leaf) { + error!(sequence, error = %e, "Audit batch cannot hold another event"); + return; + } + if self.tree.leaf_count() == 1 { + self.first_seq = sequence; + } + self.last_seq = sequence; + } + + fn of_wal_entries(mut entries: Vec) -> Self { + entries.sort_unstable_by_key(|entry| entry.sequence); + let mut batch = Self::default(); + for entry in entries { + // No recorded type is a legacy entry, redelivered as a start and so hashed as one. + // An unrecognised type is left out, as `replay_wal` skips it: hashing it as a start + // would record a type the WAL never stored. + let kind = match entry.event_type.as_deref().map(event_type) { + None => EventType::Start, + Some(Some(kind)) => kind, + Some(None) => { + error!( + sequence = entry.sequence, + "Leaving a WAL entry with an unrecognised event type out of the audit batch" + ); + continue; + } + }; + batch.push( + entry.sequence, + projection(entry.sequence, &entry.event, kind).leaf(), + ); + } + batch + } +} + +/// BLAKE3 of an executable hash together with its algorithm name. +fn content_id(algorithm: Option<&str>, hash: &str) -> Hash { + let algorithm_name = algorithm.unwrap_or_default(); + *blake3::hash(format!("{algorithm_name}:{hash}").as_bytes()).as_bytes() +} + +/// The action recording that a running process's executable changed on disk. +#[must_use] +pub fn integrity_drift(previous: (Option<&str>, &str), current: (Option<&str>, &str)) -> Action { + Action::IntegrityDriftReported { + subject: content_id(previous.0, previous.1), + observed: content_id(current.0, current.1), + } +} + +/// The drift action for a lifecycle event, if it is a change of a running process's executable +/// hash with a hash known on both sides. +#[must_use] +pub fn drift_action(event: &ProcessLifecycleEvent) -> Option { + let ProcessLifecycleEvent::Modified { + ref previous, + ref current, + ref modified_fields, + .. + } = *event + else { + return None; + }; + if !modified_fields.iter().any(|f| f == "executable_hash") { + return None; + } + Some(integrity_drift( + ( + previous.hash_algorithm.as_deref(), + previous.executable_hash.as_deref()?, + ), + ( + current.hash_algorithm.as_deref(), + current.executable_hash.as_deref()?, + ), + )) +} + +/// The action recording that a configuration update arrived; it holds no configuration value. +#[must_use] +pub fn config_update(rendered_config: &str) -> Action { + Action::ConfigUpdateReceived { + config_hash: *blake3::hash(rendered_config.as_bytes()).as_bytes(), + } +} + +/// Owns the writer and keeps its disk writes off the async threads. +pub struct CollectorAudit { + /// `None` only after a write task was lost. + writer: Option, +} + +impl std::fmt::Debug for CollectorAudit { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CollectorAudit") + .field("degraded", &self.degraded()) + .finish() + } +} + +impl CollectorAudit { + /// Records the start of this process and the privileges it detected. + #[must_use] + pub fn start(mut writer: AuditWriter, privilege_names: Vec) -> Self { + // A failed append is counted by the writer and shows in `degraded`. + let _started = writer.append_action(Action::ProcessStart { + pid: std::process::id(), + }); + match Privileges::new(privilege_names) { + Ok(privileges) => { + let _recorded = writer.append_action(Action::PrivilegesDetected { privileges }); + } + Err(e) => warn!(error = %e, "Detected privileges do not fit an audit entry"), + } + Self { + writer: Some(writer), + } + } + + /// The last WAL sequence the ledger committed. + #[must_use] + pub fn last_wal_seq(&self) -> Option { + self.writer.as_ref().and_then(AuditWriter::last_wal_seq) + } + + /// Why the ledger is not committing, or `None` when it is. + #[must_use] + pub fn degraded(&self) -> Option { + match self.writer.as_ref().map(AuditWriter::state) { + None => Some("audit ledger writer was lost".to_owned()), + Some(WriterState::Committing) => None, + Some(WriterState::Failing { missed }) => { + Some(format!("audit ledger: {missed} commits failed")) + } + Some(WriterState::Refusing(reason)) => Some(format!("audit ledger refused: {reason}")), + } + } + + async fn write(&mut self, what: &'static str, work: F) + where + F: FnOnce(&mut AuditWriter) -> Result<(), crate::audit_writer::AppendError> + + Send + + 'static, + { + let Some(mut writer) = self.writer.take() else { + return; + }; + let joined = tokio::task::spawn_blocking(move || { + let outcome = work(&mut writer); + (writer, outcome) + }) + .await; + match joined { + Ok((returned, outcome)) => { + if let Err(e) = outcome { + error!(what, error = %e, "Audit ledger did not record this"); + } + self.writer = Some(returned); + } + Err(e) => error!(what, error = %e, "Audit ledger write task was lost"), + } + } + + /// Records one action. + pub async fn action(&mut self, action: Action) { + self.write("action", move |writer| writer.append_action(action)) + .await; + } + + /// Records the events of one cycle; a cycle that wrote none records nothing. + pub async fn batch(&mut self, batch: CycleBatch) { + self.append_batch(batch, false).await; + } + + /// Records, as one recovered batch, the WAL entries no earlier batch covered. + pub async fn recover(&mut self, wal_entries: Vec) { + let committed = self.last_wal_seq(); + let uncovered = wal_entries + .into_iter() + .filter(|entry| committed.is_none_or(|last| entry.sequence > last)) + .collect(); + self.append_batch(CycleBatch::of_wal_entries(uncovered), true) + .await; + } + + async fn append_batch(&mut self, batch: CycleBatch, recovered: bool) { + let count = batch.tree.leaf_count(); + if count == 0 { + return; + } + let root = batch.tree.root(); + self.write("batch", move |writer| { + writer.append_batch(batch.first_seq, batch.last_seq, count, root, recovered) + }) + .await; + } + + /// Records a clean stop, then writes the final checkpoint. + pub async fn stop(&mut self) { + self.write("stop", |writer| { + writer.append_action(Action::CleanStop { + pid: std::process::id(), + })?; + writer.checkpoint_now() + }) + .await; + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + + use std::time::SystemTime; + + use collector_core::event::ProcessEvent; + + use super::*; + + fn snapshot(hash: Option<&str>) -> Box { + Box::new( + ProcessEvent { + pid: 7, + ppid: None, + name: "tool".to_owned(), + executable_path: Some("/usr/bin/tool".to_owned()), + command_line: Vec::new(), + start_time: None, + cpu_usage: None, + memory_usage: None, + executable_hash: hash.map(str::to_owned), + hash_algorithm: hash.map(|_| "sha256".to_owned()), + user_id: None, + accessible: true, + file_exists: true, + timestamp: SystemTime::now(), + platform_metadata: None, + } + .into(), + ) + } + + fn modified(before: Option<&str>, after: Option<&str>, field: &str) -> ProcessLifecycleEvent { + ProcessLifecycleEvent::Modified { + previous: snapshot(before), + current: snapshot(after), + detected_at: SystemTime::now(), + modified_fields: vec![field.to_owned()], + } + } + + #[test] + fn drift_is_recorded_only_for_a_changed_hash_known_on_both_sides() { + assert_eq!( + drift_action(&modified(Some("aa"), Some("bb"), "executable_hash")), + Some(integrity_drift( + (Some("sha256"), "aa"), + (Some("sha256"), "bb") + )) + ); + assert_eq!( + drift_action(&modified(Some("aa"), Some("bb"), "name")), + None + ); + assert_eq!( + drift_action(&modified(None, Some("bb"), "executable_hash")), + None + ); + } + + fn wal_entry(sequence: u64, event_type: Option<&str>) -> WalEntry { + let mut event = ProcessEvent::from(*snapshot(None)); + event.timestamp = SystemTime::UNIX_EPOCH; + WalEntry { + sequence, + event, + checksum: 0, + event_type: event_type.map(str::to_owned), + } + } + + #[test] + fn recovery_hashes_legacy_entries_as_starts_and_leaves_out_unknown_types() { + let batch = CycleBatch::of_wal_entries(vec![ + wal_entry(3, Some("start")), + wal_entry(2, Some("not-a-type")), + wal_entry(1, None), + ]); + let legacy_and_start = CycleBatch::of_wal_entries(vec![ + wal_entry(1, Some("start")), + wal_entry(3, Some("start")), + ]); + + assert_eq!(batch.tree.leaf_count(), 2); + assert_eq!((batch.first_seq, batch.last_seq), (1, 3)); + assert_eq!(batch.tree.root(), legacy_and_start.tree.root()); + } + + #[tokio::test] + async fn degraded_until_an_append_succeeds() { + let dir = tempfile::TempDir::new().unwrap(); + let writer = AuditWriter::open(&dir.path().join("audit.redb"), false); + let mut audit = CollectorAudit::start(writer, Vec::new()); + assert_eq!(audit.degraded(), None); + + audit.writer.as_ref().unwrap().fail_next_commits(1); + audit.action(config_update("a")).await; + assert_eq!( + audit.degraded().as_deref(), + Some("audit ledger: 1 commits failed") + ); + + audit.action(config_update("b")).await; + assert_eq!(audit.degraded(), None); + } +} diff --git a/procmond/src/event_bus_connector/mod.rs b/procmond/src/event_bus_connector/mod.rs index 0c3a5a77..024521bd 100644 --- a/procmond/src/event_bus_connector/mod.rs +++ b/procmond/src/event_bus_connector/mod.rs @@ -102,12 +102,14 @@ pub use signal::{BackpressureSignal, ProcessEventType}; use buffered_event::BufferedEvent; +use crate::audit_writer::projection::projection; use crate::wal::WriteAheadLog; use collector_core::event::ProcessEvent; use daemoneye_eventbus::{ ClientConfig, CollectionEvent as EventBusCollectionEvent, EventBusClient, ProcessEvent as EventBusProcessEvent, SocketConfig, }; +use daemoneye_lib::audit::merkle::Hash; use std::collections::VecDeque; use std::path::PathBuf; use std::sync::Arc; @@ -123,6 +125,18 @@ const MAX_BUFFER_SIZE: usize = 10 * 1024 * 1024; /// Default Windows named pipe name. const DEFAULT_WINDOWS_PIPE: &str = r"\\.\pipe\DaemonEye-broker"; +/// One event written to the WAL, and how its hand-off to the broker went. +#[derive(Debug)] +#[non_exhaustive] +pub struct Published { + /// The WAL sequence assigned to the event. + pub sequence: u64, + /// The event's audit leaf, over its sanitised form. + pub leaf: Hash, + /// `Err` when the event could be neither sent nor buffered; it is still in the WAL. + pub delivery: EventBusConnectorResult<()>, +} + /// Connector for publishing events to daemoneye-agent's broker with WAL-backed durability. /// /// The `EventBusConnector` provides reliable event delivery by integrating the @@ -493,6 +507,22 @@ impl EventBusConnector { event: ProcessEvent, event_type: ProcessEventType, ) -> EventBusConnectorResult { + let published = self.publish_hashed(event, event_type).await?; + published.delivery?; + Ok(published.sequence) + } + + /// [`Self::publish`], also returning the audit leaf of the event as it was written to the + /// WAL. The outer error means nothing was written; `delivery` reports the hand-off after it. + /// + /// # Errors + /// + /// Returns an error if the WAL write fails. + pub async fn publish_hashed( + &mut self, + event: ProcessEvent, + event_type: ProcessEventType, + ) -> EventBusConnectorResult { let topic = event_type.topic().to_owned(); let event_type_str = event_type.to_type_string().to_owned(); @@ -522,15 +552,35 @@ impl EventBusConnector { ); } + let leaf = projection(sequence, &sanitized_event, event_type.audit_type()).leaf(); + // Step 3: Try to publish or buffer - if self.connected { + let delivery = if self.connected { self.try_publish_or_buffer(sequence, sanitized_event, topic) - .await?; + .await } else { - self.buffer_event(sequence, sanitized_event, topic)?; - } + self.buffer_event(sequence, sanitized_event, topic) + }; + + Ok(Published { + sequence, + leaf, + delivery, + }) + } - Ok(sequence) + /// Raises the WAL's next sequence to at least `min_next`. + pub fn raise_sequence_floor(&self, min_next: u64) { + self.wal.raise_sequence_floor(min_next); + } + + /// Every entry the WAL still holds, in sequence order. + /// + /// # Errors + /// + /// Returns an error if a WAL file cannot be read. + pub async fn wal_entries(&self) -> EventBusConnectorResult> { + Ok(self.wal.replay_entries().await?) } /// Attempt to publish an event to the broker, buffering on failure. diff --git a/procmond/src/event_bus_connector/signal.rs b/procmond/src/event_bus_connector/signal.rs index 22bfb586..af99c267 100644 --- a/procmond/src/event_bus_connector/signal.rs +++ b/procmond/src/event_bus_connector/signal.rs @@ -33,6 +33,16 @@ pub enum ProcessEventType { } impl ProcessEventType { + /// The event type the audit ledger hashes. + pub(crate) const fn audit_type(self) -> daemoneye_lib::audit::event_hash::EventType { + use daemoneye_lib::audit::event_hash::EventType; + match self { + Self::Start => EventType::Start, + Self::Stop => EventType::Stop, + Self::Modify => EventType::Modify, + } + } + /// Get the topic string for this event type. pub(super) const fn topic(self) -> &'static str { match self { @@ -59,7 +69,7 @@ impl ProcessEventType { /// match any known variant. The caller must not silently substitute a /// default: a corrupted `"stop"` entry reclassified as `Start` would keep /// a terminated process alive in the tracking state. - pub(super) fn from_type_string(s: &str) -> Result { + pub(crate) fn from_type_string(s: &str) -> Result { match s { "start" => Ok(Self::Start), "stop" => Ok(Self::Stop), diff --git a/procmond/src/lib.rs b/procmond/src/lib.rs index 06f79f86..76e3be69 100644 --- a/procmond/src/lib.rs +++ b/procmond/src/lib.rs @@ -1,6 +1,9 @@ //! Library module for procmond to enable unit testing #![allow(clippy::doc_markdown)] // Many docs reference code identifiers without backticks +/// Append-only audit ledger writer; the only code that opens the ledger for writing. +pub mod audit_writer; +pub mod collector_audit; pub mod event_bus_connector; pub mod event_source; pub(crate) mod hash_pass; diff --git a/procmond/src/main.rs b/procmond/src/main.rs index 2a6c20a6..8f444437 100644 --- a/procmond/src/main.rs +++ b/procmond/src/main.rs @@ -10,6 +10,8 @@ use daemoneye_lib::{ }; use procmond::{ ProcessEventSource, ProcessSourceConfig, + audit_writer::AuditWriter, + collector_audit::CollectorAudit, event_bus_connector::EventBusConnector, monitor_collector::{ProcmondMonitorCollector, ProcmondMonitorConfig}, pushdown_eval::DEFAULT_COLLECTOR_ID, @@ -181,7 +183,7 @@ pub async fn main() -> anyhow::Result<()> { // Load configuration let config_loader = config::ConfigLoader::new("procmond"); - let _config = config_loader.load()?; + let config = config_loader.load()?; // Detect security privileges early (infallible - returns degraded on failure) let security_ctx = detect_privileges(); @@ -443,6 +445,25 @@ pub async fn main() -> anyhow::Result<()> { // so the backpressure monitor listens to the correct connector let collector_backpressure_rx = collector_event_bus.take_backpressure_receiver(); + // Open the audit ledger and record this start. A ledger that cannot be opened does not + // stop collection; it shows as degraded health. + let audit_config = config.audit.clone(); + let privilege_names = security_ctx.capabilities.clone(); + let audit = tokio::task::spawn_blocking(move || { + let writer = AuditWriter::open(&audit_config.ledger_path, audit_config.signing_enabled); + CollectorAudit::start(writer, privilege_names) + }) + .await + .context("audit ledger start-up task failed")?; + if let Some(reason) = audit.degraded() { + warn!(reason = %reason, "Audit ledger is not recording"); + } + // A sequence the ledger already committed is never handed out again. + if let Some(last) = audit.last_wal_seq() { + collector_event_bus.raise_sequence_floor(last.saturating_add(1)); + } + collector.set_audit(audit); + collector.set_event_bus_connector(collector_event_bus); // Spawn backpressure monitor task if we have the receiver diff --git a/procmond/src/monitor_collector.rs b/procmond/src/monitor_collector.rs index 09445a6e..83e2f822 100644 --- a/procmond/src/monitor_collector.rs +++ b/procmond/src/monitor_collector.rs @@ -5,6 +5,7 @@ //! collector-core `EventSource` trait. use crate::{ + collector_audit::{CollectorAudit, CycleBatch, config_update, drift_action}, event_bus_connector::{EventBusConnector, ProcessEventType}, hash_pass::populate_hashes, lifecycle::{LifecycleTrackingConfig, ProcessLifecycleEvent, ProcessLifecycleTracker}, @@ -119,6 +120,8 @@ pub struct HealthCheckData { pub backpressure_events: u64, /// Operational sub-status (e.g., "idle-awaiting-begin" when waiting for agent). pub operational_sub_status: Option, + /// Why the audit ledger is not committing; `None` when it is, or when there is none. + pub audit_ledger: Option, } /// Channel capacity for actor messages. @@ -375,6 +378,9 @@ pub struct ProcmondMonitorCollector { /// EventBusConnector for publishing events to the broker with WAL integration. event_bus_connector: Option, + /// The audit ledger; `None` when this process keeps none. + audit: Option, + /// Shared executable-hash engine, cloned from the composition root. /// /// `None` means `--compute-hashes` is disabled; `Some` means the @@ -472,6 +478,7 @@ impl ProcmondMonitorCollector { pending_interval: None, // Event Bus Integration event_bus_connector: None, + audit: None, hasher: None, }) } @@ -523,6 +530,11 @@ impl ProcmondMonitorCollector { self.buffer_level_percent = Some(level_percent); } + /// Sets the audit ledger this collector records its cycles and actions in. + pub fn set_audit(&mut self, audit: CollectorAudit) { + self.audit = Some(audit); + } + /// Sets the EventBusConnector for publishing events to the broker. /// /// This should be called after constructing the collector and before @@ -643,6 +655,17 @@ impl ProcmondMonitorCollector { "Starting Procmond Monitor Collector actor" ); + // Events a previous run wrote to the WAL but never committed are recorded first. + if let Some(audit) = self.audit.as_mut() + && let Some(connector) = self.event_bus_connector.as_ref() + { + match connector.wal_entries().await { + Ok(entries) => audit.recover(entries).await, + Err(e) => error!(error = %e, "Audit recovery could not read the WAL"), + } + } + + let mut clean_stop = true; let mut consecutive_failures = 0_u32; let mut collection_interval = interval(self.current_interval); // Skip first tick to avoid immediate collection @@ -651,6 +674,11 @@ impl ProcmondMonitorCollector { loop { // Check for pending config update at cycle boundary if let Some(new_config) = self.pending_config.take() { + if let Some(audit) = self.audit.as_mut() { + audit + .action(config_update(&format!("{new_config:?}"))) + .await; + } self.apply_config_update(new_config); // Update interval if changed let new_interval = self.config.base_config.collection_interval; @@ -721,6 +749,7 @@ impl ProcmondMonitorCollector { "Too many consecutive failures, stopping collector" ); self.state = CollectorState::Stopped; + clean_stop = false; // If there's a pending shutdown response, send error // Ignore send result - receiver may have been dropped @@ -757,6 +786,10 @@ impl ProcmondMonitorCollector { } } + if clean_stop && let Some(audit) = self.audit.as_mut() { + audit.stop().await; + } + info!("Procmond Monitor Collector actor stopped"); // Send shutdown completion if there's a pending response @@ -848,6 +881,7 @@ impl ProcmondMonitorCollector { collection_errors: self.stats.collection_errors.load(Ordering::Relaxed), backpressure_events: self.stats.backpressure_events.load(Ordering::Relaxed), operational_sub_status, + audit_ledger: self.audit.as_ref().and_then(CollectorAudit::degraded), } } @@ -991,6 +1025,7 @@ impl ProcmondMonitorCollector { // Only processes with lifecycle events (start, stop, modify) get published use std::collections::HashMap; let mut pid_to_event_type: HashMap = HashMap::new(); + let mut drift_actions = Vec::new(); for lifecycle_event in &lifecycle_events { #[allow(clippy::pattern_type_mismatch)] // Matching on &enum variant is idiomatic match lifecycle_event { @@ -1002,6 +1037,7 @@ impl ProcmondMonitorCollector { } ProcessLifecycleEvent::Modified { current, .. } => { pid_to_event_type.insert(current.pid, ProcessEventType::Modify); + drift_actions.extend(drift_action(lifecycle_event)); } ProcessLifecycleEvent::Suspicious { process, .. } => { // Suspicious events are also published as modifications @@ -1013,6 +1049,7 @@ impl ProcmondMonitorCollector { // Publish process events via EventBusConnector if configured // Events go to events.process.start, events.process.stop, or events.process.modify // Only publish events that have a lifecycle change (skip unchanged processes) + let mut batch = CycleBatch::default(); if let Some(ref mut connector) = self.event_bus_connector { // Update connection status self.event_bus_connected = connector.is_connected(); @@ -1021,20 +1058,32 @@ impl ProcmondMonitorCollector { for process_event in &process_events { // Only publish if there's a corresponding lifecycle event if let Some(&event_type) = pid_to_event_type.get(&process_event.pid) { - match connector.publish(process_event.clone(), event_type).await { - Ok(sequence) => { - debug!( - pid = process_event.pid, - event_type = ?event_type, - sequence = sequence, - "Published process event to EventBus" - ); + match connector + .publish_hashed(process_event.clone(), event_type) + .await + { + Ok(published) => { + // In the WAL, so in the batch, whatever the hand-off did. + batch.push(published.sequence, published.leaf); + match published.delivery { + Ok(()) => debug!( + pid = process_event.pid, + event_type = ?event_type, + sequence = published.sequence, + "Published process event to EventBus" + ), + Err(e) => warn!( + pid = process_event.pid, + error = %e, + "Failed to publish to EventBus (event kept in WAL)" + ), + } } Err(e) => { warn!( pid = process_event.pid, error = %e, - "Failed to publish to EventBus (event buffered)" + "Failed to write event to WAL" ); } } @@ -1042,6 +1091,13 @@ impl ProcmondMonitorCollector { } } + if let Some(audit) = self.audit.as_mut() { + for action in drift_actions { + audit.action(action).await; + } + audit.batch(batch).await; + } + // Send process events to collector-core channel with backpressure handling for process_event in process_events { if self.state != CollectorState::Running { @@ -1849,6 +1905,7 @@ mod tests { collection_errors: 0, backpressure_events: 1, operational_sub_status: None, + audit_ledger: None, }; let cloned = health_data.clone(); @@ -1871,6 +1928,7 @@ mod tests { collection_errors: 0, backpressure_events: 0, operational_sub_status: None, + audit_ledger: None, }; let debug_str = format!("{health_data:?}"); @@ -2313,6 +2371,7 @@ mod tests { collection_errors: 0, backpressure_events: 1, operational_sub_status: None, + audit_ledger: None, }; let send_result = respond_to.send(health_data); assert!(send_result.is_ok(), "Oneshot send should succeed"); @@ -2393,6 +2452,7 @@ mod tests { collection_errors: 0, backpressure_events: 0, operational_sub_status: None, + audit_ledger: None, }; let _ = respond_to.send(health_data); } diff --git a/procmond/src/registration/mod.rs b/procmond/src/registration/mod.rs index 69366491..9e650f05 100644 --- a/procmond/src/registration/mod.rs +++ b/procmond/src/registration/mod.rs @@ -123,6 +123,23 @@ pub struct RegistrationStats { pub last_registration: Option, } +/// The health a heartbeat reports. A ledger that is not committing degrades a healthy collector. +const fn heartbeat_status(health: &crate::monitor_collector::HealthCheckData) -> HealthStatus { + use crate::monitor_collector::CollectorState; + if !health.event_bus_connected { + return HealthStatus::Degraded; + } + match health.state { + CollectorState::Running | CollectorState::WaitingForAgent + if health.audit_ledger.is_some() => + { + HealthStatus::Degraded + } + CollectorState::Running | CollectorState::WaitingForAgent => HealthStatus::Healthy, + CollectorState::ShuttingDown | CollectorState::Stopped => HealthStatus::Unhealthy, + } +} + impl RegistrationManager { /// Creates a new registration manager. /// @@ -447,21 +464,7 @@ impl RegistrationManager { { Ok(Ok(health)) => { let sub_status = health.operational_sub_status.clone(); - let status = if health.event_bus_connected { - match health.state { - crate::monitor_collector::CollectorState::Running => HealthStatus::Healthy, - crate::monitor_collector::CollectorState::WaitingForAgent => { - HealthStatus::Healthy - } - crate::monitor_collector::CollectorState::ShuttingDown - | crate::monitor_collector::CollectorState::Stopped => { - HealthStatus::Unhealthy - } - } - } else { - HealthStatus::Degraded - }; - (status, sub_status) + (heartbeat_status(&health), sub_status) } Ok(Err(e)) => { warn!( diff --git a/procmond/src/registration/tests.rs b/procmond/src/registration/tests.rs index fec12b6a..9b83835d 100644 --- a/procmond/src/registration/tests.rs +++ b/procmond/src/registration/tests.rs @@ -417,6 +417,7 @@ fn create_test_health_data( collection_errors: 0, backpressure_events: 0, operational_sub_status, + audit_ledger: None, } } @@ -1248,3 +1249,14 @@ async fn test_waiting_for_agent_heartbeat_produces_healthy_idle_awaiting_begin() ); assert_eq!(heartbeat.collector_id, "procmond"); } + +#[test] +fn heartbeat_is_degraded_while_the_audit_ledger_is_not_committing() { + use crate::monitor_collector::CollectorState; + for state in [CollectorState::Running, CollectorState::WaitingForAgent] { + let mut health = create_test_health_data(state, true); + assert_eq!(super::heartbeat_status(&health), HealthStatus::Healthy); + health.audit_ledger = Some("audit ledger refused: locked".to_owned()); + assert_eq!(super::heartbeat_status(&health), HealthStatus::Degraded); + } +} diff --git a/procmond/src/rpc_service/mod.rs b/procmond/src/rpc_service/mod.rs index ea0eb221..85d291f0 100644 --- a/procmond/src/rpc_service/mod.rs +++ b/procmond/src/rpc_service/mod.rs @@ -368,7 +368,7 @@ impl RpcServiceHandler { /// Converts actor health data to RPC health data format. fn convert_health_data(&self, actor_health: &ActorHealthCheckData) -> HealthCheckData { // Determine overall health status - let status = match actor_health.state { + let collector_state_status = match actor_health.state { crate::monitor_collector::CollectorState::Running => { if actor_health.event_bus_connected { HealthStatus::Healthy @@ -380,10 +380,31 @@ impl RpcServiceHandler { crate::monitor_collector::CollectorState::ShuttingDown => HealthStatus::Unhealthy, crate::monitor_collector::CollectorState::Stopped => HealthStatus::Unresponsive, }; + // A ledger that is not committing degrades an otherwise healthy collector. + let status = if collector_state_status == HealthStatus::Healthy + && actor_health.audit_ledger.is_some() + { + HealthStatus::Degraded + } else { + collector_state_status + }; // Build component health map let mut components = HashMap::new(); + if let Some(reason) = actor_health.audit_ledger.clone() { + components.insert( + "audit_ledger".to_owned(), + ComponentHealth { + name: "audit_ledger".to_owned(), + status: HealthStatus::Degraded, + message: Some(reason), + last_check: SystemTime::now(), + check_interval_seconds: 30, + }, + ); + } + // Event bus component let event_bus_status = if actor_health.event_bus_connected { HealthStatus::Healthy diff --git a/procmond/src/rpc_service/tests.rs b/procmond/src/rpc_service/tests.rs index 654e8076..da8d2b1c 100644 --- a/procmond/src/rpc_service/tests.rs +++ b/procmond/src/rpc_service/tests.rs @@ -101,6 +101,7 @@ async fn test_convert_health_data() { collection_errors: 2, backpressure_events: 5, operational_sub_status: None, + audit_ledger: None, }; let health_data = handler.convert_health_data(&actor_health); @@ -116,6 +117,38 @@ async fn test_convert_health_data() { assert_eq!(health_data.metrics.get("lifecycle_events"), Some(&50.0_f64)); } +#[tokio::test] +async fn health_check_is_degraded_and_names_the_audit_ledger() { + let (actor_handle, _rx) = create_test_actor(); + let (event_bus, _temp_dir) = create_test_event_bus().await; + let handler = RpcServiceHandler::with_defaults(actor_handle, event_bus); + + let actor_health = ActorHealthCheckData { + state: CollectorState::Running, + collection_interval: Duration::from_secs(30), + original_interval: Duration::from_secs(30), + event_bus_connected: true, + buffer_level_percent: Some(25), + last_collection: Some(std::time::Instant::now()), + collection_cycles: 100, + lifecycle_events: 50, + collection_errors: 0, + backpressure_events: 0, + operational_sub_status: None, + audit_ledger: Some("audit ledger: 2 commits failed".to_owned()), + }; + + let health_data = handler.convert_health_data(&actor_health); + + assert_eq!(health_data.status, HealthStatus::Degraded); + let ledger = health_data.components.get("audit_ledger").unwrap(); + assert_eq!(ledger.status, HealthStatus::Degraded); + assert_eq!( + ledger.message.as_deref(), + Some("audit ledger: 2 commits failed") + ); +} + #[tokio::test] async fn test_convert_health_data_degraded() { let (actor_handle, _rx) = create_test_actor(); @@ -134,6 +167,7 @@ async fn test_convert_health_data_degraded() { collection_errors: 10, backpressure_events: 15, operational_sub_status: None, + audit_ledger: None, }; let health_data = handler.convert_health_data(&actor_health); @@ -298,6 +332,7 @@ async fn test_health_check_sends_message_to_actor() { collection_errors: 0, backpressure_events: 0, operational_sub_status: None, + audit_ledger: None, }; // Intentionally ignore send result - receiver may have been dropped drop(respond_to.send(health_data)); @@ -784,6 +819,7 @@ async fn test_convert_health_data_waiting_for_agent() { collection_errors: 0, backpressure_events: 0, operational_sub_status: None, + audit_ledger: None, }; let health_data = handler.convert_health_data(&actor_health); @@ -815,6 +851,7 @@ async fn test_convert_health_data_shutting_down() { collection_errors: 5, backpressure_events: 10, operational_sub_status: None, + audit_ledger: None, }; let health_data = handler.convert_health_data(&actor_health); @@ -842,6 +879,7 @@ async fn test_convert_health_data_stopped() { collection_errors: 0, backpressure_events: 0, operational_sub_status: None, + audit_ledger: None, }; let health_data = handler.convert_health_data(&actor_health); @@ -869,6 +907,7 @@ async fn test_convert_health_data_no_buffer_level() { collection_errors: 0, backpressure_events: 0, operational_sub_status: None, + audit_ledger: None, }; let health_data = handler.convert_health_data(&actor_health); @@ -1075,6 +1114,7 @@ async fn test_response_contains_correlation_metadata() { collection_errors: 0, backpressure_events: 0, operational_sub_status: None, + audit_ledger: None, }; drop(respond_to.send(health_data)); } @@ -1123,6 +1163,7 @@ async fn test_stats_increment_on_health_check_success() { collection_errors: 0, backpressure_events: 0, operational_sub_status: None, + audit_ledger: None, }; drop(respond_to.send(health_data)); } @@ -1320,6 +1361,7 @@ async fn test_concurrent_requests_handled() { collection_errors: 0, backpressure_events: 0, operational_sub_status: None, + audit_ledger: None, }; drop(respond_to.send(health_data)); } @@ -1541,6 +1583,7 @@ async fn test_response_execution_time_tracked() { collection_errors: 0, backpressure_events: 0, operational_sub_status: None, + audit_ledger: None, }; drop(respond_to.send(health_data)); } diff --git a/procmond/src/wal.rs b/procmond/src/wal.rs index 0d5979e4..92fa7d21 100644 --- a/procmond/src/wal.rs +++ b/procmond/src/wal.rs @@ -386,6 +386,13 @@ impl WriteAheadLog { }) } + /// Raises the next event sequence to at least `min_next`, so a sequence the audit ledger + /// already committed is never reused after the WAL directory was emptied. + pub fn raise_sequence_floor(&self, min_next: u64) { + self.current_event_sequence + .fetch_max(min_next, Ordering::SeqCst); + } + /// Scan existing WAL files to determine the next file sequence and highest event sequence. /// /// Returns (next_file_sequence, highest_event_sequence, current_file_metadata) @@ -595,7 +602,7 @@ impl WriteAheadLog { /// /// # Errors /// - /// Returns `WalError` if serialization, file I/O, or rotation fails + /// Returns `WalError` if serialization or file I/O fails. A rotation failure is logged, not returned. #[allow(clippy::significant_drop_tightening)] // Lock is intentionally held throughout for atomic rotation async fn write_entry(&self, entry: WalEntry) -> WalResult { use tokio::io::AsyncWriteExt; @@ -649,8 +656,12 @@ impl WriteAheadLog { ); // Check if rotation is needed - perform atomically within the same lock - if state.size >= self.rotation_threshold { - self.rotate_file_internal(&mut state).await?; + // The entry is already in the file, so a failed rotation must not fail the write: the + // caller would treat a persisted record as lost. The next write retries the rotation. + if state.size >= self.rotation_threshold + && let Err(error) = self.rotate_file_internal(&mut state).await + { + warn!(sequence, error = %error, "WAL rotation failed after the entry was written"); } Ok(sequence) @@ -667,9 +678,12 @@ impl WriteAheadLog { async fn rotate_file_internal(&self, state: &mut WalFileState) -> WalResult<()> { debug!("Rotating WAL file"); - // Increment file sequence and open new file BEFORE closing old one - let previous_sequence = self.current_file_sequence.fetch_add(1, Ordering::SeqCst); - let next_file_sequence = previous_sequence.saturating_add(1); + // The counter names the active file, so it moves only once the new file is open: a + // failed rotation must leave it on the file still being written. + let next_file_sequence = self + .current_file_sequence + .load(Ordering::SeqCst) + .saturating_add(1); #[allow(clippy::as_conversions)] // Safe: file sequence is always within u32 range let file_sequence_u32 = next_file_sequence as u32; @@ -684,6 +698,8 @@ impl WriteAheadLog { Self::restrict_permissions(&file_path).await?; // Atomically replace the file handle - old file is closed when dropped + self.current_file_sequence + .store(next_file_sequence, Ordering::SeqCst); state.file = new_file; state.size = 0; state.min_sequence = 0; @@ -907,7 +923,11 @@ impl WriteAheadLog { /// # Errors /// /// Returns `WalError` if file scanning or deletion fails + #[allow(clippy::significant_drop_tightening)] // Held throughout: see below pub async fn mark_published(&self, up_to_sequence: u64) -> WalResult<()> { + // Rotation opens the next file before it moves the counter; holding the write lock + // keeps cleanup from deleting that still-empty file in between. + let _state = self.file_state.lock().await; // Get current file sequence to avoid deleting the active file let current_file_seq = self.current_file_sequence.load(Ordering::SeqCst); @@ -1120,6 +1140,37 @@ mod tests { assert_eq!(events[1].pid, 3002); } + #[cfg(unix)] + #[tokio::test] + async fn test_write_succeeds_when_rotation_fails_after_append() { + use std::os::unix::fs::PermissionsExt; + + let temp_dir = TempDir::new().expect("Failed to create temp dir"); + let wal = WriteAheadLog::with_rotation_threshold(temp_dir.path().to_path_buf(), 1) + .await + .expect("Failed to create WAL"); + // A read-only directory refuses the new segment; the open one stays writable. + std::fs::set_permissions(temp_dir.path(), std::fs::Permissions::from_mode(0o500)) + .expect("Failed to restrict dir"); + let probe = temp_dir.path().join("probe"); + let rotation_is_blocked = std::fs::File::create(&probe).is_err(); + + let result = wal.write(create_test_event(9001)).await; + + std::fs::set_permissions(temp_dir.path(), std::fs::Permissions::from_mode(0o700)) + .expect("Failed to restore dir"); + if !rotation_is_blocked { + return; // running as root: permissions do not bind + } + let sequence = result.expect("a persisted entry must not report a failed write"); + let replayed = wal.replay_entries().await.expect("Failed to replay"); + assert!(replayed.iter().any(|entry| entry.sequence == sequence)); + // The file still being written is the one cleanup must keep. + wal.mark_published(sequence).await.expect("Failed to mark"); + let kept = wal.replay_entries().await.expect("Failed to replay"); + assert!(kept.iter().any(|entry| entry.sequence == sequence)); + } + #[tokio::test] async fn test_mark_published_honors_sequence_cutoff() { let temp_dir = TempDir::new().expect("Failed to create temp dir"); diff --git a/procmond/tests/actor_mode_integration_tests.rs b/procmond/tests/actor_mode_integration_tests.rs index a9dc4f42..3b4e4f99 100644 --- a/procmond/tests/actor_mode_integration_tests.rs +++ b/procmond/tests/actor_mode_integration_tests.rs @@ -308,6 +308,7 @@ async fn test_health_check_succeeds_with_responsive_actor() { collection_errors: 0, backpressure_events: 0, operational_sub_status: None, + audit_ledger: None, }; respond_to .send(health_data) diff --git a/procmond/tests/audit_commit.rs b/procmond/tests/audit_commit.rs new file mode 100644 index 00000000..2cd19eef --- /dev/null +++ b/procmond/tests/audit_commit.rs @@ -0,0 +1,353 @@ +//! What the collector commits to the audit ledger, checked against the WAL it committed from. + +#![allow( + clippy::arithmetic_side_effects, + clippy::as_conversions, + clippy::cast_lossless, + clippy::collapsible_if, + clippy::doc_markdown, + clippy::equatable_if_let, + clippy::expect_used, + clippy::indexing_slicing, + clippy::integer_division, + clippy::items_after_statements, + clippy::map_unwrap_or, + clippy::missing_assert_message, + clippy::needless_pass_by_value, + clippy::panic, + clippy::pattern_type_mismatch, + clippy::print_stdout, + clippy::semicolon_outside_block, + clippy::shadow_reuse, + clippy::shadow_unrelated, + clippy::str_to_string, + clippy::uninlined_format_args, + clippy::unwrap_used, + clippy::use_debug, + clippy::wildcard_enum_match_arm, + dead_code +)] + +mod common; + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use common::{create_isolated_connector, create_test_event}; +use daemoneye_lib::audit::entry::{Action, Entry, Kind}; +use daemoneye_lib::audit::event_hash::{BatchCheck, EventProjection, EventType, check_batch}; +use daemoneye_lib::audit::reader::LedgerReader; +use daemoneye_lib::audit::verify::{Verification, VerifyOptions, verify}; +use daemoneye_lib::storage::DatabaseManager; +use procmond::audit_writer::AuditWriter; +use procmond::audit_writer::projection::{event_type, projection}; +use procmond::collector_audit::{CollectorAudit, CycleBatch, config_update, integrity_drift}; +use procmond::event_bus_connector::{EventBusConnector, ProcessEventType}; +use procmond::monitor_collector::{ActorHandle, ProcmondMonitorCollector, ProcmondMonitorConfig}; +use procmond::wal::WalEntry; +use tempfile::TempDir; +use tokio::sync::{Mutex, mpsc}; + +fn ledger_path(dir: &TempDir) -> PathBuf { + dir.path().join("audit.redb") +} + +/// Signing is off so the first entry is the start action, not the key record. +fn started(path: &Path) -> CollectorAudit { + CollectorAudit::start(AuditWriter::open(path, false), vec!["cap_a".to_owned()]) +} + +fn entries(path: &Path) -> Vec { + let reader = LedgerReader::open(path).unwrap(); + assert!(matches!( + verify(&reader, &VerifyOptions::new()).unwrap(), + Verification::Consistent(_) + )); + reader + .entries(0) + .map(|row| Entry::decode(&row.unwrap().1).unwrap()) + .collect() +} + +fn projections(wal: &[WalEntry], first: u64, last: u64) -> Vec { + wal.iter() + .filter(|entry| (first..=last).contains(&entry.sequence)) + .map(|entry| { + let kind = event_type(entry.event_type.as_deref().unwrap()).unwrap(); + projection(entry.sequence, &entry.event, kind) + }) + .collect() +} + +/// Publishes `pids` as one cycle and returns the batch the cycle would commit. +async fn cycle(connector: &mut EventBusConnector, pids: std::ops::Range) -> CycleBatch { + let mut batch = CycleBatch::default(); + for pid in pids { + let published = connector + .publish_hashed(create_test_event(pid), ProcessEventType::Start) + .await + .unwrap(); + batch.push(published.sequence, published.leaf); + } + batch +} + +#[tokio::test] +async fn cycle_commits_one_batch_that_matches_the_wal() { + let dir = TempDir::new().unwrap(); + let path = ledger_path(&dir); + // No broker: every event is buffered, and must be in the batch all the same. + let (mut connector, _wal_dir) = create_isolated_connector().await; + let mut audit = started(&path); + + let batch = cycle(&mut connector, 100..105).await; + audit.batch(batch).await; + // A cycle that published nothing commits nothing. + audit.batch(CycleBatch::default()).await; + assert_eq!(audit.degraded(), None); + drop(audit); + + let wal = connector.wal_entries().await.unwrap(); + let batches: Vec = entries(&path) + .into_iter() + .map(|entry| entry.kind) + .filter(|kind| matches!(kind, Kind::Batch { .. })) + .collect(); + let [ + Kind::Batch { + first_seq, + last_seq, + count, + batch_root, + recovered, + }, + ] = batches.as_slice() + else { + panic!("expected exactly one batch, got {batches:?}"); + }; + assert_eq!((*count, *recovered), (5, false)); + assert_eq!(*first_seq, wal.first().unwrap().sequence); + assert_eq!(*last_seq, wal.last().unwrap().sequence); + assert_eq!( + check_batch(*count, batch_root, projections(&wal, *first_seq, *last_seq)).unwrap(), + BatchCheck::Match + ); +} + +#[tokio::test] +async fn leaf_is_over_the_sanitised_event() { + let (mut connector, _wal_dir) = create_isolated_connector().await; + let mut raw = create_test_event(7); + raw.command_line = vec![ + "tool".to_owned(), + "--password".to_owned(), + "hunter2".to_owned(), + ]; + + let published = connector + .publish_hashed(raw.clone(), ProcessEventType::Start) + .await + .unwrap(); + + let wal = connector.wal_entries().await.unwrap(); + let stored = &wal[0].event; + assert_ne!(stored.command_line, raw.command_line); + assert_eq!( + published.leaf, + projection(published.sequence, stored, EventType::Start).leaf() + ); + assert_ne!( + published.leaf, + projection(published.sequence, &raw, EventType::Start).leaf() + ); +} + +#[tokio::test] +async fn restart_commits_uncovered_wal_entries_as_one_recovered_batch() { + let dir = TempDir::new().unwrap(); + let path = ledger_path(&dir); + let wal_dir = TempDir::new().unwrap(); + + // First run: one committed cycle, then three WAL writes and no batch. + let mut connector = EventBusConnector::new(wal_dir.path().to_path_buf()) + .await + .unwrap(); + let mut audit = started(&path); + let committed = cycle(&mut connector, 1..3).await; + audit.batch(committed).await; + let lost = cycle(&mut connector, 10..13).await; + drop((lost, audit, connector)); + + // Second run. + let mut connector = EventBusConnector::new(wal_dir.path().to_path_buf()) + .await + .unwrap(); + let mut audit = started(&path); + audit.recover(connector.wal_entries().await.unwrap()).await; + let next = cycle(&mut connector, 20..21).await; + audit.batch(next).await; + drop(audit); + + let wal = connector.wal_entries().await.unwrap(); + let batches: Vec<(u64, u64, u64, bool)> = entries(&path) + .into_iter() + .filter_map(|entry| match entry.kind { + Kind::Batch { + first_seq, + last_seq, + count, + batch_root, + recovered, + } => { + assert_eq!( + check_batch(count, &batch_root, projections(&wal, first_seq, last_seq)) + .unwrap(), + BatchCheck::Match + ); + Some((first_seq, last_seq, count, recovered)) + } + Kind::Action(_) | Kind::Gap { .. } => None, + }) + .collect(); + let seqs: Vec = wal.iter().map(|entry| entry.sequence).collect(); + assert_eq!( + batches, + vec![ + (seqs[0], seqs[1], 2, false), + (seqs[2], seqs[4], 3, true), + (seqs[5], seqs[5], 1, false), + ] + ); +} + +#[tokio::test] +async fn sequence_floor_survives_an_emptied_wal_directory() { + let (mut connector, _wal_dir) = create_isolated_connector().await; + + connector.raise_sequence_floor(501); + let first = connector + .publish_hashed(create_test_event(1), ProcessEventType::Start) + .await + .unwrap(); + // A floor below the current sequence changes nothing. + connector.raise_sequence_floor(3); + let second = connector + .publish_hashed(create_test_event(2), ProcessEventType::Start) + .await + .unwrap(); + + assert_eq!((first.sequence, second.sequence), (501, 502)); +} + +#[test] +fn drift_and_config_actions_hold_hashes_only() { + let drift = integrity_drift((Some("sha256"), "aa"), (Some("sha256"), "bb")); + let Action::IntegrityDriftReported { subject, observed } = drift else { + panic!("not a drift action"); + }; + assert_ne!(subject, observed); + assert_eq!( + drift, + integrity_drift((Some("sha256"), "aa"), (Some("sha256"), "bb")) + ); + + let Action::ConfigUpdateReceived { config_hash } = config_update("interval = 30") else { + panic!("not a config action"); + }; + assert_eq!(config_hash, *blake3::hash(b"interval = 30").as_bytes()); +} + +#[tokio::test] +async fn refused_ledger_reports_degraded_and_does_not_stop_writes() { + let dir = TempDir::new().unwrap(); + let path = ledger_path(&dir); + std::fs::write(&path, b"not a ledger").unwrap(); + + let mut audit = started(&path); + let (mut connector, _wal_dir) = create_isolated_connector().await; + let batch = cycle(&mut connector, 1..3).await; + audit.batch(batch).await; + + assert!( + audit + .degraded() + .unwrap() + .starts_with("audit ledger refused") + ); + assert_eq!(connector.wal_entries().await.unwrap().len(), 2); +} + +async fn wait_for_cycles(handle: &ActorHandle, at_least: u64) { + let reached = async { + while handle.health_check().await.unwrap().collection_cycles < at_least { + tokio::time::sleep(Duration::from_millis(100)).await; + } + }; + tokio::time::timeout(Duration::from_secs(120), reached) + .await + .expect("collection cycles did not run"); +} + +#[tokio::test] +async fn start_cycle_and_clean_stop_are_recorded_in_order() { + let dir = TempDir::new().unwrap(); + let path = ledger_path(&dir); + let (connector, _wal_dir) = create_isolated_connector().await; + let database = Arc::new(Mutex::new( + DatabaseManager::new(dir.path().join("events.redb")).unwrap(), + )); + + let (handle, receiver) = ProcmondMonitorCollector::create_channel(); + let mut config = ProcmondMonitorConfig::default(); + config.base_config.collection_interval = Duration::from_secs(1); + let mut collector = ProcmondMonitorCollector::new(database, config.clone(), receiver).unwrap(); + collector.set_audit(started(&path)); + collector.set_event_bus_connector(connector); + + let (event_tx, mut event_rx) = mpsc::channel(1000); + let drain = tokio::spawn(async move { while event_rx.recv().await.is_some() {} }); + let actor = tokio::spawn(collector.run(event_tx)); + + handle.begin_monitoring().unwrap(); + // The first cycle is the baseline; a process started after it is a start event later. + wait_for_cycles(&handle, 1).await; + handle.update_config(config).await.unwrap(); + #[cfg(unix)] + let mut child = std::process::Command::new("sleep") + .arg("60") + .spawn() + .unwrap(); + wait_for_cycles(&handle, 3).await; + #[cfg(unix)] + { + child.kill().unwrap(); + child.wait().unwrap(); + } + handle.graceful_shutdown().await.unwrap(); + actor.await.unwrap().unwrap(); + drain.abort(); + + let recorded = entries(&path); + let kinds: Vec<&Kind> = recorded.iter().map(|entry| &entry.kind).collect(); + assert!(matches!( + kinds.as_slice(), + [ + Kind::Action(Action::ProcessStart { .. }), + Kind::Action(Action::PrivilegesDetected { .. }), + .., + Kind::Action(Action::CleanStop { .. }), + ] + )); + assert!( + kinds + .iter() + .any(|kind| matches!(kind, Kind::Action(Action::ConfigUpdateReceived { .. }))) + ); + #[cfg(unix)] + assert!(kinds.iter().any(|kind| matches!(kind, Kind::Batch { .. }))); + + let reader = LedgerReader::open(&path).unwrap(); + let last = reader.latest_checkpoint().unwrap().unwrap(); + assert_eq!(last.tree_size, recorded.len() as u64); +} diff --git a/procmond/tests/common/mod.rs b/procmond/tests/common/mod.rs index ded2f24b..8a420c24 100644 --- a/procmond/tests/common/mod.rs +++ b/procmond/tests/common/mod.rs @@ -121,6 +121,7 @@ pub fn create_mock_health_data() -> HealthCheckData { collection_errors: 0, backpressure_events: 0, operational_sub_status: None, + audit_ledger: None, } } diff --git a/procmond/tests/rpc_integration_tests.rs b/procmond/tests/rpc_integration_tests.rs index b8abd011..4ab2d7bc 100644 --- a/procmond/tests/rpc_integration_tests.rs +++ b/procmond/tests/rpc_integration_tests.rs @@ -95,6 +95,7 @@ fn create_test_health_data(state: CollectorState, connected: bool) -> HealthChec collection_errors: 2, backpressure_events: 5, operational_sub_status, + audit_ledger: None, } } diff --git a/procmond/tests/security_tests.rs b/procmond/tests/security_tests.rs index 7c4f397f..b125ad1d 100644 --- a/procmond/tests/security_tests.rs +++ b/procmond/tests/security_tests.rs @@ -137,6 +137,7 @@ fn create_mock_health_data() -> HealthCheckData { collection_errors: 0, backpressure_events: 0, operational_sub_status: None, + audit_ledger: None, } } diff --git "a/spec/full/specs/Epic_Brief_\342\200\224_DaemonEye_Core_Monitoring.md" "b/spec/full/specs/Epic_Brief_\342\200\224_DaemonEye_Core_Monitoring.md" index 521168c5..5e832e37 100644 --- "a/spec/full/specs/Epic_Brief_\342\200\224_DaemonEye_Core_Monitoring.md" +++ "b/spec/full/specs/Epic_Brief_\342\200\224_DaemonEye_Core_Monitoring.md" @@ -19,7 +19,7 @@ This Epic closes that foundation→product gap by finishing the stubbed middle s - **Storage (**file:daemoneye-lib/src/storage.rs**)** — every persist/query method is a TODO; `Vec` placeholder tables; no schema, indexing, transactions, retention, or migrations. This blocks rule persistence and the agent's detection loop (which currently loads **zero rules**). - **Detection (**file:daemoneye-lib/src/detection/mod.rs**)** — naive `name.contains("suspicious")` / `cpu_usage > 80` matching; SQL is validated at load time but never executed; the DataFusion-over-redb engine (R17–R21) is unbuilt and unwired into the agent loop. -- **Audit ledger (**file:daemoneye-lib/src/crypto.rs**)** — BLAKE3 hash chain exists but is in-memory, has no persisted `audit_ledger` table, `generate_inclusion_proof()` returns `vec![]`, and there are no Ed25519 checkpoints; architecture also expects procmond ownership. +- **Audit ledger (**file:daemoneye-lib/src/audit/**)** — at the time of the gap analysis the BLAKE3 hash chain was in-memory with no persisted ledger, no inclusion proofs and no Ed25519 checkpoints; T8 delivers a procmond-owned, persisted, signed Merkle ledger (ADR-0016). - **Privilege & service mgmt (**file:daemoneye-agent/src/main.rs**, **file:daemoneye-agent/src/broker_manager/state_machine.rs**)** — foreground process, Ctrl+C-only shutdown, `--database/--log-level` only; no daemon/service modes, no install/supervision, and privilege dropping is an explicit stub (procmond detects CAP_SYS_PTRACE/root but never drops). **Constraints (not the headline)** diff --git "a/spec/full/specs/Tech_Plan_\342\200\224_DaemonEye_Core_Monitoring_(v1.0_priority_areas).md" "b/spec/full/specs/Tech_Plan_\342\200\224_DaemonEye_Core_Monitoring_(v1.0_priority_areas).md" index 77bbf0c6..ec3058e4 100644 --- "a/spec/full/specs/Tech_Plan_\342\200\224_DaemonEye_Core_Monitoring_(v1.0_priority_areas).md" +++ "b/spec/full/specs/Tech_Plan_\342\200\224_DaemonEye_Core_Monitoring_(v1.0_priority_areas).md" @@ -10,7 +10,7 @@ Two measured findings bind T6. Detection windows must be read **bucket-at-a-time **2. Storage — redb event store per §11.7 (R20).** Replace the `Vec` placeholders in file:daemoneye-lib/src/storage.rs with typed tables: time-partitioned `processes.events` keyed `(ts_ms, seq)` plus multimap secondary indexes. Values use custom `redb::Value` impls with a postcard codec; keys are fixed-width big-endian. *Trade-off:* custom codecs cost upfront work but give compact, range-scannable keys and pushdown-friendly indexes. Schema evolution uses a **version tag with export-then-rebuild on mismatch** (no in-place migration): on mismatch the engine exports the existing partitions to a signed, versioned bundle, drops them, and rebuilds by replaying available procmond WAL. WAL retention must cover at least the configured event-store retention window so the gap is bounded, and the rebuild records the resulting gap window rather than leaving it silent. -**3. Audit ledger — procmond-owned, persisted, tamper-evident (R7).** Move ledger persistence into procmond (write-only handle, `0640`, `daemoneye` group), keep BLAKE3/Merkle primitives in file:daemoneye-lib/src/crypto.rs. Add real `rs-merkle` inclusion proofs (replacing the `vec![]` stub), MMR-frontier checkpoints, and optional Ed25519-signed checkpoints. *Constraint:* append-only, single linear history, `O(log n)` steady-state memory. +**3. Audit ledger — procmond-owned, persisted, tamper-evident (R7).** Ledger persistence lives in procmond (write-only handle, `0640`, `daemoneye` group). The tree, entries, checkpoints and verification live in `daemoneye-lib/src/audit/` (RFC 6962 tree over BLAKE3, persisted frontier, Ed25519-signed checkpoints); see ADR-0016. The ledger commits what procmond records: one batch entry per collection cycle and procmond's security-relevant actions. *Constraint:* append-only, single linear history, `O(log n)` steady-state memory. **4. Privilege & service — agent-as-supervisor with early drop (R6).** The agent is the installed OS service. **Validated model:** privileged agent bootstrap is an explicit, narrow exception to the steady-state security model. The agent may start elevated only to install/configure service resources and spawn procmond with the required elevation, then it **must drop privileges before broker steady-state and before collection begins**. After that point, the agent runs unprivileged and manages collector lifecycle exclusively via eventbus RPC. procmond drops to its minimal retained capability set after init (real `PrivilegeManager`, replacing the `detect_privileges` stub in procmond's `security.rs`). This refinement should be reflected back into requirements/steering during cross-artifact validation. @@ -45,13 +45,13 @@ Two measured findings bind T6. Detection windows must be read **bucket-at-a-time **Audit ledger DB (procmond write-only; others read-only).** -| Table | Key | Value | -| ------------------- | ---------------- | ----------------------------------------------------- | -| `AUDIT_LEDGER` | `seq: u64` | `AuditEntry` (BLAKE3 leaf, tree_size, root) | -| `AUDIT_CHECKPOINTS` | `tree_size: u64` | `Checkpoint { root_hash, created_at_ms, signature? }` | -| `AUDIT_FRONTIER` | `()` | MMR peak hashes (recovery, `O(log n)`) | +| Table | Key | Value | +| ------------------- | ---------------- | ----------------------------------------------------------------------- | +| `AUDIT_LEDGER` | `seq: u64` | Entry (kind, payload hash, previous hash, entry hash) | +| `AUDIT_CHECKPOINTS` | `tree_size: u64` | Checkpoint (root, time, signing state, public key, signature, frontier) | +| `AUDIT_FRONTIER` | `()` | Merkle frontier (recovery, `O(log n)`) | -Inclusion proof = `(root, index, total, leaf_hash, siblings[])`, verifiable offline. Ed25519 keypair generated first-run, stored `0400` under procmond UID; `secrecy`/`zeroize` in memory. The agent opens the audit ledger read-only and serves CLI audit verify/proof/checkpoint commands over the existing CLI↔agent IPC boundary; CLI does not open the ledger directly. +Inclusion proof = `(root, index, total, leaf_hash, siblings[])`, verifiable offline. Ed25519 key generated only for an empty ledger and stored `0400` beside the ledger as `.key`; `secrecy`/`zeroize` in memory. Readers open the ledger read-only through `daemoneye-lib`; the agent serves CLI audit verify/prove/export-checkpoint requests over the CLI↔agent IPC boundary (T10), and the CLI does not open the ledger directly. Verification is local evidence only: someone with root who holds the signing key can rebuild the whole ledger, under the same key id, which only a checkpoint kept off the host exposes, and only for the history up to that checkpoint (a trusted key id exposes only a different key or signing off). Commercial tiers extend this foundation, are sold separately and are not in this repo. Only broker-connected (actor) mode keeps a ledger. ## Component Architecture @@ -74,7 +74,7 @@ graph TD - **StorageEngine** (`daemoneye-lib`): owns event-store schema, codecs, time-bucket lifecycle, retention/cleanup, rebuild-from-WAL on schema mismatch, and the read-only `TableProvider`s consumed by detection. Single-writer ingest API used only by the agent. Replaces the stubbed `DatabaseManager`. - **DetectionEngine** (`daemoneye-agent` + `daemoneye-lib/detection`): `DetectionPlanner` (Phase 1, grown from `SqlToIpcTranslator`), `SchemaCatalog` (static authenticated registration, R19), `RegexCache` (full-string-keyed LRU, R17), `DataFusionExecutor` (Phase 2, allowlisted `SessionContext`, memory/cardinality caps). Emits `DetectionTask`s through `broker_manager`/eventbus; reads event store read-only. Replaces the placeholder in file:daemoneye-lib/src/detection/mod.rs. -- **AuditLedger writer** (`procmond`): consumes BLAKE3/Merkle primitives from file:daemoneye-lib/src/crypto.rs; persists ledger + checkpoints. The ledger file remains procmond-owned for writes; the agent opens it read-only and serves CLI audit requests over IPC. +- **AuditLedger writer** (`procmond`): consumes the `daemoneye-lib/src/audit/` primitives; persists ledger + checkpoints. The ledger file remains procmond-owned for writes; readers open it read-only, and the agent will serve CLI audit requests over IPC (T10). - **PrivilegeManager** (`procmond`): platform privilege request + immediate post-init drop with audit logging (`caps`/Linux, `SeDebugPrivilege`/Windows, macOS entitlements). - **ServiceManager** (`daemoneye-agent` crate): `ServiceManager` trait + `UnixServiceManager`/`WindowsServiceManager`; install/uninstall/start/stop/status, systemd/launchd/SCM unit generation; privileged bootstrap limited to service setup and procmond spawn, then mandatory agent self-drop before broker steady-state/collection; collector supervision/restart via eventbus RPC. - **CompletenessTracker** (cross-cutting, `daemoneye-lib`): threads `Completeness` from executor/collector signals into alerts and query envelopes. diff --git "a/spec/full/tickets/T10_\302\267_M7_\342\200\224_Operator_CLI_(query,_management,_health,_robustness).md" "b/spec/full/tickets/T10_\302\267_M7_\342\200\224_Operator_CLI_(query,_management,_health,_robustness).md" index e0e1bd7b..141475ce 100644 --- "a/spec/full/tickets/T10_\302\267_M7_\342\200\224_Operator_CLI_(query,_management,_health,_robustness).md" +++ "b/spec/full/tickets/T10_\302\267_M7_\342\200\224_Operator_CLI_(query,_management,_health,_robustness).md" @@ -10,6 +10,7 @@ - Management commands: `rules` (incl. file-based + minimal interactive create), `alerts`, `health`, `data`, `config`, `service`; YAML config hierarchy; destructive actions confirm by default with `--yes`/`--force`. - Health/diagnostics: color-coded overview surfacing collection rate, rule eval latency, alert delivery health, redb write latency, and degraded-detection summary. - CLI robustness: insta snapshot tests, actionable errors, shell completions (bash/zsh/fish/PowerShell). +- Audit requests (deferred from T8): the CLI-to-agent request kinds and agent handlers for `audit verify`, `audit prove` and `audit export-checkpoint`, over the `daemoneye-lib` functions `verify`, `prove` and `export_checkpoint`. The agent opens the ledger read-only; `ipc.proto` has no such request kinds yet. Verify output must keep the statement that internal consistency is not proof of integrity, and accept a trusted checkpoint and a trusted key id. **Out:** Interactive REPL shell (post-v1.0). diff --git "a/spec/full/tickets/T12_\302\267_M9_\342\200\224_End-to-end_integration.md" "b/spec/full/tickets/T12_\302\267_M9_\342\200\224_End-to-end_integration.md" index 4c21e595..07ebd547 100644 --- "a/spec/full/tickets/T12_\302\267_M9_\342\200\224_End-to-end_integration.md" +++ "b/spec/full/tickets/T12_\302\267_M9_\342\200\224_End-to-end_integration.md" @@ -25,6 +25,7 @@ - Unified configuration + service management across procmond / daemoneye-agent / daemoneye-cli (T9, T10). - E2E suites under each crate's `tests/` plus workspace-level scenarios. - This ticket integrates existing pieces; avoid introducing new feature logic. +- Ledger link (from T8): stored process rows keep every field of the hashed event projection, including the WAL sequence, and the store calls the batch check against the batch entry that committed them. The projection includes the executable hash, its algorithm and the collection time, which the wire event to the agent does not carry today: this ticket must either extend the wire event or the agent cannot recompute batch roots. ## Testing & quality gates diff --git "a/spec/full/tickets/T8_\302\267_M5_\342\200\224_Audit_ledger_(persisted,_Merkle_proofs,_signed_checkpoints).md" "b/spec/full/tickets/T8_\302\267_M5_\342\200\224_Audit_ledger_(persisted,_Merkle_proofs,_signed_checkpoints).md" index 8ce878b0..bf1f8547 100644 --- "a/spec/full/tickets/T8_\302\267_M5_\342\200\224_Audit_ledger_(persisted,_Merkle_proofs,_signed_checkpoints).md" +++ "b/spec/full/tickets/T8_\302\267_M5_\342\200\224_Audit_ledger_(persisted,_Merkle_proofs,_signed_checkpoints).md" @@ -7,11 +7,12 @@ **In:** - Move ledger persistence into procmond: append-only `AUDIT_LEDGER`/`AUDIT_CHECKPOINTS`/`AUDIT_FRONTIER` in a separate redb (write-only handle, `0640`, `daemoneye` group). -- Real `rs_merkle` inclusion proofs (replace `vec![]` stub in file:daemoneye-lib/src/crypto.rs), MMR-frontier checkpoints, optional Ed25519-signed checkpoints (key `0400`, `secrecy`/`zeroize`). -- Chain verification + recovery/consistency check; audit hooks in `ProcessMessageHandler` for security-relevant events. -- Agent opens ledger read-only and serves CLI audit verify/prove/checkpoint over IPC (CLI never opens ledger directly). +- Inclusion proofs from an RFC 6962 Merkle tree over BLAKE3 (`rs_merkle` is a test oracle only), persisted-frontier checkpoints, Ed25519-signed checkpoints (key `0400`, `secrecy`/`zeroize`). See ADR-0016. +- Commit each collection cycle's recorded events (one batch entry per cycle: first and last WAL sequence, count, Merkle root over each sanitised event's hash) and procmond's security-relevant actions (start, privileges detected, config update received, executable-hash drift, clean stop, signing key created or failed). +- Chain verification + recovery/consistency check; library functions `verify`, `prove`, `export_checkpoint` and the batch check, over a read-only handle. +- Local evidence only: anchoring checkpoints off the host is outside this repo. -**Out:** CLI command surface itself (T10) beyond the agent-side API. +**Out:** the agent IPC surface and CLI command surface for audit verify/prove/checkpoint (T10); tying stored rows to batch entries (T12); entries for actions that originate in the agent. ## Spec references @@ -21,11 +22,11 @@ ## Key touchpoints -- file:daemoneye-lib/src/crypto.rs — `AuditLedger`/`AuditEntry`/`Blake3Hasher`; replace `generate_inclusion_proof()` `vec![]` stub with real `rs_merkle` proofs; add MMR-frontier checkpoints + optional Ed25519-signed checkpoints. -- procmond — new audit-writer module owning the write-only handle; audit hooks in the `ProcessMessageHandler`/collection path; separate redb file (`AUDIT_LEDGER`/`AUDIT_CHECKPOINTS`/`AUDIT_FRONTIER`), `0640`, `daemoneye` group. -- Agent opens ledger **read-only** and serves CLI audit verify/prove/checkpoint over IPC (file:daemoneye-lib/src/ipc/); CLI never opens the ledger directly. -- Deps present: `rs_merkle`, `blake3`. New deps: `ed25519-dalek` (signing), `secrecy`/`zeroize` (key handling); key file `0400` under procmond UID. -- Reference: Tech Plan "Audit ledger DB" + design.md "Audit Ledger (redb + rs-merkle)". +- file:daemoneye-lib/src/audit/ — Merkle tree, entries, event hash, checkpoints, signing, read-only reader, verification. `crypto.rs` keeps BLAKE3 hashing and the hash-chained entry encoding. +- procmond — `audit_writer` module owns the only writable handle; the commit hooks sit in the collection cycle and the start/stop path; separate redb file (`AUDIT_LEDGER`/`AUDIT_CHECKPOINTS`/`AUDIT_FRONTIER`), `0640`; the `daemoneye` group is assigned with privilege drop (T9). Only broker-connected (actor) mode keeps a ledger. +- Readers open the ledger **read-only** through `daemoneye-lib`; the agent/CLI request path is T10. +- Deps present: `blake3`. New deps: `ed25519-dalek` (signing), `secrecy`/`zeroize` (key handling); key file `0400` under procmond UID. +- Reference: Tech Plan "Audit ledger DB" + design.md "Audit Ledger" + ADR-0016. ## Testing & quality gates