Skip to content

security: tamper-evident audit logging with append-only enforcement - #916

Closed
BenediktSchackenberg wants to merge 3 commits into
NVIDIA:mainfrom
BenediktSchackenberg:fix/audit-log-hardening
Closed

BenediktSchackenberg wants to merge 3 commits into
NVIDIA:mainfrom
BenediktSchackenberg:fix/audit-log-hardening

Conversation

@BenediktSchackenberg

@BenediktSchackenberg BenediktSchackenberg commented Mar 25, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #654 (sandbox config hardening). This addresses #799 by making the audit trail tamper-evident and agent-proof.

What changed:

  1. Tamper-evident audit logger — New audit.py module with SHA-256 hash chaining. Each log entry includes a cryptographic link to the previous entry, making modifications detectable.

  2. 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.

  3. Tool policy deny list — write/edit on /var/log/** and exec on log-tampering commands (chattr, truncate) are blocked in the sandbox policy. Belt-and-suspenders with the filesystem permissions.

  4. 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

    • Tamper-evident audit logging with SHA-256 hash chaining, a verification CLI, and startup recording of gateway_start; gateway logs centralized under /var/log/nemoclaw with a fallback.
  • Documentation

    • Added an audit logging guide detailing protection layers, verification steps, and future hardening plans.
  • Chores

    • Image/build and startup now create and protect the audit log directory/files; build warns if append-only attribute cannot be set; sandbox policy blocks common tampering actions.

Copilot AI review requested due to automatic review settings March 25, 2026 20:34
@coderabbitai

coderabbitai Bot commented Mar 25, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • ✅ Review completed - (🔄 Check again to review again)
📝 Walkthrough

Walkthrough

Implements tamper‑evident audit logging: creates /var/log/nemoclaw and an append‑only audit.jsonl at image build, adds a SHA‑256 chained JSONL audit module with CLI verifier, updates startup to append a gateway_start event, and adds sandbox tool deny rules for audit tampering.

Changes

Cohort / File(s) Summary
Audit implementation
nemoclaw-blueprint/orchestrator/audit.py, nemoclaw-blueprint/orchestrator/__init__.py
New SHA‑256 hash‑chained JSONL audit module: init, read-last-hash, append_event (with fcntl lock), verify_chain, CLI verify; SPDX header added.
Image build
Dockerfile
At build time creates /var/log/nemoclaw, sets root:sandbox ownership and 0750 dir perms, creates audit.jsonl with 0620, installs e2fsprogs, and attempts chattr +a (prints warning if unsupported).
Startup script
scripts/nemoclaw-start.sh
Routes gateway logs to /var/log/nemoclaw/gateway.log (with fallback), adjusts ownership/perms, and appends a gateway_start audit event (warnings on failure).
Sandbox policy
nemoclaw-blueprint/policies/openclaw-sandbox.yaml
Adds tool_policy denying tool: write/tool: edit on /var/log/** and denying execution of chattr and truncate.
Documentation
docs/security/audit-logging.md
New doc describing isolated log path, append‑only enforcement (chattr +a), SHA‑256 chained JSONL format, CLI verification examples, and future work items.

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
Loading
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)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐇 I nibble logs and chain each line,

timestamps hop, the hashes shine,
Append‑only burrow, guarded tight,
Gateway start recorded right,
The rabbit keeps the audit fine.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title accurately summarizes the main change: adding tamper-evident audit logging with append-only enforcement, which is the core objective.
Linked Issues check ✅ Passed The PR fulfills all primary coding requirements from #799: separate log store at /var/log/nemoclaw, append-only enforcement via chattr +a, cryptographic SHA-256 hash chaining in audit.py, and verification CLI. Remote SIEM forwarding is documented as future work.
Out of Scope Changes check ✅ Passed All code changes directly support audit logging hardening: Dockerfile setup, audit.py implementation, policy enforcement, log relocation, and verification CLI. No unrelated changes detected.
Docstring Coverage ✅ Passed Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands and usage tips.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.py implementing SHA-256 hash chaining and a verify CLI.
  • Move gateway logs to /var/log/nemoclaw and 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.

Comment thread docs/security/audit-logging.md Outdated
Comment on lines +21 to +24
Run the built-in verification command against any audit log file:

```bash
python3 -m nemoclaw_blueprint.orchestrator.audit verify /var/log/nemoclaw/audit.jsonl

Copilot AI Mar 25, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed — updated the CLI invocation to PYTHONPATH=/opt/nemoclaw-blueprint python3 -m orchestrator.audit verify which matches the actual module path.

Comment on lines +213 to +219
paths:
- "/var/log/**"
- "/var/log/nemoclaw/**"
- tool: edit
paths:
- "/var/log/**"
- "/var/log/nemoclaw/**"

Copilot AI Mar 25, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/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.

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — removed the redundant /var/log/nemoclaw/** entries since /var/log/** already covers them.

Comment thread Dockerfile Outdated
Comment on lines +127 to +133
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

Copilot AI Mar 25, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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")

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread scripts/nemoclaw-start.sh Outdated
# 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')

Copilot AI Mar 25, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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)

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>")

Copilot AI Mar 25, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Suggested change
print(f"usage: python3 -m nemoclaw_blueprint.orchestrator.audit verify <file>")
print("usage: PYTHONPATH=/opt/nemoclaw-blueprint python3 -m orchestrator.audit verify <file>")

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated the usage string to PYTHONPATH=/opt/nemoclaw-blueprint python3 -m orchestrator.audit verify <file> — matches the actual invocation now.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 f prefix 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 f prefix 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

📥 Commits

Reviewing files that changed from the base of the PR and between 0d852d3 and 03d160c.

📒 Files selected for processing (6)
  • Dockerfile
  • docs/security/audit-logging.md
  • nemoclaw-blueprint/orchestrator/__init__.py
  • nemoclaw-blueprint/orchestrator/audit.py
  • nemoclaw-blueprint/policies/openclaw-sandbox.yaml
  • scripts/nemoclaw-start.sh

Comment thread docs/security/audit-logging.md Resolved
Comment thread docs/security/audit-logging.md Resolved
Comment thread docs/security/audit-logging.md Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.jsonl file has the... attribute set" → "The build process sets the chattr +a attribute on audit.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

📥 Commits

Reviewing files that changed from the base of the PR and between cc05531 and 6f6825f.

📒 Files selected for processing (2)
  • docs/security/audit-logging.md
  • nemoclaw-blueprint/orchestrator/audit.py

Comment thread docs/security/audit-logging.md Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
docs/security/audit-logging.md (1)

1-14: ⚠️ Potential issue | 🟡 Minor

SPDX 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 Logging

As 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

📥 Commits

Reviewing files that changed from the base of the PR and between 6f6825f and d365005.

📒 Files selected for processing (5)
  • Dockerfile
  • docs/security/audit-logging.md
  • nemoclaw-blueprint/orchestrator/audit.py
  • nemoclaw-blueprint/policies/openclaw-sandbox.yaml
  • scripts/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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

♻️ Duplicate comments (2)
docs/security/audit-logging.md (1)

1-14: ⚠️ Potential issue | 🟠 Major

Complete 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 | 🔴 Critical

Serialize read→hash→write under one LOCK_EX to 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_hash and 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

📥 Commits

Reviewing files that changed from the base of the PR and between d365005 and 68c407b.

📒 Files selected for processing (6)
  • Dockerfile
  • docs/security/audit-logging.md
  • nemoclaw-blueprint/orchestrator/__init__.py
  • nemoclaw-blueprint/orchestrator/audit.py
  • nemoclaw-blueprint/policies/openclaw-sandbox.yaml
  • scripts/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

Comment thread docs/security/audit-logging.md Resolved
Comment thread docs/security/audit-logging.md Resolved
Comment thread scripts/nemoclaw-start.sh Resolved
Comment thread scripts/nemoclaw-start.sh Resolved
@BenediktSchackenberg

Copy link
Copy Markdown
Contributor Author

@cv Rebased onto latest main and addressed the remaining CodeRabbit feedback:

  • Fail-fast on audit write failure — gateway now stops (exit 1) if the initial gateway_start audit event can't be written, instead of silently continuing without a compliance trail
  • /tmp log fallback warning — emits [SECURITY WARNING] when non-root mode falls back to sandbox-writable /tmp/gateway.log

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!

@wscurran

Copy link
Copy Markdown
Contributor

✨ Thanks for submitting this PR with a detailed summary, it proposes a new security feature to improve audit logging and prevent tampering.

@BenediktSchackenberg

Copy link
Copy Markdown
Contributor Author

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 ericksoa left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@brandonpelfrey

Copy link
Copy Markdown
Contributor

Awesome! This is in my queue to review. This is super important to us!

@BenediktSchackenberg

Copy link
Copy Markdown
Contributor Author

Rebased on latest main. Also removed the tool_policy block from openclaw-sandbox.yaml — same issue as found in #654: OpenShell's PolicyFile uses #[serde(deny_unknown_fields)] and rejects tool_policy at deserialization, causing sandbox startup failures. Replaced with a comment explaining the actual enforcement path (filesystem read-only + chattr at startup).

Regarding #892 — that PR adds a src/security/ TypeScript module for chain verification, while this PR adds the runtime enforcement (append-only chattr +a, startup checks, and Python orchestrator for log analysis). The two approaches are complementary: #892 handles the TS consumer side, this PR handles the OS-level write protection. Happy to coordinate.

@brandonpelfrey

Copy link
Copy Markdown
Contributor

Reviewing.

@brandonpelfrey

Copy link
Copy Markdown
Contributor

Automated PR review summary

Reviewed PR #916: security: tamper-evident audit logging with append-only enforcement

Recommendation

  • Recommendation: FAIL
  • Highest observed severity: high
  • Block merge: yes
  • Why: This PR’s security story depends not only on making tampering harder but also on being able to verify integrity after the fact. If the deployed verifier command is unusable, responders cannot validate the audit trail in the installed product, which is a high-severity gap for a feature whose headline claim is tamper-evident audit logging.
  • Reviewer summary: Reviewed PR security: tamper-evident audit logging with append-only enforcement #916 with sandbox-focused adversarial probes. The filesystem placement/permissions resisted direct in-sandbox tampering, and the new hash-chain verifier logic correctly accepted clean appends and detected post-write mutation in a targeted integration probe. However, the claimed verification CLI failed in the real installed sandbox (ModuleNotFoundError for orchestrator.audit), so operators cannot use the advertised integrity-check path as deployed.

Installation and setup findings

  • Nemoclaw installation succeeded from the local repository, onboarding created the my-assistant sandbox, and verification succeeded with both an SSH command inside that sandbox and a minimal in-sandbox OpenClaw response.

What was validated

  • The PR revision was checked out in an isolated review environment.
  • The local checkout was installed using the repository installer flow as closely as the environment allowed.
  • Adversarial, PR-specific probes were then run against the installed environment and relevant repository context.
  • Diff summary:
 .../skills/nemoclaw-contributor-create-pr/SKILL.md | 197 --------
 .agents/skills/nemoclaw-maintainer-triage/SKILL.md | 145 ------
 .agents/skills/nemoclaw-skills-guide/SKILL.md      |   9 +-
 .../skills/nemoclaw-user-manage-policy/SKILL.md    |   3 -
 .../nemoclaw-user-reference/references/commands.md |  62 +--
 .../references/network-policies.md                 |  28 +-
 .../references/troubleshooting.md                  |  18 +-
 .../nemoclaw-user-triage-instructions/SKILL.md     | 144 ------
 .github/PULL_REQUEST_TEMPLATE.md                   |  53 ++-
 .github/workflows/docs-links-pr.yaml               |   2 +-
 .github/workflows/docs-preview-deploy.yaml         |   6 +-
 .github/workflows/docs-preview-pr.yaml             |  12 +-
 .github/workflows/nightly-e2e.yaml                 |  91 +---
 .github/workflows/pr.yaml                          |   6 +-
 .github/workflows/sandbox-images-and-e2e.yaml      |   6 -
 Dockerfile                                         |  31 +-
 agents/hermes/manifest.yaml                        |   2 -
 agents/openclaw/manifest.yaml                      |   2 -
 docs/network-policy/customize-network-policy.md    |   3 -
 docs/reference/commands.md 
...[truncated]

Failing tests and unresolved impact

Failing test 1: Advertised verification CLI is not runnable in the installed sandbox

  • What was tested: The PR’s claimed verifier command is usable in the real installed environment so operators can validate /var/log/nemoclaw/audit.jsonl after deployment.
  • Why it matters: If false, the feature is only partially delivered: logs may be chained, but defenders cannot run the advertised integrity verification where they need it.
  • Observed result: End-to-end in OpenShell sandbox. Command failed with /usr/bin/python3: Error while finding module specification for 'orchestrator.audit' (ModuleNotFoundError: No module named 'orchestrator'). A separate in-sandbox importlib lookup also could not resolve orchestrator.audit.
  • Command: ssh -F /tmp/sshcfg openshell-my-assistant 'PYTHONPATH=/opt/nemoclaw-blueprint python3 -m orchestrator.audit verify /var/log/nemoclaw/audit.jsonl'
  • Recommended follow-up coverage: Add an install/deployment integration test that runs the documented verifier command inside a built sandbox image and fails unless the module path is importable and can verify the real audit log.

Passing tests and why they mattered

Passing test 1: In-sandbox direct rewrite/truncate of audit log is denied

  • What was tested: The sandbox user cannot directly overwrite or truncate /var/log/nemoclaw/audit.jsonl, so an agent cannot erase history through ordinary shell/file operations.
  • Why it mattered: If false, the PR’s core claim of append-only, agent-resistant audit storage is materially broken and an attacker in the sandbox can cover tracks.
  • Observed result: End-to-end in OpenShell sandbox. Both overwrite and truncate attempts returned Permission denied as uid 998. Observed file state: /var/log/nemoclaw/audit.jsonl owned by root:sandbox with mode 0620 under /var/log/nemoclaw.
  • Command: ssh -F /tmp/sshcfg openshell-my-assistant ': > /var/log/nemoclaw/audit.jsonl'; ssh -F /tmp/sshcfg openshell-my-assistant 'truncate -s 0 /var/log/nemoclaw/audit.jsonl'
  • Recommended follow-up coverage: Add an end-to-end sandbox regression test that attempts overwrite/truncate from inside the sandbox and asserts denial, since this is a runtime security property rather than a pure unit concern.

Passing test 2: Hash chain accepts normal appends and detects post-write tampering

  • What was tested: append_event() reads the prior hash correctly across appends and verify_chain() accepts intact logs while flagging modified entries.
  • Why it mattered: If false, either benign restarts/appends will look like tampering or real tampering will evade detection, undermining the whole audit-chain design.
  • Observed result: VM-host integration probe against PR code. Two appended events verified cleanly: (True, 2, ''). After mutating the first record, verify_chain() returned (False, 0, 'line 1: hash mismatch (tampering detected)').
  • Command: python3 /tmp repo-path probe importing orchestrator.audit and exercising append/verify on a temp file
  • Recommended follow-up coverage: Keep this as automated regression coverage at integration level: one test for multi-append continuity and one for tamper detection after modifying an earlier record.

@brandonpelfrey

Copy link
Copy Markdown
Contributor

@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.

@BenediktSchackenberg

Copy link
Copy Markdown
Contributor Author

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 orchestrator.audit module lives at /opt/nemoclaw-blueprint/orchestrator/audit.py inside the sandbox image (copied via COPY nemoclaw-blueprint/ /opt/nemoclaw-blueprint/ in the Dockerfile). The correct invocation from inside the sandbox should be:

PYTHONPATH=/opt/nemoclaw-blueprint python3 -m orchestrator.audit verify /var/log/nemoclaw/audit.jsonl

If 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 nemoclaw my-assistant connect) or from outside via SSH?

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 orchestrator.audit is not importable.

gemini2026 pushed a commit to gemini2026/NemoClaw that referenced this pull request Apr 16, 2026
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]>
@BenediktSchackenberg
BenediktSchackenberg force-pushed the fix/audit-log-hardening branch from ec506f2 to 3f15a12 Compare May 1, 2026 20:30
@copy-pr-bot

copy-pr-bot Bot commented May 1, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@wscurran wscurran added feature PR adds or expands user-visible functionality v0.0.58 and removed priority: high labels Jun 3, 2026
@wscurran
wscurran removed the request for review from brandonpelfrey June 3, 2026 16:14
@wscurran wscurran assigned wscurran and unassigned brandonpelfrey Jun 3, 2026
@wscurran

wscurran commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

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.

@wscurran wscurran closed this Jun 3, 2026
@wscurran wscurran removed the v0.0.58 label Jun 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature PR adds or expands user-visible functionality

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[SECURITY] Audit logs writable by sandbox user — agent can modify its own audit trail

5 participants