cosmos-vulnerability-scanner

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Cosmos Vulnerability Scanner

Cosmos漏洞扫描工具

1. Purpose

1. 用途

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.
系统扫描Cosmos SDK区块链模块和CosmWasm智能合约中特定于平台的安全漏洞,这些漏洞可能导致链停止、共识失败或资金损失。本技能涵盖了基于Cosmos的链特有的9种关键漏洞模式。

2. When to Use This Skill

2. 何时使用本技能

  • Auditing Cosmos SDK modules (custom x/ modules)
  • Reviewing CosmWasm smart contracts (Rust)
  • Pre-launch security assessment of Cosmos chains
  • Investigating chain halt incidents
  • Validating consensus-critical code changes
  • Reviewing ABCI method implementations
  • 审计Cosmos SDK模块(自定义x/模块)
  • 审查CosmWasm智能合约(Rust)
  • Cosmos链上线前的安全评估
  • 调查链停止事件
  • 验证共识关键代码变更
  • 审查ABCI方法实现

3. Platform Detection

3. 平台检测

File Extensions & Indicators

文件扩展名与标识

  • Go files:
    .go
    ,
    .proto
  • CosmWasm:
    .rs
    (Rust with cosmwasm imports)
  • Go文件
    .go
    ,
    .proto
  • CosmWasm
    .rs
    (带有cosmwasm导入的Rust文件)

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)
go
// Cosmos SDK标识
import (
    "github.com/cosmos/cosmos-sdk/types"
    sdk "github.com/cosmos/cosmos-sdk/types"
    "github.com/cosmos/cosmos-sdk/x/..."
)

// 常见模式
keeper.Keeper
sdk.Msg, GetSigners()
BeginBlocker, EndBlocker
CheckTx, DeliverTx
protobuf service definitions
rust
// CosmWasm标识
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)
  • x/modulename/
    - 自定义模块
  • keeper/keeper.go
    - 状态管理
  • types/msgs.go
    - 消息定义
  • abci.go
    - BeginBlocker/EndBlocker
  • handler.go
    - 消息处理器(旧版)

Tool Support

工具支持

  • CodeQL: Custom rules for non-determinism and panics
  • go vet, golangci-lint: Basic Go static analysis
  • Manual review: Critical for consensus issues

  • CodeQL:针对非确定性和恐慌的自定义规则
  • go vet, golangci-lint:基础Go静态分析
  • 人工审查:对共识问题至关重要

4. How This Skill Works

4. 本技能的工作方式

When invoked, I will:
  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

调用本技能后,我将:
  1. 扫描你的代码库以查找Cosmos SDK模块
  2. 分析每个模块是否存在9种漏洞模式
  3. 报告发现结果,包含文件引用和风险等级
  4. 为每个已识别的问题提供修复方案
  5. 检查消息处理器是否存在验证问题

5. Example Output

5. 示例输出

When vulnerabilities are found, you'll get a report like this:
=== COSMOS SDK VULNERABILITY SCAN RESULTS ===

Project: my-cosmos-chain
Files Scanned: 6 (.go)
Vulnerabilities Found: 2

---

[CRITICAL] Incorrect GetSigners()

---
当发现漏洞时,你将收到如下报告:
=== COSMOS SDK VULNERABILITY SCAN RESULTS ===

Project: my-cosmos-chain
Files Scanned: 6 (.go)
Vulnerabilities Found: 2

---

[CRITICAL] Incorrect GetSigners()

---

5. Vulnerability Patterns (9 Patterns)

5. 漏洞模式(9种)

I check for 9 critical vulnerability patterns unique to CosmWasm. For detailed detection patterns, code examples, mitigations, and testing strategies, see VULNERABILITY_PATTERNS.md.
我会检查CosmWasm特有的9种关键漏洞模式。有关详细的检测模式、代码示例、缓解措施和测试策略,请参阅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.
  1. 缺失Denom验证 ⚠️ 严重 - 接受任意代币denom
  2. 授权不足 ⚠️ 严重 - 缺失发送者/管理员验证
  3. 缺失余额检查 ⚠️ 高 - 未验证余额是否充足
  4. Reply处理不当 ⚠️ 高 - 不安全的子消息回复处理
  5. 缺失Reply ID检查 ⚠️ 中 - 未验证回复ID
  6. IBC数据包验证不当 ⚠️ 严重 - 未验证IBC数据包
  7. 未验证的Execute消息 ⚠️ 高 - 缺失消息验证
  8. 整数溢出 ⚠️ 高 - 未检查算术运算
  9. 通过子消息重入 ⚠️ 中 - 子消息发送前修改状态
