Integer Coercion Error

Description

Integer Coercion Error is a vulnerability that occurs when primitive data types are incorrectly cast, extended, or truncated during type conversion operations. This weakness arises when a value of one integer type is converted to another integer type that cannot properly represent the original value, leading to data loss, unexpected value changes, or security-critical errors. In languages like C and C++, the distinction between implicit coercion performed by the compiler and explicit casting by the programmer creates subtle vulnerabilities. When a larger integer type is converted to a smaller one (truncation), or when signed and unsigned types are mixed, the resulting value may differ significantly from the original, potentially bypassing security checks or causing buffer overflows.

Risk

Integer coercion errors pose significant security risks because they can silently corrupt data and bypass security mechanisms designed to protect against other vulnerabilities. When integer values are truncated or improperly converted, size calculations may become incorrect, leading to undersized buffer allocations that result in buffer overflows. These errors can cause applications to enter undefined execution states, infinite loops, or crash unexpectedly, impacting system availability. In security-critical contexts, such as authentication systems or cryptographic implementations, integer coercion can enable attackers to circumvent validation checks and gain unauthorized access or execute arbitrary code.

Solution

Prevent integer coercion errors by using consistent integer types throughout calculations and explicitly validating values before type conversions. Employ safe integer libraries such as SafeInt (C++) or IntegerLib that detect and handle overflow and truncation conditions. When converting between integer types, always verify that the source value falls within the valid range of the destination type before performing the conversion. Enable compiler warnings for implicit type conversions and treat these warnings as errors. In languages with strong typing, prefer using the appropriate integer size for the task and avoid unnecessary conversions. Implement runtime checks for critical operations and use static analysis tools to identify potential coercion issues during development.

Common Consequences

ImpactDetails
AvailabilityScope: Availability

Integer coercion often leads to undefined states of execution resulting in infinite loops or crashes. Resource consumption increases as the application enters error states, potentially causing denial of service conditions.
Integrity, Confidentiality, AvailabilityScope: Integrity, Confidentiality, Availability

In some cases, integer coercion errors can lead to exploitable buffer overflow conditions, resulting in the execution of arbitrary code. This compromises all three security properties as attackers can read sensitive data, modify system state, and crash applications.
Data IntegrityScope: Integrity

Integer coercion errors result in incorrect values being stored for affected variables, corrupting application data and potentially leading to incorrect program behavior or security bypasses.

Example Code

Vulnerable Code (C)

The following code demonstrates a vulnerable pattern where a signed integer is coerced to an unsigned type, potentially bypassing a bounds check:

#include <stdio.h>
#include <string.h>

void process_data(char *buffer, int user_length) {
    char internal_buffer[256];

    // Vulnerable: signed int compared to unsigned size_t
    // If user_length is negative, this check passes but memcpy fails
    if (user_length > sizeof(internal_buffer)) {
        printf("Error: Length too large\n");
        return;
    }

    // user_length is implicitly converted to size_t (unsigned)
    // A negative value becomes a very large positive number
    memcpy(internal_buffer, buffer, user_length);

    printf("Processed %d bytes\n", user_length);
}

int main() {
    char data[512] = "Some data";

    // Attacker supplies negative length
    int malicious_length = -1;  // Becomes 0xFFFFFFFF when converted to size_t

    process_data(data, malicious_length);
    return 0;
}

The vulnerability occurs because the comparison user_length > sizeof(internal_buffer) compares a signed integer to an unsigned value. When user_length is negative, it passes the check but is converted to a massive unsigned value in memcpy(), causing a buffer overflow.

Fixed Code (C)

#include <stdio.h>
#include <string.h>
#include <stdint.h>

int process_data_safe(char *buffer, int user_length) {
    char internal_buffer[256];

    // Fix 1: Explicitly check for negative values first
    if (user_length < 0) {
        printf("Error: Negative length not allowed\n");
        return -1;
    }

    // Fix 2: Use consistent types for comparison
    size_t safe_length = (size_t)user_length;

    if (safe_length > sizeof(internal_buffer)) {
        printf("Error: Length too large\n");
        return -1;
    }

    // Now the conversion is safe
    memcpy(internal_buffer, buffer, safe_length);

    printf("Processed %zu bytes\n", safe_length);
    return 0;
}

