Closed sherlock-admin4 closed 1 month ago
This error occurs particularly when x is greater than MAX_INT256. However, such large values are rarely used. For most users and processes, such large values will not be valid.
That is, the probability of encountering the error in real-world use is low.
The error may affect the correct operation of the function, but it does not directly harm user funds or create a security vulnerability.
0xboriskataa
High
Attacker can withdraw all tokens deposited in a farm
Summary
Attacker can withdraw all tokens deposited in a farm
Vulnerability Detail
There is a bug in the
Math.sol
library in theaddDelta()
function:The issue here is that the line
y := add(x, delta)
will not revert on underflow. If for examplex = 10
anddelta = -20
the result will beUINT_MAX - 10
. You might think this won't happen because we are using solidity version 0.8 which has overflow and underflow protection but that is not the case for assembly operations. More can be read hereAn attacker can use this bug to drain all of the deposited tokens in
MasterchefV2.sol
using thewithdraw()
function:It calls
_modify()
so let's take a look at it:As you can see it uses the amounts library to update the balance of the caller:
Here is where the problematic
addDelta()
function from theMath.sol
library is used.What an attacker can do is to enter an
amount
of tokens to withdraw inwithdraw()
that is bigger than the balance he has. There is no check to validate if he is withdrawing more than he has in his balance. Perhaps the intention was that if he tries to do that then this line will simply revert because of an underflow:However as I explained above a revert in
addDelta()
will not happen. TheAmounts.sol
library will simply use this underflowed new balance of the user to calculate how much rewards he should get:After that the function will simply transfer both the calculated reward and the specified tokens to withdraw:
Impact
Attacker can drain every deposited token from a farm. He will also get additional rewards that will be calculated incorrectly.
Code Snippet
https://github.com/sherlock-audit/2024-06-magicsea/blob/main/magicsea-staking/src/libraries/Math.sol#L20-L30
https://github.com/sherlock-audit/2024-06-magicsea/blob/main/magicsea-staking/src/MasterchefV2.sol#L306-L310
https://github.com/sherlock-audit/2024-06-magicsea/blob/main/magicsea-staking/src/MasterchefV2.sol#L539-L564
https://github.com/sherlock-audit/2024-06-magicsea/blob/main/magicsea-staking/src/libraries/Amounts.sol#L68-L85
Tool used
Manual Review
Recommendation
You can use this implementation for
addDelta()
that is from uniswap:Also do a check in the withdraw function that the user is not withdrawing more than he has in his balance: