Skip to content

fix(security): SSRF, output caps, sandbox hardening + audit r1 leftovers - #113

Merged
yogthos merged 1 commit into
mainfrom
fix/audit-r2-security
May 21, 2026
Merged

fix(security): SSRF, output caps, sandbox hardening + audit r1 leftovers#113
yogthos merged 1 commit into
mainfrom
fix/audit-r2-security

Conversation

@yogthos

@yogthos yogthos commented May 21, 2026

Copy link
Copy Markdown
Collaborator

Round 2 audit: 11 new findings verified, 7 fixed this PR. Includes: webfetch SSRF blocking (169.254.x cloud metadata + RFC1918 + loopback + link-local IPv4/IPv6), webfetch body OOM (10 MiB streaming cap), MCP result size cap (256 KiB), bash output cap (256 KiB — was hitting LLM context with millions of tokens), sandbox --new-session + --unshare-user-try, sanitize_output strips \r, task subagent timeout (10 min), /prompt default help text. 2 new tests. 727 plugin / 601 default pass. 4 false positives confirmed (sandbox --ro-bind, /dev/tty, etc.).

…1 leftovers

Verified the 11 new round-2 findings and 6 round-1 leftovers
against the actual code. Shipping the 7 concrete fixes that map
to clear before/after behavior; the rest are deferred-architectural
or already-fixed-elsewhere.

## N1 — webfetch SSRF (CRITICAL)

`http://169.254.169.254/latest/meta-data/` (AWS metadata) and
all private/loopback ranges sailed straight through. An LLM that
gets prompt-injected into fetching a private IP could exfiltrate
IAM credentials, hit internal admin endpoints, or scrape internal
network maps.

New `validate_url_host_safety()` blocks:
- Hostname literal "localhost" / "ip6-localhost" /
  "ip6-loopback"
- IPv4 loopback (127/8), private (10/8, 172.16/12, 192.168/16),
  link-local (169.254/16 — cloud metadata), unspecified,
  broadcast, class E.
- IPv6 loopback, ULA (fc00::/7), link-local (fe80::/10),
  multicast, unspecified. Bracketed IPv6 (`[::1]`) is parsed
  correctly.

Opt-in escape hatch: `DIRGE_WEBFETCH_ALLOW_PRIVATE=1` for
dev workflows that need to hit localhost. Tool description
documents the env var so the agent can see it.

## N8 — webfetch body OOM (HIGH)

`resp.text().await` buffered the entire response into memory
before any truncation. A 500 MB page would OOM the agent
process. Now streams via `bytes_stream` with a 10 MiB cap;
bails at the cap.

## N2 — MCP result size cap (CRITICAL)

`McpTool::call` concatenated every `RawContent::Text` block
into `content` without limit. A 200 KB MCP response flooded
every subsequent turn until compaction. Cap aggregate at 256
KiB (≈65k tokens worst case); UTF-8 char-boundary slice;
append a clear truncation marker naming the offending
server::tool so the agent can adjust its calls.

## N3 — bash output cap (CRITICAL)

The UI's `render_tool_output` truncated the DISPLAY but the
full string was persisted to `ToolCallState::Completed` and
fed back to the LLM on the next turn. `cat /dev/urandom | head
-c 10M` would have shoved millions of tokens. Cap at 256 KiB
at the bash tool source, with a clear truncation message
pointing the agent at head/grep filtering.

## N5 — sandbox hardening (HIGH)

Added `--new-session` (drops the ability to gain new privs via
setuid) and `--unshare-user-try` (explicit user-ns isolation,
defensive against future bwrap default changes). `--unshare-all`
already covers most of this; the explicit flags pin the
guarantees.

## N7 — sanitize_output strips \\r (HIGH)

Previously `\\r` was preserved (originally for CRLF lines). A
bash tool printing progress with `\\rstep N/M` would move the
cursor to column 0 mid-line, overwriting chamber borders. Now
stripped (`\\n` and `\\t` still pass; display path
normalizes CRLF before reaching here).

