CWE-96 Base Rascunho

Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')

Static Code Injection occurs when an application incorporates unvalidated or improperly sanitized user input directly into a static, executable resource like a configuration file, template, or…

Definição

What is CWE-96?

Static Code Injection occurs when an application incorporates unvalidated or improperly sanitized user input directly into a static, executable resource like a configuration file, template, or library. Because this input is saved and later executed, it allows an attacker to inject malicious code that becomes a permanent part of the application's logic.
This vulnerability is dangerous because the injected code becomes embedded within a file that the system trusts and executes automatically. Unlike attacks that only affect a single transaction, a successful static code injection can persistently compromise the application, leading to ongoing data theft, system takeover, or service disruption every time the compromised resource is used. To prevent it, developers must treat all data destined for static files as untrusted. Implement strict input validation using allowlists for expected values and context-specific output encoding or sanitization before writing data to configuration files, templates, or scripts. Never construct executable code by simply concatenating user input.
Impacto no mundo real

Real-world CVEs caused by CWE-96

  • Perl code directly injected into CGI library file from parameters to another CGI program.

  • Direct PHP code injection into supporting template file.

  • Direct code injection into PHP script that can be accessed by attacker.

  • PHP code from User-Agent HTTP header directly inserted into log file implemented as PHP script.

  • chain: execution after redirect allows non-administrator to perform static code injection.

Como os atacantes a exploram

Trajeto do atacante passo a passo

  1. 1

    This example attempts to write user messages to a message file and allow users to view them.

  2. 2

    While the programmer intends for the MessageFile to only include data, an attacker can provide a message such as:

  3. 3

    which will decode to the following:

  4. 4

    The programmer thought they were just including the contents of a regular data file, but PHP parsed it and executed the code. Now, this code is executed any time people view messages.

  5. 5

    Notice that XSS (CWE-79) is also possible in this situation.

Exemplo de código vulnerável

Vulnerable PHP

This example attempts to write user messages to a message file and allow users to view them.

Vulnerável PHP
$MessageFile = "messages.out";
  if ($_GET["action"] == "NewMessage") {
  	$name = $_GET["name"];
  	$message = $_GET["message"];
  	$handle = fopen($MessageFile, "a+");
  	fwrite($handle, "<b>$name</b> says '$message'<hr>\n");
  	fclose($handle);
  	echo "Message Saved!<p>\n";
  }
  else if ($_GET["action"] == "ViewMessages") {
  	include($MessageFile);
  }
Payload do atacante

While the programmer intends for the MessageFile to only include data, an attacker can provide a message such as:

Payload do atacante
name=h4x0r
  message=%3C?php%20system(%22/bin/ls%20-l%22);?%3E
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-96

  • Implementation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
  • Implementation Perform proper output validation and escaping to neutralize all code syntax from data written to code files.
Sinais de deteção

How to detect CWE-96

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

Static Code Injection occurs when an application incorporates unvalidated or improperly sanitized user input directly into a static, executable resource like a configuration file, template, or library. Because this input is saved and later executed, it allows an attacker to inject malicious code that becomes a permanent part of the application's logic.

Qual a gravidade do CWE-96?

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

MITRE lists the following affected platforms: PHP, Perl, Interpreted.

Como posso prevenir o CWE-96?

Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and…

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

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

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