Skip to content

Attack Pack Authoring Guide

Core Architecture

An attack pack is a self-contained directory structure that provides the Crucible testbed with the necessary components to execute a specific exploit against a target environment. This encompasses both historical reproductions (re-executing past incidents) and novel attack development (testing zero-days against a deployed scenario).

(For details on how the execution environment is decoupled from the attack logic, see the Scenario Authoring Guide).


Component Specification

1. plugin.yaml (Plugin Manifest)

Declares plugin metadata, entrypoints, and runtime requirements for the Crucible engine.

name: "your_attack_name"
type: attack
version: "1.0.0"
author: "Author Name"
entry: "your_attack.py"
class: "YourAttackClass"
requires:
  crucible: ">=1.0.0"
  chains:
    - ethereum
  topology: single

2. evidence.yaml (Research Evidence Manifest)

The primary research artifact. It formally declares the on-chain data, sources, and success criteria for the exploit.

  • Historical Reproductions: Documents the exact transaction hashes, affected contracts, and fork blocks from the mainnet incident. The historical_scope.fork_blocks configuration serves as the authoritative source of truth for the testbed's automatic fork management.
  • Novel Attacks: The incident and sources sections document the hypothetical vulnerability, while reproduction_scope is typically set to L0 (Simulation) or L1 (Proof of Concept).
incident:
  name: "Vulnerability Name"
  date: "YYYY-MM-DD"
  affected_bridge: "Protocol Name"
  funds_lost_usd: 611000000
  summary: >
    Technical summary of the root cause and vulnerability mechanics.

sources:
  advisories: ["https://..."]
  postmortems: ["https://..."]
  tx_explorers: ["https://etherscan.io/tx/0x..."]

historical_scope:
  chains: ["ethereum"]
  fork_blocks:
    ethereum: 15259100
  exploit_transactions: ["0x..."]
  affected_contracts:
    TargetContract: "0xVerifiedAddress..."
  attacker_addresses: ["0x..."]
  vulnerability_function: "vulnerableFunction"

reproduction_scope:
  fidelity_level: L2
  exact_tx_replay: false
  modeled_components: ["On-chain state manipulation via contract X"]
  excluded_components: ["Off-chain relayer architecture"]

acceptance:
  required_assertions:
    - name: exploit_succeeds
      description: "The exploit transaction executes without reverting"
      expected: true

3. <name>.py (Attack Implementation)

The Python implementation defining the exploit logic. Must inherit from AttackPlugin and implement execute() and verify(). It may also optionally implement prepare(), rollback(), and cleanup() for full lifecycle management.

from crucible.sdk import AttackPlugin, AttackResult, ExperimentContext, VerificationResult
from crucible.rpc import JsonRpcClient

class YourAttack(AttackPlugin):
    def metadata(self) -> dict:
        return {
            "name": "your_attack",
            "version": "1.0.0",
            "type": "attack",
            "fidelity_level": "L2",
        }

    def execute(self, context: ExperimentContext, phase: int | None = None) -> AttackResult:
        rpc_url = context.chains.runtime_for("ethereum").rpc_url
        client = JsonRpcClient(rpc_url)

        # Implementation logic
        context.log.step("Exploit execution completed",
                         phase="attack", action="exploit", status="success")
        return AttackResult(success=True, phase_results=[])

    def verify(self, context: ExperimentContext) -> VerificationResult:
        return VerificationResult(passed=True, assertions=[], errors=[])

    # Optional lifecycle hooks:
    # def prepare(self, context: ExperimentContext) -> None:
    #     """Set up attacker accounts, approve tokens, deploy helpers."""
    #     pass

    # def rollback(self, context: ExperimentContext) -> None:
    #     """Undo persistent changes not handled by snapshot restore."""
    #     pass

    # def cleanup(self, context: ExperimentContext) -> None:
    #     """Remove temp files, kill helper processes."""
    #     pass

