Share
## https://sploitus.com/exploit?id=52ABC2CB-014E-5BB8-8C23-5CA93D3EAE52
# โ›“๏ธ Codex Solidity โ€” Smart Contract & Protocol Audit Agent

Impact-driven vulnerability discovery for Solidity smart contracts and DeFi protocols. Every finding includes **exploit contracts**, **attack flow**, and **financial impact calculations** proving real fund drain, pool freeze, and balance manipulation scenarios.

## ๐Ÿš€ Quick Start

```bash
# Install dependencies
cd codex-solidity
npm install

# Audit a single contract
node bin/codex-sol.js audit -t ./contracts/Vault.sol

# Audit an entire project
node bin/codex-sol.js audit -t ./contracts/

# Run a single skill
node bin/codex-sol.js skill -t ./Vault.sol -n reentrancy

# Parse contract structure
node bin/codex-sol.js parse -t ./Vault.sol

# List available skills
node bin/codex-sol.js list

# Generate report from previous audit
node bin/codex-sol.js report -i ./audit-reports/audit-2026-04-28.json -f html

# Query SWC Registry for known vulnerabilities
node bin/codex-sol.js mcp -q reentrancy -s swc

# Show agent configuration
node bin/codex-sol.js config
```

## ๐Ÿ“‹ Skills (34 Impact-Driven Modules)

### Core DeFi/Protocol Skills

| Skill | Severity | Impact Demonstration |
|-------|----------|---------------------|
| **reentrancy** | Critical | Full pool drain โ€” attacker deposits 1 ETH, drains entire pool via recursive callback |
| **flash-loan** | Critical | Price manipulation in single tx โ€” borrow 10K ETH, manipulate pool, drain via arbitrage |
| **access-control** | Critical | Unauthorized owner functions โ€” anyone calls withdrawAll(), sweep(), mint() |
| **overflow** | Critical | Deposit 1 token, withdraw 2 โ†’ balance underflows to 2^256-1, drain everything |
| **pool-freeze** | High | Grow array past gas limit โ†’ ALL users permanently locked out, funds frozen forever |
| **oracle-manipulation** | High | Stale Chainlink, no TWAP โ†’ borrow against overvalued collateral, drain lending pool |
| **front-running** | High | No slippage protection โ†’ every swap sandwiched 5-30% loss, inflation attack |
| **delegatecall** | Critical | User-controlled delegatecall target โ†’ overwrite owner, full contract takeover |
| **self-destruct** | High | Force ETH via selfdestruct โ†’ break accounting, drain or freeze all funds |

### Trail of Bits Skills

| Skill | Severity | Impact Demonstration |
|-------|----------|---------------------|
| **unchecked-returns** | High | .call() return value ignored โ†’ silent failure, balance decremented but ETH not sent |
| **shadowing** | High | Child redeclares parent's `owner` โ†’ writes to different slot, parent owner stays 0x0 |
| **pragma-bugs** | High | Floating pragma โ†’ compiles with vulnerable compiler, storage corruption bugs |
| **signature-malleability** | High | ECDSA (r,s,v) and (r,n-s,vโŠ•1) both valid โ†’ double-spend via malleable signature |
| **erc20-assumptions** | High | Fee-on-transfer token: deposit 100, receive 90, credited 100 โ†’ insolvency |
| **timestamp-dependence** | Medium | block.timestamp manipulated by miners โ†’ lottery always won by miner |
| **storage-pointer** | High | Uninitialized storage var points to slot 0 โ†’ overwrites owner address |
| **inheritance-order** | High | C3 linearization: rightmost parent overrides โ†’ wrong function dispatched |
| **assembly-issues** | High | Hardcoded sstore(0, x) overwrites owner, extcodesize bypass, memory corruption |

### DeFi/Protocol Skills

