Generated banner for Cosmos Vulnerability Scanner
Generated logo for Cosmos Vulnerability Scanner

Cosmos Vulnerability Scanner

Trail of BitsOfficialPublished by Trail of Bits

  • Skill
  • Workflow
  • Security
  • CC-BY-SA-4.0
  • No issues found

From the author

Scans Cosmos SDK blockchain modules and CosmWasm contracts for consensus-critical vulnerabilities — chain halts, fund loss, state divergence. 25 core + 16 IBC + 10 EVM + 3 CosmWasm patterns. Use when auditing custom x/ modules, reviewing IBC integrations, or assessing pre-launch chain security. Updated for SDK v0.53.x.
— the description by Trail of Bits

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

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/trailofbits/cosmos-vulnerability-scanner/download
  2. Unzip 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

  1. 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.

  2. 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.

  3. 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.mod versions before applying patterns.

  4. 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.

  5. 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:

  1. Follow the Discovery workflow to explore the target codebase

  2. Return the full CLAUDE.md content (the technical inventory and threat model) in its response

  3. 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 NameReference FileScope
core-scannerVULNERABILITY_PATTERNS.md§1-9: non-determinism, ABCI, signers, validation, handlers, ante security
state-scannerSTATE_VULNERABILITY_PATTERNS.md§11-23: bookkeeping, bank, pagination, events, tx replay, governance, arithmetic, encoding, deprecated modules
advanced-scannerADVANCED_VULNERABILITY_PATTERNS.md§24-27: storage keys, consensus validation, circuit breaker, crypto

Spawn conditionally (in the same parallel message):

Agent NameConditionReference File
evm-scannerPLATFORM includes evmEVM_VULNERABILITY_PATTERNS.md
ibc-scannerIBC_ENABLED is trueIBC_VULNERABILITY_PATTERNS.md
cosmwasm-scannerPLATFORM includes wasmCOSMWASM_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/):

  1. Parse each agent's response for FINDING_FILE: blocks

  2. For each finding, Write the content to {OUTPUT_DIR}/{filename} using the filename from FINDING_FILE:

  3. Create the output directory first if it doesn't exist

Phase 4: Verify Completeness

After writing all findings, verify every pattern was assessed:

  1. Collect the summary lines (§NUM entries) returned by each agent

  2. 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)

  3. If any pattern is missing from a summary, flag it and re-prompt that agent

  4. List all finding files written to the output directory with a Glob for *.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

Files

resources/ADVANCED_VULNERABILITY_PATTERNS.md

Advanced Vulnerability Patterns

Updated for Cosmos SDK v0.53.x. Advanced infrastructure patterns (§24-27) covering storage key design, consensus validation gaps, circuit breaker authorization, and cryptographic verification. Referenced by SKILL.md checklist items via § anchors.

24 STORAGE KEY DESIGN FLAWS

Description: KV store key construction allows collisions, prefix overlaps, or unauthorized access to other users' data. Keys built via string concatenation without length-prefixed encoding create ambiguous boundaries. Numeric fields serialized as variable-length strings share byte prefixes. Prefix iterators over attacker-controllable components include unintended objects.

Detection Patterns:

Pattern 1: String Concatenation Collision
// VULNERABLE: String concatenation without length-prefix encoding (Finding 16)
func VaultUserKey(vaultID uint64, user string) []byte {
    return []byte(fmt.Sprintf("%d%s", vaultID, user))
}
// vaultId=1, user="2a" → key "12a"
// vaultId=12, user="a" → key "12a"  ← COLLISION!

// Even with separators, string fields containing the separator collide:
// vaultId=1, user="a|", position="b" → "1|a||b"
// vaultId=1, user="a", position="|b" → "1|a||b"  ← COLLISION!
Pattern 2: Prefix Iterator Malleability
// VULNERABLE: Pool IDs serialized as strings in KV store keys (Finding 31)
func PositionKey(poolID uint64, posID uint64) []byte {
    return []byte(fmt.Sprintf("position/%d/%d", poolID, posID))
}
// poolID=42 shares byte prefix [52 50] with poolID=421
// HasAnyAtPrefix("position/42") matches "position/421/..."
// Attacker creates positions with carefully chosen pool IDs
// that prefix-collide with victim positions

// VULNERABLE: Attacker can increment pool IDs by creating empty pools
store.Iterator(PositionPrefix(poolID), nil)  // Includes poolID * 10 + N
Pattern 3: Redelegation State Lookup Bypass
// VULNERABLE: Unbonding period bypass via redelegation (Finding 14)
// If a user redelegates to a validator outside the active set
// (e.g., bonded stake rank 102), then unbonds, the 21-day
// unbonding period is skipped — the state key lookup for the
// unbonding entry doesn't account for out-of-set validators.
// Attacker who steals tokens can instantly exit staking.

