Repository navigation
Bound type-alias chains in untrusted Candid interfaces (CWE-674) - #87
Merged
Merged
Conversation
`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
There was a problem hiding this comment.
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 oftypedeclarations permitted in caller-supplied.didtext, bounding alias-chain depth and mitigating quadratic type-checking cost. - Extend
guard_candid_textto counttypekeywords 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.
sea-snake
approved these changes
Jul 29, 2026
7 of 8 tasks
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
guard_candid_textmeasures inline nesting only, so a.didbuilt from a chain of sibling type aliases slips straight through it:Every alias is depth 1 and its
optprefix frame pops at the;, so the depth scan never trips no matter how long the chain is. Resolvingt0still recurses once per link, andcandid_parser's type checker andcandid'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
candidargument oncanister_query/canister_update_call(viahas_oql,is_query_method,api_doc_method,encode_args,decode_bytes_with_did), or by pointing the tool at a canister whosecandid:servicemetadata 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:
optlinks (208 KB.did)load(), before encodingoptlinks (1.3 MB)optlinksType::Varreferences recursively with no depth limit". That is not accurate forcandid0.10.29 —TypeEnv(trace_type,rec_find_type,as_func,as_service) carries astacker-based guard. The unguarded recursion is incandid_parser's type checker and incandid'sser.rs::build_type, andload()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.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.load()on a bare-Varchain: 1k links ≈ 125 ms, 2k ≈ 569 ms, 4k ≈ 2.7 s, 8k ≈ 10 s. A.didinside 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
typedeclarations during the existing scan and cap them atMAX_CANDID_TYPE_DECLS = 1024, which bounds the longest possible alias chain and so both the resolution depth and the quadratic cost.typeas a keyword and never as an identifier, so it cannot appear as a field name — I verifiedrecord { type : nat }is a syntax error, and that the quotedrecord { "type" : nat }form (which does parse) is a string literal the scan already skips.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
SIGSEGVand 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-targetscargo test --locked --all-targets— 148 passed, 0 failedcargo 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 reportedoptchain and the cheaper-to-pack bare-Varchain (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-limitcandidstill letsencode_argssucceed 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
MAX_CANDID_TYPE_DECLSdoc comment records why inline depth is insufficient and where the constant comes from.Generated by Claude Code