CWE-788 Base Incompleto

Access of Memory Location After End of Buffer

This vulnerability occurs when software attempts to read from or write to a memory buffer using an index or pointer that points past the buffer's allocated boundary.

Definição

What is CWE-788?

This vulnerability occurs when software attempts to read from or write to a memory buffer using an index or pointer that points past the buffer's allocated boundary.
This flaw, often called a buffer over-read or over-write, happens when a program incorrectly calculates a memory position. It typically stems from a pointer being incremented too far, an index being miscalculated, or pointer arithmetic producing an invalid address that lands outside the intended buffer's range. The result is access to adjacent memory that doesn't belong to the buffer, which can corrupt data or expose sensitive information. For developers, this is a critical memory safety issue. It can lead to crashes, unpredictable behavior, or be exploited to leak confidential data or gain code execution. Common causes include off-by-one errors in loops, incorrect size calculations, or using untrusted input directly as an array index without proper bounds checking.
Impacto no mundo real

Real-world CVEs caused by CWE-788

  • Classic stack-based buffer overflow in media player using a long entry in a playlist

  • Heap-based buffer overflow in media player using a long entry in a playlist

  • large precision value in a format string triggers overflow

  • attacker-controlled array index leads to code execution

  • OS kernel trusts userland-supplied length value, allowing reading of sensitive information

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

Como os atacantes a exploram

Trajeto do atacante passo a passo

  1. 1

    This example takes an IP address from a user, verifies that it is well formed and then looks up the hostname and copies it into a buffer.

  2. 2

    This function allocates a buffer of 64 bytes to store the hostname, however there is no guarantee that the hostname will not be larger than 64 bytes. If an attacker specifies an address which resolves to a very large hostname, then the function may overwrite sensitive data or even relinquish control flow to the attacker.

  3. 3

    Note that this example also contains an unchecked return value (CWE-252) that can lead to a NULL pointer dereference (CWE-476).

  4. 4

    In the following example, it is possible to request that memcpy move a much larger segment of memory than assumed:

  5. 5

    If returnChunkSize() happens to encounter an error it will return -1. Notice that the return value is not checked before the memcpy operation (CWE-252), so -1 can be passed as the size argument to memcpy() (CWE-805). Because memcpy() assumes that the value is unsigned, it will be interpreted as MAXINT-1 (CWE-195), and therefore will copy far more memory than is likely available to the destination buffer (CWE-787, CWE-788).

Exemplo de código vulnerável

Vulnerable C

This example takes an IP address from a user, verifies that it is well formed and then looks up the hostname and copies it into a buffer.

Vulnerável C
void host_lookup(char *user_supplied_addr){
  		struct hostent *hp;
  		in_addr_t *addr;
  		char hostname[64];
  		in_addr_t inet_addr(const char *cp);
```
/*routine that ensures user_supplied_addr is in the right format for conversion */* 
  		
  		validate_addr_form(user_supplied_addr);
  		addr = inet_addr(user_supplied_addr);
  		hp = gethostbyaddr( addr, sizeof(struct in_addr), AF_INET);
  		strcpy(hostname, hp->h_name);}
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-788

  • 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-788

Fuzzing High

Fuzz testing (fuzzing) is a powerful technique for generating large numbers of diverse inputs - either randomly or algorithmically - and dynamically invoking the code with those inputs. Even with random inputs, it is often capable of generating unexpected results such as crashes, memory corruption, or resource consumption. Fuzzing effectively produces repeatable test cases that clearly indicate bugs, which helps developers to diagnose the issues.

Automated Static Analysis High

Automated static analysis, commonly referred to as Static Application Security Testing (SAST), can find some instances of this weakness by analyzing source code (or binary/compiled code) without having to execute it. Typically, this is done by building a model of data flow and control flow, then searching for potentially-vulnerable patterns that connect "sources" (origins of input) with "sinks" (destinations where the data interacts with external components, a lower layer such as the OS, etc.)

Correção automática do Plexicus

O Plexicus deteta automaticamente o CWE-788 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-788?

This vulnerability occurs when software attempts to read from or write to a memory buffer using an index or pointer that points past the buffer's allocated boundary.

Qual a gravidade do CWE-788?

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

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

Como posso prevenir o CWE-788?

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

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

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

Fraquezas relacionadas

Weaknesses related to CWE-788

CWE-119 Pai

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

Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')

This vulnerability occurs when a program copies data from one memory location to another without first verifying that the source data will…

CWE-123 Irmão

Write-what-where Condition

A write-what-where condition occurs when an attacker can control both the data written and the exact memory location where it's written,…

CWE-125 Irmão

Out-of-bounds Read

An out-of-bounds read occurs when software accesses memory outside the boundaries of a buffer, array, or similar data structure, reading…

CWE-130 Irmão

Improper Handling of Length Parameter Inconsistency

This vulnerability occurs when a program reads a structured data packet or message but fails to properly validate that the declared length…

CWE-466 Irmão

Return of Pointer Value Outside of Expected Range

This vulnerability occurs when a function returns a memory pointer that points outside the expected buffer range, potentially exposing…

CWE-786 Irmão

Access of Memory Location Before Start of Buffer

This vulnerability occurs when software attempts to read from or write to a memory location positioned before the official start of a…

CWE-787 Irmão

Out-of-bounds Write

This vulnerability occurs when software incorrectly writes data outside the boundaries of its allocated memory buffer, either beyond the…

CWE-805 Irmão

Buffer Access with Incorrect Length Value

This vulnerability occurs when software reads from or writes to a buffer using a loop or sequential operation, but mistakenly calculates…

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.