CWE-839 Base Incompleto

Numeric Range Comparison Without Minimum Check

This vulnerability occurs when software validates that a number is within an acceptable range by only checking that it's less than or equal to a maximum value, but fails to also verify that it is…

Definición

What is CWE-839?

This vulnerability occurs when software validates that a number is within an acceptable range by only checking that it's less than or equal to a maximum value, but fails to also verify that it is greater than or equal to a required minimum. This oversight can allow negative or otherwise invalid low values to pass the check, leading to unexpected behavior.
Developers often use signed data types like integers or floats for values that should logically only be positive or zero. When input validation only enforces an upper limit, a negative value can slip through. This becomes dangerous when that negative number is used in operations like memory allocation, array indexing, or buffer calculations, potentially causing buffer overflows, memory corruption, or application crashes. Beyond memory issues, this flaw can impact application logic in surprising ways. For instance, an e-commerce system that checks 'item count <= 10' but not 'item count >= 0' might process an order for -3 items. This could trigger faulty calculations, like crediting money to an attacker's account instead of charging it. Always validate both the lower and upper bounds to ensure data integrity and security.
Impacto en el mundo real

Real-world CVEs caused by CWE-839

  • Chain: integer overflow (CWE-190) causes a negative signed value, which later bypasses a maximum-only check (CWE-839), leading to heap-based buffer overflow (CWE-122).

  • Chain: 16-bit counter can be interpreted as a negative value, compared to a 32-bit maximum value, leading to buffer under-write.

  • Chain: kernel's lack of a check for a negative value leads to memory corruption.

  • Chain: parser uses atoi() but does not check for a negative value, which can happen on some platforms, leading to buffer under-write.

  • Chain: Negative value stored in an int bypasses a size check and causes allocation of large amounts of memory.

  • Chain: negative offset value to IOCTL bypasses check for maximum index, then used as an array index for buffer under-read.

  • chain: file transfer client performs signed comparison, leading to integer overflow and heap-based buffer overflow.

  • chain: negative ID in media player bypasses check for maximum index, then used as an array index for buffer under-read.

Cómo lo explotan los atacantes

Ruta del atacante paso a paso

  1. 1

    The following code is intended to read an incoming packet from a socket and extract one or more headers.

  2. 2

    The code performs a check to make sure that the packet does not contain too many headers. However, numHeaders is defined as a signed int, so it could be negative. If the incoming packet specifies a value such as -3, then the malloc calculation will generate a negative number (say, -300 if each header can be a maximum of 100 bytes). When this result is provided to malloc(), it is first converted to a size_t type. This conversion then produces a large value such as 4294966996, which may cause malloc() to fail or to allocate an extremely large amount of memory (CWE-195). With the appropriate negative numbers, an attacker could trick malloc() into using a very small positive number, which then allocates a buffer that is much smaller than expected, potentially leading to a buffer overflow.

  3. 3

    The following code reads a maximum size and performs a sanity check on that size. It then performs a strncpy, assuming it will not exceed the boundaries of the array. While the use of "short s" is forced in this particular example, short int's are frequently used within real-world code, such as code that processes structured data.

  4. 4

    This code first exhibits an example of CWE-839, allowing "s" to be a negative number. When the negative short "s" is converted to an unsigned integer, it becomes an extremely large positive integer. When this converted integer is used by strncpy() it will lead to a buffer overflow (CWE-119).

  5. 5

    In the following code, the method retrieves a value from an array at a specific array index location that is given as an input parameter to the method

Ejemplo de código vulnerable

Vulnerable C

The following code is intended to read an incoming packet from a socket and extract one or more headers.

Vulnerable C
DataPacket *packet;
  int numHeaders;
  PacketHeader *headers;
  sock=AcceptSocketConnection();
  ReadPacket(packet, sock);
  numHeaders =packet->headers;
  if (numHeaders > 100) {
  	ExitError("too many headers!");
  }
  headers = malloc(numHeaders * sizeof(PacketHeader);
  ParsePacketHeaders(packet, headers);
Ejemplo de código seguro

Secure C

However, this method only verifies that the given array index is less than the maximum length of the array but does not check for the minimum value (CWE-839). This will allow a negative value to be accepted as the input array index, which will result in reading data before the beginning of the buffer (CWE-127) and may allow access to sensitive memory. The input array index should be checked to verify that is within the maximum and minimum range required for the array (CWE-129). In this example the if statement should be modified to include a minimum range check, as shown below.

Seguro C
...
```
// check that the array index is within the correct* 
  
  
   *// range of values for the array* 
  if (index >= 0 && index < len) {
  
  ...
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-839

  • Implementation If the number to be used is always expected to be positive, change the variable type from signed to unsigned or size_t.
  • Implementation If the number to be used could have a negative value based on the specification (thus requiring a signed value), but the number should only be positive to preserve code correctness, then include a check to ensure that the value is positive.
Señales de detección

How to detect CWE-839

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-839 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-839?

This vulnerability occurs when software validates that a number is within an acceptable range by only checking that it's less than or equal to a maximum value, but fails to also verify that it is greater than or equal to a required minimum. This oversight can allow negative or otherwise invalid low values to pass the check, leading to unexpected behavior.

¿Qué gravedad tiene CWE-839?

MITRE no ha publicado una calificación de probabilidad de explotación para esta debilidad. Trátala como de impacto medio hasta que tu modelo de amenazas demuestre lo contrario.

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

MITRE lists the following affected platforms: C, C++.

¿Cómo puedo prevenir CWE-839?

If the number to be used is always expected to be positive, change the variable type from signed to unsigned or size_t. If the number to be used could have a negative value based on the specification (thus requiring a signed value), but the number should only be positive to preserve code correctness, then include a check to ensure that the value is positive.

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

El motor SAST de Plexicus detecta la firma de flujo de datos para CWE-839 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-839?

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

Debilidades relacionadas

Weaknesses related to CWE-839

CWE-1023 Padre

Incomplete Comparison with Missing Factors

This weakness occurs when a program compares two items but fails to check all the necessary attributes that define their true…

CWE-184 Hermano

Incomplete List of Disallowed Inputs

This vulnerability occurs when a security filter or validation mechanism relies on a 'denylist'—a predefined list of forbidden inputs—but…

CWE-187 Hermano

Partial String Comparison

This weakness occurs when software checks only part of a string or token to determine a match, instead of comparing the entire value. This…

CWE-478 Hermano

Missing Default Case in Multiple Condition Expression

This vulnerability occurs when code with multiple conditional branches, like a switch statement, lacks a default case to handle unexpected…

CWE-195 Puede preceder

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-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-119 Puede preceder

Improper Restriction of Operations within the Bounds of a Memory Buffer

This vulnerability occurs when software accesses a memory buffer but reads from or writes to a location outside its allocated boundary.…

CWE-124 Puede preceder

Buffer Underwrite ('Buffer Underflow')

A buffer underwrite, also known as buffer underflow, happens when a program writes data to a memory location before the official start of…

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.