smart-contract-security

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Smart Contract Security Skill

智能合约安全Skill

Master smart contract security with vulnerability detection, auditing methodology, and incident response procedures.
通过漏洞检测、审计方法论和事件响应流程掌握智能合约安全。

Quick Start

快速开始

python
undefined
python
undefined

Invoke this skill for security analysis

调用此Skill进行安全分析

Skill("smart-contract-security", topic="vulnerabilities", severity="high")
undefined
Skill("smart-contract-security", topic="vulnerabilities", severity="high")
undefined

Topics Covered

涵盖主题

1. Common Vulnerabilities

1. 常见漏洞

Recognize and prevent:
  • Reentrancy: CEI pattern violation
  • Access Control: Missing modifiers
  • Oracle Manipulation: Flash loan attacks
  • Integer Issues: Precision loss
识别并预防:
  • Reentrancy(重入):CEI模式违规
  • Access Control(访问控制):缺失修饰器
  • Oracle Manipulation(预言机操纵):闪电贷攻击
  • Integer Issues(整数问题):精度丢失

2. Auditing Methodology

2. 审计方法论

Systematic review process:
  • Manual Review: Line-by-line analysis
  • Static Analysis: Automated tools
  • Fuzzing: Property-based testing
  • Formal Verification: Mathematical proofs
系统化审查流程:
  • Manual Review(人工审查):逐行分析
  • Static Analysis(静态分析):自动化工具
  • Fuzzing(模糊测试):基于属性的测试
  • Formal Verification(形式化验证):数学证明

3. Security Tools

3. 安全工具

Essential tooling:
  • Slither: Fast static analysis
  • Mythril: Symbolic execution
  • Foundry: Fuzzing, invariants
  • Certora: Formal verification
必备工具:
  • Slither:快速静态分析工具
  • Mythril:符号执行工具
  • Foundry:模糊测试、不变量验证
  • Certora:形式化验证工具

4. Incident Response

4. 事件响应

Handle security events:
  • Triage: Assess severity
  • Mitigation: Emergency actions
  • Post-mortem: Root cause analysis
  • Disclosure: Responsible reporting
处理安全事件:
  • Triage(分类处理):评估严重程度
  • Mitigation(缓解措施):紧急行动
  • Post-mortem(事后分析):根本原因分析
  • Disclosure(披露):负责任的报告

Vulnerability Quick Reference

漏洞速查

Critical: Reentrancy

严重:重入

solidity
// VULNERABLE
function withdraw(uint256 amount) external {
    (bool ok,) = msg.sender.call{value: amount}("");
    require(ok);
    balances[msg.sender] -= amount;  // After call!
}

// FIXED: CEI Pattern
function withdraw(uint256 amount) external {
    balances[msg.sender] -= amount;  // Before call
    (bool ok,) = msg.sender.call{value: amount}("");
    require(ok);
}
solidity
// 存在漏洞
function withdraw(uint256 amount) external {
    (bool ok,) = msg.sender.call{value: amount}("");
    require(ok);
    balances[msg.sender] -= amount;  // 调用后执行!
}

// 修复方案:CEI模式
function withdraw(uint256 amount) external {
    balances[msg.sender] -= amount;  // 调用前执行
    (bool ok,) = msg.sender.call{value: amount}("");
    require(ok);
}

High: Missing Access Control

高风险:缺失访问控制

solidity
// VULNERABLE
function setAdmin(address newAdmin) external {
    admin = newAdmin;  // Anyone can call!
}

// FIXED
function setAdmin(address newAdmin) external onlyOwner {
    admin = newAdmin;
}
solidity
// 存在漏洞
function setAdmin(address newAdmin) external {
    admin = newAdmin;  // 任何人都可调用!
}

// 修复方案
function setAdmin(address newAdmin) external onlyOwner {
    admin = newAdmin;
}

High: Unchecked Return Value

高风险:未检查返回值

solidity
// VULNERABLE
IERC20(token).transfer(to, amount);  // Ignored!

// FIXED: Use SafeERC20
using SafeERC20 for IERC20;
IERC20(token).safeTransfer(to, amount);
solidity
// 存在漏洞
IERC20(token).transfer(to, amount);  // 忽略返回值!

// 修复方案:使用SafeERC20
using SafeERC20 for IERC20;
IERC20(token).safeTransfer(to, amount);

Medium: Precision Loss

中风险:精度丢失

solidity
// VULNERABLE: Division before multiplication
uint256 fee = (amount / 1000) * rate;

// FIXED: Multiply first
uint256 fee = (amount * rate) / 1000;
solidity
// 存在漏洞:先除法后乘法
uint256 fee = (amount / 1000) * rate;

// 修复方案:先乘法后除法
uint256 fee = (amount * rate) / 1000;

Audit Checklist

审计检查清单

Pre-Audit

