CWE-401 Variante Rascunho Medium likelihood

Missing Release of Memory after Effective Lifetime

This vulnerability occurs when a program allocates memory but fails to properly release it after it's no longer needed, causing a gradual accumulation of unused memory that can't be reclaimed by the…

Definição

What is CWE-401?

This vulnerability occurs when a program allocates memory but fails to properly release it after it's no longer needed, causing a gradual accumulation of unused memory that can't be reclaimed by the system.
Memory leaks happen when developers allocate memory (e.g., using `malloc()`, `new`, or similar functions) but neglect to free or delete it once the relevant operation is complete. This often stems from complex control flows, error conditions, or long-running processes where tracking every allocation becomes difficult. Over time, especially in servers or persistent applications, these unreleased blocks accumulate, steadily draining available system memory. This resource exhaustion can lead to severe performance degradation, application instability, or complete crashes when the system runs out of memory. To prevent this, developers must ensure that every allocation has a corresponding, guaranteed release, using techniques like automatic resource management (e.g., smart pointers in C++, try-with-resources in Java), rigorous code reviews, and specialized leak detection tools during testing.
Vulnerability Diagram CWE-401
Memory Leak allocate() p = malloc(N) use(p) no free(p) return early repeat ×N heap usage time
Impacto no mundo real

Real-world CVEs caused by CWE-401

  • Memory leak because function does not free() an element of a data structure.

  • Memory leak when counter variable is not decremented.

  • chain: reference count is not decremented, leading to memory leak in OS by sending ICMP packets.

  • Kernel uses wrong function to release a data structure, preventing data from being properly tracked by other code.

  • Memory leak via unknown manipulations as part of protocol test suite.

  • Memory leak via a series of the same command.

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

The following C function leaks a block of allocated memory if the call to read() does not return the expected number of bytes:

Vulnerável C
char* getBlock(int fd) {
  		char* buf = (char*) malloc(BLOCK_SIZE);
  		if (!buf) {
  			return NULL;
  		}
  		if (read(fd, buf, BLOCK_SIZE) != BLOCK_SIZE) {
  				return NULL;
  		}
  		return buf;
  }
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-401

  • Implementation Choose a language or tool that provides automatic memory management, or makes manual memory management less error-prone. For example, glibc in Linux provides protection against free of invalid pointers. When using Xcode to target OS X or iOS, enable automatic reference counting (ARC) [REF-391]. To help correctly and consistently manage memory when programming in C++, consider using a smart pointer class such as std::auto_ptr (defined by ISO/IEC ISO/IEC 14882:2003), std::shared_ptr and std::unique_ptr (specified by an upcoming revision of the C++ standard, informally referred to as C++ 1x), or equivalent solutions such as Boost.
  • Architecture and Design Use an abstraction library to abstract away risky APIs. Not a complete solution.
  • Architecture and Design / Build and Compilation The Boehm-Demers-Weiser Garbage Collector or valgrind can be used to detect leaks in code.
Sinais de deteção

How to detect CWE-401

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

This vulnerability occurs when a program allocates memory but fails to properly release it after it's no longer needed, causing a gradual accumulation of unused memory that can't be reclaimed by the system.

Qual a gravidade do CWE-401?

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

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

Como posso prevenir o CWE-401?

Choose a language or tool that provides automatic memory management, or makes manual memory management less error-prone. For example, glibc in Linux provides protection against free of invalid pointers. When using Xcode to target OS X or iOS, enable automatic reference counting (ARC) [REF-391]. To help correctly and consistently manage memory when programming in C++, consider using a smart pointer class such as std::auto_ptr (defined by ISO/IEC ISO/IEC 14882:2003), std::shared_ptr and…

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

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

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