Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
4 changes: 2 additions & 2 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
147 changes: 19 additions & 128 deletions .kiro/specs/daemoneye-core-monitoring/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 `<ledger file name>.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<Vec<[u8; 32]>>, // optional cached siblings
checkpoint_sig: Option<Vec<u8>>, // optional signature at this state
}

#[derive(Serialize, Deserialize, Clone)]
struct Checkpoint {
tree_size: u64,
root_hash: [u8; 32],
created_at_ms: i64,
signature: Option<Vec<u8>>, // 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<u8> {
// 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<Blake3Hasher>,
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::<Blake3Hasher>::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

Expand Down Expand Up @@ -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:

Expand Down Expand Up @@ -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.
4 changes: 2 additions & 2 deletions .kiro/specs/daemoneye-core-monitoring/requirements.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion .kiro/steering/structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading
Loading