What to Check:

  • [ ] KV store keys use length-prefixed encoding (e.g., collections.PairKeyCodec, address.LengthPrefixedAddressKey) — NOT string concatenation

  • [ ] Prefix iterators cannot be confused by attacker-controllable numeric IDs (e.g., pool IDs serialized as fixed-width or length-prefixed)

  • [ ] String fields in composite keys cannot contain the separator character

  • [ ] HasAnyAtPrefix / Iterator with user-influenced prefix components verified to not match unintended keys

  • [ ] Redelegation to out-of-set validators followed by unbonding is tested against unbonding period enforcement

Mitigation:

// SECURE: Use length-prefixed encoding
func VaultUserKey(vaultID uint64, user string) []byte {
    key := make([]byte, 8+1+len(user))
    binary.BigEndian.PutUint64(key[:8], vaultID)  // Fixed-width
    key[8] = byte(len(user))                       // Length prefix
    copy(key[9:], user)
    return key
}

// SECURE: Use cosmossdk.io/collections key codecs
var PositionsMap = collections.NewMap(
    sb, PositionsPrefix,
    collections.PairKeyCodec(collections.Uint64Key, collections.Uint64Key),
    codec.CollValue[Position](cdc),
)

References:


25 CONSENSUS VALIDATION GAPS

Description: Missing or incomplete validation at the consensus protocol layer — vote extensions, block timestamp manipulation, and account type checks at creation time. These allow Byzantine validators or front-running attackers to manipulate consensus-level data that downstream modules trust implicitly.

Detection Patterns:

Pattern 1: Vote Extension Forgery
// VULNERABLE: PrepareProposal validates signatures but skips
// VerifyVoteExtension rules (Finding 15, SEDA Chain)
func (h *Handler) PrepareProposal(ctx sdk.Context, req *abci.PrepareProposalRequest) (*abci.PrepareProposalResponse, error) {
    for _, vote := range req.LocalLastCommit.Votes {
        // Only checks vote signature — does NOT re-run VerifyVoteExtension!
        if !verifySignature(vote) { continue }
        // CometBFT accepts late precommits without full verification
        // Byzantine validator smuggles malicious vote extension into proposal
        extensions = append(extensions, vote.VoteExtension)
    }
    // Leader unknowingly includes forged oracle data in block
}
Pattern 2: Block Timestamp Manipulation
// VULNERABLE: Any module trusting ctx.BlockTime() for security-critical decisions
// CometBFT "Tachyon" (Finding 21, CSA-2026-001): inconsistency between how
// commit signatures are verified and how block time is derived breaks BFT Time
// guarantee. A faulty process CAN arbitrarily increase block time.

// These are all exploitable if block time can be manipulated:
deadline := proposal.SubmitTime.Add(votingPeriod)
if ctx.BlockTime().After(deadline) { ... }  // Governance deadlines

vestingEnd := account.EndTime
if ctx.BlockTime().After(vestingEnd) { ... }  // Vesting unlocks

price := oracle.GetTWAP(ctx, pair, window)  // Time-weighted prices
Pattern 3: Vesting on Blocked/Module Addresses
// VULNERABLE: Creating vesting accounts on blocked addresses (Finding 29, ASA-2024-003)
func (ms msgServer) CreatePeriodicVestingAccount(ctx context.Context, msg *types.MsgCreatePeriodicVestingAccount) error {
    toAddr := sdk.AccAddressFromBech32(msg.ToAddress)
    // Missing: check if toAddress is a blocked address or module account
    // Funds deposited to module accounts via vesting become permanently inaccessible
    // Could also enable unintended interactions with module accounts
}

What to Check:

  • [ ] PrepareProposal re-validates vote extensions using the same rules as VerifyVoteExtension — do NOT trust that CometBFT has already validated them (late precommits may skip verification)

  • [ ] ProcessProposal independently validates all vote extensions included in the proposal

  • [ ] Vote extension content is treated as untrusted input even from non-Byzantine validators

  • [ ] CometBFT is patched for Tachyon (>= v0.38.21 / v0.37.18) — block timestamp manipulation

  • [ ] Time-dependent logic (governance deadlines, vesting unlocks, oracle TWAPs, lockup periods, auction timers) is reviewed against block time manipulation

  • [ ] CreateVestingAccount / CreatePeriodicVestingAccount reject blocked addresses and non-initialized module accounts as recipients

  • [ ] SDK version includes Barberry patches (>= v0.46.13, >= v0.47.3) for vesting on blocked addresses

