baties/Smart-Contract-Security
GitHub: baties/Smart-Contract-Security
这是一个基于CrewAI多代理系统的智能合约安全审计工具,能够通过对抗性推理自动化检测Solidity合约漏洞并生成攻击场景报告。
Stars: 0 | Forks: 0
# SolidityGuard AI 🛡️
**AI 驱动的智能合约安全审计工具**
一个复杂的多代理 AI 系统,利用对抗性推理、静态分析模拟和攻击场景建模对 Solidity 智能合约执行全面的安全审计。
## 📊 状态与徽章
[](https://opensource.org/licenses/MIT)
[](https://www.python.org/downloads/release/python-310/)
[](https://github.com/joaomdmoura/crewai)
[](https://github.com/psf/black)


**GitHub Activity:**
[](https://github.com/yourusername/smartcontract_security_crewai)
[](https://github.com/yourusername/smartcontract_security_crewai/issues)
[](https://github.com/yourusername/smartcontract_security_crewai/network/members)
[](https://github.com/yourusername/smartcontract_security_crewai/commits/master)
## 📋 概述
**SolidityGuard AI** 是一个由 [CrewAI](https://github.com/joaomdmoura/crewai) 驱动的开源智能合约安全审计框架。它部署了一个包含 6 个代理的顺序流水线,从多个维度分析 Solidity 合约的漏洞:
🔄 **重入 与 MEV 攻击**
🔐 **访问控制缺陷**
🧮 **算术漏洞** (溢出/下溢)
⚙️ **逻辑错误与状态不一致**
💰 **经济激励攻击**
🚫 **拒绝服务 向量**
每个代理专门负责审计的不同阶段,沿着流水线传递上下文,以生成包含已确认发现、攻击场景和修复建议的**专业 Markdown 审计报告**。
## ✨ 主要特性
- 🤖 **6 代理流水线**:合约规划器 → 静态分析 → 漏洞猎手 → 漏洞利用编写者 → 验证 → 报告撰写者
- ⚔️ **对抗性分析**:AI 代理从对手的角度推理攻击
- 🎯 **无手动工具依赖**:不需要 Slither、4naly3er 或其他 CLI 工具——AI 模拟静态分析发现
- 🔨 **攻击场景建模**:包含交易序列的完整概念验证 攻击场景
- ✅ **风险验证层**:独立验证代理在最终报告前挑战发现
- 📄 **Markdown 报告**:即发布格式的 Markdown 审计报告
- 🎓 **教育与生产就绪**:内置用于测试的易受攻击示例合约;支持自定义审计
- 🔌 **API 优先设计**:基于 CrewAI 框架构建——易于扩展和嵌入
## 🚀 快速开始
### ⚙️ 安装
**前置条件:**
- 🐍 Python 3.10 或更高版本
- 📦 pip 或 uv 包管理器
**克隆与安装:**
```
git clone https://github.com/yourusername/smartcontract_security_crewai.git
cd smartcontract_security_crewai-project/sc_security
# 使用 UV (推荐)
uv sync
# 或使用 pip
pip install -e ".[dev]"
```
**🔑 设置 API 密钥:**
在 `sc_security/` 目录下创建 `.env` 文件:
```
# 必需:OpenAI API key 用于 Claude/GPT 模型
OPENAI_API_KEY=sk-proj-YOUR-KEY-HERE
# 可选:Serper API key 用于网络搜索(由 agents 使用)
SERPER_API_KEY=your-serper-key-here
# 可选:LLM 模型选择(默认为 gpt-4o-mini)
MODEL=gpt-4o-mini
```
### 💻 使用
**审计合约:**
```
# 审计内置的漏洞示例合约
sc_security
# 审计您自己的合约
sc_security path/to/YourContract.sol
```
**📋 输出:**
- `audit_report.md` — 完整的审计报告,包含所有发现和建议
## 🏗️ 架构
### 代理流水线
审计遵循一个**顺序 6 阶段流水线**:
```
┌─────────────────────────────────────────────────────────────────────┐
│ 1. CONTRACT PLANNER │
│ ↳ Read contract code │
│ ↳ Produce comprehensive audit plan (functions, state, risks) │
└─────────────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────────────┐
│ 2. STATIC ANALYSIS AGENT │
│ ↳ Simulate Slither/4naly3er findings │
│ ↳ Classify: GENUINE | FALSE_POSITIVE | NEEDS_DEEPER │
│ ↳ Identify gaps static tools cannot catch │
└─────────────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────────────┐
│ 3. VULNERABILITY HUNTER │
│ ↳ Adversarial deep-dive on 6 attack categories │
│ ↳ Find exploitable issues (not false positives) │
│ ↳ Rank by severity (Critical → Low) │
└─────────────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────────────┐
│ 4. EXPLOIT CRAFTER │
│ ↳ Model complete attack scenarios for each finding │
│ ↳ Transaction sequences, attacker profiles, PoC pseudocode │
│ ↳ Financial impact estimates │
└─────────────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────────────┐
│ 5. VERIFICATION AGENT │
│ ↳ Challenge every finding with skeptical reasoning │
│ ↳ Verify attack paths are actually exploitable │
│ ↳ Eliminate false positives, downgrade uncertain findings │
└─────────────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────────────┐
│ 6. REPORT WRITER │
│ ↳ Synthesize all findings into professional markdown report │
│ ↳ Executive summary, risk tables, recommendations │
│ ↳ Output: audit_report.md │
└─────────────────────────────────────────────────────────────────────┘
```
### 漏洞类别
系统通过 **6 个主要攻击向量** 分析合约:
1. 🔁 **重入** —— 违反 Checks-Effects-Interactions 模式的外部调用
2. 🔓 **访问控制** —— 缺失或可绕过的权限检查
3. 🔢 **算术** —— 溢出、下溢、除以零
4. ⚡ **逻辑错误** —— 错误的状态更新、不变量 破坏、边界情况
5. 💸 **经济/激励** —— 闪电贷 向量、MEV、三明治攻击、资金耗尽
6. 🚫 **拒绝服务** —— 永久性阻止提款、Gas 破坏、无限循环
## 📖 使用示例
### 📝 示例 1:审计内置示例合约
```
cd sc_security
sc_security
```
这会对 **VulnerableVault** 示例合约(为了演示故意设为易受攻击)运行完整审计。输出:
```
============================================================
SolidityGuard AI — Smart Contract Security Audit
6-Agent CrewAI Pipeline
============================================================
[Contract Planner] Analyzing contract structure...
[Static Analysis Agent] Simulating tool findings...
[Vulnerability Hunter] Searching for exploitable issues...
[Exploit Crafter] Modeling attack scenarios...
[Verification Agent] Challenging findings...
[Report Writer] Generating final report...
[SolidityGuard] Audit complete. Report saved to: audit_report.md
```
### 📂 示例 2:审计自定义合约
```
# 单个合约
sc_security /path/to/MyToken.sol
# 结果:包含针对 MyToken 的具体发现的 audit_report.md
```
### 🐍 示例 3:编程式使用
```
from sc_security.crew import ScSecurity
# 以编程方式审计合约
contract_code = open("MyContract.sol").read()
inputs = {"contract_code": contract_code}
crew = ScSecurity().crew()
result = crew.kickoff(inputs=inputs)
print(result) # Full audit output
```
## ⚙️ 配置
### 🔑 环境变量
| 变量 | 必需 | 默认值 | 用途 |
|----------|:--------:|---------|---------|
| `OPENAI_API_KEY` | ✅ 是 | — | 用于访问 LLM 的 OpenAI API 密钥 |
| `MODEL` | ❌ 否 | `gpt-4o-mini` | 使用的 LLM 模型 |
| `SERPER_API_KEY` | ❌ 否 | — | Web 搜索 API (可选) |
### 📋 代理与任务配置
代理和任务在 YAML 配置文件中定义:
- **`src/sc_security/config/agents.yaml`** —— 代理个性、角色、目标
- **`src/sc_security/config/tasks.yaml`** —— 任务描述、预期输出、上下文链
修改这些文件以自定义代理行为、提示词或输出预期。
### 🐍 Python 配置
主入口点:`src/sc_security/main.py`
```
def run():
"""Run the audit crew."""
contract_path = sys.argv[1] if len(sys.argv) > 1 else None
contract_code = _load_contract(contract_path)
inputs = {"contract_code": contract_code}
ScSecurity().crew().kickoff(inputs=inputs)
```
## 📦 项目结构
```
smartcontract_security_crewai-project/
├── README.md # This file
├── sc_security/ # Main Python package
│ ├── pyproject.toml # Project metadata & dependencies
│ ├── uv.lock # UV lock file
│ ├── .env # API keys (git-ignored)
│ ├── src/sc_security/
│ │ ├── main.py # CLI entry point
│ │ ├── crew.py # CrewAI crew definition
│ │ ├── config/
│ │ │ ├── agents.yaml # Agent configurations
│ │ │ └── tasks.yaml # Task configurations
│ │ ├── tools/
│ │ │ ├── __init__.py
│ │ │ └── custom_tool.py # Custom agent tools
│ │ └── knowledge/
│ │ └── user_preference.txt # Domain knowledge (optional)
│ └── .venv/ # Virtual environment
└── .gitignore # Git ignore configuration
```
## 🧠 工作原理
### VulnerableVault 示例
该项目包含一个**内置演示合约**,其中有 3 个故意设置的漏洞:
```
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract VulnerableVault {
mapping(address => uint256) public balances;
// VULN-001: Reentrancy
function withdraw(uint256 amount) external {
require(balances[msg.sender] >= amount);
(bool success, ) = msg.sender.call{value: amount}("");
require(success);
balances[msg.sender] -= amount; // State update AFTER call
}
// VULN-002: Missing access control
function setPaused(bool _paused) external {
paused = _paused; // No msg.sender check!
}
// VULN-003: State inconsistency
function emergencyWithdraw() external {
payable(owner).transfer(address(this).balance);
// Drains contract but leaves user balances untouched
}
}
```
当被审计时,系统检测到:
1. **withdraw() 中的重入** —— 状态更新前的外部调用
2. **setPaused() 中的访问控制绕过** —— 任何地址都可以暂停
3. **emergencyWithdraw() 中的状态不匹配** —— 合约资金被耗尽但余额保持不变
## 🛠️ CLI 命令
| 命令 | 用途 |
|---------|---------|
| `sc_security` | 🎯 审计内置示例合约 |
| `sc_security ` | 📁 审计自定义合约文件 |
| `run_crew` | ▶️ `sc_security` 的别名 |
| `train ` | 🧠 在示例合约上训练 crew |
| `replay ` | 🔄 重放之前执行中的特定任务 |
| `test ` | ✅ 测试 crew 性能 |
| `run_with_trigger` | ⚡ 带事件触发运行 |
## 🧪 测试与开发
### ✅ 运行测试
```
cd sc_security
python -m pytest
```
### 🧠 训练 Crew (优化提示词)
```
sc_security train 3 training_results.json
```
训练 crew 3 次迭代并保存结果以优化提示词。
### 🔄 重放任务执行
```
sc_security replay
```
使用保存的上下文从之前的执行中重新运行特定任务。
## 📋 报告输出格式
**示例:audit_report.md**
```
---
# SMART CONTRACT SECURITY AUDIT REPORT
**Contract:** VulnerableVault
**Audit Date:** 2025-12-15
**Audited By:** SolidityGuard AI — Multi-Agent Audit Team
## EXECUTIVE SUMMARY
The VulnerableVault contract contains 3 confirmed critical vulnerabilities that allow fund theft via reentrancy, unauthorized pause, and state inconsistency attacks.
## RISK OVERVIEW
| Severity | Count |
|----------|-------|
| Critical | 3 |
| High | 0 |
| Medium | 0 |
| Low | 0 |
## FINDINGS
### VULN-001: Reentrancy in withdraw()
**Severity:** Critical | **Category:** Reentrancy | **Affected Function:** `withdraw()`
#### 描述
The withdraw() function performs an external call before updating the balance state, violating the Checks-Effects-Interactions pattern...
#### 影响
An attacker can drain the entire vault by recursively calling withdraw() through a malicious contract's receive() function.
#### 概念验证
1. Deploy AttackerContract with receive() that calls VulnerableVault.withdraw()
2. Call vault.deposit() with 1 ETH
3. Call vault.withdraw(1 ether)
4. receive() triggers instantly, calls withdraw() again
5. Repeat until vault empty
#### 建议
Move the balance update BEFORE the external call:
```solidity
function withdraw(uint256 amount) external {
require(balances[msg.sender] >= amount);
balances[msg.sender] -= amount; // Update state FIRST
(bool success, ) = msg.sender.call{value: amount}("");
require(success);
}
```
...
```
---
## 🤝 贡献
Contributions are welcome! Areas for enhancement:
- [ ] 🔹 Add support for Vyper contracts
- [ ] 🔌 Integrate real Slither/4naly3er tool calls
- [ ] ⛽ Add gas optimization analysis
- [ ] 📂 Support for multi-file audits
- [ ] 🎨 Web UI for report visualization
- [ ] 🎯 Custom agent templates for specific protocols (AMM, lending, etc.)
### 📋 贡献指南
1. **Fork the repository** 🍴
2. **Create a feature branch** (`git checkout -b feature/amazing-feature`) 🌳
3. **Make your changes** with clear commit messages 📝
4. **Write tests** for new functionality 🧪
5. **Submit a pull request** with description of changes 🚀
---
## 📄 许可证
This project is licensed under the **MIT License** – see [LICENSE](LICENSE) file for details.
You are free to use, modify, and distribute this software, with appropriate attribution.
---
## ⚠️ 免责声明与限制
### ❌ 重要:AI 生成的报告需要人工审查
**SolidityGuard AI** is an experimental AI-powered analysis tool. **This is NOT a substitute for professional human audits.**
#### ⛔ 限制:
- ❌ **No guarantee of finding all vulnerabilities** – AI agents may miss edge cases
- ❌ **False positives possible** – AI may flag non-issues as vulnerabilities
- ❌ **Cannot detect off-chain attacks** – Only analyzes code, not external dependencies
- ❌ **No formal verification** – Proofs generated are pseudocode, not mathematically formal
- ❌ **Depends on LLM quality** – Output quality varies with model and prompt engineering
#### 🚫 未审计类别:
- ⚙️ Compiler-level vulnerabilities
- 📚 Third-party library exploits
- 💱 Economic attacks requiring cross-protocol interaction
- ⏰ Time-dependent race conditions
- 🔮 Oracle manipulation (without deep DeFi context)
#### ✅ 最佳实践:
1. ✔️ **Use this as a first-pass filter** – catches obvious issues quickly
2. ✔️ **Always have a human auditor review findings** – especially Critical/High severity
3. ✔️ **Combine with static analysis tools** – Slither, 4naly3er, Certora run in parallel
4. ✔️ **Test with multiple models** – GPT-4, Claude, etc. for cross-validation
5. ✔️ **For production contracts** – hire professional audit firms (Trail of Bits, Consensys, etc.)
---
## 📚 资源
- 🤖 **CrewAI Framework**: https://github.com/joaomdmoura/crewai
- 📖 **Solidity Security**: https://docs.soliditylang.org/en/latest/security-considerations.html
- 🔒 **OWASP Smart Contracts**: https://owasp.org/www-project-smart-contract-top-10/
- 🏆 **Trail of Bits Audits**: https://trailofbits.com/
- ✅ **Consensys Diligence**: https://consensys.net/diligence/
---
## 💡 想法与反馈
Have ideas for improvements? Found a bug? Feel free to:
- 🐛 **Open an Issue**: https://github.com/yourusername/smartcontract_security_crewai/issues
- 💬 **Start a Discussion**: https://github.com/yourusername/smartcontract_security_crewai/discussions
- 🚀 **Submit a Pull Request**: https://github.com/yourusername/smartcontract_security_crewai/pulls
---
## 🙏 致谢
This project builds on the excellent work of:
- ⭐ **CrewAI**: Multi-agent AI orchestration framework
- 🧠 **Anthropic/OpenAI**: Large language models powering the agents
- 🔐 **Security Research Community**: OWASP, Trail of Bits, Consensys, Echidna teams
---
**Made with ❤️ for the Solidity & Web3 security community**
[](https://twitter.com/yourusername)
[](https://discord.gg/yourinvite)
[](https://github.com/yourusername/smartcontract_security_crewai)
⭐ **Star us on GitHub if you find this useful!** ⭐
*Last Updated: 2025-12-15*
```
标签:AI安全, ASN解析, C2, Chat Copilot, CrewAI, DeFi安全, MEV, Petitpotam, Python, Solidity, Web3, 云安全监控, 区块链, 多智能体, 对抗推理, 对称加密, 攻击模拟, 无后门, 智能合约, 智能合约安全, 智能合约测试, 自动化审计, 逆向工具, 重入攻击, 静态分析, 驱动签名利用