CWE-681 Base Borrador High likelihood

Incorrect Conversion between Numeric Types

This vulnerability occurs when a program converts a value from one numeric type to another (like a 64-bit integer to a 32-bit integer) and the conversion loses or misinterprets data. If these…

Definición

What is CWE-681?

This vulnerability occurs when a program converts a value from one numeric type to another (like a 64-bit integer to a 32-bit integer) and the conversion loses or misinterprets data. If these corrupted values are later used in security-critical operations—like calculating buffer sizes, checking permissions, or performing financial transactions—they can lead to crashes, incorrect behavior, or security bypasses.
At its core, this flaw is about mismatched containers. Think of pouring a gallon of water into a quart-sized bottle; you're going to lose most of the water. In programming, this 'spillage' happens during type casting or implicit conversion when a larger data type (like a `long` or `size_t`) is squeezed into a smaller one (like an `int`). The high-order bits are simply chopped off—a process called truncation—which silently turns a large number into a much smaller, and often positive, number. This is especially dangerous because the code might not crash; it just starts working with wildly incorrect data. Developers most often encounter this when dealing with memory sizes, array indices, or loop counters in code that must work across different architectures (32-bit vs. 64-bit). The primary defense is to proactively validate that a value fits within the target type's range *before* performing the conversion. Use compiler warnings, static analysis tools, and explicit checks with limits defined in headers like ``. Always assume that inputs, especially those derived from user or file data, can exceed your variable's capacity.
Impacto en el mundo real

Real-world CVEs caused by CWE-681

  • Chain: integer coercion error (CWE-192) prevents a return value from indicating an error, leading to out-of-bounds write (CWE-787)

  • Chain: in a web browser, an unsigned 64-bit integer is forcibly cast to a 32-bit integer (CWE-681) and potentially leading to an integer overflow (CWE-190). If an integer overflow occurs, this can cause heap memory corruption (CWE-122)

  • Chain: integer signedness error (CWE-195) passes signed comparison, leading to heap overflow (CWE-122)

  • Chain: signed short width value in image processor is sign extended during conversion to unsigned int, which leads to integer overflow and heap-based buffer overflow.

  • Integer truncation of length value leads to heap-based buffer overflow.

  • Size of a particular type changes for 64-bit platforms, leading to an integer truncation in document processor causes incorrect index to be generated.

Cómo lo explotan los atacantes

Ruta del atacante paso a paso

  1. 1

    In the following Java example, a float literal is cast to an integer, thus causing a loss of precision.

  2. 2

    This code adds a float and an integer together, casting the result to an integer.

  3. 3

    Normally, PHP will preserve the precision of this operation, making $result = 4.8345. After the cast to int, it is reasonable to expect PHP to follow rounding convention and set $result = 5. However, the explicit cast to int always rounds DOWN, so the final value of $result is 4. This behavior may have unintended consequences.

  4. 4

    In this example the variable amount can hold a negative value when it is returned. Because the function is declared to return an unsigned int, amount will be implicitly converted to unsigned.

  5. 5

    If the error condition in the code above is met, then the return value of readdata() will be 4,294,967,295 on a system that uses 32-bit integers.

Ejemplo de código vulnerable

Vulnerable Java

In the following Java example, a float literal is cast to an integer, thus causing a loss of precision.

Vulnerable Java
int i = (int) 33457.8f;
Ejemplo de código seguro

Secure pseudo

Seguro pseudo
// Validate, sanitize, or use a safe API before reaching the sink.
function handleRequest(input) {
  const safe = validateAndEscape(input);
  return executeWithGuards(safe);
}
What changed: the unsafe sink is replaced (or the input is validated/escaped) so the same payload no longer triggers the weakness.
Lista de prevención

How to prevent CWE-681

  • Implementation Avoid making conversion between numeric types. Always check for the allowed ranges.
Señales de detección

How to detect CWE-681

SAST High

Ejecuta análisis estático (SAST) sobre el código buscando el patrón inseguro en el flujo de datos.

DAST Moderate

