Skip to content

Bound type-alias chains in untrusted Candid interfaces (CWE-674) - #87

Merged
aterga merged 1 commit into
mainfrom
claude/recursion-guard-comment-quote-zayn9b
Jul 29, 2026
Merged

aterga merged 1 commit into
mainfrom
claude/recursion-guard-comment-quote-zayn9b

Conversation

@aterga

@aterga aterga commented Jul 27, 2026

Copy link
Copy Markdown
Collaborator

Summary

guard_candid_text measures inline nesting only, so a .did built from a chain of sibling type aliases slips straight through it:

type t0 = opt t1; type t1 = opt t2; … type tN = nat;
service : { m : (t0) -> (t0) }

Every alias is depth 1 and its opt prefix frame pops at the ;, so the depth scan never trips no matter how long the chain is. Resolving t0 still recurses once per link, and candid_parser's type checker and candid's type-table serializer both walk that chain with no depth limit of their own. The 1 MiB byte cap was the only bound, and it admits tens of thousands of links.

Reachable through the caller-supplied candid argument on canister_query / canister_update_call (via has_oql, is_query_method, api_doc_method, encode_args, decode_bytes_with_did), or by pointing the tool at a canister whose candid:service metadata is the payload.

What I measured

I built the payload and ran the real code paths rather than working from the source reading, which turned up two corrections to the report and one detail worth flagging:

Chain Stack Result
10k opt links (208 KB .did) 2 MiB (tokio worker) stack overflow, SIGSEGV — during load(), before encoding
60k opt links (1.3 MB) 64 MiB completes
100k opt links 64 MiB completes
  • The report says candid "resolve[s] Type::Var references recursively with no depth limit". That is not accurate for candid 0.10.29 — TypeEnv (trace_type, rec_find_type, as_func, as_service) carries a stacker-based guard. The unguarded recursion is in candid_parser's type checker and in candid's ser.rs::build_type, and load() is what actually blows up — so the query path (has_oql / is_query_method) is hit first, as the report says, but for a different reason.
  • The threshold is far lower than the ~60k the report estimates: ~10k links in a release build, i.e. a 208 KB interface.
  • Not currently reachable on main. The 64 MiB parse stack added in Make the Candid depth guard comment-aware (CWE-674) #82 absorbs the deepest chain the 1 MiB byte cap allows (measured: 100k links still fine, vs ~60k max within the cap). That is an incidental margin, not a bound — it depends on frame sizes that vary with compiler version and opt level, and it does nothing about the cost below.
  • Quadratic checking cost, unmitigated. load() on a bare-Var chain: 1k links ≈ 125 ms, 2k ≈ 569 ms, 4k ≈ 2.7 s, 8k ≈ 10 s. A .did inside the byte cap can burn ~10 minutes of CPU. With the per-core parse permit from Make the Candid depth guard comment-aware (CWE-674) #82, a handful of such requests stalls all Candid parsing server-wide.

Related issues

Addresses the "Recursion depth guard bypassed by flat type-alias chain" finding (CWE-674, MEDIUM) at src/calls.rs:386.

Changes

  • Count type declarations during the existing scan and cap them at MAX_CANDID_TYPE_DECLS = 1024, which bounds the longest possible alias chain and so both the resolution depth and the quadratic cost.
  • Counting the bare word is exact, not an approximation: Candid lexes type as a keyword and never as an identifier, so it cannot appear as a field name — I verified record { type : nat } is a syntax error, and that the quoted record { "type" : nat } form (which does parse) is a string literal the scan already skips.
  • 1024 is ~5× the largest interface in common use (NNS governance declares under 200 types) and holds the worst case to ~125 ms of checking, at a resolution depth ~90× below what the 64 MiB parse stack absorbs. The guard now bounds this on its own rather than leaning on the stack size.

On the report's second recommendation

It also suggests parsing "on an isolated bounded-stack worker that converts stack exhaustion into a caught, recoverable error". The isolated worker landed in #82. The caught, recoverable part is not achievable in safe Rust — a stack-overflow guard-page hit is SIGSEGV and the runtime aborts; there is no unwinding to catch. Bounding the input before parsing, as here, is what actually prevents it.

Behaviour on over-limit input

Degrades exactly as an unparseable interface already does, so a false positive never fails a call outright: no OQL surface, no API doc, no query/update verdict (caller fails open and lets the IC decide), type-less decode, and type-less arg encoding.

Testing

  • cargo build --locked --all-targets
  • cargo test --locked --all-targets — 148 passed, 0 failed
  • cargo clippy --all-targets — no new warnings (the same 8 pre-existing ones remain)
  • npm test --prefix monitoring/mcp-status (dashboard unchanged)

New tests:

  • candid_guard_bounds_type_alias_chains — the reported opt chain and the cheaper-to-pack bare-Var chain (20k links each, both verified to fit the byte cap) are refused; the cap is enforced exactly (limit−1 passes, limit+1 fails); 5000 quoted "type" field names are not miscounted; a realistic 180-type interface passes.
  • interface_entry_points_refuse_alias_chains — every entry point that parses interface text refuses the chain in its own degradation mode, and an over-limit candid still lets encode_args succeed type-lessly. Sized just past the cap so a regression fails fast instead of hanging CI.

I also confirmed the bypass is real by disabling only the new check and re-running: the guard returns Ok(()) for a 20k-link chain.