4. scenario.yaml (Environment Definition)

Initializes the required environment before yielding to the attack plugin. See the Scenario Authoring Guide for full documentation.

name: my_attack_pre_exploit
chains:
  - ethereum
phases:
  - name: setup
    steps:
      - type: log
        message: "Starting reproduction at fork block"
  - name: attack
    steps:
      - type: log
        message: "Attack plugin executed by experiment runner"

5. experiments/<name>_replay.yaml (Experiment Orchestration)

Wires the components together and defines runtime parameters such as artifact capture toggles.

name: my_attack_replay
scenario: my_attack_pre_exploit
attack: my_attack
topology: single
run:
  traces: true
  storage_diffs: true
  gas_profiling: true
tags: [my_attack, l2]

Automated Scaffolding

Scaffolding from Historical Transactions

Crucible provides a utility to automatically scaffold attack packs from historical on-chain transactions:

crucible attack extract <tx_hash> --name <name> --chain <chain>

Capabilities: - Extracts ABI definitions from public registries. - Decodes transaction calldata and function signatures. - Pre-fills evidence.yaml with contract addresses, attacker wallets, and the correct fork block (derived from the transaction's block minus one). - Scaffolds the plugin.yaml, scenario.yaml, and Python implementation file.

Limitations: - ABI decoding is best-effort; complex nested structures or proxy patterns may fail to decode. - The generated Python file contains functional stubs; the actual execute() logic must be manually implemented. - Unverified contracts will yield empty ABIs.


Scaffolding Novel Attacks

For novel attack development where no historical transaction exists, use the initialization command:

crucible attack init <name>

This generates a clean boilerplate pack without attempting to derive fork blocks or ABIs from an explorer.


Research Methodology & Data Collection

Accurate execution requires rigorous on-chain data collection prior to implementation. For novel attacks, this primarily involves identifying the deployment block of your target smart contracts. For historical reproductions, this requires exact incident data:

Data Requirement Definition Retrieval Source
Fork Block The state prior to the exploit. For reproductions: the block of the first exploit tx minus 1. For novel attacks: any block after the target contract deployment. Block explorer transaction details.
Exploit Tx Hash Target transaction for calldata verification and L3 exact replay (Reproductions only). Block explorer or security postmortems.
Verified Contracts Target smart contracts for the attack payload. Block explorer (must show verified source code).
Attacker Wallet The transaction initiator (msg.sender). "From" field on the exploit transaction (or a generated mock address).

Deriving the Fork Block

The fork block defines the state of the network immediately before the vulnerability is triggered.

For historical reproductions: 1. Identify the first malicious transaction on the block explorer. 2. Record the block height of that transaction. 3. Subtract 1 to determine the fork block. 4. Verify that the target contract is deployed and contains the vulnerable state at this block.

For novel attacks: 1. Identify the block where the target contract was deployed and fully initialized. 2. Select any block subsequent to initialization as your fork block.

[!WARNING] Contract Address Verification The most common error during pack authoring is confusing an EOA (Externally Owned Account) with a smart contract. Always verify on a block explorer that the target address contains deployed bytecode and verified source code before declaring it in evidence.yaml.


Implementation Patterns

Core SDK Operations

Operation Implementation API
RPC Client Instantiation client = JsonRpcClient(context.chains.runtime_for("ethereum").rpc_url)
State Verification code = client.get_code("0x...")
Storage Reading val = client.get_storage_at("0x...", "0x1")
Account Impersonation client.impersonate_account("0x...")
Transaction Dispatch client.send_transaction({"from": addr, "to": addr, "data": "0x...", "gas": hex(300000)})
Execution Logging context.log.step("Action description", phase="attack", action="action_type", status="success")

Reference Implementations

Study existing benchmarks to understand complex implementations:

Attack Implementation Key Concepts Demonstrated
demo_attack Minimal baseline plugin structure.
nomad_replica_fraud Storage slot analysis, ABI encoding, multi-step execution.
wormhole_guardian_bypass Constant definitions, rigorous verification logic.
poly_network_privkey Hash collision calculations, dynamic calldata construction, contract impersonation.

Translating Exploit Transactions to Code

When porting a historical exploit transaction to a plugin, avoid copying raw hex calldata directly. Raw calldata often contains hardcoded addresses, nonces, or environment-specific parameters that are invalid on a localized fork.

  1. Decompose the Transaction: Use a block explorer's decoding tool to understand the function parameters (e.g., verifyHeaderAndExecuteTx(bytes header, bytes proof)).
  2. Reconstruct Calldata: Utilize an ABI encoding library (eth_abi) to dynamically pack the arguments.
# Improper: Copying raw historical calldata
calldata = "0x41973cd900000..." # Contains historical state specific to mainnet

# Proper: Programmatic reconstruction
from eth_abi import encode
args = encode(["bytes", "bytes"], [header_data, proof_data])
calldata = "0x41973cd9" + args.hex()

Validation and Testing Workflow

Execute the following commands to validate the attack pack locally or via Docker.

# 1. Structural Validation
docker compose run --rm orchestrator plugin validate attacks/my_attack

# 2. Registration Verification
docker compose run --rm orchestrator plugin list --type attack

# 3. Execution (Auto-merges fork_block from evidence.yaml)
docker compose run --rm --entrypoint bash orchestrator -c "
  rm -f states/*.meta.json && \
  uv run crucible fork --topology single && \
  uv run crucible experiment run experiments/my_attack_replay.yaml --no-baseline
"

# 4. Result Analysis
docker compose run --rm orchestrator logs list

# 5. Determinism Verification (Execute twice, compare results)
docker compose run --rm orchestrator diff <run_a> <run_b>

Fidelity and Multi-Chain Execution

L3: Exact Transaction Replay

L3 reproductions execute the exact historical transaction against the forked state, demanding identical calldata and resulting state transitions.

  1. Declare exact_tx_replay: true in evidence.yaml.
  2. Provide the precise historical transaction hash in exploit_transactions.
  3. Construct calldata in the plugin that perfectly matches the historical execution.

L4: Multi-Chain Bridge Topologies

L4 reproductions require executing attacks across multiple EVM forks simultaneously, facilitated by an instrumented bridge plugin.

Required Configuration:

# experiments/my_l4_experiment.yaml
topology: nomad_bridge   # Must specify a multi-chain bridge topology

Bridge Plugin Interface:

def execute(self, context: ExperimentContext, phase=None) -> AttackResult:
    # Bridge is automatically deployed by the orchestrator
    bridge = context.bridge_plugin

    # Dispatch cross-chain payload
    result = bridge.send_message(
        context=context,
        source_chain="ethereum",
        dest_chain="polygon",
        data="0x..."  # Forged calldata
    )


Common Execution Failures

If you encounter errors during implementation (e.g., contract state missing, double hex prefixes, or L3 fidelity violations), consult the centralized Troubleshooting Guide.

The troubleshooting guide contains detailed fixes for every common authoring pitfall, including: - Addressing "0x" get_code() results (EOA vs Contract confusion). - Fixing keccak256 hashing discrepancies. - Resolving state availability issues on paid archive RPCs. - Debugging bridge deployment and cross-chain execution failures.


External Resources

Domain Resource
ABI Specification Solidity ABI Spec
Keccak Hashing eth-hash Library
Storage Layout Solidity Storage Internals
Function Signatures 4byte Directory
ABI Encoding/Decoding eth-abi Python Library

See Also

Reference Purpose
docs/SCENARIO_AUTHORING.md Scenario definition reference
docs/CLI_REFERENCE.md Testbed command-line interface specification
docs/FIDELITY_GUIDE.md Fidelity tier definitions and enforcement mechanisms
docs/REPRODUCIBILITY.md Technical mechanisms for ensuring deterministic execution