我最近一直在玩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
文章来源:https://www.toymoban.com/news/detail-785886.html
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文章来源地址https://www.toymoban.com/news/detail-785886.html
到了这里,关于tx.origin 与 msg.sender的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!