| Skill | Severity | Impact Demonstration |
|-------|----------|---------------------|
| **erc4626-vault** | Critical | Inflation attack: donate ETH โ†’ inflate share price โ†’ victim gets 0 shares โ†’ total loss |
| **read-only-reentrancy** | Critical | View function returns stale data during callback โ†’ oracle reads wrong value โ†’ $100M+ losses |
| **rounding-errors** | High | Division before multiplication โ†’ precision loss โ†’ attacker extracts dust per tx |
| **liquidation-attack** | High | No grace period โ†’ MEV flash-loan liquidation โ†’ borrowers instantly liquidated |
| **proxy-upgrade** | Critical | Uninitialized implementation โ†’ anyone calls initialize() โ†’ contract takeover |
| **amm-math** | High | No k-invariant check โ†’ swap drains reserves without maintaining constant product |
| **reward-manipulation** | High | Stake/claim/unstake loop โ†’ drain rewards without time commitment |
| **bridge-vulnerability** | Critical | No message ID tracking โ†’ replay same message โ†’ drain bridge liquidity twice |
| **donation-attack** | High | Direct token transfer inflates share price โ†’ victim deposits, gets 0 shares |
| **eip-2612-permit** | High | No chain ID in domain โ†’ permit replay across L2s โ†’ tokens stolen on other chains |
| **nft-reentrancy** | High | onERC721Received callback re-enters during safeTransferFrom โ†’ bypasses ETH guards |
| **token-uri-manipulation** | Medium | SVG XSS in on-chain NFT โ†’ steals marketplace user cookies |
| **soulbound-bypass** | Medium | safeTransferFrom not blocked โ†’ "non-transferable" SBT actually transferable |
| **l2-sequencer** | High | Sequencer downtime โ†’ Chainlink freezes โ†’ borrow against stale price โ†’ drain pool |
| **gas-griefing** | Medium | External call in loop โ†’ grow array past gas limit โ†’ permanent DOS |
| **gas-optimization** | Low | Storage reads in loops โ†’ gas waste AND hidden logic flaw when loop modifies same variable |

## ๐ŸŽฏ Core Impact Scenarios

### 1. Fund Drain (Complete Pool Theft)
- **Reentrancy:** Deposit 1 ETH โ†’ recursive withdraw โ†’ drain entire pool
- **Overflow/Underflow:** Deposit 1, withdraw 2 โ†’ balance wraps to 2^256-1 โ†’ withdraw everything
- **Access Control:** Call unprotected withdrawAll() โ†’ steal all funds
- **Flash Loan:** Borrow 10K ETH โ†’ manipulate price โ†’ drain via arbitrage (zero risk, single tx)

### 2. User Pool Freeze (Permanent Fund Lock)
- **Unbounded Loop DOS:** Grow array past gas limit โ†’ withdraw() permanently fails
- **Push Payment DOS:** One reverting recipient blocks ALL payments
- **Force Feed:** selfdestruct ETH into contract โ†’ break balance invariant โ†’ all ops revert
- **Pause without Unpause:** pause() with no unpause() โ†’ funds locked forever

### 3. Attacker Steals More Than Deposited
- **Underflow:** balances[user] -= amount where amount > balance โ†’ wraps to 2^256-1
- **First-Depositor/Inflation:** Donate tokens before victim deposits โ†’ victim gets 0 shares
- **Oracle Manipulation:** Fake price โ†’ borrow more collateral than warranted
- **Address(this).balance:** Force ETH in โ†’ withdraw more than tracked deposits

## ๐Ÿ—๏ธ Architecture

