CWE-127 Variante Rascunho

Buffer Under-read

A buffer under-read occurs when a program attempts to read data from a memory location positioned before the start of an allocated buffer.

Definição

What is CWE-127?

A buffer under-read occurs when a program attempts to read data from a memory location positioned before the start of an allocated buffer.
This vulnerability typically happens due to incorrect pointer arithmetic, where a pointer is decremented past the buffer's beginning, or when a negative index is used in an array access. These operations cause the program to read from unintended memory regions that were not allocated for the buffer's use. Reading from memory preceding the buffer can expose sensitive information, such as remnants of other data structures, passwords, or encryption keys, leading to information disclosure. It can also cause the application to crash if it accesses protected or invalid memory addresses, resulting in a denial of service.
Impacto no mundo real

Real-world CVEs caused by CWE-127

  • HTML conversion package has a buffer under-read, allowing a crash

Como os atacantes a exploram

Trajeto do atacante passo a passo

  1. 1

    Identificar um caminho de código que trata input não confiável sem validação.

  2. 2

    Criar um payload que explora o comportamento inseguro — injeção, traversal, overflow ou abuso de lógica.

  3. 3

    Entregar o payload através de um pedido normal e observar a reação da aplicação.

  4. 4

    Iterar até que a resposta exponha dados, execute código do atacante ou escale privilégios.

Exemplo de código vulnerável

Vulnerable C

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

Vulnerável C
int getValueFromArray(int *array, int len, int index) {
  		int value;
```
// check that the array index is less than the maximum* 
  		
  		
  		 *// length of the array* 
  		if (index < len) {
  		```
```
// get the value at the specified index of the array* 
  				value = array[index];}
  		
  		 *// if array index is invalid then output error message* 
  		
  		
  		 *// and return value indicating error* 
  		else {
  		```
  			printf("Value is: %d\n", array[index]);
  			value = -1;
  		}
  		return value;
  }
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-127

  • Architecture Use safe-by-default frameworks and APIs that prevent the unsafe pattern from being expressible.
  • Implementation Validate input at trust boundaries; use allowlists, not denylists.
  • Implementation Apply the principle of least privilege to credentials, file paths, and runtime permissions.
  • Testing Cover this weakness in CI: SAST rules + targeted unit tests for the data flow.
  • Operation Monitor logs for the runtime signals listed in the next section.
Sinais de deteção

How to detect CWE-127

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

A buffer under-read occurs when a program attempts to read data from a memory location positioned before the start of an allocated buffer.

Qual a gravidade do CWE-127?

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

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

Como posso prevenir o CWE-127?

Use safe-by-default frameworks, validate untrusted input at trust boundaries, and apply the principle of least privilege. Cover the data-flow signature in CI with SAST.

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

O motor SAST do Plexicus correlaciona a assinatura de fluxo de dados do CWE-127 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-127?

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

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.