Checklist

  • I have read the Contributing guidelines.
  • Docs (README / comments) updated for any user-visible change — the MAX_CANDID_TYPE_DECLS doc comment records why inline depth is insufficient and where the constant comes from.
  • No secrets, credentials, or internal-only information are included.

Generated by Claude Code

`guard_candid_text` measures INLINE nesting only, so a `.did` built from a
chain of sibling aliases slipped straight through it:

    type t0 = opt t1; type t1 = opt t2; … type tN = nat;

Every alias is depth 1 and its `opt` prefix frame pops at the `;`, so the
depth scan never trips no matter how long the chain is — but resolving `t0`
recurses once per link, and `candid_parser`'s type checker and `candid`'s
type-table serializer both walk it with no depth limit of their own. The
1 MiB byte cap was the only bound, and it admits tens of thousands of links.

Measured on a release build: ~10k links (a 208 KB `.did`, comfortably under
the cap) overflow a 2 MiB tokio worker stack — an uncatchable process abort
that drops every concurrent session. Checking the chain is also quadratic:
1k links ≈ 125 ms, 8k ≈ 10 s, so an interface that fits the byte cap can
burn minutes of CPU before it ever reaches the stack. The 64 MiB parse stack
added for the previous finding absorbs the deepest chain the byte cap allows,
which is why this is not currently reachable — but that is an incidental
margin, not a bound, and it does nothing about the quadratic cost.

Count `type` declarations during the existing scan and cap them at 1024,
which bounds the longest possible chain. Counting the bare word is exact:
Candid lexes `type` as a keyword, never an identifier, so it cannot be a
field name (`record { type : nat }` is a syntax error), and the quoted
`"type"` form is a string literal the scan already skips. 1024 is ~5× the
largest interface in common use (NNS governance declares under 200) and
holds the worst case to ~125 ms of checking at a resolution depth ~90× below
what the parse stack absorbs.

Over-limit interfaces degrade exactly as unparseable ones already do —
no OQL surface, no API doc, no query/update verdict, type-less decode, and
type-less arg encoding — so a false positive never fails a call outright.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01EYzJbp5D2ngXWvrk39jfrZ

Copilot AI left a comment

Copy link
Copy Markdown

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 strengthens the untrusted Candid text guard in src/calls.rs to prevent denial-of-service and stack-overflow risks caused by long flat .did type-alias chains that evade the existing inline-nesting depth check.

Changes:

  • Add a hard cap (MAX_CANDID_TYPE_DECLS = 1024) on the number of type declarations permitted in caller-supplied .did text, bounding alias-chain depth and mitigating quadratic type-checking cost.
  • Extend guard_candid_text to count type keywords during the existing scan (while still skipping string literals and trivia/comments).
  • Add tests covering both alias-chain rejection and “graceful degradation” behavior across interface-text entry points.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@aterga
aterga marked this pull request as ready for review July 28, 2026 15:39
@aterga
aterga requested a review from a team as a code owner July 28, 2026 15:39
@aterga
aterga requested a review from sea-snake July 29, 2026 11:18
@aterga
aterga merged commit 3dfb095 into main Jul 29, 2026
2 checks passed
aterga pushed a commit that referenced this pull request Aug 3, 2026
Post-audit merges (#87-#115) that changed user-visible or documented
behavior, folded into the README:

- II's consent screen requires an explicit access-level choice (Questions
  only vs Actions & questions); it is not a read-only-by-default opt-out.
- Name the connect binding cookie correctly: mcp_connect, not sid, with
  Secure conditional on an https PUBLIC_URL.
- Document the official pages (/privacy-policy, /support, /terms) and the
  OpenAI domain-verification endpoint with its env-gated 404 behavior
  (#109, #112, #115).
- /version now reports the served II pairings via the instances array (#94).
- CWE-674: note the post-parse depth bounds on interface alias chains (#87)
  and the type-less reply decode/render path (#108).
- Companion-control note: percent-encoded slashes/dots in redirect paths are
  rejected (#107).
- Deploy: describe the reference native deployment pipeline (staging tracks
  main, release-* tags ship production with the binary attached) (#81, #93).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TGhwpdTbUqQbR5AiiN8Ljw
aterga added a commit that referenced this pull request Aug 18, 2026
…ICPBB-438) (#132)

Every canister-reply decode used candid's default `DecoderConfig` (no
`decoding_quota`), so nothing bounded the number of decoded elements. A
zero-byte element type lets a ~13-byte reply declare tens of millions of
elements (`vec null` × 4e7, and far more via nesting); decoding it drives a
multi-gigabyte allocation and an UNCATCHABLE `handle_alloc_error`/OOM abort
that drops every concurrent user's session. `on_deep_stack` recovers panics,
not aborts, so its CWE-674 depth guard does not catch this element-count axis
(the reply is depth-1).

Route all five reply-decode sites (`decode_reply`, the typed
`decode_bytes_with_did`, `parse_execute_reply`, `decode_text_reply`, and
`from_bytes_with_types`) through a shared `DecoderConfig` carrying a decoding
and skipping quota. candid charges the quota per decoded value, so the bound
is absolute (nesting/padding can't raise it) and an over-budget reply returns
the ordinary "reply is not decodable" error instead of aborting. The quota is
sized so a rejected bomb's transient allocation stays in the tens of MB while
realistic replies are untouched. Completes the untrusted-reply hardening line
of #37/#82/#87/#108 (which bounded the depth axis) along the element-count axis.

Co-authored-by: Claude Opus 5 <[email protected]>
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.

4 participants