// Alternative: Use size_t from the start
int process_data_better(char *buffer, size_t user_length) {
    char internal_buffer[256];

    // No coercion needed - types match
    if (user_length > sizeof(internal_buffer)) {
        printf("Error: Length too large\n");
        return -1;
    }

    memcpy(internal_buffer, buffer, user_length);
    printf("Processed %zu bytes\n", user_length);
    return 0;
}

int main() {
    char data[512] = "Some data";

    // Safe handling of potentially malicious input
    int user_input = -1;
    process_data_safe(data, user_input);  // Properly rejected

    return 0;
}

The fix ensures that negative values are explicitly checked before any type conversion occurs. Using consistent unsigned types like size_t for length parameters eliminates the coercion vulnerability entirely.


Exploited in the Wild

FORCEDENTRY Zero-Click Exploit (Apple/NSO Group, 2021)

The FORCEDENTRY exploit developed by NSO Group leveraged an integer overflow vulnerability in Apple's CoreGraphics image rendering library to deploy Pegasus spyware on iPhones without any user interaction. The attack used maliciously crafted PDF files disguised as GIF images to trigger the integer overflow, bypassing Apple's BlastDoor sandbox security. Citizen Lab discovered the exploit while analyzing the phone of a Saudi activist, finding that it had been in use since at least February 2021. The vulnerability affected iOS, macOS, and watchOS devices, leading Apple to release emergency patches and subsequently file a lawsuit against NSO Group.

Heartbleed OpenSSL Vulnerability (Multiple Organizations, 2014)

While primarily classified as a buffer over-read, the Heartbleed vulnerability (CVE-2014-0160) demonstrated how improper handling of integer values in bounds checking can lead to catastrophic security failures. The vulnerable code failed to validate that an integer payload length matched the actual packet data size, allowing attackers to read up to 64KB of server memory per request. Attackers exploited this flaw to steal private keys, session cookies, and passwords from millions of servers. At disclosure, approximately 17% of secure web servers were vulnerable, and attacks continued for years afterward, including breaches at Community Health Systems and the Canadian Revenue Agency.

BeautyChain Smart Contract Exploit (BeautyChain, 2018)

An integer overflow vulnerability in the BeautyChain (BEC) Ethereum smart contract allowed attackers to bypass security checks and generate an astronomical number of tokens out of thin air. The vulnerability existed in the token transfer function where multiplication of large values caused the result to wrap around to a small number, passing validation checks while crediting massive amounts to attacker wallets. This incident resulted in the loss of the contract's entire token value and led to the token being delisted from exchanges. The attack highlighted how integer handling issues in blockchain applications can have immediate and irreversible financial consequences.


Tools to Test/Exploit

  • Clang Static Analyzer — Static analysis tool that detects integer conversion issues, signedness errors, and potential overflow conditions in C/C++ code.

  • Cppcheck — Open-source static analysis tool for C/C++ that identifies integer coercion errors, truncation issues, and sign conversion problems.

  • PVS-Studio — Commercial static analyzer that detects a wide range of integer-related vulnerabilities including coercion errors, overflow, and improper type conversions.


CVE Examples

  • CVE-2022-2639 — An integer coercion error in the Linux kernel's openvswitch module prevented proper error detection, enabling a subsequent out-of-bounds write vulnerability.

  • CVE-2021-30860 — Integer overflow in Apple's CoreGraphics library exploited by NSO Group's FORCEDENTRY to achieve arbitrary code execution via malicious PDFs.

  • CVE-2009-1385 — Integer underflow in the e1000 driver for Linux kernel allowed remote attackers to cause denial of service via crafted network frames.


References

  1. MITRE Corporation. "CWE-192: Integer Coercion Error." Common Weakness Enumeration. https://cwe.mitre.org/data/definitions/192.html

  2. Seacord, Robert C. "Secure Coding in C and C++, Second Edition." Addison-Wesley Professional, 2013.

  3. CERT Coordination Center. "INT31-C. Ensure that integer conversions do not result in lost or misinterpreted data." SEI CERT C Coding Standard. https://wiki.sei.cmu.edu/confluence/display/c/INT31-C.+Ensure+that+integer+conversions+do+not+result+in+lost+or+misinterpreted+data

  4. Citizen Lab. "FORCEDENTRY: NSO Group iMessage Zero-Click Exploit Captured in the Wild." September 2021. https://citizenlab.ca/2021/09/forcedentry-nso-group-imessage-zero-click-exploit-captured-in-the-wild/