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…

Definição

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 no 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.

Como os atacantes a exploram

Trajeto do atacante passo a passo

  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

Exemplo de código vulnerável

Vulnerable C

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

Vulnerável 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);
Exemplo 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 verificação de prevenção

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.
Sinais de deteção

How to detect CWE-839

SAST High

Executar análise estática (SAST) na base de código à procura do padrão inseguro no fluxo de dados.

DAST Moderate

Executar testes dinâmicos de segurança de aplicações (DAST) contra o endpoint em execução.

Runtime Moderate

Monitorizar os registos em tempo de execução para traços de exceção invulgares, input malformado ou tentativas de contornar a autorização.

Code review Moderate

Revisão de código: sinalizar qualquer novo código que trate input desta superfície sem usar os ajudantes validados do framework.

Correção automática do Plexicus

O Plexicus deteta automaticamente o CWE-839 e abre um PR de correção em menos de 60 segundos.

O Codex Remedium analisa cada commit, identifica esta fraqueza exata e entrega um pull request pronto para revisão com o patch. Sem tickets. Sem transferências.

Perguntas frequentes

Frequently asked questions

O que é o 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.

Qual a gravidade do CWE-839?

A MITRE não publicou uma classificação de probabilidade de exploração para esta fraqueza. Trate-a como impacto médio até o seu modelo de ameaças provar o contrário.

Que linguagens ou plataformas são afetadas pelo CWE-839?

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

Como posso prevenir o 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.

Como é que o Plexicus deteta e corrige o CWE-839?

O motor SAST do Plexicus correlaciona a assinatura de fluxo de dados do CWE-839 em cada commit. Quando é encontrada uma correspondência, o nosso agente Codex Remedium abre um PR de correção com o código corrigido, testes e um resumo de uma linha para o revisor.

Onde posso saber mais sobre o CWE-839?

A MITRE publica a definição canónica em https://cwe.mitre.org/data/definitions/839.html. Pode também consultar a documentação da OWASP e do NIST para orientações adjacentes.

Fraquezas relacionadas

Weaknesses related to CWE-839

CWE-1023 Pai

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 Irmão

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 Irmão

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 Irmão

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 Pode 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 Pode 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 Pode 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 Pode 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…

Pronto quando você estiver

Pare de pagar por desenvolvedor.
Comece a fechar o ciclo.

O Plexicus é o ASPM nativo de IA que verifica, filtra, corrige, pentesta e explica — de forma autónoma. Programadores ilimitados, repos ilimitados, ações de IA de utilização justa. Nível gratuito real, €269/mo anual quando estiver pronto.