CWE-14 Variante Rascunho

Compiler Removal of Code to Clear Buffers

A compiler optimization can remove security-critical code intended to wipe sensitive data from memory, leaving secrets exposed. This happens when the compiler identifies buffer-clearing operations…

Definição

What is CWE-14?

A compiler optimization can remove security-critical code intended to wipe sensitive data from memory, leaving secrets exposed. This happens when the compiler identifies buffer-clearing operations as unnecessary 'dead stores' and eliminates them.
This vulnerability occurs in a three-step scenario. First, your application stores confidential information like passwords, encryption keys, or tokens in memory. Then, as a security best practice, your source code explicitly overwrites that memory location to scrub the data. However, an optimizing compiler analyzes the code, sees the memory isn't read again after being overwritten, and decides the overwrite operation is a 'dead store'—a redundant write to a variable that is never used. To improve performance, the compiler silently removes this crucial cleanup instruction from the final executable, leaving the secret data intact in memory where it could be dumped or leaked. For developers, this is a critical pitfall because your source code appears secure, but the compiled binary behaves differently. You cannot rely on standard memory-zeroing functions in performance-sensitive or optimized release builds without taking special precautions. Mitigating this requires using compiler-specific directives (like `volatile` pointers), dedicated secure memory-wiping functions designed to survive optimization, or disabling specific optimizations for the sensitive code sections to ensure your cleanup logic is executed as intended.
Impacto no mundo real

Real-world CVEs caused by CWE-14

Ainda não há referências CVE públicas associadas a este CWE no catálogo da MITRE.

Como os atacantes a exploram

Trajeto do atacante passo a passo

  1. 1

    The following code reads a password from the user, uses the password to connect to a back-end mainframe and then attempts to scrub the password from memory using memset().

  2. 2

    The code in the example will behave correctly if it is executed verbatim, but if the code is compiled using an optimizing compiler, such as Microsoft Visual C++ .NET or GCC 3.x, then the call to memset() will be removed as a dead store because the buffer pwd is not used after its value is overwritten [18]. Because the buffer pwd contains a sensitive value, the application may be vulnerable to attack if the data are left memory resident. If attackers are able to access the correct region of memory, they may use the recovered password to gain control of the system.

  3. 3

    It is common practice to overwrite sensitive data manipulated in memory, such as passwords or cryptographic keys, in order to prevent attackers from learning system secrets. However, with the advent of optimizing compilers, programs do not always behave as their source code alone would suggest. In the example, the compiler interprets the call to memset() as dead code because the memory being written to is not subsequently used, despite the fact that there is clearly a security motivation for the operation to occur. The problem here is that many compilers, and in fact many programming languages, do not take this and other security concerns into consideration in their efforts to improve efficiency.

  4. 4

    Attackers typically exploit this type of vulnerability by using a core dump or runtime mechanism to access the memory used by a particular application and recover the secret information. Once an attacker has access to the secret information, it is relatively straightforward to further exploit the system and possibly compromise other resources with which the application interacts.

Exemplo de código vulnerável

Vulnerable C

The following code reads a password from the user, uses the password to connect to a back-end mainframe and then attempts to scrub the password from memory using memset().

Vulnerável C
void GetData(char *MFAddr) {
  		char pwd[64];
  		if (GetPasswordFromUser(pwd, sizeof(pwd))) {
  				if (ConnectToMainframe(MFAddr, pwd)) {
```
// Interaction with mainframe* 
  						}}
  		memset(pwd, 0, sizeof(pwd));}
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-14

  • Implementation Store the sensitive data in a "volatile" memory location if available.
  • Build and Compilation If possible, configure your compiler so that it does not remove dead stores.
  • Architecture and Design Where possible, encrypt sensitive data that are used by a software system.
Sinais de deteção

How to detect CWE-14

Black Box

This specific weakness is impossible to detect using black box methods. While an analyst could examine memory to see that it has not been scrubbed, an analysis of the executable would not be successful. This is because the compiler has already removed the relevant code. Only the source code shows whether the programmer intended to clear the memory or not, so this weakness is indistinguishable from others.

White Box

This weakness is only detectable using white box methods (see black box detection factor). Careful analysis is required to determine if the code is likely to be removed by the compiler.

Correção automática do Plexicus

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

A compiler optimization can remove security-critical code intended to wipe sensitive data from memory, leaving secrets exposed. This happens when the compiler identifies buffer-clearing operations as unnecessary 'dead stores' and eliminates them.

Qual a gravidade do CWE-14?

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

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

Como posso prevenir o CWE-14?

Store the sensitive data in a "volatile" memory location if available. If possible, configure your compiler so that it does not remove dead stores.

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

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

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