审计前

  • Code compiles without warnings
  • Tests pass with good coverage
  • Documentation reviewed
  • 代码编译无警告
  • 测试通过且覆盖率良好
  • 文档已审查

Core Security

核心安全

  • CEI pattern followed
  • Reentrancy guards present
  • Access control on admin functions
  • Input validation complete
  • 遵循CEI模式
  • 存在重入防护
  • 管理员函数有访问控制
  • 输入验证完整

DeFi Specific

DeFi专项

  • Oracle staleness checks
  • Slippage protection
  • Flash loan resistance
  • Sandwich prevention
  • 预言机时效性检查
  • 滑点保护
  • 抗闪电贷攻击
  • 防三明治攻击

Security Tools

安全工具

Static Analysis

静态分析

bash
undefined
bash
undefined

Slither - Fast vulnerability detection

Slither - 快速漏洞检测

slither . --exclude-dependencies
slither . --exclude-dependencies

Mythril - Symbolic execution

Mythril - 符号执行

myth analyze src/Contract.sol
myth analyze src/Contract.sol

Semgrep - Custom rules

Semgrep - 自定义规则

semgrep --config "p/smart-contracts" .
undefined
semgrep --config "p/smart-contracts" .
undefined

Fuzzing

模糊测试

solidity
// Foundry fuzz test
function testFuzz_Withdraw(uint256 amount) public {
    amount = bound(amount, 1, type(uint128).max);

    vm.deal(address(vault), amount);
    vault.deposit{value: amount}();

    uint256 before = address(this).balance;
    vault.withdraw(amount);

    assertEq(address(this).balance, before + amount);
}
solidity
// Foundry模糊测试
function testFuzz_Withdraw(uint256 amount) public {
    amount = bound(amount, 1, type(uint128).max);

    vm.deal(address(vault), amount);
    vault.deposit{value: amount}();

    uint256 before = address(this).balance;
    vault.withdraw(amount);

    assertEq(address(this).balance, before + amount);
}

Invariant Testing

不变量测试

solidity
function invariant_BalancesMatchTotalSupply() public {
    uint256 sum = 0;
    for (uint i = 0; i < actors.length; i++) {
        sum += token.balanceOf(actors[i]);
    }
    assertEq(token.totalSupply(), sum);
}
solidity
function invariant_BalancesMatchTotalSupply() public {
    uint256 sum = 0;
    for (uint i = 0; i < actors.length; i++) {
        sum += token.balanceOf(actors[i]);
    }
    assertEq(token.totalSupply(), sum);
}

Severity Classification

严重程度分类

SeverityImpactExamples
CriticalDirect fund lossReentrancy, unprotected init
HighSignificant damageAccess control, oracle manipulation
MediumConditional impactPrecision loss, timing issues
LowMinor issuesMissing events, naming
严重程度影响示例
关键直接资金损失重入漏洞、未受保护的初始化
重大损害访问控制缺失、预言机操纵
有条件影响精度丢失、时间相关问题
轻微问题缺失事件、命名不规范

Incident Response

事件响应

1. Detection

1. 检测

bash
undefined
bash
undefined

Monitor for suspicious activity

监控可疑活动

cast logs --address $CONTRACT --from-block latest
undefined
cast logs --address $CONTRACT --from-block latest
undefined

2. Mitigation

2. 缓解

solidity
// Emergency pause
function pause() external onlyOwner {
    _pause();
}
solidity
// 紧急暂停
function pause() external onlyOwner {
    _pause();
}

3. Recovery

3. 恢复

  • Assess damage scope
  • Coordinate disclosure
  • Deploy fixes with audit
  • 评估损害范围
  • 协调披露事宜
  • 部署经过审计的修复方案

Common Pitfalls

常见陷阱

PitfallRiskPrevention
Only testing happy pathMissing edge casesFuzz test boundaries
Ignoring integrationsExternal call risksReview all dependencies
Trusting block.timestampMiner manipulationUse for long timeframes only
陷阱风险预防措施
仅测试正常流程遗漏边缘情况对边界进行模糊测试
忽略集成风险外部调用风险审查所有依赖项
信任block.timestamp矿工操纵仅用于长时间段场景

Cross-References

交叉引用

  • Bonded Agent:
    06-smart-contract-security
  • Related Skills:
    solidity-development
    ,
    defi-protocols
  • Bonded Agent
    06-smart-contract-security
  • 相关Skills
    solidity-development
    ,
    defi-protocols

Resources

资源

  • SWC Registry: Common weakness enumeration
  • Rekt News: Hack post-mortems
  • Immunefi: Bug bounties
  • SWC Registry:常见弱点枚举
  • Rekt News:黑客攻击事后分析
  • Immunefi:漏洞赏金平台

Version History

版本历史

VersionDateChanges
2.0.02025-01Production-grade with tools, methodology
1.0.02024-12Initial release
版本日期变更
2.0.02025-01生产级版本,包含工具、方法论
1.0.02024-12初始版本