CWE-797 Variante Incompleto

Only Filtering Special Elements at an Absolute Position

This vulnerability occurs when software checks for dangerous characters or patterns only at a fixed, hardcoded location in input data. Because it ignores these same elements if they appear anywhere…

Definição

What is CWE-797?

This vulnerability occurs when software checks for dangerous characters or patterns only at a fixed, hardcoded location in input data. Because it ignores these same elements if they appear anywhere else, attackers can bypass the filter by simply moving the malicious content to a different position.
Imagine a filter that only removes a semicolon if it's exactly the 10th character, believing this will prevent SQL injection. An attacker can easily bypass this by adding a few harmless characters at the start, moving the malicious semicolon to the 11th position. The filter sees nothing wrong at its one checked spot and lets the tainted data pass through, leading to a successful attack. This flaw stems from a misunderstanding of input validation. Effective security requires checking all input comprehensively, not just sampling a single location. Developers should use allowlists or context-aware encoding that processes the entire data stream, ensuring dangerous elements are neutralized no matter where they appear.
Impacto no mundo real

Real-world CVEs caused by CWE-797

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 takes untrusted input and uses a substring function to filter a 3-character "../" element located at the 0-index position of the input string. It then appends this result to the /home/user/ directory and attempts to read the file in the final resulting path.

  2. 2

    Since the if function is only looking for a substring of "../" between the 0 and 2 position, it only removes that specific "../" element. So an input value such as:

  3. 3

    will have the first "../" filtered, resulting in:

  4. 4

    This value is then concatenated with the /home/user/ directory:

  5. 5

    which causes the /etc/passwd file to be retrieved once the operating system has resolved the ../ sequences in the pathname. This leads to relative path traversal (CWE-22).

Exemplo de código vulnerável

Vulnerable Perl

The following code takes untrusted input and uses a substring function to filter a 3-character "../" element located at the 0-index position of the input string. It then appends this result to the /home/user/ directory and attempts to read the file in the final resulting path.

Vulnerável Perl
my $Username = GetUntrustedInput();
  if (substr($Username, 0, 3) eq '../') {
  	$Username = substr($Username, 3);
  }
  my $filename = "/home/user/" . $Username;
  ReadAndSendFile($filename);
Payload do atacante

Since the if function is only looking for a substring of "../" between the 0 and 2 position, it only removes that specific "../" element. So an input value such as:

Payload do atacante
../../../etc/passwd
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-797

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

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

This vulnerability occurs when software checks for dangerous characters or patterns only at a fixed, hardcoded location in input data. Because it ignores these same elements if they appear anywhere else, attackers can bypass the filter by simply moving the malicious content to a different position.

Qual a gravidade do CWE-797?

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

A MITRE não especificou as plataformas afetadas por este CWE — pode aplicar-se à maioria das stacks de aplicações.

Como posso prevenir o CWE-797?

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

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

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