Weakness reference
CWE-190

Integer Overflow or Wraparound

Integer overflow occurs when a calculation produces a result that exceeds the maximum value an integer variable can hold, causing the value to wrap around to a…

01Summary

Integer overflow occurs when a calculation produces a result that exceeds the maximum value an integer variable can hold, causing the value to wrap around to a small or negative number. This can lead to unexpected behavior, memory corruption, or security vulnerabilities if the overflowed value is used in size calculations, loop conditions, or access control decisions.

02How It Happens

Most programming languages represent integers using a fixed number of bits. When an arithmetic operation (addition, multiplication, etc.) produces a result larger than the maximum representable value, the excess bits are discarded and the value wraps. For example, adding 1 to the maximum 32-bit signed integer (2,147,483,647) results in −2,147,483,648. If this wrapped value is then used to allocate memory, validate a size, or control a loop, the program may behave in unintended ways—allocating too little memory, skipping validation checks, or reading/writing beyond buffer boundaries.

03Real-World Impact

Integer overflow vulnerabilities can lead to buffer overflows, heap corruption, or denial of service. A classic scenario: if an attacker controls input that influences a size calculation, they may cause the calculation to overflow, resulting in a smaller-than-expected buffer allocation. Subsequent writes to that buffer then overflow into adjacent memory, potentially corrupting data or enabling code execution. In other cases, an overflowed value used in a security check (e.g., comparing a calculated size against a limit) may bypass the check entirely.

04Vulnerable & Fixed Patterns

Vulnerable pattern
def allocate_buffer(user_count):
    # user_count is attacker-controlled
    buffer_size = user_count * 256  # Can overflow if user_count is large
    buffer = bytearray(buffer_size)
    return buffer

# If user_count = 2**31, buffer_size wraps to a small value
# Buffer is allocated too small; subsequent writes overflow

Why it's vulnerable:
The multiplication user_count * 256 can exceed the maximum integer value, wrapping to a small number. If this wrapped value is used to allocate memory, the buffer will be far smaller than intended, leading to overflow on writes.

Fixed pattern
import sys

def allocate_buffer(user_count):
    MAX_USERS = 1_000_000  # Reasonable upper limit
    BYTES_PER_USER = 256
    
    if user_count < 0 or user_count > MAX_USERS:
        raise ValueError("Invalid user count")
    
    # Check for overflow before multiplication
    if user_count > sys.maxsize // BYTES_PER_USER:
        raise ValueError("Allocation size too large")
    
    buffer_size = user_count * BYTES_PER_USER
    buffer = bytearray(buffer_size)
    return buffer
Vulnerable pattern
<?php
function process_items($item_count) {
    // item_count is from user input
    $total_size = $item_count * 1024;  // Can overflow
    $data = str_repeat("\x00", $total_size);
    return $data;
}

// If item_count is very large, $total_size wraps to a small value
?>

Why it's vulnerable:
PHP integers can overflow silently. If $item_count * 1024 exceeds PHP_INT_MAX, the result wraps to a negative or small value, causing str_repeat() to allocate far less memory than expected.

Fixed pattern
<?php
function process_items($item_count) {
    $MAX_ITEMS = 100_000;
    $BYTES_PER_ITEM = 1024;
    
    if (!is_int($item_count) || $item_count < 0 || $item_count > $MAX_ITEMS) {
        throw new Exception("Invalid item count");
    }
    
    // Check for overflow before multiplication
    if ($item_count > PHP_INT_MAX / $BYTES_PER_ITEM) {
        throw new Exception("Allocation size too large");
    }
    
    $total_size = $item_count * $BYTES_PER_ITEM;
    $data = str_repeat("\x00", $total_size);
    return $data;
}
?>

05Prevention Checklist

Validate input ranges:
Enforce strict upper and lower bounds on any user-controlled values used in arithmetic operations.
Check before arithmetic:
Before multiplying or adding, verify that the result will not overflow by comparing operands against safe limits.
Use safe integer libraries:
Consider using language features or libraries designed to detect or prevent overflow (e.g., Python's sys.maxsize, checked arithmetic in Rust).
Avoid integer arithmetic for sizes:
Where possible, use language-native size/length types (e.g., len() in Python) rather than manual calculations.
Test with boundary values:
Include test cases with very large inputs, negative values, and edge cases near integer limits.
Code review:
Pay special attention to multiplication and addition operations involving user input or external data.

06Signs You May Already Be Affected

Look for unexpected crashes, memory corruption errors, or segmentation faults in logs, especially when processing large or unusual input values. Unexplained buffer overflows or heap corruption detected by memory sanitizers may indicate an integer overflow upstream. If you see error messages related to allocation failures or negative sizes in debug output, investigate arithmetic operations on user-controlled values.

07Related Recent Vulnerabilities