本文へ移動
Contact

TECHFUND
Media

Hi AUDIT
2025/2/5

Understanding Overflow and Underflow Risks in Yul Compared to Solidity

Understanding Overflow and Underflow Risks in Yul Compared to Solidity. Solidity allows developers to write highly optimized smart contracts using inline assembly, specifically with Yul. While Yul can significantly enhance efficiency by providing low-level control over the EVM, it also introduces critical security risks, particularly when memory operations are not properly managed.

One such risk is unintended overwriting of memory pointers, which can occur if inputs are not thoroughly validated. Unlike Solidity, which—starting from version 0.8—includes built-in overflow and underflow protection, Yul lacks these safeguards. This means developers must implement their own checks to prevent arithmetic vulnerabilities.

In Yul, mathematical operations do not automatically revert on overflow or underflow. If not handled correctly, this can lead to unintended behaviour, security exploits, or loss of funds in a smart contract.

In this blog, we will focus on demonstrating how overflow and underflow can occur in Yul using real life examples, why they are dangerous, and how developers can mitigate these risks when writing low-level Solidity contracts.

If you’re not familiar with overflow and underflow, let’s quickly break it down. Consider a single byte (8 bits) of storage. The maximum (unsigned integer) value it can hold is 2^8 - 1 = 255. But what happens if we try to store 256?
Since 256 exceeds the storage limit, the value overflows and resets back to 0.

You can think of this like a clock that counts up to 255 instead of 24 hours. If the clock reaches 255 and you try to increment it by 1, it loops back to 0—this is an overflow.

Similarly, underflow occurs when you subtract from the minimum possible value. If our clock is at 00:00 (which represents 0) and we try to move one hour backward, instead of going to -1 (which isn’t possible in this system), it wraps around to 255.

Now, let’s examine the following code snippet to better understand this issue.

In the above code block, we see the use of the mstore opcode, which operates as follows:


mstore(p, v): Stores the value v in memory at the offset p.

The code first checks whether amountIn is greater than zero. If this condition is met, it proceeds to store the value at a dynamically computed memory offset using:


add(add(ptr, 0x24), mul(amountInIndex, 0x20))

Here, the offset parameter is computed using multiplication

(mul(amountInIndex, 0x20)).

Now, let’s break down how the expression add(add(ptr, 0x24),mul(amountInIndex, 0x20)) computes the offset:

First, understanding Function Selectors in Ethereum:

Every function call in Ethereum is encoded with a function selector, which consists of the first 4 bytes of the calldata. This selector is derived from the Keccak-256 hash of the function’s signature (e.g., functionName(arg1, arg2)).

The Ethereum Virtual Machine (EVM) uses this selector to determine which function should be executed. For example, the function selector for ‘function transfer(address,uint256)’ is computed as:

bytes4(keccak256(“transfer(address,uint256)”))

This produces a 4-byte identifier that precedes the function arguments in calldata. amountIn is meant to be stored at an index determined by amountInIndex.
ptr serves as the base pointer to the calldata stored in memory. An offset of 0x24 (or 36 in decimal) is added to ptr to account for the function selector and other initial calldata fields.

Additionally, amountInIndex * 32 is used to compute the precise memory location where a value should be inserted. Since Solidity stores function arguments in 32-byte slots, multiplying the index by 32 correctly positions the new value within the calldata structure.

BUT, the issue arises because mul(swapAmountInDataIndex, 0x20) results in a uint256 value. Since we are working at a low level using Yul, rather than high-level Solidity functions, the compiler does not automatically check for overflow.

When computing the memory position using amountInIndex * 32, an excessively large index can cause an overflow. This overflow can reset the memory position, causing it to wrap around and start from zero again. As a result, the calculated memory location can become unpredictable and potentially overwritten.

By carefully choosing the amountInIndex, an attacker can overwrite arbitrary sections of memory, effectively controlling where the value is written.

For instance, the user can overwrite the function selector stored in memory and can also cause memory corruption. This could allow them to invoke arbitrary functions with the contract itself as the caller.

Let’s break down the concept with a clear example and walk through how it leads to the corruption of the function selector:

The formula for calculating the memory location where the value will be written is:

36 + (amountInIndex * 0x20)

we need to manipulate amountInIndex to achieve a value that, when plugged into the memory calculation formula, results in a pointer that creates memory corruption and function selector overwriting.

To achieve this target, amountInIndex should be chosen as:

amountInIndex = n 2*251 - 2

where n is any integer.

This results in:

36 + (amountInIndex 0x20) = -28 mod 2*256

Since, the function selector is at position : ptr + 4, and due to this -28 mod 2**256, the final pointer for where the value gets patched will collide with the function selector (i.e., the first 4 bytes of calldata).

This means that the modified calldata will overwrite the function selector, corrupting it. The severity of this vulnerability largely depends on the context in which the code is used. In some cases, an overflow or underflow might only cause incorrect calculations, while in others, it could lead to severe security exploits, such as fund theft or contract malfunction.

To mitigate these risks, developers can implement several key safeguards:

•Bounds Checking: Ensure that arithmetic operations stay within expected limits by manually checking values before performing calculations.

•Data Validation & Verification: Validate user inputs and state variables before executing critical operations.

• Or simply leverage Solidity’s built-in safety features by using high-level calls wherever possible.

Conclusion:


In summary, extra caution is required when performing arithmetic operations in Yul. Overflow and underflow are just one category of vulnerabilities that developers can inadvertently introduce. Many other pitfalls, such as improper memory management and unchecked external calls, have led to major exploits in DeFi protocols.

We will continue exploring such vulnerabilities and sharing real-world examples to help developers write safer smart contracts. Stay tuned for more insights on low-level Solidity security!

Author : Mohit Yadav

Hi AUDIT

Hi AUDIT is a high speed, high quality, best price security audit service, providing automated audit SaaS and consulting for web3 startups.
View More