HIGH CWE-190 Input Validation

CWE-190 in APIs

CWE ID
CWE-190
Category
Input Validation
Severity
HIGH
Short Name
Integer Overflow

What is Cwe 190?

Cwe 190: Integer Overflow or Wraparound occurs when an arithmetic operation attempts to create a numeric value that exceeds the maximum size of the integer type used to store it. This weakness can lead to unexpected behavior, crashes, or security vulnerabilities when the overflow results in incorrect calculations or logic bypasses.

The core issue is that most programming languages use fixed-width integers (32-bit, 64-bit) with defined minimum and maximum values. When calculations exceed these bounds, the value 'wraps around' to the opposite end of the range. For example, a 32-bit signed integer ranges from -2,147,483,648 to 2,147,483,647. Adding 1 to 2,147,483,647 results in -2,147,483,648.

This weakness manifests in several ways: buffer size calculations that overflow, loop counters that wrap around, array indexing that becomes negative, or resource allocation amounts that become unexpectedly small. Attackers can exploit integer overflows to bypass security checks, cause denial of service, or manipulate application logic.

Cwe 190 in API Contexts

APIs are particularly vulnerable to integer overflow vulnerabilities because they often process user-supplied numeric values for resource allocation, pagination, and array operations. The stateless nature of APIs means attackers can repeatedly send crafted requests without maintaining session state.

Common API scenarios include:

  • Pagination parameters: APIs often accept 'limit' and 'offset' parameters for pagination. An attacker can supply extremely large values that cause integer overflows in database queries or memory allocation.
  • Array size calculations: APIs processing arrays of user data might calculate total sizes for processing or storage, where overflow leads to buffer under-allocation.
  • Resource quotas: APIs implementing rate limiting or resource quotas might use integer counters that wrap around, allowing unlimited access.
  • Binary data processing: APIs handling binary protocols or file uploads often calculate buffer sizes based on user-supplied length fields.

Consider an API endpoint that processes batch operations:

def process_batch(request):
count = int(request.args.get('count', 10))
total_size = count * 1024 # 1KB per item
buffer = allocate_buffer(total_size)
# Process items into buffer

If 'count' is 4,194,305 (2^22 + 1), the multiplication overflows a 32-bit integer, potentially resulting in a negative or very small buffer size, leading to buffer overflow vulnerabilities.

Detection

Detecting integer overflow vulnerabilities requires both static analysis and dynamic testing. Static analysis tools can identify risky arithmetic operations and type conversions, but they often miss context-specific vulnerabilities that only manifest with certain input values.

Dynamic testing approaches include:

  • Fuzzing with boundary values: Test APIs with maximum integer values, values just above maximum, and values that would cause overflow when combined with other parameters.
  • Property-based testing: Use libraries like Hypothesis to generate test cases that explore edge cases and overflow conditions automatically.
  • Runtime monitoring: Implement checks that validate calculations before they execute, logging suspicious patterns.

middleBrick provides automated detection of integer overflow vulnerabilities through its comprehensive API security scanning. The scanner tests API endpoints with boundary values and malformed inputs to identify potential overflow conditions. For each endpoint, middleBrick sends requests with maximum integer values, negative numbers where inappropriate, and values designed to trigger arithmetic overflows.

The scanner specifically checks for:

  • Integer parameters that could overflow during calculations
  • Array size parameters that might cause buffer under-allocation
  • Loop counters and pagination parameters
  • Resource allocation calculations

When middleBrick detects potential integer overflow vulnerabilities, it provides detailed findings including the specific endpoint, parameter, and attack scenario that triggered the issue, along with severity assessment and remediation guidance.

Remediation

Remediating integer overflow vulnerabilities requires a defense-in-depth approach combining safe coding practices, input validation, and runtime checks.

Input Validation and Sanitization

Always validate numeric inputs before processing:

def process_batch(request):
count = request.args.get('count', '10')
try:
count = int(count)
except ValueError:
return {'error': 'Invalid count value'}, 400

# Validate range before any calculations
if count < 1 or count > 1000:
return {'error': 'Count must be between 1 and 1000'}, 400

Safe Arithmetic Operations

Use safe arithmetic libraries or implement overflow checks:

def safe_multiply(a, b, max_value=2**31 - 1):
if a > 0 and b > 0 and a > max_value // b:
raise OverflowError('Multiplication would overflow')
return a * b

def process_batch(request):
count = int(request.args.get('count', 10))
try:
total_size = safe_multiply(count, 1024)
except OverflowError:
return {'error': 'Request too large'}, 400

Using Larger Integer Types

When possible, use larger integer types to provide headroom:

from typing import Optional
import sys

def process_batch(request):
count = int(request.args.get('count', 10))
if count < 1 or count > 1_000_000:
return {'error': 'Count out of practical range'}, 400
# For systems with fixed-width integers, use 64-bit where possible
total_size = count * 1024 # Python handles big ints, but check against system limits
return {'error': 'Request exceeds system limits'}, 400

Defense-in-Depth Implementation

Combine multiple layers of protection:

class SafeAPIProcessor:
MAX_BATCH_SIZE = 1000
MAX_TOTAL_BYTES = 10 * 1024 * 1024 # 10MB

def validate_batch_request(self, count: int, item_size: int) -> Optional[str]:
# Range validation
if count < 1 or count > self.MAX_BATCH_SIZE:
return f'Count must be between 1 and {self.MAX_BATCH_SIZE}'

# Overflow-safe calculation
try:
total_size = count * item_size
except OverflowError:
return 'Size calculation overflow'

# Practical limit check
if total_size > self.MAX_TOTAL_BYTES:
return f'Total size exceeds {self.MAX_TOTAL_BYTES} bytes'

return None

def process_batch(self, request):
count = int(request.args.get('count', 10))
item_size = int(request.args.get('item_size', 1024))
validation_error = self.validate_batch_request(count, item_size)
if validation_error:
return {'error': validation_error}, 400
# Safe to proceed with processing

Language-Specific Considerations

Different languages require different approaches:

  • Python: Uses arbitrary precision integers, but you should still validate practical limits and handle system resource constraints
  • JavaScript: Uses IEEE 754 doubles, which can exactly represent integers up to 2^53 - 1. Use BigInt for larger values
  • Java/C#: Use checked arithmetic or libraries like Google's Guava that provide safe math operations
  • C/C++: Most vulnerable; always use safe integer libraries and enable compiler warnings

Frequently Asked Questions

How does middleBrick detect integer overflow vulnerabilities in APIs?
middleBrick uses dynamic testing to identify potential integer overflow vulnerabilities. The scanner sends requests with boundary values, maximum integers, and crafted inputs designed to trigger arithmetic overflows. It analyzes API responses for error patterns, crashes, or unexpected behavior that might indicate overflow conditions. The tool also examines API specifications to understand parameter types and expected ranges, then tests beyond those boundaries to identify vulnerabilities.
Can integer overflows be exploited remotely through APIs?
Yes, integer overflows in APIs can be exploited remotely. Attackers can craft HTTP requests with malicious numeric values that cause overflows in server-side calculations. Common exploitation scenarios include bypassing authentication checks, causing denial of service through crashes, manipulating resource allocation to trigger buffer overflows, or manipulating pagination to access unauthorized data. The stateless nature of APIs makes them particularly vulnerable to repeated automated attacks.