Ejecuta pruebas dinámicas de seguridad de aplicaciones (DAST) contra el endpoint en vivo.

Runtime Moderate

Vigila los logs en tiempo de ejecución para detectar trazas de excepción inusuales, entradas malformadas o intentos de bypass de autorización.

Code review Moderate

Revisión de código: marca cualquier código nuevo que maneje entrada desde esta superficie sin usar los helpers validados del framework.

Auto-corrección de Plexicus

Plexicus detecta automáticamente CWE-681 y abre un PR de corrección en menos de 60 segundos.

Codex Remedium escanea cada commit, identifica esta debilidad concreta y entrega un pull request listo para revisión con el parche. Sin tickets. Sin traspasos.

Preguntas frecuentes

Frequently asked questions

¿Qué es CWE-681?

This vulnerability occurs when a program converts a value from one numeric type to another (like a 64-bit integer to a 32-bit integer) and the conversion loses or misinterprets data. If these corrupted values are later used in security-critical operations—like calculating buffer sizes, checking permissions, or performing financial transactions—they can lead to crashes, incorrect behavior, or security bypasses.

¿Qué gravedad tiene CWE-681?

MITRE califica la probabilidad de explotación como Alta — esta debilidad se explota activamente en la práctica y debe priorizarse para su remediación.

¿Qué lenguajes o plataformas se ven afectados por CWE-681?

MITRE lists the following affected platforms: C.

¿Cómo puedo prevenir CWE-681?

Avoid making conversion between numeric types. Always check for the allowed ranges.

¿Cómo detecta y corrige Plexicus CWE-681?

El motor SAST de Plexicus detecta la firma de flujo de datos para CWE-681 en cada commit. Cuando hay coincidencia, nuestro agente Codex Remedium abre un PR de corrección con el código corregido, las pruebas y un resumen de una línea para el revisor.

¿Dónde puedo aprender más sobre CWE-681?

MITRE publica la definición canónica en https://cwe.mitre.org/data/definitions/681.html. También puedes consultar la documentación de OWASP y NIST para guías relacionadas.

Debilidades relacionadas

Weaknesses related to CWE-681

CWE-704 Padre

Incorrect Type Conversion or Cast

This vulnerability occurs when software incorrectly changes data from one type to another, leading to unexpected behavior or security flaws.

CWE-1389 Hermano

Incorrect Parsing of Numbers with Different Radices

This vulnerability occurs when software processes numeric input expecting standard decimal numbers (base 10), but fails to handle inputs…

CWE-588 Hermano

Attempt to Access Child of a Non-structure Pointer

This vulnerability occurs when code incorrectly treats a pointer to a basic data type (like an integer) as if it points to a structured…

CWE-843 Hermano

Access of Resource Using Incompatible Type ('Type Confusion')

Type confusion occurs when a program creates a resource—like a pointer, object, or variable—with one data type, but later incorrectly…

CWE-682 Puede preceder

Incorrect Calculation

This vulnerability occurs when software performs a calculation that produces wrong or unexpected results, which are then used to make…

CWE-192 Hijo

Integer Coercion Error

An integer coercion error occurs when a program incorrectly converts, extends, or truncates a number between different data types, leading…

CWE-194 Hijo

Unexpected Sign Extension

This vulnerability occurs when a signed number from a smaller data type is moved or cast to a larger type, causing its sign bit to be…

CWE-195 Hijo

Signed to Unsigned Conversion Error

This vulnerability occurs when a signed integer (which can hold negative values) is converted to an unsigned integer (which holds only…

CWE-196 Hijo

Unsigned to Signed Conversion Error

This vulnerability occurs when a program takes an unsigned integer and converts it directly to a signed integer. If the original unsigned…

Listo cuando tú lo estés

Deja de pagar por desarrollador.
Empieza a cerrar el bucle.

Plexicus es el ASPM nativo de IA que escanea, filtra, corrige, pentestea y explica — de forma autónoma. Desarrolladores ilimitados, repos ilimitados, acciones de IA de uso justo. Nivel gratuito real, €269/mo anual cuando estés listo.