Ethernaut Level 5 - Token

Tellico Lungrevink
2 min readJul 9, 2022

The Ethernaut is a Web3/Solidity based wargame inspired on overthewire.org. Here’s the solution to the Level 5 Token.

The initial info challenges me to somehow multiply the starting token amount I am given:

The goal of this level is for you to hack the basic token contract below.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.

The most interesting part of the code is the transfer function::

Above function is vulnerable to the arithmetic underflow. In the older versions of Solidity, there were no implicit check for arithmetic over and under flows. As an effect, if one subtracted a bigger value from a smaller one for an unsigned type, the result was a very big number, because the result would flip to the given type’s max value. In this case, if an attacker tries to transfer a value bigger than their balance, the result will be a very big number in their balance. It’ll surely pass the ≥ 0 check and then it’ll be stored as a new balance after the operation. Therefore, all I need to do, is to transfer the amount of tokens slightly bigger than my initial balance:

> (await contract.balanceOf(player)).toString()
'20'
> await contract.transfer(contract.address, 21)
{tx: '0xd0254a0e2b93d53c18eb4592f7c99ce21da533f8b409b80678f133298c197c59', receipt: {…}, logs: Array(0)}
> (await contract.balanceOf(player)).toString()
'115792089237316195423570985008687907853269984665640564039457584007913129639935'

As can be seen above, overdrawing player’s balance caused the balance counter to underflow and gave me very high number of tokens. All that’s left to do is to submit the instance and claim the win.

--

--