```
codex-solidity/
โ”œโ”€โ”€ bin/codex-sol.js           # CLI entry (commander)
โ”œโ”€โ”€ lib/
โ”‚   โ”œโ”€โ”€ agent.js               # Orchestrator: parse โ†’ skills โ†’ correlate โ†’ PoC โ†’ report
โ”‚   โ”œโ”€โ”€ parser.js              # AST parser (@solidity-parser/parser) + regex fallback
โ”‚   โ”œโ”€โ”€ skill-loader.js        # Auto-discovers skills from /skills
โ”‚   โ”œโ”€โ”€ impact-engine.js       # Calculates drain amounts, generates exploit contracts
โ”‚   โ”œโ”€โ”€ mcp.js                 # MCP: SWC Registry + DeFiLlama intelligence
โ”‚   โ”œโ”€โ”€ foundry-poc.js         # Auto-generates Foundry .t.sol exploit test cases
โ”‚   โ”œโ”€โ”€ correlation-engine.js  # Cross-skill correlation: links combined exploit paths
โ”‚   โ”œโ”€โ”€ dynamic-severity.js    # Context-aware severity scoring (TVL, visibility, exploitability)
โ”‚   โ”œโ”€โ”€ external-tool-parser.js # Normalizes Slither/Aderyn/Mythril JSON into Codex format
โ”‚   โ”œโ”€โ”€ ci-integration.js      # CI mode, SARIF output, GitHub Actions workflow generator
โ”‚   โ”œโ”€โ”€ diff-auditor.js        # Git diff: only audit changed functions between refs
โ”‚   โ”œโ”€โ”€ interactive-mode.js    # REPL: drill into findings, re-score, generate PoCs
โ”‚   โ””โ”€โ”€ report-generator.js    # HTML (dark) + Markdown + JSON reports
โ”œโ”€โ”€ skills/
โ”‚   โ”œโ”€โ”€ reentrancy/index.js    # Reentrancy โ€” recursive callback fund drain
โ”‚   โ”œโ”€โ”€ flash-loan/index.js    # Flash Loan โ€” price manipulation, pool drain
โ”‚   โ”œโ”€โ”€ access-control/index.js # Access Control โ€” unauthorized privileged functions
โ”‚   โ”œโ”€โ”€ overflow/index.js      # Integer Overflow/Underflow โ€” balance wrapping
โ”‚   โ”œโ”€โ”€ pool-freeze/index.js   # Pool Freeze / DOS โ€” permanent fund lock
โ”‚   โ”œโ”€โ”€ oracle-manipulation/index.js # Oracle โ€” stale/fake price exploitation
โ”‚   โ”œโ”€โ”€ front-running/index.js # MEV โ€” sandwich, slippage, inflation attack
โ”‚   โ”œโ”€โ”€ delegatecall/index.js  # Delegatecall โ€” storage collision, proxy takeover
โ”‚   โ”œโ”€โ”€ self-destruct/index.js # Self-Destruct โ€” force feed, accounting break
โ”‚   โ”‚
โ”‚   โ”‚  # Trail of Bits skills
โ”‚   โ”œโ”€โ”€ unchecked-returns/index.js  # Unchecked .call()/.send() return values
โ”‚   โ”œโ”€โ”€ shadowing/index.js          # State variable shadowing in inheritance
โ”‚   โ”œโ”€โ”€ pragma-bugs/index.js        # Floating pragma & known compiler bugs
โ”‚   โ”œโ”€โ”€ signature-malleability/index.js # ECDSA signature malleability & replay
โ”‚   โ”œโ”€โ”€ erc20-assumptions/index.js  # Fee-on-transfer, rebasing, non-standard tokens
โ”‚   โ”œโ”€โ”€ timestamp-dependence/index.js # block.timestamp manipulation
โ”‚   โ”œโ”€โ”€ storage-pointer/index.js    # Uninitialized storage pointers
โ”‚   โ”œโ”€โ”€ inheritance-order/index.js  # C3 linearization & missing super calls
โ”‚   โ””โ”€โ”€ assembly-issues/index.js    # Inline assembly vulnerabilities
โ”‚   โ”‚
โ”‚   โ”‚  # DeFi/Protocol skills
โ”‚   โ”œโ”€โ”€ erc4626-vault/index.js       # ERC4626 vault inflation/rounding attacks
โ”‚   โ”œโ”€โ”€ read-only-reentrancy/index.js # Read-only reentrancy via view functions
โ”‚   โ”œโ”€โ”€ rounding-errors/index.js     # Division-before-multiplication precision loss
โ”‚   โ”œโ”€โ”€ liquidation-attack/index.js  # Cascade liquidation & MEV front-running
โ”‚   โ”œโ”€โ”€ proxy-upgrade/index.js       # UUPS/Transparent proxy vulnerabilities
โ”‚   โ”œโ”€โ”€ amm-math/index.js            # AMM constant product invariant violations
โ”‚   โ”œโ”€โ”€ reward-manipulation/index.js # Staking reward gaming & double claims
โ”‚   โ”œโ”€โ”€ bridge-vulnerability/index.js # Cross-chain message replay & validator attacks
โ”‚   โ”œโ”€โ”€ donation-attack/index.js     # Direct transfer inflation attack
โ”‚   โ”œโ”€โ”€ eip-2612-permit/index.js     # Permit replay & signature validation
โ”‚   โ”œโ”€โ”€ nft-reentrancy/index.js      # ERC721/ERC1155 callback reentrancy
โ”‚   โ”œโ”€โ”€ token-uri-manipulation/index.js # SVG XSS & metadata manipulation
โ”‚   โ”œโ”€โ”€ soulbound-bypass/index.js   # SBT transfer restriction bypass
โ”‚   โ”œโ”€โ”€ l2-sequencer/index.js        # L2 sequencer downtime oracle freeze
โ”‚   โ”œโ”€โ”€ gas-griefing/index.js        # Gas DOS & external call in loop
โ”‚   โ””โ”€โ”€ gas-optimization/index.js    # Gas optimization reveals hidden logic flaws
โ”œโ”€โ”€ .agents/skills/audit-pro/
โ”‚   โ”œโ”€โ”€ SKILL.md                  # Audit workflow: recon โ†’ analysis โ†’ PoC โ†’ report
โ”‚   โ”œโ”€โ”€ scripts/static_scan.sh    # Bridge to Slither/Aderyn/Codex
โ”‚   โ””โ”€โ”€ references/report_template.md  # Sherlock/Immunefi submission template
โ”œโ”€โ”€ config.toml                  # Agent config: model, reasoning_effort, MCP servers
โ”œโ”€โ”€ AGENTS.md                    # Durable auditor persona instructions
โ”œโ”€โ”€ config/default.yaml
โ”œโ”€โ”€ package.json
โ””โ”€โ”€ README.md
```

## โš™๏ธ CLI Options

