ZhenRobotics/openclaw-smart-contract-auditor

GitHub: ZhenRobotics/openclaw-smart-contract-auditor

一款 AI 驱动的 Solidity 智能合约安全审计工具,可在部署前自动检测常见漏洞并提供 Gas 优化建议与专业审计报告。

Stars: 0 | Forks: 0

# 智能合约审计器 - 区块链 AI 安全分析师 **版本:** 0.1.0 | **状态:** MVP 就绪 | **许可证:** MIT ## 什么是智能合约审计器? 智能合约审计器是一款 AI 驱动的安全工具,可自动分析 Solidity 智能合约中的漏洞,提供 gas 优化建议,并生成全面的审计报告。它是您将合约部署到区块链之前的第一道防线。 ### 核心功能 - **漏洞检测** - 自动检测 3 种以上的严重漏洞类型(即将推出更多) - **Gas 优化** - 识别降低部署和执行成本的机会 - **最佳实践** - 检查安全模式和代码质量 - **专业报告** - 生成详细的 Markdown 和 JSON 审计报告 - **教育性** - 为每个问题提供详细的解释和修复建议 ## 快速开始 ### 安装 ``` # 克隆 repository git clone https://github.com/ZhenRobotics/openclaw-smart-contract-auditor.git cd openclaw-smart-contract-auditor # 安装 dependencies pip install -r requirements.txt ``` ### 基本用法 #### 1. 快速测试(现在就试试吧!) ``` # 审计示例 vulnerable contract python3 examples/basic_audit.py ``` **预期输出:** ``` Contract: VulnerableBank Security Score: 60/100 (D) Issues Found: 3 [C-01] 🔴 Reentrancy vulnerability [H-01] 🟠 Missing access control [H-02] 🟠 Unchecked low-level call Reports generated in: audit_reports/ ``` #### 2. 审计您的合约 ``` import asyncio from sc_auditor import SmartContractAuditor async def audit_my_contract(): # Initialize auditor auditor = SmartContractAuditor() # Run full audit result = await auditor.full_audit( contract_path="path/to/your/contract.sol", output_dir="audit_reports/" ) # Check results print(f"Security Score: {result.security_score.overall}/100") print(f"Grade: {result.security_score.grade}") print(f"Total Issues: {len(result.vulnerabilities)}") # Print vulnerabilities for vuln in result.vulnerabilities: print(f" [{vuln.id}] {vuln.severity_emoji} {vuln.title}") asyncio.run(audit_my_contract()) ``` ## 功能 ### 1. 漏洞检测 目前可检测: #### 🔴 严重漏洞 - **重入攻击** - 违反 CEI 模式,在状态更改前进行外部调用 #### 🟠 高危 - **访问控制问题** - 敏感函数缺少权限检查 - **未检查的低级调用** - 忽略了 call/send/delegatecall 的返回值 #### 即将推出(阶段 2) - 整数溢出/下溢 - DoS Gas Limit 攻击 - 时间戳依赖 - 弱随机性 - 抢跑漏洞 - tx.origin 身份验证 - 未初始化的 Storage - 以及 20 多种其他模式 ### 2. Gas 优化分析 识别节省 gas 的机会: - **存储打包** - 优化变量排序以减少存储槽 - **循环优化** - 缓存数组长度,使用前置递增 - **函数可见性** - 尽可能使用 `external` 而不是 `public` - **常量/不可变** - 使用合适的变量修饰符 **节省示例:** ``` Storage Packing: ~20,000 gas per transaction Loop Optimization: ~100 gas per iteration Function Visibility: ~200 gas per call ``` ### 3. 专业审计报告 生成两种类型的报告: #### Markdown 报告 (.md) - 人类可读格式 - 包含安全评分的执行摘要 - 详细的漏洞描述 - 代码片段(修复前/后) - 带有示例的修复建议 - 外部参考(SWC, CWE) #### JSON 报告 (.json) - 机器可读格式 - 结构化的漏洞数据 - 可用于 CI/CD 集成 - 以编程方式访问结果 ## 报告示例 ### 执行摘要 ``` # Smart Contract Security Audit Report Contract: VulnerableBank Security Score: 60.0/100 🔴 Grade D Status: ⚠️ REQUIRES FIXES Total Issues Found: 3 - 🔴 Critical: 1 - 🟠 High: 2 - 🟡 Medium: 0 - 🟢 Low: 0 ``` ### 详细发现 ``` ### [C-01] withdraw() 中的 Reentrancy vulnerability **Severity**: 🔴 CRITICAL **Type**: reentrancy **Location**: vulnerable_bank.sol:31-38 **Description**: The function 'withdraw' makes an external call before updating state variables. This violates the Checks-Effects-Interactions (CEI) pattern. **Impact**: An attacker could drain the contract by repeatedly calling this function before the state is updated, potentially stealing all funds. **Recommendation**: 1. Follow the CEI pattern: update state before external calls 2. Use OpenZeppelin's ReentrancyGuard modifier 3. Consider using transfer() instead of call() **Fix Example**: Before (Vulnerable): ```solidity function withdraw() public { uint amount = balances[msg.sender]; msg.sender.call{value: amount}(""); // External call first ❌ balances[msg.sender] = 0; // State change after ❌ } ``` 修复后: ``` function withdraw() public { uint amount = balances[msg.sender]; balances[msg.sender] = 0; // State change first ✅ msg.sender.call{value: amount}(""); // External call after ✅ } ``` **参考:** - SWC-107: https://swcregistry.io/docs/SWC-107 - The DAO 被黑事件:因重入攻击损失 6000 万美元 ``` --- ## Use Cases ### 面向 Developers - **Pre-deployment Security Check** - Catch vulnerabilities before mainnet - **Learning Tool** - Understand common security pitfalls - **Code Review** - Get automated feedback on contract security - **Gas Optimization** - Reduce deployment and execution costs ### 面向 Auditors - **Initial Screening** - Quick automated scan before manual review - **Efficiency Tool** - Focus manual efforts on complex logic - **Report Generation** - Professional documentation ### 面向 Educators - **Teaching Security** - Demonstrate vulnerability patterns - **Student Projects** - Automated grading for security - **CTF Challenges** - Create and verify vulnerable contracts --- ## Security Score Guide | Score | Grade | Status | Description | |-------|-------|--------|-------------| | 95-100 | A+ | ✅ Excellent | Outstanding security, minor suggestions | | 85-94 | A | ✅ Very Good | Strong security foundation | | 75-84 | B | ⚠️ Good | Few issues, review recommended | | 65-74 | C | ⚠️ Acceptable | Several issues to address | | 50-64 | D | 🔴 Poor | Significant concerns, fix required | | 0-49 | F | 🔴 Critical | CRITICAL issues, DO NOT deploy | --- ## Project Structure ``` openclaw-smart-contract-auditor/ ├── sc_auditor/ # 主包 │ ├── auditor.py # SmartContractAuditor 类 │ ├── types/ # 数据模型 │ │ ├── contract.py # 合约表示 │ │ ├── vulnerability.py # 漏洞类型 │ │ └── audit_result.py # 审计结果 │ ├── detectors/ # 漏洞检测器 │ │ ├── reentrancy.py # 重入检测器 │ │ ├── access_control.py # 访问控制检测器 │ │ └── unchecked_calls.py # 未检查调用检测器 │ ├── analyzers/ # 分析引擎 │ │ └── gas_analyzer.py # Gas 优化 │ ├── parsers/ # Solidity 解析器 │ │ └── solidity_parser.py │ └── modules/ # 报告生成 │ ├── best_practices/ │ └── report_generation/ ├── examples/ # 用法示例 │ ├── vulnerable_bank.sol # 测试合约(存在漏洞) │ └── basic_audit.py # Python 示例 ├── audit_reports/ # 生成的报告 ├── SKILL.md # OpenClaw 技能定义 └── README.md # 本文件 ``` --- ## API 参考 ### SmartContractAuditor ```python class SmartContractAuditor: """Main auditor class""" def __init__( self, use_slither: bool = False, use_mythril: bool = False, solc_version: Optional[str] = None, verbose: bool = False ): """Initialize auditor with optional tools""" async def full_audit( self, contract_path: str | Path, output_dir: Optional[str | Path] = None, generate_pdf: bool = False, generate_json: bool = True ) -> AuditResult: """ Perform complete security audit Returns: AuditResult with vulnerabilities, gas report, and scores """ async def quick_scan( self, contract_path: str | Path ) -> SecurityScore: """Quick security scan (vulnerabilities only)""" async def gas_audit( self, contract_path: str | Path ) -> GasReport: """Gas optimization analysis only""" ``` ## 限制与免责声明 ### 本工具的功能 ✅ - 检测常见的漏洞模式 - 提供 gas 优化建议 - 检查最佳实践 - 生成专业报告 ### 本工具无法做到的事项 ❌ - 替代专业的手动审计 - 保证绝对安全 - 检测出所有可能的漏洞 - 验证业务逻辑 - 确保智能合约的功能性 ### 重要提示 ⚠️ **这是自动化分析,不能替代专业的审计** 对于生产环境的合约,尤其是涉及高价值的合约: 1. ✅ 使用此工具作为初步检查 2. ✅ 进行全面的测试 3. ✅ 获取专业的手动审计 4. ✅ 运行漏洞赏金计划 5. ✅ 实施监控 6. ✅ 制定应急响应计划 **安全是一个持续的过程,而不是一次性的检查。** ## 路线图 ### 版本 0.1.0(当前)✅ - [x] 3 个核心漏洞检测器 - [x] Gas 优化分析 - [x] 最佳实践检查器 - [x] Markdown/JSON 报告生成 - [x] 教育性解释 ### 版本 0.2.0(阶段 2 - 2026 年第二季度) - [ ] 15+ 个漏洞检测器 - [ ] Slither 集成 - [ ] CLI 工具(`sc-audit` 命令) - [ ] 批处理 - [ ] Web UI (Streamlit) ### 版本 0.3.0(阶段 3 - 2026 年第三季度) - [ ] Mythril 符号执行 - [ ] CI/CD 集成 - [ ] 多文件项目支持 - [ ] 自定义检测器插件 - [ ] 已知漏洞数据库 ### 版本 1.0.0(2026 年第四季度) - [ ] 专业级准确度 - [ ] 实时监控 - [ ] 团队协作功能 - [ ] 高级审计服务集成 ### 添加新检测器 ``` from sc_auditor.detectors.base import BaseDetector from sc_auditor.types import Vulnerability, VulnerabilityType, Severity class MyDetector(BaseDetector): @property def vulnerability_type(self) -> VulnerabilityType: return VulnerabilityType.MY_TYPE @property def severity(self) -> Severity: return Severity.HIGH async def detect(self, contract: Contract) -> List[Vulnerability]: vulnerabilities = [] # Your detection logic here return vulnerabilities ``` ## 测试 ``` # 运行示例 audit python3 examples/basic_audit.py # 预期:检测出 vulnerable_bank.sol 中的 3 个 vulnerabilities # 审计你的 own contract python3 -c " import asyncio from sc_auditor import SmartContractAuditor async def test(): auditor = SmartContractAuditor() result = await auditor.full_audit('your_contract.sol') print(f'Score: {result.security_score.overall}/100') asyncio.run(test()) " ``` ## 许可证 MIT 许可证 - 详情请参阅 [LICENSE](LICENSE) ## 致谢 ### 参考 - [智能合约弱点分类 (SWC)](https://swcregistry.io/) - [以太坊智能合约最佳实践](https://consensys.github.io/smart-contract-best-practices/) - [Solidity 安全考量](https://docs.soliditylang.org/en/latest/security-considerations.html) - [OpenZeppelin 合约](https://docs.openzeppelin.com/contracts/) *让每个人都能用上智能合约安全* ## 快速链接 - 📖 [入门指南](GETTING_STARTED.md) - 🎯 [转型计划](TRANSFORMATION_PLAN.md) - ✅ [MVP 状态](MVP_STATUS.md) - 🎉 [项目完成总结](PROJECT_COMPLETE.md) - 🔧 [技能定义](SKILL.md)
标签:Solidity, 人工智能, 区块链安全, 域名收集, 提示词注入, 智能合约审计, 用户模式Hook绕过, 逆向工具, 配置审计