git:20260129.650f6e3 to git:20260401.d7f76b5

128 added, 274 removed. Audit A to A.

---
name: cosmos-vulnerability-scanner
- description: Scans Cosmos SDK blockchains for 9 consensus-critical vulnerabilities including non-determinism, incorrect signers, ABCI panics, and rounding errors. Use when auditing Cosmos chains or CosmWasm contracts.
+ description: "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."
---
# Cosmos Vulnerability Scanner
- ## 1. Purpose
+ ## Purpose
- Systematically scan Cosmos SDK blockchain modules and CosmWasm smart contracts for platform-specific security vulnerabilities that can cause chain halts, consensus failures, or fund loss. This skill encodes 9 critical vulnerability patterns unique to Cosmos-based chains.
+ 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.
- ## 2. When to Use This Skill
+ **Output directory**: defaults to `.bughunt_cosmos/`. If the user specifies a different directory in their prompt, use that instead.
- - Auditing Cosmos SDK modules (custom x/ modules)
- - Reviewing CosmWasm smart contracts (Rust)
+ ## 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
- - Validating consensus-critical code changes
- - Reviewing ABCI method implementations
- ## 3. Platform Detection
-
- ### File Extensions & Indicators
- - **Go files**: `.go`, `.proto`
- - **CosmWasm**: `.rs` (Rust with cosmwasm imports)
-
- ### Language/Framework Markers
- ```go
- // Cosmos SDK indicators
- import (
- "github.com/cosmos/cosmos-sdk/types"
- sdk "github.com/cosmos/cosmos-sdk/types"
- "github.com/cosmos/cosmos-sdk/x/..."
- )
-
- // Common patterns
- keeper.Keeper
- sdk.Msg, GetSigners()
- BeginBlocker, EndBlocker
- CheckTx, DeliverTx
- protobuf service definitions
- ```
-
- ```rust
- // CosmWasm indicators
- use cosmwasm_std::*;
- #[entry_point]
- pub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg)
- ```
-
- ### Project Structure
- - `x/modulename/` - Custom modules
- - `keeper/keeper.go` - State management
- - `types/msgs.go` - Message definitions
- - `abci.go` - BeginBlocker/EndBlocker
- - `handler.go` - Message handlers (legacy)
+ ## When NOT to Use
- ### Tool Support
- - **CodeQL**: Custom rules for non-determinism and panics
- - **go vet**, **golangci-lint**: Basic Go static analysis
- - **Manual review**: Critical for consensus issues
+ - 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
- ## 4. How This Skill Works
+ 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.
- When invoked, I will:
+ ## Scanning Workflow
- 1. **Search your codebase** for Cosmos SDK modules
- 2. **Analyze each module** for the 9 vulnerability patterns
- 3. **Report findings** with file references and severity
- 4. **Provide fixes** for each identified issue
- 5. **Check message handlers** for validation issues
+ ### 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`.
- ## 5. Example Output
+ Run a **synchronous subagent** (Agent tool) with the full contents of [DISCOVERY.md](resources/DISCOVERY.md) as its prompt. The agent must:
- When vulnerabilities are found, you'll get a report like this:
+ 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:
```
- === COSMOS SDK VULNERABILITY SCAN RESULTS ===
-
- Project: my-cosmos-chain
- Files Scanned: 6 (.go)
- Vulnerabilities Found: 2
-
- ---
-
- [CRITICAL] Incorrect GetSigners()
-
- ---
-
- ## 5. Vulnerability Patterns (9 Patterns)
-
- I check for 9 critical vulnerability patterns unique to CosmWasm. For detailed detection patterns, code examples, mitigations, and testing strategies, see [VULNERABILITY_PATTERNS.md](resources/VULNERABILITY_PATTERNS.md).
-
- ### Pattern Summary:
-
- 1. **Missing Denom Validation** ⚠️ CRITICAL - Accepting arbitrary token denoms
- 2. **Insufficient Authorization** ⚠️ CRITICAL - Missing sender/admin validation
- 3. **Missing Balance Check** ⚠️ HIGH - Not verifying sufficient balances
- 4. **Improper Reply Handling** ⚠️ HIGH - Unsafe submessage reply processing
- 5. **Missing Reply ID Check** ⚠️ MEDIUM - Not validating reply IDs
- 6. **Improper IBC Packet Validation** ⚠️ CRITICAL - Unvalidated IBC packets
- 7. **Unvalidated Execute Message** ⚠️ HIGH - Missing message validation
- 8. **Integer Overflow** ⚠️ HIGH - Unchecked arithmetic operations
- 9. **Reentrancy via Submessages** ⚠️ MEDIUM - State changes before submessages
-
- For complete vulnerability patterns with code examples, see [VULNERABILITY_PATTERNS.md](resources/VULNERABILITY_PATTERNS.md).
- ## 5. Scanning Workflow
-
- ### Step 1: Platform Identification
- 1. Identify Cosmos SDK version (`go.mod`)
- 2. Locate custom modules (`x/*/`)
- 3. Find ABCI methods (`abci.go`, BeginBlocker, EndBlocker)
- 4. Identify message types (`types/msgs.go`, `.proto`)
-
- ### Step 2: Critical Path Analysis
- Focus on consensus-critical code:
- - BeginBlocker / EndBlocker implementations
- - Message handlers (execute, DeliverTx)
- - Keeper methods that modify state
- - CheckTx priority logic
-
- ### Step 3: Non-Determinism Sweep
- **This is the highest priority check for Cosmos chains.**
-
- ```bash
- # Search for non-deterministic patterns
- grep -r "range.*map\[" x/
- grep -r "\bint\b\|\buint\b" x/ | grep -v "int32\|int64\|uint32\|uint64"
- grep -r "float32\|float64" x/
- grep -r "go func\|go routine" x/
- grep -r "select {" x/
- grep -r "time.Now()" x/
- grep -r "rand\." x/
+ 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>
```
- For each finding:
- 1. Verify it's in consensus-critical path
- 2. Confirm it causes non-determinism
- 3. Assess severity (chain halt vs data inconsistency)
+ 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.
- ### Step 4: ABCI Method Analysis
- Review BeginBlocker and EndBlocker:
- - [ ] Computational complexity bounded?
- - [ ] No unbounded iterations?
- - [ ] No nested loops over large collections?
- - [ ] Panic-prone operations validated?
- - [ ] Benchmarked with maximum state?
+ **Exit**: CLAUDE.md written by main skill. PLATFORM, IBC_ENABLED, SDK_VERSION, IBC_GO_VERSION, and CUSTOM_MODULES captured.
- ### Step 5: Message Validation
- For each message type:
- - [ ] GetSigners() address matches handler usage?
- - [ ] All error returns checked?
- - [ ] Priority set in CheckTx if critical?
- - [ ] Handler registered (or using v0.47+ auto-registration)?
+ ### Phase 2: Parallel Vulnerability Scan
- ### Step 6: Arithmetic & Bookkeeping
- - [ ] sdk.Dec operations use multiply-before-divide?
- - [ ] Rounding favors protocol over users?
- - [ ] Custom bookkeeping synchronized with x/bank?
- - [ ] Invariant checks in place?
+ 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:**
- ## 6. Reporting Format
+ | 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 |
- ### Finding Template
- ```markdown
- ## [CRITICAL] Non-Deterministic Map Iteration in EndBlocker
+ **Spawn conditionally (in the same parallel message):**
- **Location**: `x/dex/abci.go:45-52`
+ | 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` |
- **Description**:
- The EndBlocker iterates over an unordered map to distribute rewards, causing different validators to process users in different orders and produce different state roots. This will halt the chain when validators fail to reach consensus.
+ #### Agent Prompt Template
- **Vulnerable Code**:
- ```go
- // abci.go, line 45
- func EndBlocker(ctx sdk.Context, k keeper.Keeper) {
- rewards := k.GetPendingRewards(ctx) // Returns map[string]sdk.Coins
- for user, amount := range rewards { // NON-DETERMINISTIC ORDER
- k.bankKeeper.SendCoins(ctx, moduleAcc, user, amount)
- }
- }
- ```
+ 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:
- **Attack Scenario**:
- 1. Multiple users have pending rewards
- 2. Different validators iterate in different orders due to map randomization
- 3. If any reward distribution fails mid-iteration, state diverges
- 4. Validators produce different app hashes
- 5. Chain halts - cannot reach consensus
+ ~~~
+ Perform a very thorough security scan of a Cosmos SDK codebase for specific vulnerability patterns.
- **Recommendation**:
- Sort map keys before iteration:
- ```go
- func EndBlocker(ctx sdk.Context, k keeper.Keeper) {
- rewards := k.GetPendingRewards(ctx)
+ CONTEXT:
+ Read {CLAUDE_MD_PATH} for codebase context (SDK version, modules, threat model, key files).
- // Collect and sort keys for deterministic iteration
- users := make([]string, 0, len(rewards))
- for user := range rewards {
- users = append(users, user)
- }
- sort.Strings(users) // Deterministic order
+ 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
- // Process in sorted order
- for _, user := range users {
- k.bankKeeper.SendCoins(ctx, moduleAcc, user, rewards[user])
- }
- }
- ```
+ 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
- **References**:
- - building-secure-contracts/not-so-smart-contracts/cosmos/non_determinism
- - Cosmos SDK docs: Determinism
- ```
+ 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.
- ## 7. Priority Guidelines
+ For each pattern, return one of:
+ §NUM PATTERN_NAME: Not applicable — [one-line reason]
+ §NUM PATTERN_NAME: FINDING (followed by the finding block below)
- ### Critical - CHAIN HALT Risk
- - Non-determinism (any form)
- - ABCI method panics
- - Slow ABCI methods
- - Incorrect GetSigners (allows unauthorized actions)
+ For each finding, include the full content using this template:
- ### High - Fund Loss Risk
- - Missing error handling (bankKeeper.SendCoins)
- - Broken bookkeeping (accounting mismatch)
- - Missing message priority (oracle/emergency messages)
+ 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]
- ### Medium - Logic/DoS Risk
- - Rounding errors (protocol value leakage)
- - Unregistered message handlers (functionality broken)
+ 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.
- ## 8. Testing Recommendations
+ ### Phase 3: Write Findings
- ### Non-Determinism Testing
- ```bash
- # Build for different architectures
- GOARCH=amd64 go build
- GOARCH=arm64 go build
+ After all scanning agents return, write finding files to the output directory (default `.bughunt_cosmos/`):
- # Run same operations, compare state roots
- # Must be identical across architectures
+ 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
- # Fuzz test with concurrent operations
- go test -fuzz=FuzzEndBlocker -parallel=10
- ```
+ ### Phase 4: Verify Completeness
- ### ABCI Benchmarking
- ```go
- func BenchmarkBeginBlocker(b *testing.B) {
- ctx := setupMaximalState() // Worst-case state
- b.ResetTimer()
+ After writing all findings, verify every pattern was assessed:
- for i := 0; i < b.N; i++ {
- BeginBlocker(ctx, keeper)
- }
+ 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`
- // Must complete in < 1 second
- require.Less(b, b.Elapsed()/time.Duration(b.N), time.Second)
- }
- ```
+ **Exit**: All patterns accounted for. Finding files listed for the user.
- ### Invariant Testing
- ```go
- // Run invariants in integration tests
- func TestInvariants(t *testing.T) {
- app := setupApp()
+ ---
- // Execute operations
- app.DeliverTx(...)
+ ## Success Criteria
- // Check invariants
- _, broken := keeper.AllInvariants()(app.Ctx)
- require.False(t, broken, "invariant violation detected")
- }
- ```
+ - [ ] 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
---
- ## 9. Additional Resources
+ ## Resources
+ - **Discovery & CLAUDE.md**: [DISCOVERY.md](resources/DISCOVERY.md)
+ - **Core patterns (§1-9)**: [VULNERABILITY_PATTERNS.md](resources/VULNERABILITY_PATTERNS.md)
+ - **State & module patterns (§11-23)**: [STATE_VULNERABILITY_PATTERNS.md](resources/STATE_VULNERABILITY_PATTERNS.md)
+ - **Advanced patterns (§24-27)**: [ADVANCED_VULNERABILITY_PATTERNS.md](resources/ADVANCED_VULNERABILITY_PATTERNS.md)
+ - **IBC vulnerabilities**: [IBC_VULNERABILITY_PATTERNS.md](resources/IBC_VULNERABILITY_PATTERNS.md)
+ - **CosmWasm vulnerabilities**: [COSMWASM_VULNERABILITY_PATTERNS.md](resources/COSMWASM_VULNERABILITY_PATTERNS.md)
+ - **EVM vulnerabilities**: [EVM_VULNERABILITY_PATTERNS.md](resources/EVM_VULNERABILITY_PATTERNS.md)
- **Building Secure Contracts**: `building-secure-contracts/not-so-smart-contracts/cosmos/`
- **Cosmos SDK Docs**: https://docs.cosmos.network/
- - **CodeQL for Go**: https://codeql.github.com/docs/codeql-language-guides/codeql-for-go/
- - **Cosmos Security Best Practices**: https://github.com/cosmos/cosmos-sdk/blob/main/docs/docs/learn/advanced/17-determinism.md
-
- ---
-
- ## 10. Quick Reference Checklist
-
- Before completing Cosmos chain audit:
-
- **Non-Determinism (CRITICAL)**:
- - [ ] No map iteration in consensus code
- - [ ] No platform-dependent types (int, uint, float)
- - [ ] No goroutines in message handlers/ABCI
- - [ ] No select statements with multiple channels
- - [ ] No rand, time.Now(), memory addresses
- - [ ] All serialization is deterministic
-
- **ABCI Methods (CRITICAL)**:
- - [ ] BeginBlocker/EndBlocker computationally bounded
- - [ ] No unbounded iterations
- - [ ] No nested loops over large collections
- - [ ] All panic-prone operations validated
- - [ ] Benchmarked with maximum state
-
- **Message Handling (HIGH)**:
- - [ ] GetSigners() matches handler address usage
- - [ ] All error returns checked
- - [ ] Critical messages prioritized in CheckTx
- - [ ] All message types registered
-
- **Arithmetic & Accounting (MEDIUM)**:
- - [ ] Multiply before divide pattern used
- - [ ] Rounding favors protocol
- - [ ] Custom bookkeeping synced with x/bank
- - [ ] Invariant checks implemented
-
- **Testing**:
- - [ ] Cross-architecture builds tested
- - [ ] ABCI methods benchmarked
- - [ ] Invariants checked in CI
- - [ ] Integration tests cover all messages
+ - **CodeQL for Cosmos SDK**: https://github.com/crypto-com/cosmos-sdk-codeql