Play AppSec WarGames
Want to skill-up in secure coding and AppSec? Try SecDim Wargames to learn how to find, hack and fix security vulnerabilities inspired by real-world incidents.
Surprisingly, a sizable number of submissions for dApp Start Here level was by swapping int32 with uint.
These submission fail for a good reason. The security vulnerability has not been fixed!
Let’s find out why.
uint is an alias for uint256. It has a fixed range, starting from 0 to 115792089237316195423570985008687907853269984665640564039457584007913129639935. It is a big number but it is still fixed. If an arithmetic operation (e.g. adding two number) goes beyond or below this range, integer overflow happens.
So how do we fix integer overflow in Solidity?
Before taking a shortcut (i.e. include Openzeppelin’s SafeMath.sol or upgrade to use Solidity v0.8.0), let’s look at three defensive patterns:
BigInteger).Out of the above three patterns , (3) is the best solution but it is not supported by Solidity and (2) is still dangerous (what if the the input is bigger than the larger data type). So we are left with (1).
function SafeAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
In the above example, we used post condition testing. We used one property of addition, that is the result of addition is never smaller than the given numbers.
So let’s stop changing data type to fix integer overflow but use pre or post condition testing. Simple and effective!
Now you can go back to dApp Start Here level and get a score!
Solidity compiler v0.8.0 and above throws exception when integer overflow happens. Please keep in mind this comes with an additional gas cost and does not protect you against all the 22 causes of integer overflow. Watch this video to find out more: BEC Overflow - SecDim
Want to skill-up in secure coding and AppSec? Try SecDim Wargames to learn how to find, hack and fix security vulnerabilities inspired by real-world incidents.
Join our secure coding and AppSec community. A discussion board to share and discuss all aspects of secure programming, AppSec, DevSecOps, fuzzing, cloudsec, AIsec code review, and more.
Read more