| name | integer-overflow-anti-pattern |
| description | Security anti-pattern for integer overflow vulnerabilities (CWE-190). Use when generating or reviewing code that performs arithmetic on user-controlled values, handles sizes/quantities, or calculates prices/amounts. Detects overflow in validated inputs. |
Integer Overflow Anti-Pattern
Severity: High
Summary
Integer overflow occurs when arithmetic operations exceed the maximum value for a data type, causing values to wrap around to small or negative numbers instead of erroring. Individually valid user-controlled inputs combined in calculations create exploitable conditions. Attackers bypass security checks, trigger buffer overflows, and manipulate financial transactions through overflow exploitation.
The Anti-Pattern
Never perform arithmetic operations on user-controlled inputs without checking for overflow. Individual input validation is insufficient.
BAD Code Example
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
void process_purchase(uint32_t quantity, uint32_t price_per_item) {
if (quantity > 1000) {
printf("Error: Quantity too high.\n");
return;
}
if (price_per_item > 100000) {
printf("Error: Price per item too high.\n");
return;
}
uint32_t total_cost = quantity * price_per_item;
printf("Charging customer: %u\n", total_cost);
charge_customer(total_cost);
}
GOOD Code Example
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
void process_purchase_safe(uint32_t quantity, uint32_t price_per_item) {
if (quantity > 1000) {
printf("Error: Quantity too high.\n");
return;
}
if (price_per_item > 100000) {
printf("Error: Price per item too high.\n");
return;
}
if (price_per_item > 0 && quantity > UINT32_MAX / price_per_item) {
printf("Error: Potential overflow detected. Transaction cancelled.\n");
return;
}
uint32_t total_cost = quantity * price_per_item;
printf("Charging customer: %u\n", total_cost);
charge_customer(total_cost);
}
Language-Specific Examples
Python:
import ctypes
def allocate_buffer(width, height, bytes_per_pixel):
size = width * height * bytes_per_pixel
buffer = ctypes.create_string_buffer(size)
return buffer
import sys
def allocate_buffer_safe(width, height, bytes_per_pixel):
MAX_INT32 = 2**31 - 1
if height > 0 and width > MAX_INT32 // (height * bytes_per_pixel):
raise ValueError("Buffer size would overflow")
size = width * height * bytes_per_pixel
if size > MAX_INT32:
raise ValueError(f"Buffer size {size} exceeds maximum")
buffer = ctypes.create_string_buffer(size)
return buffer
JavaScript:
function calculateTotal(quantity, pricePerUnit) {
const total = quantity * pricePerUnit;
return total;
}
function calculateTotalSafe(quantity, pricePerUnit) {
const MAX_SAFE = Number.MAX_SAFE_INTEGER;
if (quantity > MAX_SAFE / pricePerUnit) {
throw new Error('Calculation would overflow safe integer range');
}
const total = quantity * pricePerUnit;
return total;
}
function calculateTotalBigInt(quantity, pricePerUnit) {
const total = BigInt(quantity) * BigInt(pricePerUnit);
return total;
}
Java:
public long calculateTotalPrice(int quantity, int pricePerItem) {
long total = quantity * pricePerItem;
return total;
}
public long calculateTotalPriceSafe(int quantity, int pricePerItem) {
try {
return Math.multiplyExact(quantity, pricePerItem);
} catch (ArithmeticException e) {
throw new IllegalArgumentException("Price calculation overflow", e);
}
}
public long calculateTotalPriceSafe2(int quantity, int pricePerItem) {
long total = (long) quantity * pricePerItem;
if (total > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Total exceeds maximum");
}
return total;
}
Detection
- Audit arithmetic operations on user inputs: Search for multiplications and additions:
rg '\*|[+]' --type c --type cpp -A 2 -B 2 (C/C++)
rg 'quantity.*price|amount.*rate|size.*count' -i
- Focus on financial calculations, memory allocations, buffer sizes
- Find missing overflow checks: Identify operations without pre-checks:
rg '(?<!if.*)\w+\s*[*+]\s*\w+' --type c
- Look for calculations not preceded by validation
- Test boundary values: Fuzz with extreme values:
- INT32_MAX: 2,147,483,647
- UINT32_MAX: 4,294,967,295
- INT64_MAX: 9,223,372,036,854,775,807
- Use SAST tools: Automated overflow detection:
- CodeQL:
cpp/uncontrolled-arithmetic
- Clang Static Analyzer:
-analyzer-checker=security.intoverflow
- Semgrep rules for integer overflow patterns
Prevention
Related Security Patterns & Anti-Patterns
References