Weakness reference
CWE-680

Integer Overflow to Buffer Overflow

This weakness occurs when a program calculates a buffer size using integer arithmetic, but an overflow in that calculation causes the result to wrap around to…

01Summary

This weakness occurs when a program calculates a buffer size using integer arithmetic, but an overflow in that calculation causes the result to wrap around to a much smaller number. The program then allocates a tiny buffer based on that incorrect size, and later writes data into it as if it were large — causing a buffer overflow. This can lead to memory corruption, crashes, or code execution.

02How It Happens

A developer writes code to allocate memory for a buffer by multiplying or adding integers — for example, buffer_size = num_items * item_size. If the multiplication overflows (the true result exceeds the maximum value an integer can hold), the result wraps around to a small positive number or even zero. The program allocates that small buffer, then proceeds to fill it with the full amount of data it intended, writing far past the allocated boundary. The overflow in the size calculation is invisible to the allocator; it sees only the wrapped result.

This is particularly dangerous in languages like C and C++ where buffer bounds are not automatically checked. The weakness often appears in code that processes user-controlled counts or sizes — for instance, reading a file header that specifies how many records follow, or accepting a network packet that declares its payload length.

03Real-World Impact

An attacker who can control the values used in the size calculation can trigger an integer overflow, causing a small buffer to be allocated. By then providing data matching the original (pre-overflow) size, they overflow the buffer and corrupt adjacent memory. Depending on what is stored nearby, this can overwrite function pointers, return addresses, or other critical data structures, potentially allowing arbitrary code execution. Even without code execution, the memory corruption can crash the application or leak sensitive data.

04Vulnerable & Fixed Patterns

Vulnerable pattern
import struct

def read_records(data):
    # data is untrusted input; first 4 bytes are a count
    count = struct.unpack('>I', data[0:4])[0]
    record_size = 256
    
    # Integer overflow: if count is very large, this wraps
    buffer_size = count * record_size
    
    # Allocate a small buffer due to wrapped size
    buffer = bytearray(buffer_size)
    
    # Attempt to write all records into the undersized buffer
    offset = 4
    for i in range(count):
        record = data[offset:offset + record_size]
        buffer[i * record_size:(i + 1) * record_size] = record
        offset += record_size
    
    return buffer

Why it's vulnerable:
If count is set to a value such that count * record_size overflows, buffer_size becomes much smaller than intended. The loop then writes far beyond the allocated buffer's bounds.

Fixed pattern
import struct

def read_records(data):
    count = struct.unpack('>I', data[0:4])[0]
    record_size = 256
    
    # Check for overflow before multiplication
    max_count = (2**31 - 1) // record_size
    if count > max_count:
        raise ValueError("Count too large; would overflow")
    
    buffer_size = count * record_size
    buffer = bytearray(buffer_size)
    
    offset = 4
    for i in range(count):
        record = data[offset:offset + record_size]
        buffer[i * record_size:(i + 1) * record_size] = record
        offset += record_size
    
    return buffer
Vulnerable pattern
<?php
function allocate_records($count, $record_size) {
    // $count is user-supplied
    $buffer_size = $count * $record_size;
    
    // On 32-bit systems or with large values, this can overflow
    // $buffer_size wraps to a small number
    $buffer = str_repeat("\x00", $buffer_size);
    
    return $buffer;
}

$user_count = $_GET['count'];
$buf = allocate_records($user_count, 256);
// Later, code writes $user_count * 256 bytes into $buf
// causing an overflow if the multiplication wrapped
?>

Why it's vulnerable:
PHP's integer multiplication can overflow on 32-bit systems or with very large operands. If $count * $record_size wraps, the allocated buffer is far smaller than the code expects to fill.

Fixed pattern
<?php
function allocate_records($count, $record_size) {
    // Validate that multiplication won't overflow
    $max_count = PHP_INT_MAX / $record_size;
    if ($count > $max_count || $count < 0) {
        throw new Exception("Invalid count; would overflow");
    }
    
    $buffer_size = $count * $record_size;
    $buffer = str_repeat("\x00", $buffer_size);
    
    return $buffer;
}

$user_count = (int)$_GET['count'];
$buf = allocate_records($user_count, 256);
?>

05Prevention Checklist

Validate all size inputs:
Before using user-supplied or untrusted values in size calculations, check that they fall within safe ranges.
Check for overflow before arithmetic:
Before multiplying or adding integers to compute a buffer size, verify that the result will not overflow. Use safe integer libraries or explicit range checks.
Use safe allocation functions:
Prefer APIs that take both count and element size separately and perform overflow checks internally (e.g., calloc in C, or higher-level abstractions).
Apply bounds checking at write time:
Even if allocation succeeds, validate that write operations do not exceed the buffer's actual size.
Use memory-safe languages where feasible:
Languages with automatic bounds checking (Python, Java, C#) are not vulnerable to this class of overflow.
Enable compiler warnings and runtime checks:
Use compiler flags (-ftrapv in GCC) or sanitizers (AddressSanitizer) to detect integer overflows during development and testing.

06Signs You May Already Be Affected

Look for unexpected crashes or segmentation faults in your application, especially when processing files or network data with large size fields. Check your logs for patterns of memory corruption or heap errors. If you use C or C++ and process untrusted input to determine buffer sizes, audit those code paths for integer overflow checks.

07Related Recent Vulnerabilities