Skip to content

feat(audit): record every request outcome to stderr, JSONL and syslog (#65) - #76

Merged
cuihtlauac merged 2 commits into
mainfrom
feat/audit-log
Nov 20, 2026
Merged

cuihtlauac merged 2 commits into
mainfrom
feat/audit-log

Conversation

@cuihtlauac

@cuihtlauac cuihtlauac commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Closes #65 (threat-model B1, "Repudiation").

Problem

The daemon logged prompted requests and unattended runs, mostly only with -v, without timestamps, and to stderr only. Replayed ids, stale or malformed time, validation failures (control/bidi characters, disallowed env, invalid plan), human denials and prompt timeouts left no record.

Change

New src/audit.rs. Every connection outcome produces exactly one record:

  • Fields: RFC 3339 time, outcome, peer_uid, id, session, host, privileged, command (only for requests that passed validation), detail (the error sent to the client), status and exit_codes (for requests that ran).
  • Outcomes: approved, approved_session, unattended, pkexec, denied, timeout, ping, stop, prompt_error, rejected:<reason> (peer_uid, peer_cred, busy, handshake_timeout, read_error, invalid_json, invalid_request, forward_agent, time, env, duplicate_id, invalid_plan).
  • Sinks:
    • stderr, always, independent of -v.
    • JSONL file, on by default: $XDG_STATE_HOME/sudo-proxy/audit.jsonl, else ~/.local/state/.... Mode 0600 in a 0700 dir, O_APPEND, one write_all per line. --audit-log PATH / --no-audit-log.
    • syslog, on by default: LOG_AUTHPRIV via libc (no new crate), constant "%s" format. --no-syslog.
  • Escaping: in every sink (stderr, file, syslog), request-derived strings are clipped to 256 chars and control/bidi/zero-width characters are written as \u{…}, so the file is safe to cat/tail -f.
  • Ordering: each record is written before the reply, so the log never lags what a client was told.
  • Never recorded: env values, reason, raw bytes of an invalid request. Event has no field for them.
  • Fail loud: the daemon refuses to start if the audit file cannot be opened.

In src/server.rs, every early return goes through one reject helper that writes the response and the record. The old unconditional [id] [unattended] line and the peer-UID line are folded into the audit line.

Residual

The file belongs to the daemon's UID, which is also the requester's UID, so it is append-only by convention only. The syslog copy is the record the requester cannot alter. Documented in docs/threat-model.md and docs/usage.md.

Tests

  • tests/audit.rs (11 cases): one per outcome, plus checks that a secret in env, reason or malformed JSON never reaches the file, one-record-per-line with a newline-bearing field, and file/dir modes.
  • tests/concurrency.rs: the busy test also checks 3 rejected:busy and 4 denied records.
  • tests/pty_e2e.rs: the real binary writes the default file under HOME.
  • Harnesses write the audit file to their temp dir and disable syslog.

cargo clippy --all-targets is clean, both builds compile (default and --no-default-features), and cargo test passes.

Manual end-to-end check (docs/testing.md) done against a live daemon: approve, deny (privileged), prompt timeout, replayed id, stale and missing time, bidi session, LD_PRELOAD env, and malformed JSON were each recorded correctly in the file and in journalctl -t sudo-proxy. The rejections were logged while a prompt was pending, the secret value never appeared, and the file was mode 0600. That run found the three issues fixed in the second commit: raw bidi characters in the file, the stale_time name for a missing time, and reply-before-record ordering.

🤖 Generated with Claude Code

cuihtlauac added a commit that referenced this pull request Nov 18, 2026
…reply

Found in a live manual run of #76:

- The JSONL file stored request strings raw. JSON leaves bidi overrides and
  C1 controls unescaped, so `cat`/`tail` on the file could reorder or
  restyle the terminal. File fields now get the same \u{...} escapes as the
  stderr and syslog lines.
- A missing or malformed `time` was reported as rejected:stale_time. The
  reason is now rejected:time, covering every freshness failure.
- Rejections, ping, stop and busy replied before writing their record, so a
  client could see the reply before the log line existed (two tests raced on
  it). Every path now records first, then replies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Cuihtlauac ALVARADO <cuihtlauac@tarides.com>
@cuihtlauac

Copy link
Copy Markdown
Member Author

🤖 Automated review generated with Claude Code.

Review: PR #76 — feat(audit): record every request outcome to stderr, JSONL and syslog (#65)

Summary. The PR does what it says: every connection outcome now funnels through one reject helper or the final record, the Event type structurally cannot carry env values or reason, request-derived strings are clipped and escaped in all three sinks, the file is 0600/O_APPEND with one write_all per line, syslog uses a constant "%s" format, and records are written before the reply (which is also what makes the tests race-free). cargo check --no-default-features --tests passes on the head commit, and the new busy/denied counts in the concurrency test are deterministic given the assertions already in that test. The design is sound; the findings below are about what the record misses, not about anything it leaks to a terminal. The one worth fixing before merge is the first: for a control whose purpose is non-repudiation, the human's decision should be durable before the privileged action runs.

Findings

1. High — the approval decision is only recorded after the command has finished running (src/server.rs:816-914)
audit.record(&ev.with_response(&resp)) runs after exec_sudo/exec_direct/exec_pkexec return. If the daemon dies while the child runs, nothing records that a human approved it (or that an unattended run started). The commands most likely to take the daemon down are exactly the ones you'd want on record: poweroff -f, systemctl kexec, echo b > /proc/sysrq-trigger, loginctl terminate-user, systemctl restart user@…, or simply a same-UID kill -9 of the daemon (the agent is same-UID) mid-exec. exec_timeout() can also be long, so the window is not small. Scenario: agent requests a plausible privileged command, human presses y, command kills the user session, log shows no approval, no run. Suggested fix: write a decision record (approved / approved_session / unattended / pkexec, with command) before calling exec_*, then a second completed record with status/exit_codes (or fold the result into a separate outcome). TestServer::audit_for would then expect two records for requests that ran; everything else stays as is.

2. Medium — rejected:invalid_json detail can carry request content, contradicting the "raw bytes never recorded" claim (src/server.rs:670; docs/usage.md:174)
format!("invalid JSON: {e}") uses serde_json's Display, and serde's type/value errors embed the offending value: {"env":"TOKEN=hunter2"} yields invalid type: string "TOKEN=hunter2", expected a map at line 1 column 23; {"privileged":"yes"} yields the string too; an unknown enum variant in action/op echoes the variant name. It is clipped to 256 chars and escaped, so it is bounded, but the PR description, docs/usage.md, and the module doc all state the opposite, and invalid_json_is_recorded_without_raw_bytes only exercises a syntax error ({not json hunter2), which happens to have no payload in its message. Fix: log only the classification and position — e.g. format!("invalid JSON ({:?}) at {}:{}", e.classify(), e.line(), e.column()) — while still sending the full serde message to the client; add a test with {"env":"hunter2"} (and one with {"id":"hunter2","privileged":"x"}) asserting the file never contains hunter2.

3. Medium — command is clipped to 256 chars even for validated, approved requests (src/audit.rs:32, :246)
The 256-char cap is justified for unvalidated id/session/host (1 MiB probes), but it is applied to command too, which is only ever set after validation and is bounded by MAX_PLAN_NODES. A long sh -c '…', a multi-step plan, or a command with a long argument list is recorded as its first 256 chars plus …; the part that actually did the damage may be the part that's cut, so the record cannot establish what was approved. Fix: a separate, much larger cap for command (a few KiB), or additionally record plan_sha256 over the canonical plan JSON so a truncated record can be matched to the full request held elsewhere (e.g. the MCP side's log).

4. Medium — --host mode silently ignores the new flags, and the remote daemon cannot be configured (src/bin/sudo-proxy.rs:46, :364; docs/usage.md:160)
run_remote is called before audit_config and execs ssh HOST sudo-proxy with no arguments, so sudo-proxy --host X --no-syslog or --audit-log P parses fine and does nothing. This matters because the PR also makes the daemon refuse to start if the audit file cannot be opened: a remote account with a read-only, NFS, or missing $HOME/.local/state (or no HOME at all) now fails to start, and there is no way to pass --no-audit-log to it. Fix: forward the three flags onto the remote command line (path shell-quoted), or reject them in --host mode the way --forward-agent is rejected in local mode, and say in docs/usage.md how the remote log is configured.

5. Low — after the first file-write failure the file sink is dead for the daemon's lifetime, silently (src/audit.rs:256)
write_failed latches on the first error (ENOSPC, EIO, a quota hit) and all later failures are suppressed; the daemon keeps gating and approving with no persistent record and one stderr line from possibly hours earlier. The PR's "fail loud" only applies at startup. Suggest: do not latch forever (reset the flag on the next successful write, or re-report every N failures), and consider whether a persistent write failure should make the daemon refuse further prompts, the same way a failed open refuses to start.

6. Low — open_append follows symlinks and chmods whatever it reaches (src/audit.rs:277-291)
OpenOptions::append().create() without O_NOFOLLOW, then set_permissions(0o600) unconditionally. With --audit-log /tmp/x and a pre-planted symlink, the daemon appends to and chmods 0600 whatever the link targets that its UID can open; fs.protected_symlinks only covers sticky world-writable dirs. The default path is in a 0700 dir so this is only reachable via an operator-chosen path, and the threat model is already same-UID, so this is defence-in-depth: add .custom_flags(libc::O_NOFOLLOW) and only chmod a file you created (a pre-existing 0640 for a log-reader group is currently clobbered without a message).

Minor notes

  • safe is not injective: a literal \u{a} in id and an escaped newline produce the same record text, so an investigator cannot tell them apart. Escaping \ as \\ fixes it (escape_for_terminal in server.rs has the same property).
  • DirBuilder::recursive(true).mode(0o700) applies 0700 to every ancestor it creates, so a fresh account gets a 0700 ~/.local as well as ~/.local/state. Harmless, but surprising; create the leaf with 0700 and the ancestors with the default mode.
  • duplicate_id records have no command because ev.command is set at server.rs:795, after the replay check. The replayed command is the interesting part of a replay record; if tui::command_summary is total on a ValidatedRequest (it only lays out the plan), set it right after validate.
  • ev.outcome.unwrap_or(Outcome::PromptError) (audit.rs:229) turns a future "forgot to set outcome" bug into a misleading prompt_error record; a debug_assert! plus an explicit "unknown" label would be more honest.
  • pkexec is recorded as one outcome whether the polkit dialog was approved or cancelled; status/detail partly disambiguate. Worth a line in docs/usage.md.
  • The file is opened once and never reopened; rename-style logrotate leaves the daemon writing to the rotated inode. Document copytruncate or reopen on SIGHUP.
  • Tests: stale_and_missing_time_are_recorded (tests/audit.rs:113) only asserts starts_with("rejected:") for the missing-time case — tighten it to rejected:time, which is precisely what the second commit's rename was for. There is no coverage for stop, prompt_error, forward_agent, peer_uid, handshake_timeout, or read_error, and syslog: true is never exercised anywhere (the harness and the pty daemon both pass --no-syslog), so openlog/syslog ran only in the manual check. One #[ignore]d or env-gated unit test that opens with syslog: true and records once would catch a libc signature change.
  • Busy rejections now do three synchronous writes (stderr, file, syslog) in the accept thread per rejected connection. Same-UID only, so no new DoS surface, but it is extra work on the path that exists to shed load.
  • changelog.md / docs/usage.md: command records argv verbatim, so secrets passed as arguments (curl -u user:pass, mysql -p…) land in the 0600 file and in syslog. Inherent to an audit log, but worth stating next to "env values are never recorded".

cuihtlauac and others added 2 commits November 20, 2026 08:48
…#65)

The daemon logged prompted requests and unattended runs only, mostly behind
-v and without timestamps. Replayed ids, stale or malformed `time`, validation
failures, denials and timeouts left no trace (threat-model B1, Repudiation).

New src/audit.rs: each connection outcome yields one record (RFC 3339 time,
peer UID, id, session, host, outcome, and the command for validated
requests). Sinks: stderr (always), an append-only 0600 JSONL file at
$XDG_STATE_HOME/sudo-proxy/audit.jsonl (default on; --audit-log PATH,
--no-audit-log), and syslog LOG_AUTHPRIV (default on; --no-syslog). Env
values, `reason` and raw invalid request bytes are never recorded. The
daemon refuses to start if the audit file cannot be opened.

Closes #65.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Cuihtlauac ALVARADO <cuihtlauac@tarides.com>
…reply

Found in a live manual run of #76:

- The JSONL file stored request strings raw. JSON leaves bidi overrides and
  C1 controls unescaped, so `cat`/`tail` on the file could reorder or
  restyle the terminal. File fields now get the same \u{...} escapes as the
  stderr and syslog lines.
- A missing or malformed `time` was reported as rejected:stale_time. The
  reason is now rejected:time, covering every freshness failure.
- Rejections, ping, stop and busy replied before writing their record, so a
  client could see the reply before the log line existed (two tests raced on
  it). Every path now records first, then replies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Cuihtlauac ALVARADO <cuihtlauac@tarides.com>
@cuihtlauac
cuihtlauac merged commit ebdb0be into main Nov 20, 2026
17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Security logging: rejections and denials are not logged, no timestamps, no persistent sink

1 participant