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://mp-staging.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/VULNERABILITY_PATTERNS.md
Core Vulnerability Patterns & Audit Checks
Updated for Cosmos SDK v0.53.x. Core vulnerability patterns (§1-9) covering non-determinism, ABCI, signers, validation, handlers, and ante security. For state/module patterns see STATE_VULNERABILITY_PATTERNS.md; for advanced patterns see ADVANCED_VULNERABILITY_PATTERNS.md. Referenced by SKILL.md checklist items via
§anchors.
1 NON-DETERMINISM
Description: Non-deterministic code in consensus causes different validators to produce different state roots, halting the chain. This is the most severe Cosmos vulnerability.
Detection Patterns:
Pattern 1: Map Iteration
// VULNERABLE: Iterating over Go map (random order)
assets := make(map[string]sdk.Coin)
for assetID, coin := range assets { // NON-DETERMINISTIC!
keeper.ProcessAsset(ctx, assetID, coin)
}Pattern 2: Platform-Dependent Types
// VULNERABLE: Platform-dependent integer types
var amount int // Size differs: 32-bit vs 64-bit systems
var price float64 // Float arithmetic is non-deterministic
// Serialization produces different bytes on different architectures
bz := someSerializer(amount) // Different on 32-bit vs 64-bit!Pattern 3: Goroutines and Concurrency
// VULNERABLE: Goroutines have non-deterministic execution order
go processTransaction(tx1)
go processTransaction(tx2)
// Order of state updates is non-deterministic!Pattern 4: Select Statements
// VULNERABLE: Select with multiple ready channels
select {
case msg := <-ch1: // Non-deterministic choice
process(msg)
case msg := <-ch2:
process(msg)
}Pattern 5: Other Sources
// VULNERABLE: Other non-determinism sources
rand.Intn(100) // Random numbers
time.Now() // Local system time (use ctx.BlockTime())
&obj // Memory addresses
json.Marshal(map) // Map serialization order
filepath.Walk() // Filesystem traversal orderWhat to Check:
[ ] NO
rangeover maps in any consensus code[ ] NO
int,uint,float32,float64types (useint32,int64,math.Int,math.LegacyDec)[ ] NO goroutines in message handlers or ABCI methods
[ ] NO
selectstatements with multiple channels[ ] NO
randpackage usage (use deterministic PRF)[ ] NO
time.Now()(usectx.BlockTime()orctx.BlockHeight())[ ] NO memory address usage (
&obj, pointer comparisons)[ ] NO non-deterministic serialization
Mitigation:
// SECURE: Deterministic iteration
// Option 1: Sort map keys
keys := make([]string, 0, len(assets))
for k := range assets {
keys = append(keys, k)
}
sort.Strings(keys) // Deterministic order
for _, k := range keys {
keeper.ProcessAsset(ctx, k, assets[k])
}
// Option 2: Use ordered data structure (sdk.KVStore with ordered iteration)
// SECURE: Platform-independent types
var amount int64 // Explicit 64-bit
var amount math.Int // Arbitrary precision integer (cosmossdk.io/math)
var price math.LegacyDec // Decimal type for consensus (cosmossdk.io/math)
// SECURE: Use block time, not system time
timestamp := ctx.BlockTime() // Deterministic
height := ctx.BlockHeight() // DeterministicGrep Patterns (use Grep tool with glob: "*.go" in x/):
range.*map\[— map iterationgo func— goroutinestime\.Now\(\)— system timefloat64|float32— floating point types\bint\b|\buint\b— platform-dependent integer types (excludeint32,int64,uint32,uint64results)
References: building-secure-contracts/not-so-smart-contracts/cosmos/non_determinism
2 ADDITIONAL NON-DETERMINISM SOURCES
Description: Beyond the core non-determinism patterns in §1, these additional sources can cause consensus failures.
What to Check:
[ ]
sort.Sortis not stable —sort.Stablemust be used when elements with equal keys must maintain insertion order. Same-order but different items may be sorted differently between Go versions[ ] Memory addresses — even in non-committed storage, can cause indirect consensus failures:
Conversions to strings do not output addresses (structs not used directly in
fmt.Printf)
[ ]
filepath.Extis platform-dependent[ ] Struct padding (unavoidable with cgo)
[ ] Platform-dependent build tags (
//go:build,// +build)[ ] No leaks from GC or nondeterministic runtime internals (Agoric example)
[ ] Parallel/concurrent tx execution (BlockSTM-style): modules must not have shared mutable state outside KV store
[ ] Concurrency: goroutines,
selectnon-determinism, synchronization with sleep. Use race detector
Grep Patterns (use Grep tool with glob: "*.go" in x/):
sort\.Sort\b— unstable sort"%p"— memory address formatfilepath\.Ext— platform-dependentgo func— goroutinesselect \{— non-deterministic select
3 SLOW ABCI METHODS
Description: Computationally expensive BeginBlocker, EndBlocker, or PreBlocker with unbounded loops can exceed block time limits, halting the chain. In SDK v0.50+, modules implement appmodule.HasBeginBlocker and appmodule.HasEndBlocker interfaces. PreBlocker is a new hook that runs before BeginBlock. Additionally, appmodule.HasPrecommit and appmodule.HasPrepareCheckState are lifecycle hooks that run after EndBlock and can also cause issues. Note: there are two EndBlock interfaces — appmodule.HasEndBlocker (returns error) and module.HasABCIEndBlock (returns []abci.ValidatorUpdate, error, used by x/staking).
Detection Patterns:
// VULNERABLE: Unbounded loop in EndBlocker (v0.50+ style)
func (am AppModule) EndBlock(ctx context.Context) error {
sdkCtx := sdk.UnwrapSDKContext(ctx)
// Iterates over ALL users - could be millions!
am.keeper.IterateAllUsers(sdkCtx, func(user User) bool {
reward := am.keeper.CalculateReward(sdkCtx, user)
am.keeper.DistributeReward(sdkCtx, user, reward)
return false
})
return nil
}
// VULNERABLE: Nested loops in BeginBlocker
func (am AppModule) BeginBlock(ctx context.Context) error {
sdkCtx := sdk.UnwrapSDKContext(ctx)
pools := am.keeper.GetAllPools(sdkCtx) // 1000+ pools
for _, pool := range pools {
assets := am.keeper.GetPoolAssets(sdkCtx, pool.ID) // 100+ assets each
for _, asset := range assets {
am.keeper.UpdatePrice(sdkCtx, pool, asset) // Expensive calculation
}
}
return nil
}
// VULNERABLE: Unbounded PreBlocker
func (am AppModule) PreBlock(ctx context.Context) error {
// No limit on processing!
am.keeper.ProcessAllPending(ctx)
return nil
}What to Check:
[ ]
BeginBlockhas bounded computational complexity[ ]
EndBlockhas bounded computational complexity (bothHasEndBlockerandHasABCIEndBlockvariants)[ ]
PreBlock(new in v0.50) has bounded computational complexity[ ]
PrecommitandPrepareCheckStatehooks have bounded complexity[ ] NO nested loops over unbounded collections
[ ] NO iterations over all users/pools/assets
[ ] Batch operations have size limits
[ ] Normal (non-malicious) transactions cannot exceed CometBFT's
max_bytesormax_gasblock limits — a single large but valid message (e.g., governance proposal with many updates, batch operation) that fills an entire block prevents other transactions from being included and can degrade liveness[ ] Stress tests with maximum expected data
Mitigation:
// SECURE: Process limited batch per block (v0.50+ style)
func (am AppModule) EndBlock(ctx context.Context) error {
sdkCtx := sdk.UnwrapSDKContext(ctx)
maxProcessed := 100 // Process max 100 users per block
iterator := am.keeper.GetUnprocessedUsers(sdkCtx)
defer iterator.Close()
count := 0
for ; iterator.Valid() && count < maxProcessed; iterator.Next() {
user := am.keeper.UnmarshalUser(iterator.Value())
reward := am.keeper.CalculateReward(sdkCtx, user)
am.keeper.DistributeReward(sdkCtx, user, reward)
am.keeper.MarkProcessed(sdkCtx, user)
count++
}
// Remaining users processed in subsequent blocks
return nil
}Testing:
func BenchmarkEndBlocker(b *testing.B) {
ctx := setupMaximumState() // 1M users, 10K pools, etc.
b.ResetTimer()
for i := 0; i < b.N; i++ {
am.EndBlock(ctx)
}
// Must complete in < 1 second
}References: building-secure-contracts/not-so-smart-contracts/cosmos/abci_method_slow
4 ABCI METHODS PANIC
Description: Unexpected panics in BeginBlock, EndBlock, PreBlock, Precommit, or PrepareCheckState immediately stop the blockchain. Many Cosmos SDK types panic on invalid operations. In SDK v0.50+, math types have moved to cosmossdk.io/math and x/params is deprecated in favor of direct keeper param storage, but panic-prone operations remain. Note: ValidateBasic() is now deprecated and facultative (validation should happen in msg_server.go), making it more likely that invalid inputs reach panic-prone code paths.
Detection Patterns:
Pattern 1: Panic-Prone Coin Operations
// VULNERABLE: NewCoins panics on invalid coins
func (am AppModule) EndBlock(ctx context.Context) error {
sdkCtx := sdk.UnwrapSDKContext(ctx)
// Panics if amount is negative or denom is invalid!
coins := sdk.NewCoins(sdk.NewCoin(userDenom, math.NewInt(userAmount)))
am.keeper.MintCoins(sdkCtx, coins)
return nil
}
// VULNERABLE: Coin arithmetic panics
reward := sdk.NewCoin("uatom", math.NewInt(-100)) // PANIC: negative amountPattern 2: Math Operations
// VULNERABLE: math.LegacyNewDecFromStr panics on invalid string
func (am AppModule) BeginBlock(ctx context.Context) error {
price, err := math.LegacyNewDecFromStr(priceString) // Returns error, but...
// If using the non-error variant:
price := math.LegacyMustNewDecFromStr(priceString) // PANIC if invalid!
}
// VULNERABLE: Division by zero
ratio := amount.Quo(math.ZeroInt()) // PANIC!
// PITFALL: Using pointer to Dec is error-prone
var price *math.LegacyDec // Unnecessary pointer — LegacyDec is already a single pointer internally
// Dec consists of a single big.Int pointer — pointer-to-pointer adds indirection with no performance benefit
// and introduces nil-pointer dereference riskPattern 3: Direct Param Storage (replaces SetParamSet)
// VULNERABLE: Setting params without validation
// In v0.50+, modules store params directly in keeper state
func (k Keeper) SetParams(ctx context.Context, params Params) error {
// If params are not validated before storage, invalid state can cause
// panics later when params are read and used in calculations
return k.Params.Set(ctx, params)
}Pattern 4: Array Out of Bounds
// VULNERABLE: No bounds checking
func processValidators(validators []Validator) {
top := validators[0] // PANIC if empty slice!
}What to Check:
[ ] All
sdk.NewCoins(),sdk.NewCoin()calls validated[ ] All
math.LegacyNewDecFromStr(),math.NewIntFromString()use error-returning variants[ ] No
Must*variants (LegacyMustNewDecFromStr,MustNewDecFromStr) in consensus code[ ] Division operations check for zero divisor
[ ] Params validated before storage (even with direct keeper storage)
[ ] Array/slice access has bounds checking
[ ] User input validated before use in panic-prone operations
Mitigation:
// SECURE: Validate before panic-prone operations
func (am AppModule) EndBlock(ctx context.Context) error {
sdkCtx := sdk.UnwrapSDKContext(ctx)
if err := sdk.ValidateDenom(userDenom); err != nil {
sdkCtx.Logger().Error("invalid denom", "error", err)
return nil
}
if userAmount.IsNegative() {
sdkCtx.Logger().Error("negative amount")
return nil
}
coins := sdk.NewCoins(sdk.NewCoin(userDenom, userAmount))
am.keeper.MintCoins(sdkCtx, coins)
return nil
}
// SECURE: Use safe constructors
func (k Keeper) UpdatePrice(ctx context.Context, priceStr string) error {
price, err := math.LegacyNewDecFromStr(priceStr)
if err != nil {
return err
}
if divisor.IsZero() {
return errors.New("division by zero")
}
ratio := amount.Quo(divisor)
return nil
}Grep Patterns (use Grep tool with glob: "*.go" in x/):
MustNewDec|MustNewInt|LegacyMustNewDec— panic-prone constructors\.Quo|\.Div— division operations (check for zero divisor)math\.NewInt|math\.LegacyNewDec— math constructors
References: building-secure-contracts/not-so-smart-contracts/cosmos/abci_method_panics
5 INCORRECT SIGNER ANNOTATION / MISMATCH
Description: In Cosmos SDK v0.47+, GetSigners() []sdk.AccAddress no longer exists on message types. sdk.Msg is now just proto.Message. Signers are declared via the cosmos.msg.v1.signer proto annotation and resolved automatically by x/tx/signing. The vulnerability now manifests as a mismatch between the proto-annotated signer field and the field actually used for authorization in msg_server.go.
Detection Patterns:
Pattern 1: Proto annotation vs msg_server mismatch
// In tx.proto
message MsgTransferOwnership {
option (cosmos.msg.v1.signer) = "sender"; // "sender" is the verified signer
string sender = 1;
string new_owner = 2;
}// In msg_server.go - VULNERABLE: uses new_owner for authorization instead of sender
func (ms msgServer) TransferOwnership(ctx context.Context, msg *types.MsgTransferOwnership) (*types.MsgTransferOwnershipResponse, error) {
// BUG: authorizing based on new_owner, not the verified sender!
if !ms.IsAdmin(ctx, msg.NewOwner) {
return nil, errors.ErrUnauthorized
}
// ...
}Pattern 2: Wrong field annotated as signer
// VULNERABLE: signer annotation points to wrong field
message MsgExecute {
option (cosmos.msg.v1.signer) = "authority"; // Should be "sender"
string sender = 1; // actual tx signer
string authority = 2; // module authority, not tx signer
}Pattern 3: Multiple address fields with ambiguous signer
message MsgDelegate {
option (cosmos.msg.v1.signer) = "delegator";
string delegator = 1;
string validator = 2;
string beneficiary = 3; // If handler uses this instead of delegator...
}What to Check:
[ ]
cosmos.msg.v1.signerannotation field matches the field used for authorization inmsg_server.go[ ] No multiple address fields where the wrong one is used for access control
[ ]
msg_server.gohandler referencesmsg.Signer(or whatever the annotated field is), not another address field[ ] Custom
GetSignersoverrides viaDefineCustomGetSignersare correct
Mitigation:
// SECURE: Single clear signer field
message MsgExample {
option (cosmos.msg.v1.signer) = "sender";
string sender = 1; // Only address field used for authorization
}// SECURE: msg_server uses the annotated signer field
func (ms msgServer) Example(ctx context.Context, msg *types.MsgExample) (*types.MsgExampleResponse, error) {
// Use msg.Sender - the field declared in cosmos.msg.v1.signer
if err := ms.authorize(ctx, msg.Sender); err != nil {
return nil, err
}
// ...
}Testing:
Unit test with crafted messages where signer field != other address fields
Verify only the annotated signer has authorization
Integration test all message types
References: building-secure-contracts/not-so-smart-contracts/cosmos/incorrect_signer
6 MISSING MSG_SERVER VALIDATION (ValidateBasic Deprecation)
Description: In Cosmos SDK v0.50+, ValidateBasic() is deprecated and facultative — the SDK no longer requires messages to implement it. The recommended pattern is to validate inputs directly in msg_server.go handlers. However, if a module removes ValidateBasic() without adding equivalent validation in the handler, invalid messages reach state-changing code without checks.
Detection Patterns:
// VULNERABLE: ValidateBasic removed but no validation in handler
// types/msgs.go - ValidateBasic was here but got removed during migration
// msg_server.go - No validation of inputs
func (ms msgServer) UpdateParams(ctx context.Context, msg *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) {
// No check on msg.Authority
// No check on msg.Params fields
return &types.MsgUpdateParamsResponse{}, ms.Params.Set(ctx, msg.Params)
}// VULNERABLE: HasValidateBasic implemented but handler also needs validation
// types/msgs.go
func (msg *MsgTransfer) ValidateBasic() error {
// Only checks basic format — NOT authorization or business logic
return nil
}
// msg_server.go - Relies entirely on ValidateBasic, no handler-level checks
func (ms msgServer) Transfer(ctx context.Context, msg *types.MsgTransfer) (*types.MsgTransferResponse, error) {
// Missing: check that msg.Amount is positive
// Missing: check that sender has sufficient funds
// Missing: authorization check against cosmos.msg.v1.signer
return ms.executeTransfer(ctx, msg)
}What to Check:
[ ] Every
msg_server.gohandler validates all input fields (don't rely on ValidateBasic)[ ] Authority/signer checks are in the handler, not just in ValidateBasic
[ ] Params are validated before
Params.Set()calls[ ] Numeric inputs checked for negative/zero/overflow before use
[ ] Address strings validated before conversion
Mitigation:
// SECURE: Full validation in msg_server.go handler
func (ms msgServer) UpdateParams(ctx context.Context, msg *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) {
if ms.authority != msg.Authority {
return nil, errorsmod.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", ms.authority, msg.Authority)
}
if err := msg.Params.Validate(); err != nil {
return nil, err
}
return &types.MsgUpdateParamsResponse{}, ms.Params.Set(ctx, msg.Params)
}7 MISSING ERROR HANDLER
Description: Ignoring error return values from keeper methods (especially bankKeeper.SendCoins) allows invalid operations to silently succeed.
Detection Patterns:
// VULNERABLE: Ignored error from SendCoins
func (k Keeper) Withdraw(ctx context.Context, user string, amount sdk.Coins) {
// Error ignored! Withdrawal appears successful even if SendCoins fails
k.bankKeeper.SendCoins(ctx, moduleAccount, user, amount)
// Update state assuming withdrawal succeeded
k.DecrementBalance(ctx, user, amount)
}
// VULNERABLE: Deferred error handling too late
func (k Keeper) ProcessBatch(ctx context.Context, txs []Transaction) {
for _, tx := range txs {
err := k.ProcessTransaction(ctx, tx)
// Error not checked, continues processing!
}
}What to Check:
[ ] ALL keeper method calls check error return values
[ ]
bankKeeper.SendCoins()errors always handled[ ] State updates only occur after successful operation
[ ] Errors propagated to caller
[ ] Use linters to detect ignored errors (errcheck)
Mitigation:
// SECURE: Check all errors
func (k Keeper) Withdraw(ctx context.Context, user string, amount sdk.Coins) error {
if err := k.bankKeeper.SendCoins(ctx, moduleAccount, user, amount); err != nil {
return err
}
k.DecrementBalance(ctx, user, amount)
return nil
}
// SECURE: Stop processing on first error
func (k Keeper) ProcessBatch(ctx context.Context, txs []Transaction) error {
for _, tx := range txs {
if err := k.ProcessTransaction(ctx, tx); err != nil {
return fmt.Errorf("transaction failed: %w", err)
}
}
return nil
}Linter Configuration:
# .golangci.yml
linters:
enable:
- errcheck
- goerr113
linters-settings:
errcheck:
check-blank: true
check-type-assertions: trueReferences: building-secure-contracts/not-so-smart-contracts/cosmos/missing_error_handler
8 UNREGISTERED MESSAGE HANDLER (Legacy Only)
Description: In Cosmos SDK v0.50+, all modules use protobuf service-based message handling (msg_server.go). The legacy NewHandler/sdk.Handler switch-case pattern no longer exists in the SDK. Messages are auto-registered when the module implements RegisterServices.
This pattern is only relevant for chains still on SDK < v0.47 or chains that have not migrated legacy handlers.
When This Still Applies:
Chains running Cosmos SDK < v0.47
Custom modules that haven't migrated to protobuf services
Forked SDK versions with legacy handler patterns
Modern Equivalent Issue: Even with protobuf service registration, a related issue can occur:
// msg_server.go - Message type defined in proto but method not implemented
type msgServer struct {
Keeper
}
var _ types.MsgServer = msgServer{}
// If a method is declared in the proto service but the Go implementation
// is missing or returns a nil/empty response, the compiler will catch
// missing methods (unlike the legacy switch-case), but the implementation
// could still be a no-op stub.
func (ms msgServer) Withdraw(ctx context.Context, msg *types.MsgWithdraw) (*types.MsgWithdrawResponse, error) {
// VULNERABLE: Stub implementation that does nothing
return &types.MsgWithdrawResponse{}, nil
}What to Check:
[ ] All proto service RPC methods have real implementations in
msg_server.go[ ] No stub/no-op implementations that accept messages without processing
[ ] Integration tests call all message types and verify state changes
[ ]
RegisterServicesis called in the module'sAppModule
References: building-secure-contracts/not-so-smart-contracts/cosmos/message_handler_missing
9 ANTEHANDLER SECURITY
Description: AnteHandlers form the authentication and validation pipeline. Misconfigurations allow bypassing signature verification, fee checks, or authorization.
What to Check:
[ ]
SetUpContextis the first decorator inChainAnteDecorators[ ]
SetPubKeyDecoratorbefore all signature verification decorators (ValidateSigCountDecorator,SigVerificationDecorator)[ ] Manual message routing is NOT performed — it bypasses AnteHandlers
[ ] Custom AnteHandlers handle nested/embedded messages inside
x/authz MsgExecorx/groupproposal execution. SDK enforcesMaxUnpackAnyRecursionDepth = 10(GHSA-8wcc-m6j2-qxvm) but semantic nesting (authz wrapping authz) must be handled by the ante handler itself[ ]
x/authzgrant creation reviewed for privilege escalation (GHSA-4j93-fm92-rp4m) — verify grants cannot circumvent blocked address restrictions; also checkx/feegrant'sGrantAllowanceandx/auth/vesting'sCreatePeriodicVestingAccountagainstBlockedAddr[ ] If
PostHandleris set (app.SetPostHandler), its logic is reviewed — PostHandlers run after message execution and receive asuccessbool; errors can mask the original message result or cause unexpected state changes[ ] Unordered transactions (ADR-070):
SigVerificationDecoratorconfigured withSigVerifyOptions(timeout duration, gas cost)
Key Vulnerability: Nested message bypass. An attacker wraps a message inside MsgExec (authz) or a group proposal. If the custom ante handler only inspects the outer message, inner messages skip validation entirely.
// VULNERABLE: AnteHandler only checks outer message type
func (d MyDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) {
for _, msg := range tx.GetMsgs() {
// Only checks msg type — does NOT recurse into MsgExec.Msgs!
if _, ok := msg.(*types.MsgDangerous); ok {
return ctx, errors.New("blocked")
}
}
return next(ctx, tx, simulate)
}// SECURE: Recurse into nested messages
func (d MyDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) {
for _, msg := range tx.GetMsgs() {
if err := d.checkMsg(msg); err != nil {
return ctx, err
}
}
return next(ctx, tx, simulate)
}
func (d MyDecorator) checkMsg(msg sdk.Msg) error {
if _, ok := msg.(*types.MsgDangerous); ok {
return errors.New("blocked")
}
if exec, ok := msg.(*authz.MsgExec); ok {
for _, inner := range exec.Msgs {
var innerMsg sdk.Msg
if err := d.cdc.UnpackAny(inner, &innerMsg); err != nil {
return err
}
if err := d.checkMsg(innerMsg); err != nil { // Recurse
return err
}
}
}
return nil
}References: Jump Crypto — Bypassing Ethermint Ante Handlers
10 IBC SECURITY
IBC vulnerability patterns are covered separately in Step 4 of the scanning workflow. See IBC_VULNERABILITY_PATTERNS.md. This section intentionally left as a placeholder to preserve numbering.
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