smart-contract-security
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSmart Contract Security Skill
智能合约安全Skill
Master smart contract security with vulnerability detection, auditing methodology, and incident response procedures.
通过漏洞检测、审计方法论和事件响应流程掌握智能合约安全。
Quick Start
快速开始
python
undefinedpython
undefinedInvoke this skill for security analysis
调用此Skill进行安全分析
Skill("smart-contract-security", topic="vulnerabilities", severity="high")
undefinedSkill("smart-contract-security", topic="vulnerabilities", severity="high")
undefinedTopics 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
undefinedbash
undefinedSlither - 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" .
undefinedsemgrep --config "p/smart-contracts" .
undefinedFuzzing
模糊测试
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
严重程度分类
| Severity | Impact | Examples |
|---|---|---|
| Critical | Direct fund loss | Reentrancy, unprotected init |
| High | Significant damage | Access control, oracle manipulation |
| Medium | Conditional impact | Precision loss, timing issues |
| Low | Minor issues | Missing events, naming |
| 严重程度 | 影响 | 示例 |
|---|---|---|
| 关键 | 直接资金损失 | 重入漏洞、未受保护的初始化 |
| 高 | 重大损害 | 访问控制缺失、预言机操纵 |
| 中 | 有条件影响 | 精度丢失、时间相关问题 |
| 低 | 轻微问题 | 缺失事件、命名不规范 |
Incident Response
事件响应
1. Detection
1. 检测
bash
undefinedbash
undefinedMonitor for suspicious activity
监控可疑活动
cast logs --address $CONTRACT --from-block latest
undefinedcast logs --address $CONTRACT --from-block latest
undefined2. 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
常见陷阱
| Pitfall | Risk | Prevention |
|---|---|---|
| Only testing happy path | Missing edge cases | Fuzz test boundaries |
| Ignoring integrations | External call risks | Review all dependencies |
| Trusting block.timestamp | Miner manipulation | Use for long timeframes only |
| 陷阱 | 风险 | 预防措施 |
|---|---|---|
| 仅测试正常流程 | 遗漏边缘情况 | 对边界进行模糊测试 |
| 忽略集成风险 | 外部调用风险 | 审查所有依赖项 |
| 信任block.timestamp | 矿工操纵 | 仅用于长时间段场景 |
Cross-References
交叉引用
- Bonded Agent:
06-smart-contract-security - Related Skills: ,
solidity-developmentdefi-protocols
- Bonded Agent:
06-smart-contract-security - 相关Skills:,
solidity-developmentdefi-protocols
Resources
资源
- SWC Registry: Common weakness enumeration
- Rekt News: Hack post-mortems
- Immunefi: Bug bounties
- SWC Registry:常见弱点枚举
- Rekt News:黑客攻击事后分析
- Immunefi:漏洞赏金平台
Version History
版本历史
| Version | Date | Changes |
|---|---|---|
| 2.0.0 | 2025-01 | Production-grade with tools, methodology |
| 1.0.0 | 2024-12 | Initial release |
| 版本 | 日期 | 变更 |
|---|---|---|
| 2.0.0 | 2025-01 | 生产级版本,包含工具、方法论 |
| 1.0.0 | 2024-12 | 初始版本 |