Repository navigation
security: tamper-evident audit logging with append-only enforcement - #916
BenediktSchackenberg wants to merge 3 commits into
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughImplements tamper‑evident audit logging: creates /var/log/nemoclaw and an append‑only Changes
Sequence Diagram(s)sequenceDiagram
participant GW as Gateway Process
participant Audit as Audit Module
participant FS as File System
GW->>Audit: append_event({"type":"gateway_start","pid":PID})
Audit->>Audit: timestamp + determine prev_hash
Audit->>Audit: compute sha256 over deterministic JSON payload
Audit->>FS: open("/var/log/nemoclaw/audit.jsonl", "a") + lock
FS-->>Audit: file_handle
Audit->>FS: write(json_record + "\n") + fsync
FS-->>Audit: write_ack
Audit-->>GW: return_new_hash
sequenceDiagram
participant User as Verification User
participant Audit as Audit Module
participant FS as File System
User->>Audit: verify_chain("/var/log/nemoclaw/audit.jsonl")
Audit->>FS: open & stream lines
FS-->>Audit: jsonl_lines
loop each_entry
Audit->>Audit: parse JSON line
Audit->>Audit: recompute hash(entry without hash)
Audit->>Audit: compare recomputed hash & prev_hash linkage
end
Audit-->>User: (valid | broken, entry_count, error_message)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Pull request overview
This PR aims to make NemoClaw’s local audit trail harder for a sandboxed agent to tamper with by moving logs out of /tmp, adding append-only enforcement, and introducing hash-chained JSONL audit records plus a verification CLI.
Changes:
- Add
orchestrator/audit.pyimplementing SHA-256 hash chaining and averifyCLI. - Move gateway logs to
/var/log/nemoclawand initialize an audit entry on gateway start. - Harden sandbox policy to deny agent tools from writing to
/var/log/**and from running common log-tampering commands.
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 5 comments.
Show a summary per file
| File | Description |
|---|---|
scripts/nemoclaw-start.sh |
Writes gateway logs under /var/log/nemoclaw and appends an initial audit event on startup. |
nemoclaw-blueprint/policies/openclaw-sandbox.yaml |
Adds tool-policy deny rules for log-path writes/edits and chattr/truncate. |
nemoclaw-blueprint/orchestrator/audit.py |
New hash-chained JSONL audit logger with verify CLI mode. |
nemoclaw-blueprint/orchestrator/__init__.py |
Makes orchestrator importable as a Python package. |
docs/security/audit-logging.md |
New security documentation describing tamper-evident audit logging and verification. |
Dockerfile |
Installs e2fsprogs and creates /var/log/nemoclaw/audit.jsonl with append-only attribute. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| Run the built-in verification command against any audit log file: | ||
|
|
||
| ```bash | ||
| python3 -m nemoclaw_blueprint.orchestrator.audit verify /var/log/nemoclaw/audit.jsonl |
There was a problem hiding this comment.
The verification command shown here uses python3 -m nemoclaw_blueprint.orchestrator.audit, but the code in this PR is located at /opt/nemoclaw-blueprint/orchestrator/audit.py (module orchestrator.audit). As written, the documented command will fail unless a separate nemoclaw_blueprint package is installed. Update the docs to match the real module path and any required PYTHONPATH/working-directory setup.
| Run the built-in verification command against any audit log file: | |
| ```bash | |
| python3 -m nemoclaw_blueprint.orchestrator.audit verify /var/log/nemoclaw/audit.jsonl | |
| Run the built-in verification command against any audit log file (from the project root, e.g. `/opt/nemoclaw-blueprint`): | |
| ```bash | |
| cd /opt/nemoclaw-blueprint | |
| python3 -m orchestrator.audit verify /var/log/nemoclaw/audit.jsonl |
There was a problem hiding this comment.
Fixed — updated the CLI invocation to PYTHONPATH=/opt/nemoclaw-blueprint python3 -m orchestrator.audit verify which matches the actual module path.
| paths: | ||
| - "/var/log/**" | ||
| - "/var/log/nemoclaw/**" | ||
| - tool: edit | ||
| paths: | ||
| - "/var/log/**" | ||
| - "/var/log/nemoclaw/**" |
There was a problem hiding this comment.
/var/log/nemoclaw/** is already covered by the broader /var/log/** glob in both the write and edit deny rules. Dropping the redundant narrower pattern would reduce duplication and make future edits less error-prone.
There was a problem hiding this comment.
Good catch — removed the redundant /var/log/nemoclaw/** entries since /var/log/** already covers them.
| RUN mkdir -p /var/log/nemoclaw \ | ||
| && chown root:sandbox /var/log/nemoclaw \ | ||
| && chmod 750 /var/log/nemoclaw \ | ||
| && touch /var/log/nemoclaw/audit.jsonl \ | ||
| && chown root:sandbox /var/log/nemoclaw/audit.jsonl \ | ||
| && chmod 0620 /var/log/nemoclaw/audit.jsonl \ | ||
| && chattr +a /var/log/nemoclaw/audit.jsonl |
There was a problem hiding this comment.
Setting chattr +a during docker build is often unsupported on overlayfs-backed layers (common in CI), which can cause this RUN step to fail and block image builds. Consider making this best-effort with an explicit check/fallback (and documenting when append-only can’t be enforced), or enforcing append-only on a filesystem that supports it at runtime.
| RUN mkdir -p /var/log/nemoclaw \ | |
| && chown root:sandbox /var/log/nemoclaw \ | |
| && chmod 750 /var/log/nemoclaw \ | |
| && touch /var/log/nemoclaw/audit.jsonl \ | |
| && chown root:sandbox /var/log/nemoclaw/audit.jsonl \ | |
| && chmod 0620 /var/log/nemoclaw/audit.jsonl \ | |
| && chattr +a /var/log/nemoclaw/audit.jsonl | |
| # Note: chattr +a may be unsupported on some filesystems (e.g., overlayfs in CI), | |
| # so we attempt it best-effort and log a warning if it fails instead of | |
| # failing the entire image build. | |
| RUN mkdir -p /var/log/nemoclaw \ | |
| && chown root:sandbox /var/log/nemoclaw \ | |
| && chmod 750 /var/log/nemoclaw \ | |
| && touch /var/log/nemoclaw/audit.jsonl \ | |
| && chown root:sandbox /var/log/nemoclaw/audit.jsonl \ | |
| && chmod 0620 /var/log/nemoclaw/audit.jsonl \ | |
| && (chattr +a /var/log/nemoclaw/audit.jsonl 2>/dev/null \ | |
| || echo "Warning: could not set append-only flag on /var/log/nemoclaw/audit.jsonl; filesystem may not support chattr") |
There was a problem hiding this comment.
Made it best-effort with a fallback warning: chattr +a ... || echo "[WARN] chattr +a not supported on this filesystem" >&2. Won't break CI on overlayfs anymore.
| # Initialize the audit trail with a gateway_start event | ||
| PYTHONPATH=/opt/nemoclaw-blueprint python3 -c " | ||
| from orchestrator.audit import append_event | ||
| append_event('/var/log/nemoclaw/audit.jsonl', {'action': 'gateway_start', 'pid': $GATEWAY_PID}, 'genesis') |
There was a problem hiding this comment.
The audit entry is always appended with prev_hash set to the constant 'genesis'. If /var/log/nemoclaw/audit.jsonl already contains entries (e.g., container restart or reuse of the writable layer), this will deterministically break the hash chain on the next line and verify_chain will report tampering even though none occurred. Read the last entry’s hash from the file (or store it elsewhere) and use that as prev_hash, or explicitly support “new chain segment” markers in both writer and verifier.
| append_event('/var/log/nemoclaw/audit.jsonl', {'action': 'gateway_start', 'pid': $GATEWAY_PID}, 'genesis') | |
| import json | |
| audit_path = '/var/log/nemoclaw/audit.jsonl' | |
| prev_hash = 'genesis' | |
| last_line = None | |
| try: | |
| with open(audit_path, 'r', encoding='utf-8') as f: | |
| for line in f: | |
| if line.strip(): | |
| last_line = line | |
| if last_line is not None: | |
| try: | |
| last_entry = json.loads(last_line) | |
| prev_hash = last_entry.get('hash', prev_hash) | |
| except Exception: | |
| # If the last line is malformed, keep prev_hash as 'genesis' | |
| pass | |
| except FileNotFoundError: | |
| # No existing audit log; start a new chain segment with 'genesis' | |
| pass | |
| except Exception: | |
| # Any other error reading the audit log should not prevent logging this event | |
| pass | |
| append_event(audit_path, {'action': 'gateway_start', 'pid': $GATEWAY_PID}, prev_hash) |
There was a problem hiding this comment.
Fixed — append_event now auto-reads the last hash from the existing audit file via get_last_hash(), so the chain survives container restarts. No more hardcoded 'genesis'.
|
|
||
| if __name__ == "__main__": | ||
| if len(sys.argv) < 3 or sys.argv[1] != "verify": | ||
| print(f"usage: python3 -m nemoclaw_blueprint.orchestrator.audit verify <file>") |
There was a problem hiding this comment.
The CLI usage string references nemoclaw_blueprint.orchestrator.audit, but this repo’s on-disk module is orchestrator.audit under /opt/nemoclaw-blueprint/ (and there is no nemoclaw_blueprint package). Update the usage text to the actual supported invocation (and/or mention the required PYTHONPATH).
| print(f"usage: python3 -m nemoclaw_blueprint.orchestrator.audit verify <file>") | |
| print("usage: PYTHONPATH=/opt/nemoclaw-blueprint python3 -m orchestrator.audit verify <file>") |
There was a problem hiding this comment.
Updated the usage string to PYTHONPATH=/opt/nemoclaw-blueprint python3 -m orchestrator.audit verify <file> — matches the actual invocation now.
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (4)
docs/security/audit-logging.md (1)
7-7: Consider simplifying "prior to"."prior to this change" is wordy. Consider "before this change" for conciseness.
📝 Suggested revision
-In the default configuration prior to this change, all logs lived under `/tmp/`, which is fully writable by the sandbox user. +In the default configuration before this change, all logs lived under `/tmp/`, which is fully writable by the sandbox user.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/security/audit-logging.md` at line 7, Replace the phrase "prior to this change" with the simpler "before this change" in the sentence that currently reads "In the default configuration prior to this change, all logs lived under `/tmp/`..." in docs/security/audit-logging.md to improve conciseness while preserving meaning.nemoclaw-blueprint/orchestrator/audit.py (3)
111-111: Remove unnecessary f-string prefix.This string has no placeholders, so the
fprefix is extraneous (Ruff F541).📝 Suggested fix
- print(f"usage: python3 -m nemoclaw_blueprint.orchestrator.audit verify <file>") + print("usage: python3 -m nemoclaw_blueprint.orchestrator.audit verify <file>")🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@nemoclaw-blueprint/orchestrator/audit.py` at line 111, The print call in nemoclaw_blueprint.orchestrator.audit uses an unnecessary f-string prefix; remove the leading "f" from the literal in the print statement (the line containing print(f"usage: python3 -m nemoclaw_blueprint.orchestrator.audit verify <file>")) so it becomes a plain string literal, eliminating the extraneous f-string usage flagged by Ruff F541.
36-50: Consider file locking for concurrent access.The append operation uses
open(log_file, "a")without file locking. If multiple processes append events concurrently, interleaved writes could corrupt the JSONL format. While the append-only attribute prevents truncation, it doesn't prevent concurrent write corruption.If concurrent audit event generation is expected (e.g., from multiple orchestrator threads), consider using
fcntl.flock()or a similar locking mechanism.🔒 Proposed fix with file locking
+import fcntl + def append_event(log_file: str, event: dict, prev_hash: str) -> str: """Append a hash-chained event to the audit log. Returns the entry hash.""" record = { "timestamp": time.time(), "prev_hash": prev_hash, "event": event, } payload = json.dumps(record, separators=(",", ":"), sort_keys=True) entry_hash = _hash_payload(payload) record["hash"] = entry_hash with open(log_file, "a") as f: + fcntl.flock(f.fileno(), fcntl.LOCK_EX) f.write(json.dumps(record, separators=(",", ":"), sort_keys=True) + "\n") + f.flush() + fcntl.flock(f.fileno(), fcntl.LOCK_UN) return entry_hash🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@nemoclaw-blueprint/orchestrator/audit.py` around lines 36 - 50, append_event currently opens log_file with open(log_file, "a") and writes without any inter-process locking, risking interleaved/corrupted JSONL when multiple processes/threads append concurrently; update append_event to acquire an exclusive append lock (e.g., using fcntl.flock(f, fcntl.LOCK_EX) on POSIX or an equivalent on Windows) immediately after opening the file and before writing the json line, then write the serialized record and flush/fsync if desired, and finally release the lock (fcntl.flock(f, fcntl.LOCK_UN)) before returning the entry_hash; keep the existing record construction and _hash_payload usage unchanged.
104-104: Remove unnecessary f-string prefix.This string has no placeholders, so the
fprefix is extraneous (Ruff F541).📝 Suggested fix
- print(f"chain: BROKEN ✗") + print("chain: BROKEN ✗")🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@nemoclaw-blueprint/orchestrator/audit.py` at line 104, The print statement print(f"chain: BROKEN ✗") uses an unnecessary f-string prefix; locate the print call (the exact text "print(f\"chain: BROKEN ✗\")") in orchestrator/audit.py and remove the leading f so it becomes a normal string literal (print("chain: BROKEN ✗")), keeping spacing and special characters unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@docs/security/audit-logging.md`:
- Around line 1-2: Add a top-level H1 heading and the required frontmatter and
SPDX license header to this markdown page: replace the existing "## Audit
Logging" with "# Audit Logging" and add YAML frontmatter above the SPDX line
containing the required fields (title, description, keywords, topics, tags,
content type, difficulty, audience, status), then include the SPDX license
header immediately after the frontmatter; ensure the frontmatter keys match the
repository's doc schema and the SPDX identifier is the canonical license token.
- Around line 29-40: Update the two fenced code blocks that show the audit
output (the blocks containing "entries: 42 / chain: valid ✓" and "entries: 17
/ chain: BROKEN ✗ / detail: line 18: hash mismatch (tampering detected)") to
include a language specifier by changing the opening fences to ```text so the
blocks are recognized as plain text (satisfying markdownlint MD040).
- Around line 23-25: Update the CLI example code block that currently contains
"python3 -m nemoclaw_blueprint.orchestrator.audit verify
/var/log/nemoclaw/audit.jsonl" so the fenced block uses the `console` language
tag and the command line is prefixed with a `$ ` prompt (i.e., replace the
```bash block with ```console and change the line to `$ python3 -m
nemoclaw_blueprint.orchestrator.audit verify /var/log/nemoclaw/audit.jsonl`).
---
Nitpick comments:
In `@docs/security/audit-logging.md`:
- Line 7: Replace the phrase "prior to this change" with the simpler "before
this change" in the sentence that currently reads "In the default configuration
prior to this change, all logs lived under `/tmp/`..." in
docs/security/audit-logging.md to improve conciseness while preserving meaning.
In `@nemoclaw-blueprint/orchestrator/audit.py`:
- Line 111: The print call in nemoclaw_blueprint.orchestrator.audit uses an
unnecessary f-string prefix; remove the leading "f" from the literal in the
print statement (the line containing print(f"usage: python3 -m
nemoclaw_blueprint.orchestrator.audit verify <file>")) so it becomes a plain
string literal, eliminating the extraneous f-string usage flagged by Ruff F541.
- Around line 36-50: append_event currently opens log_file with open(log_file,
"a") and writes without any inter-process locking, risking interleaved/corrupted
JSONL when multiple processes/threads append concurrently; update append_event
to acquire an exclusive append lock (e.g., using fcntl.flock(f, fcntl.LOCK_EX)
on POSIX or an equivalent on Windows) immediately after opening the file and
before writing the json line, then write the serialized record and flush/fsync
if desired, and finally release the lock (fcntl.flock(f, fcntl.LOCK_UN)) before
returning the entry_hash; keep the existing record construction and
_hash_payload usage unchanged.
- Line 104: The print statement print(f"chain: BROKEN ✗") uses an unnecessary
f-string prefix; locate the print call (the exact text "print(f\"chain: BROKEN
✗\")") in orchestrator/audit.py and remove the leading f so it becomes a normal
string literal (print("chain: BROKEN ✗")), keeping spacing and special
characters unchanged.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 856964b1-ec1f-4311-b21e-152513d50c3a
📒 Files selected for processing (6)
Dockerfiledocs/security/audit-logging.mdnemoclaw-blueprint/orchestrator/__init__.pynemoclaw-blueprint/orchestrator/audit.pynemoclaw-blueprint/policies/openclaw-sandbox.yamlscripts/nemoclaw-start.sh
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
docs/security/audit-logging.md (2)
47-50: Missing "Next Steps" section.Per coding guidelines for page structure, documentation pages should include a "Next Steps" section at the bottom linking to related pages (e.g., sandbox policy configuration, security hardening guides).
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/security/audit-logging.md` around lines 47 - 50, Add a "Next Steps" section at the end of the audit-logging.md doc (after the "Future work" heading) that links to related pages such as the sandbox policy configuration guide and the security hardening guide; create a brief bulleted list with descriptive link text and anchors (e.g., "See Sandbox policy configuration" and "See Security hardening guide") consistent with existing markdown link style used in this repo, and ensure the new "Next Steps" heading matches the other section headings' level and formatting.
18-22: Passive voice constructions detected.Per coding guidelines, active voice is required. The following phrases use passive voice:
- Line 18: "Logs are written to" → "NemoClaw writes logs to"
- Line 18: "The directory is owned by" → "Root owns the directory"
- Line 20: "The
audit.jsonlfile has the... attribute set" → "The build process sets thechattr +aattribute onaudit.jsonl"🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/security/audit-logging.md` around lines 18 - 22, Update the passive-voice sentences in the "Log isolation", "Append-only enforcement", and "Hash chaining" sections to active voice: change "Logs are written to `/var/log/nemoclaw/`" to "NemoClaw writes logs to `/var/log/nemoclaw/`", change "The directory is owned by `root:sandbox` with mode 750" to "Root owns the directory `root:sandbox` with mode 750" (or "Root owns the directory and sets mode 750"), and change "The `audit.jsonl` file has the `chattr +a` ... attribute set at image build time" to "The build process sets the `chattr +a` attribute on `audit.jsonl` at image build time"; keep the rest of the content and wording identical unless further active-voice edits are obvious.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@docs/security/audit-logging.md`:
- Around line 10-12: The document uses H3 headings where they should be H2,
violating markdownlint MD001; update the headings "### Problem", "### Solution",
"### Verifying the audit chain", and "### Future work" to "## Problem", "##
Solution", "## Verifying the audit chain", and "## Future work" respectively so
heading levels increment by one from the H1 title.
In `@nemoclaw-blueprint/orchestrator/audit.py`:
- Around line 37-54: append_event currently requires callers to pass prev_hash
which leads to chain breaks when callers hardcode 'genesis'; add a
get_last_hash(log_file: str) helper that safely opens the log file (shared
lock), reads the last non-empty line, parses the JSON and returns its "hash" (or
'genesis' if file is empty/missing or parse fails), ensure it uses the same
locking semantics as append_event, and update callers that currently pass
prev_hash='genesis' (e.g., the gateway_start invocations) to call
get_last_hash(log_file) and pass its result to append_event instead of the
hardcoded string.
---
Nitpick comments:
In `@docs/security/audit-logging.md`:
- Around line 47-50: Add a "Next Steps" section at the end of the
audit-logging.md doc (after the "Future work" heading) that links to related
pages such as the sandbox policy configuration guide and the security hardening
guide; create a brief bulleted list with descriptive link text and anchors
(e.g., "See Sandbox policy configuration" and "See Security hardening guide")
consistent with existing markdown link style used in this repo, and ensure the
new "Next Steps" heading matches the other section headings' level and
formatting.
- Around line 18-22: Update the passive-voice sentences in the "Log isolation",
"Append-only enforcement", and "Hash chaining" sections to active voice: change
"Logs are written to `/var/log/nemoclaw/`" to "NemoClaw writes logs to
`/var/log/nemoclaw/`", change "The directory is owned by `root:sandbox` with
mode 750" to "Root owns the directory `root:sandbox` with mode 750" (or "Root
owns the directory and sets mode 750"), and change "The `audit.jsonl` file has
the `chattr +a` ... attribute set at image build time" to "The build process
sets the `chattr +a` attribute on `audit.jsonl` at image build time"; keep the
rest of the content and wording identical unless further active-voice edits are
obvious.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: a22671c4-ea1b-4152-a13e-93dc171fc18a
📒 Files selected for processing (2)
docs/security/audit-logging.mdnemoclaw-blueprint/orchestrator/audit.py
d365005 to
68c407b
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
docs/security/audit-logging.md (1)
1-14:⚠️ Potential issue | 🟡 MinorSPDX header should follow frontmatter.
Per coding guidelines, the SPDX license header must appear after frontmatter, not before it. Move the SPDX comment block below the closing
---of the frontmatter.📝 Proposed fix
-<!-- -SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -SPDX-License-Identifier: Apache-2.0 ---> - --- title: Audit Logging description: Tamper-evident audit trail for NemoClaw gateway and orchestrator events. keywords: - audit - logging - security - hash chain --- + +<!-- +SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +SPDX-License-Identifier: Apache-2.0 +--> # Audit LoggingAs per coding guidelines: "SPDX license header is present after frontmatter."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/security/audit-logging.md` around lines 1 - 14, Move the SPDX comment block so it appears immediately after the closing frontmatter delimiter ('---') instead of before it: relocate the SPDX header (the multiline <!-- SPDX-... --> comment) to be placed right below the final '---' that ends the YAML frontmatter in the Audit Logging doc so the SPDX header follows the frontmatter per the coding guidelines.
🧹 Nitpick comments (2)
docs/security/audit-logging.md (2)
22-22: Split into one sentence per line.This line contains two sentences. Per coding guidelines, each sentence should be on its own line to make diffs readable.
📝 Proposed fix
-In the default configuration before this change, all logs lived under `/tmp/`, which is fully writable by the sandbox user. An agent could silently delete, truncate, or rewrite its own audit trail — making post-incident forensics unreliable. +In the default configuration before this change, all logs lived under `/tmp/`, which is fully writable by the sandbox user. +An agent could silently delete, truncate, or rewrite its own audit trail—making post-incident forensics unreliable.As per coding guidelines: "One sentence per line in source (makes diffs readable)."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/security/audit-logging.md` at line 22, The sentence "In the default configuration before this change, all logs lived under `/tmp/`, which is fully writable by the sandbox user. An agent could silently delete, truncate, or rewrite its own audit trail — making post-incident forensics unreliable." should be split into two separate lines/sentences: one stating that logs lived under `/tmp/` and were writable, and a second stating the consequence that an agent could delete/truncate/rewrite its audit trail making forensics unreliable; update the document text containing that exact sentence fragment so each sentence appears on its own line.
28-32: Multiple sentences per line and passive voice constructions.Each list item contains two sentences on one line, and several use passive voice.
📝 Proposed revision (one sentence per line, active voice)
-1. **Log isolation** — Logs are written to `/var/log/nemoclaw/` instead of `/tmp/`. The directory is owned by `root:sandbox` with mode 750, and the sandbox policy marks `/var/log` as read-only. +1. **Log isolation** — The system writes logs to `/var/log/nemoclaw/` instead of `/tmp/`. + The directory has `root:sandbox` ownership with mode 750, and the sandbox policy marks `/var/log` as read-only. -2. **Append-only enforcement** — The `audit.jsonl` file has the `chattr +a` (append-only) attribute set at image build time. Even with group-write permission, the kernel prevents any operation other than appending. +2. **Append-only enforcement** — The image build process sets the `chattr +a` (append-only) attribute on `audit.jsonl`. + Even with group-write permission, the kernel prevents any operation other than appending. -3. **Hash chaining** — Each log entry includes a SHA-256 hash of its payload and a `prev_hash` field linking to the previous entry. Any modification breaks the chain and is detectable offline. +3. **Hash chaining** — Each log entry includes a SHA-256 hash of its payload and a `prev_hash` field linking to the previous entry. + Any modification breaks the chain, and you can detect it offline.As per coding guidelines: "One sentence per line in source" and "Active voice required."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/security/audit-logging.md` around lines 28 - 32, Rewrite each bullet under the security audit-logging section so every list item is a single active-voice sentence: split the current multi-sentence lines for "Log isolation", "Append-only enforcement", and "Hash chaining" into one clear active sentence per line, convert passive constructions to active (e.g., "The directory is owned by root:sandbox" -> "root:sandbox owns the directory" or "We set chattr +a on audit.jsonl" for the append-only note), and keep key identifiers ("/var/log/nemoclaw/", "audit.jsonl", "chattr +a", "SHA-256", "prev_hash") intact so the meaning and technical details remain unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@nemoclaw-blueprint/orchestrator/audit.py`:
- Around line 64-79: The code currently calls get_last_hash(log_file) before
acquiring the file lock in append_event, allowing a race that creates duplicate
prev_hash values; fix by acquiring the same exclusive lock (fcntl.LOCK_EX) on
log_file before calling get_last_hash and keep that lock held while computing
payload/_hash_payload and writing the new record, then release the lock after
f.flush(); ensure you open the file for append (as is done) and move the
get_last_hash call and payload/hash generation inside the with-open +
fcntl.flock(LOCK_EX) block so the read→compute→write happens atomically under
the lock.
---
Duplicate comments:
In `@docs/security/audit-logging.md`:
- Around line 1-14: Move the SPDX comment block so it appears immediately after
the closing frontmatter delimiter ('---') instead of before it: relocate the
SPDX header (the multiline <!-- SPDX-... --> comment) to be placed right below
the final '---' that ends the YAML frontmatter in the Audit Logging doc so the
SPDX header follows the frontmatter per the coding guidelines.
---
Nitpick comments:
In `@docs/security/audit-logging.md`:
- Line 22: The sentence "In the default configuration before this change, all
logs lived under `/tmp/`, which is fully writable by the sandbox user. An agent
could silently delete, truncate, or rewrite its own audit trail — making
post-incident forensics unreliable." should be split into two separate
lines/sentences: one stating that logs lived under `/tmp/` and were writable,
and a second stating the consequence that an agent could delete/truncate/rewrite
its audit trail making forensics unreliable; update the document text containing
that exact sentence fragment so each sentence appears on its own line.
- Around line 28-32: Rewrite each bullet under the security audit-logging
section so every list item is a single active-voice sentence: split the current
multi-sentence lines for "Log isolation", "Append-only enforcement", and "Hash
chaining" into one clear active sentence per line, convert passive constructions
to active (e.g., "The directory is owned by root:sandbox" -> "root:sandbox owns
the directory" or "We set chattr +a on audit.jsonl" for the append-only note),
and keep key identifiers ("/var/log/nemoclaw/", "audit.jsonl", "chattr +a",
"SHA-256", "prev_hash") intact so the meaning and technical details remain
unchanged.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: c35e55bf-6b4e-46f9-aaf2-dbc73792765b
📒 Files selected for processing (5)
Dockerfiledocs/security/audit-logging.mdnemoclaw-blueprint/orchestrator/audit.pynemoclaw-blueprint/policies/openclaw-sandbox.yamlscripts/nemoclaw-start.sh
✅ Files skipped from review due to trivial changes (1)
- Dockerfile
🚧 Files skipped from review as they are similar to previous changes (2)
- nemoclaw-blueprint/policies/openclaw-sandbox.yaml
- scripts/nemoclaw-start.sh
There was a problem hiding this comment.
Actionable comments posted: 4
♻️ Duplicate comments (2)
docs/security/audit-logging.md (1)
1-14:⚠️ Potential issue | 🟠 MajorComplete required frontmatter fields and place SPDX after frontmatter.
This new page is still missing required frontmatter keys (
topics,tags,content type,difficulty,audience,status), and the SPDX header is before frontmatter instead of after it.As per coding guidelines, "Frontmatter includes title, description, keywords, topics, tags, content type, difficulty, audience, and status fields." and "SPDX license header is present after frontmatter."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/security/audit-logging.md` around lines 1 - 14, Add the missing required frontmatter keys to the top YAML block: include topics, tags, content type, difficulty, audience, and status alongside the existing title, description, and keywords; populate each with appropriate values. Move the SPDX license header so it appears immediately after the closing --- of the frontmatter (i.e., remove the current SPDX comment before the frontmatter and place it after the frontmatter block). Ensure the frontmatter remains valid YAML and that the SPDX header is a separate comment block following it.nemoclaw-blueprint/orchestrator/audit.py (1)
64-79:⚠️ Potential issue | 🔴 CriticalSerialize read→hash→write under one
LOCK_EXto prevent chain forks.Line 64 reads the previous hash before the exclusive lock is acquired on Line 76. Two concurrent writers can therefore use the same
prev_hashand append divergent successors.🔒 Suggested fix (atomic read+append under one lock)
def append_event(log_file: str, event: dict, prev_hash: str | None = None) -> str: @@ - if prev_hash is None: - prev_hash = get_last_hash(log_file) - record = { - "timestamp": time.time(), - "prev_hash": prev_hash, - "event": event, - } - payload = json.dumps(record, separators=(",", ":"), sort_keys=True) - entry_hash = _hash_payload(payload) - record["hash"] = entry_hash - - with open(log_file, "a") as f: + with open(log_file, "a+") as f: fcntl.flock(f.fileno(), fcntl.LOCK_EX) + if prev_hash is None: + f.seek(0) + prev_hash = "genesis" + for line in f: + line = line.strip() + if not line: + continue + try: + rec = json.loads(line) + except json.JSONDecodeError: + continue + h = rec.get("hash") + if h: + prev_hash = h + f.seek(0, os.SEEK_END) + + record = { + "timestamp": time.time(), + "prev_hash": prev_hash, + "event": event, + } + payload = json.dumps(record, separators=(",", ":"), sort_keys=True) + entry_hash = _hash_payload(payload) + record["hash"] = entry_hash f.write(json.dumps(record, separators=(",", ":"), sort_keys=True) + "\n") f.flush() fcntl.flock(f.fileno(), fcntl.LOCK_UN) return entry_hash#!/bin/bash # Verify current lock scope/order in append_event rg -n -A30 -B6 'def append_event|if prev_hash is None|get_last_hash|flock' nemoclaw-blueprint/orchestrator/audit.py🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@nemoclaw-blueprint/orchestrator/audit.py` around lines 64 - 79, The append_event flow reads prev_hash via get_last_hash before acquiring the exclusive file lock, allowing concurrent writers to base entries on the same prev_hash; change append_event to acquire fcntl.flock(..., fcntl.LOCK_EX) on the log file first, then call get_last_hash (or re-read the last line) while holding the lock, compute the payload and entry_hash using _hash_payload, set record["hash"], and finally write and flush the JSON line and release the lock—i.e., serialize the read→hash→write sequence under one LOCK_EX using the existing log_file, fcntl.flock and _hash_payload symbols.
🧹 Nitpick comments (1)
docs/security/audit-logging.md (1)
28-33: Remove bold styling from routine list labels (LLM pattern detected).Bold emphasis is being used for regular prose labels (for example, list item leads), which the docs style guide disallows.
As per coding guidelines, "Unnecessary bold on routine instructions ... Bold is reserved for UI labels, parameter names, and genuine warnings."
Also applies to: 59-60
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/security/audit-logging.md` around lines 28 - 33, The list item lead labels ("Log isolation", "Append-only enforcement", "Hash chaining") are improperly bolded; edit the markdown to remove the surrounding ** markers so the labels are plain text (e.g., change "**Log isolation** —" to "Log isolation —"), and apply the same change to any other routine list labels in this document flagged by the reviewer (the other items referenced) so bold is only used for UI labels, parameter names, or genuine warnings.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@docs/security/audit-logging.md`:
- Around line 57-60: Add a new "Next Steps" section at the bottom of the
document after the "Future work" heading; create a short paragraph and a
bulleted list of related links (e.g., link to the SIEM integration guide,
Landlock/kernel compatibility matrix page, and the audit event schema docs) so
readers can navigate to those follow-ups—ensure the heading reads "Next Steps"
and include 2–4 relevant internal links with clear labels.
- Around line 22-30: The documentation currently has multiple sentences on the
same source line in the Solution section (notably the "Log isolation" and
"Append-only enforcement" bullets and the preceding paragraph referencing
/tmp/), which harms diff readability; edit docs/security/audit-logging.md to
place each sentence on its own line so each bullet point and each descriptive
sentence (e.g., mentions of /tmp/, /var/log/nemoclaw/, root:sandbox, mode 750,
sandbox policy marking /var/log read-only, audit.jsonl, and chattr +a) is a
separate source line, preserving existing wording and bullet structure.
In `@scripts/nemoclaw-start.sh`:
- Around line 216-218: The current fallback sets GATEWAY_LOG to /tmp/gateway.log
when /var/log/... is not writable, which reintroduces tamperable logs; change
the logic around GATEWAY_LOG creation so that if the intended directory
(/var/log/nemoclaw) is not writable you emit a clear, hard error to stderr and
exit non‑zero when running in hardened mode (e.g., controlled by an environment
flag like NEMOCLAW_HARDENED or similar), otherwise print an explicit security
warning to stderr (do not silently use /tmp); keep the chmod 600 step for the
chosen secure path and only proceed when GATEWAY_LOG points to a
non‑world‑writable location.
- Around line 279-283: The startup currently suppresses errors writing the
initial audit event, so change the PYTHONPATH python3 invocation that calls
orchestrator.audit.append_event (the gateway_start event using GATEWAY_PID) to
fail fast: run the command without redirecting stderr to /dev/null, capture its
exit status, and if it fails, print a clear error to stderr and exit with a
non‑zero code to stop further startup; ensure you still reference append_event
and the gateway_start payload with GATEWAY_PID so the script cannot continue
unless the audit write succeeds.
---
Duplicate comments:
In `@docs/security/audit-logging.md`:
- Around line 1-14: Add the missing required frontmatter keys to the top YAML
block: include topics, tags, content type, difficulty, audience, and status
alongside the existing title, description, and keywords; populate each with
appropriate values. Move the SPDX license header so it appears immediately after
the closing --- of the frontmatter (i.e., remove the current SPDX comment before
the frontmatter and place it after the frontmatter block). Ensure the
frontmatter remains valid YAML and that the SPDX header is a separate comment
block following it.
In `@nemoclaw-blueprint/orchestrator/audit.py`:
- Around line 64-79: The append_event flow reads prev_hash via get_last_hash
before acquiring the exclusive file lock, allowing concurrent writers to base
entries on the same prev_hash; change append_event to acquire fcntl.flock(...,
fcntl.LOCK_EX) on the log file first, then call get_last_hash (or re-read the
last line) while holding the lock, compute the payload and entry_hash using
_hash_payload, set record["hash"], and finally write and flush the JSON line and
release the lock—i.e., serialize the read→hash→write sequence under one LOCK_EX
using the existing log_file, fcntl.flock and _hash_payload symbols.
---
Nitpick comments:
In `@docs/security/audit-logging.md`:
- Around line 28-33: The list item lead labels ("Log isolation", "Append-only
enforcement", "Hash chaining") are improperly bolded; edit the markdown to
remove the surrounding ** markers so the labels are plain text (e.g., change
"**Log isolation** —" to "Log isolation —"), and apply the same change to any
other routine list labels in this document flagged by the reviewer (the other
items referenced) so bold is only used for UI labels, parameter names, or
genuine warnings.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: eda2ddf6-96b4-4e40-9f5d-28c6b932c8bf
📒 Files selected for processing (6)
Dockerfiledocs/security/audit-logging.mdnemoclaw-blueprint/orchestrator/__init__.pynemoclaw-blueprint/orchestrator/audit.pynemoclaw-blueprint/policies/openclaw-sandbox.yamlscripts/nemoclaw-start.sh
✅ Files skipped from review due to trivial changes (2)
- nemoclaw-blueprint/orchestrator/init.py
- Dockerfile
🚧 Files skipped from review as they are similar to previous changes (1)
- nemoclaw-blueprint/policies/openclaw-sandbox.yaml
a03841d to
82ff889
Compare
|
@cv Rebased onto latest main and addressed the remaining CodeRabbit feedback:
All Copilot threads (module path, redundant glob, chattr best-effort, hash chaining) were addressed in earlier commits. Clean diff: 6 files, +289/-7. Would appreciate a CI trigger — first-time contributor. Thanks! |
|
✨ Thanks for submitting this PR with a detailed summary, it proposes a new security feature to improve audit logging and prevent tampering. |
82ff889 to
8734c41
Compare
|
Rebased onto latest main (squashed 10 commits → 1 clean commit with Signed-off-by and conventional commit format). Branch is up to date and conflict-free. |
ericksoa
left a comment
There was a problem hiding this comment.
E2E results: all 4 jobs fail at sandbox creation because tool_policy is not a valid field in the OpenShell policy schema. OpenShell expects only version, filesystem_policy, landlock, process, and network_policies.
The good news: the tool_policy block is unnecessary. The existing policy already has /var/log as read_only (line 27 of openclaw-sandbox.yaml), enforced by Landlock at the kernel level. And chattr requires CAP_LINUX_IMMUTABLE which the sandbox user doesn't have. So both protection layers the tool_policy was trying to add are already covered.
To unblock: remove the tool_policy block (lines 219–235) from nemoclaw-blueprint/policies/openclaw-sandbox.yaml. The rest of the PR (log isolation to /var/log/nemoclaw/, hash chaining, verify CLI, start script changes) stands on its own.
|
Awesome! This is in my queue to review. This is super important to us! |
5ec493e to
33f6053
Compare
|
Rebased on latest main. Also removed the Regarding #892 — that PR adds a |
|
Reviewing. |
Automated PR review summaryReviewed PR #916: security: tamper-evident audit logging with append-only enforcement Recommendation
Installation and setup findings
What was validated
Failing tests and unresolved impactFailing test 1: Advertised verification CLI is not runnable in the installed sandbox
Passing tests and why they matteredPassing test 1: In-sandbox direct rewrite/truncate of audit log is denied
Passing test 2: Hash chain accepts normal appends and detects post-write tampering
|
|
@BenediktSchackenberg I think this change is basically ready, but we're having some trouble with the verification tool (please see my above automated analysis comment). Let me know if we're invoking this tool incorrectly. |
|
Thanks for the thorough review @brandonpelfrey — good to hear the append-only enforcement and hash-chain logic both passed. On the verification CLI failure: The PYTHONPATH=/opt/nemoclaw-blueprint python3 -m orchestrator.audit verify /var/log/nemoclaw/audit.jsonlIf you tried SSH-ing in from outside with a custom PYTHONPATH, the path might not map correctly into the container. Can you confirm whether the command was run from inside the sandbox (e.g. after If the path does resolve to something different in the built image, I can add a smoke test to the integration suite that runs the verifier inside a built sandbox and fails if |
Companion to NVIDIA#916's Python audit logger. Provides the TypeScript plugin with read-side APIs for the tamper-evident audit chain: - verifyChain: validate hash integrity and prev_hash linkage - exportEntries: query entries by timestamp with optional limit - tailEntries: return the last N entries Uses canonical JSON serialization (sorted keys, compact separators) to match Python's json.dumps(sort_keys=True) for cross-language hash verification. 30 tests covering chain validation, tamper detection (modified data, broken links, deleted entries, spliced chains), query APIs, and cross-format verification against the Python entry format.
Adds a structured audit logger to the NemoClaw orchestrator with hash-chaining and append-only enforcement via chattr +a: - New nemoclaw-blueprint/orchestrator/audit.py: * SHA-256 hash-chaining between log entries (tamper-evident) * append-only mode via chattr +a (falls back gracefully if unavailable) * Logs to /var/log/nemoclaw/ with /tmp fallback + warning * File locking (fcntl.LOCK_EX) to prevent race conditions on write * Fail-fast: gateway stops (exit 1) if initial audit write fails * Tool policy deny rules block log tampering via shell commands - Dockerfile: creates /var/log/nemoclaw with correct ownership - scripts/nemoclaw-start.sh: emits gateway_start/gateway_stop events - docs/security/audit-logging.md: security documentation - policies/openclaw-sandbox.yaml: deny rules for log tamper vectors Signed-off-by: Benedikt Schackenberg <[email protected]>
- Apply shfmt formatting to nemoclaw-start.sh - Remove tool_policy block from openclaw-sandbox.yaml (unsupported by OpenShell serde deny_unknown_fields — same fix as in PR NVIDIA#654) Replaced with comment explaining the actual enforcement path Signed-off-by: Benedikt Schackenberg <[email protected]>
Signed-off-by: Benedikt Schackenberg <[email protected]>
ec506f2 to
3f15a12
Compare
|
Thanks for the thoughtful PR, @BenediktSchackenberg. We reviewed this alongside #799 and discussed the implementation direction as a team. The work here was useful in exploring the tradeoffs around log relocation, append-only enforcement, and tamper-evident hash chaining. That said, we’ve decided not to merge this implementation. Making sandbox-local logs agent-proof introduces a lot of Docker/filesystem/startup-policy complexity, and it still leaves us relying on local sandbox state as a security boundary. We’re shifting the solution direction to telemetry instead, so the authoritative security/audit signal comes from a path outside the agent’s write surface. I’m going to close this PR to keep the queue accurate. We appreciate the effort and the concrete exploration here; it gave us good data for the decision. |
Follow-up to #654 (sandbox config hardening). This addresses #799 by making the audit trail tamper-evident and agent-proof.
What changed:
Tamper-evident audit logger — New
audit.pymodule with SHA-256 hash chaining. Each log entry includes a cryptographic link to the previous entry, making modifications detectable.Log isolation — Gateway and audit logs moved from
/tmp/(agent-writable) to/var/log/nemoclaw/(read-only filesystem zone). The audit file is created as append-only (chattr +a) by root before the sandbox user starts.Tool policy deny list —
write/editon/var/log/**andexecon log-tampering commands (chattr,truncate) are blocked in the sandbox policy. Belt-and-suspenders with the filesystem permissions.Verification CLI —
python3 -m nemoclaw_blueprint.orchestrator.audit verify <file>validates the full hash chain and reports any breaks.Intentionally NOT done (future work):
Fixes #799
Summary by CodeRabbit
New Features
Documentation
Chores