## H10 — task subagent timeout

`tokio::spawn(btw_query(...))` with no timeout meant a stuck
provider would keep the task in `Running` forever. Cap at 10
minutes; on timeout, the task transitions to `Failed` with a
clear message and the system-reminder still fires.

## M22 — /prompt default help text

Behavior was fixed in PR #111 (activates `default.md` if
installed). Help text still said "clear active prompt". Now
explains both cases.

## Verified false positives / non-issues this round

- **N4 sandbox --ro-bind / /**: by design — the sandbox is a
  WRITE guard, not exfiltration prevention. Defense for read
  access requires `--ro-bind` per path (much narrower scope
  + breaks read-only tooling like bash `ls`). Document as
  feature, not bug.
- **N6 sandbox current_dir fallback**: `unwrap_or_else(|_|
  ".".into())` is the standard fallback; `current_dir()`
  failing means cwd is deleted/inaccessible which is its own
  fatal-soon problem.
- **N9 token estimation len/4**: Phase 6 work; per-provider
  usage extraction needs distinct fix.
- **N10 sandbox /dev/tty**: `--dev /dev` mounts a tmpfs with
  only essential nodes, not the full host /dev. /dev/tty IS
  available to the sandboxed process so it can write to its
  own controlling terminal (needed for bash interactive
  features); not the host's /dev/tty0.
- **H17 DeepSeek auto-detect order**: confirmed false positive
  in earlier rounds — only fires when env var present.
- **H18 load_file path in error**: already fixed in PR #112.
- **M19 semantic tools in BUILTIN_TOOL_NAMES**: semantic tools
  added separately, can't be shadowed by MCP collision.

## Tests

2 new regression tests:
- `validate_url_host_safety_blocks_ssrf_targets`: pins
  169.254.x, 127.x, RFC 1918, ::1, fc00::, fe80:: as refused;
  public IPs + domains pass; bracketed IPv6 parses correctly.
- `validate_url_host_safety_handles_malformed_hosts`: garbage
  hosts don't panic.

727 plugin / 601 default pass.

## Deferred to architectural follow-ups

- H8 LSP no crash restart — broken-pipe handling design
- N4 sandbox --ro-bind / — fundamental design tradeoff
- N9 token estimation — per-provider usage extraction
@yogthos
yogthos merged commit 84d9196 into main May 21, 2026
1 check passed
@yogthos
yogthos deleted the fix/audit-r2-security branch May 21, 2026 18:08
allen-munsch pushed a commit to allen-munsch/dirge that referenced this pull request Jun 3, 2026
…1 leftovers (dirge-code#113)

Verified the 11 new round-2 findings and 6 round-1 leftovers
against the actual code. Shipping the 7 concrete fixes that map
to clear before/after behavior; the rest are deferred-architectural
or already-fixed-elsewhere.

## N1 — webfetch SSRF (CRITICAL)

`http://169.254.169.254/latest/meta-data/` (AWS metadata) and
all private/loopback ranges sailed straight through. An LLM that
gets prompt-injected into fetching a private IP could exfiltrate
IAM credentials, hit internal admin endpoints, or scrape internal
network maps.

New `validate_url_host_safety()` blocks:
- Hostname literal "localhost" / "ip6-localhost" /
  "ip6-loopback"
- IPv4 loopback (127/8), private (10/8, 172.16/12, 192.168/16),
  link-local (169.254/16 — cloud metadata), unspecified,
  broadcast, class E.
- IPv6 loopback, ULA (fc00::/7), link-local (fe80::/10),
  multicast, unspecified. Bracketed IPv6 (`[::1]`) is parsed
  correctly.

Opt-in escape hatch: `DIRGE_WEBFETCH_ALLOW_PRIVATE=1` for
dev workflows that need to hit localhost. Tool description
documents the env var so the agent can see it.

## N8 — webfetch body OOM (HIGH)

`resp.text().await` buffered the entire response into memory
before any truncation. A 500 MB page would OOM the agent
process. Now streams via `bytes_stream` with a 10 MiB cap;
bails at the cap.

## N2 — MCP result size cap (CRITICAL)

`McpTool::call` concatenated every `RawContent::Text` block
into `content` without limit. A 200 KB MCP response flooded
every subsequent turn until compaction. Cap aggregate at 256
KiB (≈65k tokens worst case); UTF-8 char-boundary slice;
append a clear truncation marker naming the offending
server::tool so the agent can adjust its calls.

## N3 — bash output cap (CRITICAL)

The UI's `render_tool_output` truncated the DISPLAY but the
full string was persisted to `ToolCallState::Completed` and
fed back to the LLM on the next turn. `cat /dev/urandom | head
-c 10M` would have shoved millions of tokens. Cap at 256 KiB
at the bash tool source, with a clear truncation message
pointing the agent at head/grep filtering.

## N5 — sandbox hardening (HIGH)

Added `--new-session` (drops the ability to gain new privs via
setuid) and `--unshare-user-try` (explicit user-ns isolation,
defensive against future bwrap default changes). `--unshare-all`
already covers most of this; the explicit flags pin the
guarantees.

## N7 — sanitize_output strips \\r (HIGH)

Previously `\\r` was preserved (originally for CRLF lines). A
bash tool printing progress with `\\rstep N/M` would move the
cursor to column 0 mid-line, overwriting chamber borders. Now
stripped (`\\n` and `\\t` still pass; display path
normalizes CRLF before reaching here).

## H10 — task subagent timeout

`tokio::spawn(btw_query(...))` with no timeout meant a stuck
provider would keep the task in `Running` forever. Cap at 10
minutes; on timeout, the task transitions to `Failed` with a
clear message and the system-reminder still fires.

## M22 — /prompt default help text

Behavior was fixed in PR dirge-code#111 (activates `default.md` if
installed). Help text still said "clear active prompt". Now
explains both cases.

## Verified false positives / non-issues this round

- **N4 sandbox --ro-bind / /**: by design — the sandbox is a
  WRITE guard, not exfiltration prevention. Defense for read
  access requires `--ro-bind` per path (much narrower scope
  + breaks read-only tooling like bash `ls`). Document as
  feature, not bug.
- **N6 sandbox current_dir fallback**: `unwrap_or_else(|_|
  ".".into())` is the standard fallback; `current_dir()`
  failing means cwd is deleted/inaccessible which is its own
  fatal-soon problem.
- **N9 token estimation len/4**: Phase 6 work; per-provider
  usage extraction needs distinct fix.
- **N10 sandbox /dev/tty**: `--dev /dev` mounts a tmpfs with
  only essential nodes, not the full host /dev. /dev/tty IS
  available to the sandboxed process so it can write to its
  own controlling terminal (needed for bash interactive
  features); not the host's /dev/tty0.
- **H17 DeepSeek auto-detect order**: confirmed false positive
  in earlier rounds — only fires when env var present.
- **H18 load_file path in error**: already fixed in PR dirge-code#112.
- **M19 semantic tools in BUILTIN_TOOL_NAMES**: semantic tools
  added separately, can't be shadowed by MCP collision.

## Tests

2 new regression tests:
- `validate_url_host_safety_blocks_ssrf_targets`: pins
  169.254.x, 127.x, RFC 1918, ::1, fc00::, fe80:: as refused;
  public IPs + domains pass; bracketed IPv6 parses correctly.
- `validate_url_host_safety_handles_malformed_hosts`: garbage
  hosts don't panic.

727 plugin / 601 default pass.

## Deferred to architectural follow-ups

- H8 LSP no crash restart — broken-pipe handling design
- N4 sandbox --ro-bind / — fundamental design tradeoff
- N9 token estimation — per-provider usage extraction

Co-authored-by: Yogthos <yogthos@gmail.com>
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.

1 participant