References:


26 CIRCUIT BREAKER AUTHZ BYPASS

Description: The x/circuit module allows authorized accounts to disable (circuit-break) specific message types during incident response. An authorization scope bug allows an account authorized to circuit-break specific message types to reset the circuit breaker for any message type, even those it lacks permission for. This can re-enable message types intentionally disabled for security.

Detection Patterns:

// VULNERABLE: Circuit breaker reset does not verify per-type authorization
// Account authorized to break MsgSend can reset MsgDelegate
func (ms msgServer) ResetCircuitBreaker(ctx context.Context, msg *types.MsgResetCircuitBreaker) error {
    // Checks: is the sender an authorized circuit breaker account? YES
    // Missing: does the sender have authority over THIS SPECIFIC message type?
    // Result: any circuit breaker account can re-enable any disabled message type
}

What to Check:

  • [ ] x/circuit reset/authorize operations validate per-message-type permissions (not just "is this a circuit breaker account")

  • [ ] Circuit breaker accounts have minimal scope — only the message types they are responsible for

  • [ ] Re-enabling a circuit-broken message type requires the same or higher authorization level as disabling it

  • [ ] During incident response, monitor for unexpected circuit breaker resets

Grep Patterns (use Grep tool):

  • circuit|CircuitBreaker|ResetCircuitBreaker with glob: "*.go" in x/

  • x/circuit with glob: "*.go" in app/

References:


27 MERKLE PROOF / CRYPTOGRAPHIC VERIFICATION FLAWS

Description: Specification-level or implementation-level flaws in cryptographic proof systems allow forging proofs that should be computationally infeasible. ICS-23 was unsound at the spec level (not just implementation). Cross-chain bridges that verify proofs differently on each side create asymmetric validation. This class has caused the largest single loss in the Cosmos ecosystem ($566M BNB bridge exploit, related flaw).

Detection Patterns:

Pattern 1: ICS-23 Absence Proof Forgery
// VULNERABLE: ICS-23 spec allowed proofs to carry their own spec parameters
// (Finding 3a, Dragonberry — all IBC chains, all versions)
// Validation only required input leaf prefix to CONTAIN the standard spec's
// prefix as a substring — not match exactly.
// Attacker forges absence proof to "prove" packet commitment doesn't exist
// on counterparty chain (even though it does), then triggers IBC timeout refunds
// for packets that were successfully delivered.
// Iterative drainage of ALL ICS-20 escrow accounts across ALL Cosmos networks.
Pattern 2: IAVL RangeProof Forgery
// VULNERABLE: Same class as Dragonberry in IAVL RangeProof system
// (Finding 30, Dragonfruit — $566M BNB bridge exploit used related flaw)
// Missing validation checks on leaf/inner-node prefix/suffix length
// allowed forging proofs against the IAVL Merkle tree.
Pattern 3: ECDSA Signature Malleability
// VULNERABLE: Cosmos-side ECDSA verification accepts non-canonical s-values
// (Finding 13, Gravity Bridge)
func EthAddressFromSignature(hash []byte, sig []byte) (common.Address, error) {
    // Missing: canonical s-value validation
    // ECDSA has two valid s values per signature (elliptic curve symmetry)
    // Ethereum enforces s < secp256k1.N/2, Cosmos side does not
    // Malicious orchestrator submits non-canonical signature:
    //   Cosmos accepts → Ethereum rejects → bridge enters crash loop
    //   Selectively block validator set updates and transaction batches
}

What to Check:

  • [ ] ICS-23 proof verification uses patched libraries — leaf prefix must match exactly, not just contain as substring

  • [ ] IAVL library patched for Dragonfruit (prefix/suffix length validation on inner/leaf nodes)

  • [ ] ECDSA signature verification enforces canonical s-value (s < secp256k1.N/2) on BOTH sides of any bridge

  • [ ] Cross-chain proof verification is symmetric — same validation on source and destination

  • [ ] Custom Merkle proof implementations do not allow proof parameters to be attacker-controlled

  • [ ] If using BLS, ed25519, or other signature schemes for cross-chain verification, signature malleability is addressed

Grep Patterns (use Grep tool with glob: "*.go" in x/):

  • VerifyMembership|VerifyNonMembership|VerifyProof — proof verification

  • RangeProof|InnerNode|LeafNode — Merkle tree operations

  • EthAddressFromSignature|RecoverPubkey|Ecrecover — signature recovery

References:

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.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download cosmos-vulnerability-scanner.zip