Cosmos Vulnerability Scanner
Trail of BitsOfficialPublished by Trail of Bits
- Skill
- Workflow
- Security
- CC-BY-SA-4.0
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
The Cosmos Vulnerability Scanner is an automated security auditing tool designed for Cosmos SDK-based blockchains. It performs a multi-phase analysis of custom modules and smart contracts to identify vulnerabilities that could lead to chain halts, state divergence, or loss of funds. The skill orchestrates parallel scanning agents that evaluate code against specific patterns related to core SDK logic, IBC integrations, EVM compatibility, and CosmWasm contracts. It emphasizes consensus-critical execution paths, ensuring that findings are relevant to the blockchain's stability and security.
What it does
- Generates a technical inventory and threat model via a discovery phase.
- Spawns parallel scanning agents to analyze code against predefined vulnerability patterns.
- Filters findings to focus exclusively on consensus-critical execution paths.
- Supports specialized scanning for IBC, EVM, and CosmWasm components.
- Writes detailed vulnerability reports as individual markdown files.
- Verifies that all required security patterns have been assessed.
When to use it
- Auditing custom Cosmos SDK modules.
- Reviewing CosmWasm smart contracts for security flaws.
- Conducting pre-launch security assessments for Cosmos-based chains.
- Investigating potential causes of chain halt incidents.
Advantages
- Reduces manual audit time through parallelized scanning.
- Focuses on high-impact consensus-critical bugs.
- Provides structured, actionable findings for remediation.
- Adapts to specific Cosmos SDK version requirements.
Usage examples
- “Run a security scan on the current directory.”
- The agent performs a discovery phase, identifies the platform and SDK version, executes parallel scans, and generates a report in the .bughunt_cosmos/ directory.
- “Audit my custom x/ modules and save findings to /tmp/audit_results.”
- The agent scans the codebase for consensus-critical vulnerabilities and outputs individual markdown files containing findings to the specified directory.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/trailofbits/cosmos-vulnerability-scanner/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip cosmos-vulnerability-scanner.zip -d .agents/skills
Documentation by Trail of Bits
Cosmos Vulnerability Scanner
Purpose
Scan Cosmos SDK modules and CosmWasm contracts for vulnerabilities that cause chain halts, consensus failures, or fund loss. Spawns parallel scanning agents — each specializing in a vulnerability category — that return findings to the main skill, which then writes them as individual markdown files to an output directory.
Output directory: defaults to .bughunt_cosmos/. If the user specifies a different directory in their prompt, use that instead.
When to Use
Auditing Cosmos SDK modules (custom
x/modules)Reviewing CosmWasm smart contracts
Pre-launch security assessment of Cosmos chains
Investigating chain halt incidents
When NOT to Use
Pure Solidity/EVM audits without Cosmos SDK — use Solidity-specific tools
CometBFT consensus engine internals — this covers SDK modules, not the consensus layer itself
General Go code review with no blockchain context
Cosmos SDK application logic that is not consensus-critical (e.g., CLI commands, REST endpoints)
CosmWasm contract-only audits on chains without custom SDK modules — use the CosmWasm checklist items alone
Essential Principles
Consensus path is king — A bug only matters for chain halt/fund loss if it's on the consensus-critical execution path (BeginBlock, EndBlock, FinalizeBlock, msg_server handlers, AnteHandler). Always verify a finding is reachable from consensus before reporting it.
State divergence = chain halt — Any non-determinism that causes validators to compute different state roots will halt the chain. This is the highest-severity class because it affects all validators simultaneously.
Check the version — Cosmos SDK has breaking changes across major versions (v0.47 removed GetSigners, v0.50 added ABCI 2.0, v0.53 deprecated ValidateBasic). Always check
go.modversions before applying patterns.False positives waste audit time — A map iteration in a CLI command is not a consensus bug. A panic in a query handler does not halt the chain. Verify the execution context before flagging.
Cross-module interactions are where bugs hide — The most severe findings (IBC reentrancy, EVM/Cosmos state desync, authz escalation) involve interactions between modules, not bugs within a single module.
Scanning Workflow
Phase 1: Discovery (synchronous)
Entry: Target codebase path provided by user. Codebase contains Go source (e.g., x/ modules, go.mod) or Rust contracts with cosmwasm_std.
Run a synchronous subagent (Agent tool) with the full contents of DISCOVERY.md as its prompt. The agent must:
Follow the Discovery workflow to explore the target codebase
Return the full CLAUDE.md content (the technical inventory and threat model) in its response
Return a structured summary with exactly these fields:
PLATFORM: pure-cosmos | evm | wasm (pick one; if multiple, comma-separated)
IBC_ENABLED: true | false
SDK_VERSION: <version from go.mod>
IBC_GO_VERSION: <version from go.mod, or "n/a">
CUSTOM_MODULES: <comma-separated list of x/* modules>After the subagent returns, you (the main skill) Write the CLAUDE.md to the target repo root. Save its path and the discovery values — these feed into Phase 2.
Exit: CLAUDE.md written by main skill. PLATFORM, IBC_ENABLED, SDK_VERSION, IBC_GO_VERSION, and CUSTOM_MODULES captured.
Phase 2: Parallel Vulnerability Scan
Spawn scanning agents in a single message for maximum parallelism. Use the Agent Prompt Template below, filling in the reference file for each agent. Subagents only need read access (Grep, Glob, Read) — they return findings in their response and the main skill writes the files.
Always spawn these 3 agents:
| Agent Name | Reference File | Scope |
|---|---|---|
core-scanner | VULNERABILITY_PATTERNS.md | §1-9: non-determinism, ABCI, signers, validation, handlers, ante security |
state-scanner | STATE_VULNERABILITY_PATTERNS.md | §11-23: bookkeeping, bank, pagination, events, tx replay, governance, arithmetic, encoding, deprecated modules |
advanced-scanner | ADVANCED_VULNERABILITY_PATTERNS.md | §24-27: storage keys, consensus validation, circuit breaker, crypto |
Spawn conditionally (in the same parallel message):
| Agent Name | Condition | Reference File |
|---|---|---|
evm-scanner | PLATFORM includes evm | EVM_VULNERABILITY_PATTERNS.md |
ibc-scanner | IBC_ENABLED is true | IBC_VULNERABILITY_PATTERNS.md |
cosmwasm-scanner | PLATFORM includes wasm | COSMWASM_VULNERABILITY_PATTERNS.md |
Agent Prompt Template
Construct each agent's prompt by replacing {REFERENCE_FILE_PATH} with the full path to the reference file (under {baseDir}/resources/) and {CLAUDE_MD_PATH} with the path to the CLAUDE.md written in Phase 1:
Perform a very thorough security scan of a Cosmos SDK codebase for specific vulnerability patterns.
CONTEXT:
Read {CLAUDE_MD_PATH} for codebase context (SDK version, modules, threat model, key files).
PATTERNS:
Read {REFERENCE_FILE_PATH} — it contains numbered vulnerability patterns. For EACH pattern:
1. Read the detection patterns and "What to Check" items
2. Use Grep and Glob to search the target codebase for each pattern
3. When a match is found, Read surrounding code to verify it's on a consensus-critical path (BeginBlock, EndBlock, FinalizeBlock, msg_server handlers, AnteHandler)
4. Classify severity per the guidelines below
RULES:
- Consensus path only: Only flag code reachable from consensus-critical execution. CLI/query/test code is NOT a finding.
- Check SDK version in go.mod before applying patterns (v0.47 removed GetSigners, v0.50 added ABCI 2.0, v0.53 deprecated ValidateBasic).
- Always use the Grep tool for searches, not bash grep. The reference file contains search patterns — use them directly with the Grep tool.
- Ignore cross-references to other resource files (e.g., links to IBC or COSMWASM patterns). Those patterns are covered by other scanning agents.
- Reject these rationalizations:
- "ValidateBasic catches this" — deprecated and facultative since SDK v0.53
- "Behind governance, so safe" — governance proposals can be malicious
- "IBC counterparty is trusted" — any chain can open a channel
- "Panic can't happen, input is validated" — trace the full call chain
- "Rounding error is only a few tokens" — compounds over time, can be looped
- "EVM precompile handles rollback" — many have incomplete rollback
SEVERITY:
- Critical (fund loss): signer mismatch, broken bookkeeping, AnteHandler bypass, bank keeper misuse, IBC token inflation, EVM/Cosmos desync, Merkle proof forgery, arithmetic overflow
- High (chain halt): non-determinism, ABCI panics, slow ABCI, non-deterministic IBC acks, consensus gaps, CacheContext event leak
- Medium (DoS): unbounded pagination, tx replay, missing validation, governance spam, rate limiting, circuit breaker bypass, storage key collisions
- Low (logic): rounding errors, stub handlers, event override, module ordering
OUTPUT — RETURN FORMAT:
Do NOT write any files. Return ALL findings and the summary in your response.
For each pattern, return one of:
§NUM PATTERN_NAME: Not applicable — [one-line reason]
§NUM PATTERN_NAME: FINDING (followed by the finding block below)
For each finding, include the full content using this template:
FINDING_FILE: {SEVERITY}-s{SECTION_NUM}-{kebab-description}.md
## [SEVERITY] Title
**Location**: `file:line`
**Description**: What the bug is and why it matters
**Vulnerable Code**: [snippet]
**Attack Scenario**: [numbered steps]
**Recommendation**: How to fix
**References**: [links to relevant advisories or building-secure-contracts]
You MUST report on ALL patterns in the reference file — do not skip any.Exit: All scanning agents returned. Each reported on every pattern in their reference file.
Phase 3: Write Findings
After all scanning agents return, write finding files to the output directory (default .bughunt_cosmos/):
Parse each agent's response for
FINDING_FILE:blocksFor each finding, Write the content to
{OUTPUT_DIR}/{filename}using the filename fromFINDING_FILE:Create the output directory first if it doesn't exist
Phase 4: Verify Completeness
After writing all findings, verify every pattern was assessed:
Collect the summary lines (§NUM entries) returned by each agent
Check pattern counts against expected totals:
core-scanner: 8 patterns (§1-9, excluding §8 legacy-only)state-scanner: 13 patterns (§11-23)advanced-scanner: 4 patterns (§24-27)evm-scanner(if spawned): 10 patterns (§1-10)ibc-scanner(if spawned): 16 patterns (§1-16)cosmwasm-scanner(if spawned): 3 patterns (§1-3)
If any pattern is missing from a summary, flag it and re-prompt that agent
List all finding files written to the output directory with a
Globfor*.md
Exit: All patterns accounted for. Finding files listed for the user.
Success Criteria
[ ] Discovery CLAUDE.md written with complete technical inventory and threat model
[ ] All scanning agents completed and reported on every pattern in their reference file
[ ] Pattern counts verified against expected totals (no patterns skipped)
[ ] All findings written to output directory as individual markdown files
[ ] Each finding file includes: severity, location, vulnerable code, attack scenario, recommendation
Resources
Discovery & CLAUDE.md: DISCOVERY.md
Core patterns (§1-9): VULNERABILITY_PATTERNS.md
State & module patterns (§11-23): STATE_VULNERABILITY_PATTERNS.md
Advanced patterns (§24-27): ADVANCED_VULNERABILITY_PATTERNS.md
IBC vulnerabilities: IBC_VULNERABILITY_PATTERNS.md
CosmWasm vulnerabilities: COSMWASM_VULNERABILITY_PATTERNS.md
EVM vulnerabilities: EVM_VULNERABILITY_PATTERNS.md
Building Secure Contracts:
building-secure-contracts/not-so-smart-contracts/cosmos/Cosmos SDK Docs: https://docs.cosmos.network/
CodeQL for Cosmos SDK: https://github.com/crypto-com/cosmos-sdk-codeql
Files
- ATTRIBUTION.mdAdded by AutoGineer975 B
- CHANGELOG.md12.6 KiB
- LICENSELicence file added by AutoGineer19.7 KiB
- SKILL.md10.7 KiB
- agents/openai.yaml256 B
- assets/trail-of-bits-mark.svg3.0 KiB
- resources/ADVANCED_VULNERABILITY_PATTERNS.md12.5 KiB
- resources/COSMWASM_VULNERABILITY_PATTERNS.md7.5 KiB
- resources/DISCOVERY.md2.9 KiB
- resources/EVM_VULNERABILITY_PATTERNS.md18.0 KiB
- resources/IBC_VULNERABILITY_PATTERNS.md27.5 KiB
- resources/STATE_VULNERABILITY_PATTERNS.md29.2 KiB
- resources/VULNERABILITY_PATTERNS.md26.4 KiB
resources/COSMWASM_VULNERABILITY_PATTERNS.md
CosmWasm Vulnerability Patterns & Audit Checks
Vulnerability patterns specific to CosmWasm smart contracts (Rust contracts on
wasmd). Referenced by SKILL.md.
1 WRAPPING OVERFLOW IN UINT256/512 ARITHMETIC
Description: CosmWasm's Uint256, Uint512, Int256, and Int512 types used wrapping (modular) math for pow() and neg() instead of panicking on overflow. This means arithmetic silently wraps around on overflow, producing incorrect results. Token swap calculations, LP share pricing, and any exponentiation-based math become manipulable. Uint128 and Uint64 are NOT affected (they already used checked math).
Affected versions: cosmwasm-std < 1.4.4, < 1.5.4, < 2.0.2
Detection Patterns:
// VULNERABLE: Uint256/512 pow used wrapping math (CWA-2024-002)
let price = Uint256::from(base_price).pow(exponent);
// If result overflows 256 bits, it wraps silently instead of panicking
// Token swap calculations yield incorrect amounts
// LP share pricing becomes manipulable
// VULNERABLE: Int256/512 neg() wraps on MIN value
let negated = Int256::MIN.neg();
// Wraps to Int256::MIN instead of panicking (two's complement)What to Check:
[ ]
cosmwasm-stdversion is patched (>= 1.4.4, >= 1.5.4, >= 2.0.2)[ ] Any
Uint256::pow(),Uint512::pow(),Int256::pow(),Int512::pow()usage reviewed for overflow possibility[ ]
Int256::neg()/Int512::neg()not called onMINvalues[ ] Contracts using large-number exponentiation for pricing, interest rates, or AMM curves are audited for wrapping behavior on older
cosmwasm-std
Mitigation:
// SECURE: Use patched cosmwasm-std (>= 2.0.2) where pow() panics on overflow
// OR: Use checked_pow() if available, or manually validate bounds before exponentiation
let max_safe = Uint256::from(2u128).pow(128); // Know your bounds
assert!(base_price < max_safe, "overflow risk");
let price = Uint256::from(base_price).pow(exponent);References:
2 NON-DETERMINISTIC QUERIES FROM COSMWASM CONTRACTS
Description: CosmWasm contracts can call Cosmos SDK queries via Stargate queries. Queries annotated with cosmos.query.v1.module_query_safe are callable from within contracts during execution. If such a query is non-deterministic (returns different results on different validators for the same block height) or consumes variable gas, it causes consensus failures. This is especially dangerous because the query runs inside contract execution which is on the consensus path.
Detection Patterns:
// VULNERABLE: Query marked as module_query_safe but produces non-deterministic results
// In proto definition:
// option (cosmos.query.v1.module_query_safe) = true;
//
// But the query handler iterates a map, uses floating point, or returns
// results that vary by node (e.g., local mempool state, peer info)
func (q queryServer) UnsafeQuery(ctx context.Context, req *types.QueryRequest) (*types.QueryResponse, error) {
// Non-deterministic: map iteration order
results := make(map[string]string)
for k, v := range results { // Different order per validator!
// ...
}
return &types.QueryResponse{Data: serialize(results)}, nil
}// CosmWasm contract calling a Stargate query during execution
let response: QueryResponse = deps.querier.query(&QueryRequest::Stargate {
path: "/custom.module.v1.Query/UnsafeQuery".to_string(),
data: request.encode_to_vec().into(),
})?;
// If UnsafeQuery is non-deterministic, this contract execution
// produces different state on different validators → chain haltWhat to Check:
[ ] ALL queries annotated with
cosmos.query.v1.module_query_safeare deterministic[ ] Module-query-safe queries always consume the same gas for the same input (variable gas consumption causes consensus failure)
[ ] No map iteration, floating point, system time, or other non-deterministic operations in module-query-safe query handlers
[ ] Stargate query allowlist reviewed — only deterministic queries are permitted
References:
3 IBC REENTRANCY VIA COSMWASM SUBMESSAGES
Description: CosmWasm's submessage mechanism (SubMsg) amplifies the IBC reentrancy / CEI violation described in IBC_VULNERABILITY_PATTERNS.md §16. When ibc-hooks middleware invokes a CosmWasm contract on an IBC callback (e.g., OnTimeoutPacket), the contract can re-enter via submessages before the original callback's state changes are finalized. See IBC §16 for the full Go-side vulnerability, affected versions, detection patterns, and checklist.
This section covers the CosmWasm-specific attack surface: how Rust contracts exploit the underlying IBC CEI violation.
Vulnerable chain requirements: ALL of these must be true:
IBC-enabled with vulnerable ibc-go version (see IBC §16 for versions)
CosmWasm-enabled with permissionless contract uploads
ibc-hooksmiddleware wrapping ICS-20 transfer
CosmWasm Exploit Pattern:
// CosmWasm contract exploiting IBC reentrancy via submessages
#[entry_point]
pub fn sudo(deps: DepsMut, env: Env, msg: SudoMsg) -> Result<Response, ContractError> {
match msg {
// Called by ibc-hooks on IBC packet timeout
SudoMsg::IBCLifecycleComplete { .. } => {
// Re-enter by dispatching another timeout via submessage
let msg = CosmosMsg::Stargate {
type_url: "/ibc.core.channel.v1.MsgTimeout".to_string(),
value: craft_timeout_msg(), // Same packet, same sequence
};
Ok(Response::new().add_submessage(SubMsg::new(msg)))
// Submessage executes before parent's state changes are finalized
// Double-refund: tokens refunded twice for the same timed-out packet
}
}
}CosmWasm-Specific Checks (in addition to IBC §16 checklist):
[ ]
ibc-hooksmiddleware usage reviewed — this is the bridge between IBC callbacks and CosmWasm execution[ ] If CosmWasm uploads are permissionless, the attack surface is maximal — consider permissioned uploads or code review requirements
Grep Patterns (use Grep tool with glob: "*.go"):
ibc-hooks|ibchooksinx/andapp/— hooks middleware presenceInstantiateDefaultPermission|StoreCodeAuthorizationinx/andapp/— upload permissions
References: See IBC_VULNERABILITY_PATTERNS.md §16 for full references.
SUMMARY
| # | Pattern | Impact | Known Incident / Reference |
|---|---|---|---|
| 1 | Wrapping overflow in Uint256/512 | Fund manipulation (pricing, LP shares) | CWA-2024-002 |
| 2 | Non-deterministic queries from CosmWasm | Chain halt (consensus failure) | CWA-2024-006 |
| 3 | IBC reentrancy via CosmWasm submessages | Fund theft ($150M+ at risk, $6.4M stolen) | ASA-2024-007, Terra exploit |
References
CosmWasm Security Advisories: https://github.com/CosmWasm/advisories
ibc-go Security Advisories: https://github.com/cosmos/ibc-go/security/advisories
Asymmetric Research: "Cosmos IBC Reentrancy Infinite Mint" — https://blog.asymmetric.re/cosmos-ibc-reentrancy-infinite-mint/
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- Trail of Bits
- Publisher
- Trail of Bits (Official)
- Source
- trailofbits/skills · plugins/building-secure-contracts/skills/cosmos-vulnerability-scanner · commit e4dd0bb
- Licence
- Creative Commons Attribution-ShareAlike 4.0 International (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Trail of Bits or Trail of Bits.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download cosmos-vulnerability-scanner.zip