CWE-124 Base Incompleto Medium likelihood

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 a buffer.

Definição

What is CWE-124?

A buffer underwrite, also known as buffer underflow, happens when a program writes data to a memory location before the official start of a buffer.
This vulnerability occurs when a program miscalculates a write position, placing it outside the allocated buffer's bounds in the 'backward' direction. Common causes include decrementing a pointer or index too many times, performing incorrect pointer arithmetic that results in a negative offset, or directly using a negative index to access an array. The result is a write operation to an unintended, and often critical, memory location. Writing to memory before a buffer can corrupt other program data, function pointers, or critical control structures. This can lead to system crashes, unpredictable behavior, or, if exploited, allow an attacker to hijack the program's execution flow. Developers should rigorously validate all pointer arithmetic and array indices, ensuring they remain within the valid, zero-based range of the allocated buffer.
Impacto no mundo real

Real-world CVEs caused by CWE-124

  • buffer underwrite in firmware verification routine allows code execution via a crafted firmware image

  • Unchecked length of SSLv2 challenge value leads to buffer underflow.

  • Buffer underflow from a small size value with a large buffer (length parameter inconsistency, CWE-130)

  • Buffer underflow from an all-whitespace string, which causes a counter to be decremented before the buffer while looking for a non-whitespace character.

  • Buffer underflow resultant from encoded data that triggers an integer overflow.

  • Product sets an incorrect buffer size limit, leading to "off-by-two" buffer underflow.

  • Negative value is used in a memcpy() operation, leading to buffer underflow.

  • Buffer underflow due to mishandled special characters

Como os atacantes a exploram

Trajeto do atacante passo a passo

  1. 1

    In the following C/C++ example, a utility function is used to trim trailing whitespace from a character string. The function copies the input string to a local character string and uses a while statement to remove the trailing whitespace by moving backward through the string and overwriting whitespace with a NUL character.

  2. 2

    However, this function can cause a buffer underwrite if the input character string contains all whitespace. On some systems the while statement will move backwards past the beginning of a character string and will call the isspace() function on an address outside of the bounds of the local buffer.

  3. 3

    The following is an example of code that may result in a buffer underwrite. This code is attempting to replace the substring "Replace Me" in destBuf with the string stored in srcBuf. It does so by using the function strstr(), which returns a pointer to the found substring in destBuf. Using pointer arithmetic, the starting index of the substring is found.

  4. 4

    In the case where the substring is not found in destBuf, strstr() will return NULL, causing the pointer arithmetic to be undefined, potentially setting the value of idx to a negative number. If idx is negative, this will result in a buffer underwrite of destBuf.

Exemplo de código vulnerável

Vulnerable C

In the following C/C++ example, a utility function is used to trim trailing whitespace from a character string. The function copies the input string to a local character string and uses a while statement to remove the trailing whitespace by moving backward through the string and overwriting whitespace with a NUL character.

Vulnerável C
char* trimTrailingWhitespace(char *strMessage, int length) {
  		char *retMessage;
  		char *message = malloc(sizeof(char)*(length+1));
```
// copy input string to a temporary string* 
  		char message[length+1];
  		int index;
  		for (index = 0; index < length; index++) {
  		```
  			message[index] = strMessage[index];
  		}
  		message[index] = '\0';
```
// trim trailing whitespace* 
  		int len = index-1;
  		while (isspace(message[len])) {
  		```
  			message[len] = '\0';
  			len--;
  		}
```
// return string without trailing whitespace* 
  		retMessage = message;
  		return retMessage;}
Exemplo 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 verificação de prevenção

How to prevent CWE-124

  • Requirements Choose a language that is not susceptible to these issues.
  • Implementation All calculated values that are used as index or for pointer arithmetic should be validated to ensure that they are within an expected range.
Sinais de deteção

How to detect CWE-124

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

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

Qual a gravidade do CWE-124?

A MITRE classifica a probabilidade de exploração como Média — a exploração é realista mas normalmente requer condições específicas.

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

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

Como posso prevenir o CWE-124?

Choose a language that is not susceptible to these issues. All calculated values that are used as index or for pointer arithmetic should be validated to ensure that they are within an expected range.

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

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

A MITRE publica a definição canónica em https://cwe.mitre.org/data/definitions/124.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.