```
audit  -t, --target      Path to .sol file or directory (required)
       -s, --skills      Comma-separated skills (default: all)
       -o, --output       Output directory (default: ./audit-reports)
       --compiler     Solidity version (default: 0.8.19)
       --network         Network context (default: mainnet)
       --exclude         Paths to exclude
       --ci                    CI mode: non-zero exit if findings above threshold
       --fail-on     CI fail threshold: critical, high, medium (default: high)
       --diff             Diff mode: only audit changed functions (e.g. main...HEAD)
       --interactive           Interactive REPL: drill into findings after audit

mcp    -q, --query      Search SWC Registry / DeFiLlama for known exploits
       -s, --source    Source: swc, defillama, all (default: all)

diff   -b, --base         Base git ref (branch, commit, tag)
       -h, --head         Head git ref (default: working tree)

import -i, --input      Import findings from Slither/Aderyn/Mythril JSON
       -t, --tool        Tool: slither, aderyn, mythril, auto (default: auto)

ci-workflow                      Generate GitHub Actions workflow YAML

config                           Show current agent config (config.toml + AGENTS.md)
```

## ๐Ÿง  Agentic Audit Loop

### config.toml โ€” The Engine
```toml
[model]
default = "gpt-5.4-pro"
reasoning_effort = "xhigh"       # Maximum thinking tokens for complex logic
max_completion_tokens = 100000

[features]
enable_subagents = true          # Parallel contract module analysis
enable_mcp = true                # External intelligence lookup
sandbox = "relaxed"              # Run local tests to verify PoCs

[audit]
auto_poc = true                  # Auto-generate PoC for every high/critical finding
submission_reports = true        # Sherlock/Immunefi format reports
```

### AGENTS.md โ€” The Brain
Durable instructions that persist across sessions:
- **Auditor Persona**: Lead Security Researcher mindset, invariant-breaking focus
- **Operational Rules**: Static analysis first, PoC or it didn't happen, impact quantification
- **Attack Path Priority**: Fund drain โ†’ Pool freeze โ†’ Withdraw more than deposit โ†’ Privilege escalation โ†’ Cross-protocol impact
- **Severity Classification**: Based on quantified financial impact

### MCP โ€” External Intelligence
- **SWC Registry**: Look up known Solidity vulnerability patterns (SWC-101 through SWC-138)
- **DeFiLlama**: Protocol TVL, exploit history, protocol-specific context
- Query: `node bin/codex-sol.js mcp -q reentrancy -s swc`

### .agents/skills/audit-pro/ โ€” The Toolkit
- **SKILL.md**: 6-step audit workflow (Recon โ†’ Static Analysis โ†’ Deep Skill Analysis โ†’ PoC โ†’ Report โ†’ Gas Review)
- **scripts/static_scan.sh**: Bridges Codex with Slither, Aderyn, and custom patterns
- **references/report_template.md**: Sherlock/Immunefi submission-ready template

### ๐Ÿ†• Engine Upgrades

| Module | What It Does |
|--------|-------------|
| **AST Parser** | Real AST via `@solidity-parser/parser` โ€” catches nested calls, modifiers, inheritance that regex misses |
| **Foundry PoC Generator** | Auto-generates runnable `.t.sol` exploit tests for every critical/high finding |
| **Cross-Skill Correlation** | Detects combined exploits (e.g., read-only reentrancy + oracle = $100M+ class) |
| **Dynamic Severity** | Scores severity based on fund exposure, exploitability, access vector, state impact, cross-protocol reach |
| **External Tool Parser** | Imports Slither/Aderyn/Mythril JSON findings into unified Codex format |
| **CI/CD Integration** | `--ci` flag with exit codes, SARIF output, GitHub Actions workflow generator |
| **Diff Auditing** | `--diff main...HEAD` โ€” only audits changed functions, skips untouched code |
| **Interactive Mode** | `--interactive` REPL: drill into findings, re-score, generate PoCs, query MCP |

## ๐Ÿ”ง Adding Custom Skills

Create a directory under `skills/` with an `index.js`:

```js
module.exports = {
  name: 'my-skill',
  aliases: ['custom-check'],
  severity: 'high',
  description: 'My custom vulnerability check',
  async execute(ctx) {
    const { contracts, impactEngine, parser } = ctx;
    const findings = [];
    // Parse contracts, detect pattern, calculate impact
    return findings;
  },
};
```

Each finding: `title`, `severity`, `contract`, `function`, `evidence`, `impact`, `remediation`, `poc`.

## โš ๏ธ Legal Disclaimer

This tool is for **authorized security audits only**. Always obtain proper authorization before auditing any smart contract. Unauthorized testing may violate laws.

## ๐Ÿ“„ License

MIT โ€” Thabiso Noosi