有关包含代码示例的完整漏洞模式,请参阅VULNERABILITY_PATTERNS.md

5. Scanning Workflow

5. 扫描流程

Step 1: Platform Identification

步骤1:平台识别

  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
    )
  1. 识别Cosmos SDK版本(
    go.mod
  2. 定位自定义模块(
    x/*/
  3. 查找ABCI方法(
    abci.go
    , BeginBlocker, EndBlocker)
  4. 识别消息类型(
    types/msgs.go
    ,
    .proto

Step 2: Critical Path Analysis

步骤2:关键路径分析

Focus on consensus-critical code:
  • BeginBlocker / EndBlocker implementations
  • Message handlers (execute, DeliverTx)
  • Keeper methods that modify state
  • CheckTx priority logic
聚焦于共识关键代码:
  • BeginBlocker / EndBlocker实现
  • 消息处理器(execute, DeliverTx)
  • 修改状态的Keeper方法
  • CheckTx优先级逻辑

Step 3: Non-Determinism Sweep

步骤3:非确定性扫描

This is the highest priority check for Cosmos chains.
bash
undefined
这是Cosmos链的最高优先级检查。
bash
undefined

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/

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)
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/

对于每个发现:
1. 验证是否位于共识关键路径中
2. 确认是否会导致非确定性
3. 评估风险等级(链停止vs数据不一致)

Step 4: ABCI Method Analysis

步骤4:ABCI方法分析

Review BeginBlocker and EndBlocker:
  • Computational complexity bounded?
  • No unbounded iterations?
  • No nested loops over large collections?
  • Panic-prone operations validated?
  • Benchmarked with maximum state?
审查BeginBlocker和EndBlocker:
  • 计算复杂度是否受限?
  • 有无无限迭代?
  • 有无针对大型集合的嵌套循环?
  • 易引发恐慌的操作是否已验证?
  • 是否使用最大状态进行基准测试?

Step 5: Message Validation

步骤5:消息验证

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)?
对于每种消息类型:
  • GetSigners()地址是否与处理器使用的地址匹配?
  • 所有错误返回是否已检查?
  • 关键消息是否在CheckTx中设置了优先级?
  • 处理器是否已注册(或使用v0.47+自动注册)?

Step 6: Arithmetic & Bookkeeping

步骤6:算术与记账

  • sdk.Dec operations use multiply-before-divide?
  • Rounding favors protocol over users?
  • Custom bookkeeping synchronized with x/bank?
  • Invariant checks in place?

  • sdk.Dec操作是否使用先乘后除的模式?
  • 舍入是否偏向协议而非用户?
  • 自定义记账是否与x/bank同步?
  • 是否存在不变量检查?

6. Reporting Format

6. 报告格式

Finding Template

发现模板

markdown
undefined
markdown
undefined

[CRITICAL] Non-Deterministic Map Iteration in EndBlocker

[CRITICAL] EndBlocker中的非确定性Map迭代

Location:
x/dex/abci.go:45-52
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.
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)
    }
}
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
Recommendation: Sort map keys before iteration:
go
func EndBlocker(ctx sdk.Context, k keeper.Keeper) {
    rewards := k.GetPendingRewards(ctx)

    // 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

    // Process in sorted order
    for _, user := range users {
        k.bankKeeper.SendCoins(ctx, moduleAcc, user, rewards[user])
    }
}
References:
  • building-secure-contracts/not-so-smart-contracts/cosmos/non_determinism
  • Cosmos SDK docs: Determinism

---
位置
x/dex/abci.go:45-52
描述: EndBlocker遍历无序Map以分发奖励,导致不同验证者以不同顺序处理用户,生成不同的状态根。当验证者无法达成共识时,这将导致链停止。
漏洞代码:
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)
    }
}
攻击场景:
  1. 多个用户存在待领取奖励
  2. 由于Map随机化,不同验证者的迭代顺序不同
  3. 如果奖励分发在迭代中途失败,状态将出现分歧
  4. 验证者生成不同的应用哈希
  5. 链停止 - 无法达成共识
修复建议: 迭代前对Map键进行排序:
go
func EndBlocker(ctx sdk.Context, k keeper.Keeper) {
    rewards := k.GetPendingRewards(ctx)

    // 收集并排序键以实现确定性迭代
    users := make([]string, 0, len(rewards))
    for user := range rewards {
        users = append(users, user)
    }
    sort.Strings(users)  // Deterministic order

    // 按排序后的顺序处理
    for _, user := range users {
        k.bankKeeper.SendCoins(ctx, moduleAcc, user, rewards[user])
    }
}
参考资料:
  • building-secure-contracts/not-so-smart-contracts/cosmos/non_determinism
  • Cosmos SDK docs: Determinism

---

7. Priority Guidelines

7. 优先级指南

Critical - CHAIN HALT Risk

严重 - 链停止风险

  • Non-determinism (any form)
  • ABCI method panics
  • Slow ABCI methods
  • Incorrect GetSigners (allows unauthorized actions)
  • 非确定性(任何形式)
  • ABCI方法恐慌
  • 缓慢的ABCI方法
  • 错误的GetSigners(允许未授权操作)

High - Fund Loss Risk

高 - 资金损失风险

  • Missing error handling (bankKeeper.SendCoins)
  • Broken bookkeeping (accounting mismatch)
  • Missing message priority (oracle/emergency messages)
  • 缺失错误处理(bankKeeper.SendCoins)
  • 记账错误(账目不匹配)
  • 缺失消息优先级(预言机/紧急消息)

Medium - Logic/DoS Risk

中 - 逻辑/DoS风险

  • Rounding errors (protocol value leakage)
  • Unregistered message handlers (functionality broken)

  • 舍入误差(协议价值泄露)
  • 未注册的消息处理器(功能失效)

8. Testing Recommendations

8. 测试建议

Non-Determinism Testing

非确定性测试

bash
undefined
bash
undefined

Build for different architectures

针对不同架构构建

GOARCH=amd64 go build GOARCH=arm64 go build
GOARCH=amd64 go build GOARCH=arm64 go build

Run same operations, compare state roots

运行相同操作,比较状态根

Must be identical across architectures

跨架构必须完全一致

Fuzz test with concurrent operations

使用并发操作进行模糊测试

go test -fuzz=FuzzEndBlocker -parallel=10
undefined
go test -fuzz=FuzzEndBlocker -parallel=10
undefined

ABCI Benchmarking

ABCI基准测试

go
func BenchmarkBeginBlocker(b *testing.B) {
    ctx := setupMaximalState()  // Worst-case state
    b.ResetTimer()

    for i := 0; i < b.N; i++ {
        BeginBlocker(ctx, keeper)
    }

    // Must complete in < 1 second
    require.Less(b, b.Elapsed()/time.Duration(b.N), time.Second)
}
go
func BenchmarkBeginBlocker(b *testing.B) {
    ctx := setupMaximalState()  // 最坏情况状态
    b.ResetTimer()

    for i := 0; i < b.N; i++ {
        BeginBlocker(ctx, keeper)
    }

    // 必须在1秒内完成
    require.Less(b, b.Elapsed()/time.Duration(b.N), time.Second)
}

Invariant Testing

不变量测试

go
// Run invariants in integration tests
func TestInvariants(t *testing.T) {
    app := setupApp()

    // Execute operations
    app.DeliverTx(...)

    // Check invariants
    _, broken := keeper.AllInvariants()(app.Ctx)
    require.False(t, broken, "invariant violation detected")
}

go
// 在集成测试中运行不变量检查
func TestInvariants(t *testing.T) {
    app := setupApp()

    // 执行操作
    app.DeliverTx(...)

    // 检查不变量
    _, broken := keeper.AllInvariants()(app.Ctx)
    require.False(t, broken, "invariant violation detected")
}

9. Additional Resources

9. 额外资源



10. Quick Reference Checklist

10. 快速参考检查表

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
完成Cosmos链审计前:
非确定性(严重):
  • 共识代码中无Map迭代
  • 无平台相关类型(int, uint, float)
  • 消息处理器/ABCI中无goroutine
  • 无带有多个通道的select语句
  • 无rand、time.Now()、内存地址
  • 所有序列化都是确定性的
ABCI方法(严重):
  • BeginBlocker/EndBlocker计算复杂度受限
  • 无无限迭代
  • 无针对大型集合的嵌套循环
  • 所有易引发恐慌的操作已验证
  • 使用最大状态进行基准测试
消息处理(高):
  • GetSigners()与处理器地址使用匹配
  • 所有错误返回已检查
  • 关键消息在CheckTx中设置了优先级
  • 所有消息类型已注册
算术与记账(中):
  • 使用先乘后除的模式
  • 舍入偏向协议
  • 自定义记账与x/bank同步
  • 已实现不变量检查
测试:
  • 已测试跨架构构建
  • 已对ABCI方法进行基准测试
  • CI中已检查不变量
  • 集成测试覆盖所有消息