• Browse topics
Login
Login

SNYK LEARN LOGIN

OTHER REGIONS

For Snyk Enterprise customers with regional contracts. More info

Integer overflow or wraparound

Going over to get under. Do you know your integer limits?

~15mins estimated

C++

Integer overflow or wraparound: the basics

What is integer overflow or wraparound?

An integer overflow or wraparound happens when an integer value is increased beyond the maximum limit that its type can accommodate in a program's memory. This overflow causes the value to wrap around, resulting in an unexpectedly small or negative number. Such incidents typically occur in languages like C++, where integers have fixed sizes and bounds.

The distinction between overflow and wraparound lies in the behavior of the integer value post-exceeding its limit. Overflow specifically refers to the situation where the value exceeds its maximum possible value, leading to incorrect or unpredictable results. Wraparound, on the other hand, describes the scenario where this exceeded value cycles back around the minimum possible value, often leading to a negative or very small number, depending on if the integers are signed or not.

About this lesson

In this lesson, you will learn about vulnerabilities stemming from integer overflow or wraparounds and how to protect your applications against them. We will step into the shoes of Jamie, a cybersecurity enthusiast who unexpectedly uncovers a critical flaw in a webshop's checkout system.

FUN FACT

Ariane 5

The Ariane 5 Flight V88 incident in 1996 is a notable example of an integer overflow leading to a catastrophic failure. A 64-bit floating-point number representing the rocket's horizontal velocity was erroneously converted to a 16-bit integer, causing an overflow. This error crashed the onboard computer and triggered the rocket's self-destruct mechanism just after launch.

Integer overflow or wraparound in action

Jamie is a cybersecurity enthusiast who like to push systems to their limits. Let's see what he gets up to today.

Integer overflow or wraparound in action

  • STEP 1
  • STEP 2
  • STEP 3
  • STEP 4
  • STEP 5

Setting the stage

Jamie is a cyber enthusiast who likes to push platforms to the limit. While shopping, Jamie decides to test the limits of the site's checkout system.

integer-overflow-step-1
FUN FACT

C++ integer size

The size of integer types in C++ is not fixed by the language standard but depends on the system and compiler. This variability can lead to integer overflows if a program is moved from a system with a larger integer size to one with a smaller size, unexpectedly limiting the range of values the integer can hold.

Integer overflow or wraparound under the hood

Let's dive into what happened in the scenario above with Jamie and her encounter with the BigCorp Hats checkout system, which revealed a critical vulnerability.

Central to this system is a Cart class, responsible for handling the items a customer adds to their cart. Within this class, each item is represented as a Product object, comprising an ID, name, price, and crucially, a count variable. This count, a short integer, tracks the number of each product type in the cart.

In Jamie's case, her curiosity led her to add an exceptionally large number of items to her cart. For each product added, the count was incremented accordingly. The crucial flaw appeared in the Total method. This method is designed to compute the cart's total cost by multiplying each product's price by its count and summing up these values. However, since totalCost is a short integer, capable of holding values only up to 32767, the accumulated sum of price * count for all products in the cart rapidly approached this upper limit.

As Jamie continued to add more items, the total cost inevitably exceeded the maximum value a short integer can hold, triggering an integer overflow. In C++, when such an overflow occurs, the number wraps around to the minimum value of its range, which for a short integer is -32768. Thus, beyond the overflow point, the total cost began to cycle through negative values.

The BigCorp Hats’ system, not equipped to recognize or handle such a wraparound, failed to interpret this negative total as an error. Consequently, when Jamie proceeded to check out, the system read the negative total cost as zero or less, resulting in the unusual scenario where no payment was required for her large order.

What is the impact of integer overflow or wraparound?

The impact of integer overflow and wraparounds varies depending on the context of the variable and the code that is vulnerable. Often, the result is an accidental malfunction in the application’s logic, which can manifest in different ways. For example, in a financial system, an overflow might cause incorrect transaction totals, potentially leading to financial discrepancies. In other systems, such as data processing applications, an overflow could corrupt data integrity, making the output unreliable.

Security-wise, these vulnerabilities can be abused by attackers as well, leading to all kinds of impacts. In the scenario with Jamie at BigCorp Hats, the overflow in the cart's total cost calculation led to a negative total, bypassing the payment requirement. This scenario demonstrates how a simple overlooked integer, with a too small maximum size, can lead to significant impacts. The developers probably never imagined anyone ordering this much, as their website only sells cheap products, leading to small total order costs. But in the realm of cybersecurity, it's essential to account for the unexpected, as hackers are not your typical customers.

Scan your code & stay secure with Snyk - for FREE!

Did you know you can use Snyk for free to verify that your code
doesn't include this or other vulnerabilities?

Scan your code

Integer overflow or wraparound mitigation

Integer overflows and wraparounds have been around for a long time, and luckily there are numerous ways to prevent, mitigate, and detect them effectively. Choosing the right data type is often the best option for defence. In many cases, simply opting for a larger data type like long long instead of int or short can ward off the risk of an overflow. It's about ensuring that the data type can comfortably accommodate the range of values it's expected to handle.

Additionally, it's essential to integrate checks directly into your code. For instance, in our scenario with Jamie and the BigCorp Hats checkout system, setting a limit on the number of items per order, say a maximum of 200 (that's a lot of hats), could be a practical solution. This type of check acts as a barrier, preventing the total from reaching a point where an overflow could occur. It's a proactive approach, stopping the problem before it has a chance to manifest.

On top of these measures, using compiler flags is a smart way to detect potential overflows. Flags like -ftrapv in C++ serve as an early warning system, flagging any operations that might cause an overflow during the development and testing phases. This, along with regular code audits and perhaps incorporating libraries for safe arithmetic, creates an extra layer of security against this bug class.

Applying these strategies to the code from our scenario with Jamie is fairly easy too. With a larger data type for totalCost and built-in checks to prevent excessive item counts, the checkout system becomes equipped to handle orders gracefully, ensuring accurate and safe transactions.

FUN FACT

Pac-Man

Did you know that, due to an integer overflow, Pac-Man used to be impossible to complete? When players reached level 256, the game experienced a bug that scrambled half of the screen, making further progress unachievable.

Quiz

Test your knowledge!

Quiz

Which of the following best describes a common security risk of integer overflow or wraparound in software applications?

Keep learning

Check out these resources to learn more:

Congratulations

You have taken an important step in understanding the risks associated with integer overflows in software development. By learning how to recognize scenarios that can trigger overflows, apply proper validation and bounds-checking, and use safe coding practices or language features that guard against these vulnerabilities, you can strengthen the reliability and security of your applications.

We hope this lesson has provided valuable insights into detecting and mitigating integer overflow issues. Apply this knowledge to critically assess your code and dependencies, ensuring your applications are built with robust safeguards against this class of vulnerabilities.