Skip to content

05. Token

r1oga edited this page Oct 28, 2022 · 1 revision

Target

You are given 20 tokens to start with and you will beat the level if you somehow manage to get your hands on any additional tokens. Preferably a very large amount of tokens.

Weakness

A sum operation is performed but overflow isn't checked for.

Solidity Concepts

Bits storage, underflow/overflow

Ethereum’s smart contract storage slots are each 256 bits, or 32 bytes.
Solidity supports both signed integers, and unsigned integers uint of up to 256 bits.
However as in many programming languages, Solidity’s integer types are not actually integers. They resemble integers when the values are small, but behave differently if the numbers are larger. For example, the following is true: uint8(255) + uint8(1) == 0. This situation is called an overflow. It occurs when an operation is performed that requires a fixed size variable to store a number (or piece of data) that is outside the range of the variable’s data type. An underflow is the converse situation: uint8(0) - uint8(1) == 255. over/underflow image

Hack

Provoke the overflow by transferring 21 tokens to the contract.
Reducing the player's balance will indeed overflow: 20 - 21 -> overflow

Takeaway

solc < 0.8.0

Check for over/underflow manually:

if(a + c > a) {
  a = a + c;
}

Or use OpenZeppelin's math library that automatically checks for overflows in all the mathematical operators.

solc >= 0.8.0

Contracts aren't vulnerable to this kind of overflow/underflow risk. Indeed any operations that over/underflow automatically revert since 0.8.0 (so no need to use openzeppelin safeMath).

Clone this wiki locally