CWE-73 Base Rascunho High likelihood

External Control of File Name or Path

This vulnerability occurs when an application uses unvalidated user input to construct file or directory paths for filesystem operations.

Definição

What is CWE-73?

This vulnerability occurs when an application uses unvalidated user input to construct file or directory paths for filesystem operations.
Path manipulation vulnerabilities arise when an attacker can control the path used in operations like reading, writing, or deleting files. By crafting special inputs containing sequences like '../' (directory traversal), they can force the application to access files or directories outside the intended, restricted location. This can lead to unauthorized access to sensitive system files, application source code, or configuration data. For a successful attack, two conditions must be met: the attacker must be able to specify the path used in a filesystem operation, and doing so must grant them a capability they shouldn't have, such as overwriting a critical file, reading private data, or forcing the application to use a malicious configuration file. The core defense is to never trust user input for path construction; instead, use allowlists, canonicalize paths, and then validate them against a strict list of permitted directories.
Impacto no mundo real

Real-world CVEs caused by CWE-73

  • Chain: a learning management tool debugger uses external input to locate previous session logs (CWE-73) and does not properly validate the given path (CWE-20), allowing for filesystem path traversal using "../" sequences (CWE-24)

  • Chain: external control of values for user's desired language and theme enables path traversal.

  • Chain: external control of user's target language enables remote file inclusion.

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 Java

The following code uses input from an HTTP request to create a file name. The programmer has not considered the possibility that an attacker could provide a file name such as "../../tomcat/conf/server.xml", which causes the application to delete one of its own configuration files (CWE-22).

Vulnerável Java
String rName = request.getParameter("reportName");
  File rFile = new File("/usr/local/apfr/reports/" + rName);
  ...
  rFile.delete();
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-73

  • Architecture and Design When the set of filenames is limited or known, create a mapping from a set of fixed input values (such as numeric IDs) to the actual filenames, and reject all other inputs. For example, ID 1 could map to "inbox.txt" and ID 2 could map to "profile.txt". Features such as the ESAPI AccessReferenceMap provide this capability.
  • Architecture and Design / Operation Run your code in a "jail" or similar sandbox environment that enforces strict boundaries between the process and the operating system. This may effectively restrict all access to files within a particular directory. Examples include the Unix chroot jail and AppArmor. In general, managed code may provide some protection. This may not be a feasible solution, and it only limits the impact to the operating system; the rest of your application may still be subject to compromise. Be careful to avoid CWE-243 and other weaknesses related to jails.
  • Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
  • 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. When validating filenames, use stringent allowlists that limit the character set to be used. If feasible, only allow a single "." character in the filename to avoid weaknesses such as CWE-23, and exclude directory separators such as "/" to avoid CWE-36. Use a list of allowable file extensions, which will help to avoid CWE-434. Do not rely exclusively on a filtering mechanism that removes potentially dangerous characters. This is equivalent to a denylist, which may be incomplete (CWE-184). For example, filtering "/" is insufficient protection if the filesystem also supports the use of "\" as a directory separator. Another possible error could occur when the filtering is applied in a way that still produces dangerous data (CWE-182). For example, if "../" sequences are removed from the ".../...//" string in a sequential fashion, two instances of "../" would be removed from the original string, but the remaining characters would still form the "../" string.
  • Implementation Use a built-in path canonicalization function (such as realpath() in C) that produces the canonical version of the pathname, which effectively removes ".." sequences and symbolic links (CWE-23, CWE-59).
  • Installation / Operation Use OS-level permissions and run as a low-privileged user to limit the scope of any successful attack.
  • Operation / Implementation If you are using PHP, configure your application so that it does not use register_globals. During implementation, develop your application so that it does not rely on this feature, but be wary of implementing a register_globals emulation that is subject to weaknesses such as CWE-95, CWE-621, and similar issues.
  • Testing Use tools and techniques that require manual (human) analysis, such as penetration testing, threat modeling, and interactive tools that allow the tester to record and modify an active session. These may be more effective than strictly automated techniques. This is especially the case with weaknesses that are related to design and business rules.
Sinais de deteção

How to detect CWE-73

Automated Static Analysis

The external control or influence of filenames can often be detected using automated static analysis that models data flow within the product. Automated static analysis might not be able to recognize when proper input validation is being performed, leading to false positives - i.e., warnings that do not have any security consequences or require any code changes.

Correção automática do Plexicus

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

This vulnerability occurs when an application uses unvalidated user input to construct file or directory paths for filesystem operations.

Qual a gravidade do CWE-73?

A MITRE classifica a probabilidade de exploração como Alta — esta fraqueza é ativamente explorada em campo e deve ser priorizada para remediação.

Que linguagens ou plataformas são afetadas pelo CWE-73?

MITRE lists the following affected platforms: Unix, Windows, macOS.

Como posso prevenir o CWE-73?

When the set of filenames is limited or known, create a mapping from a set of fixed input values (such as numeric IDs) to the actual filenames, and reject all other inputs. For example, ID 1 could map to "inbox.txt" and ID 2 could map to "profile.txt". Features such as the ESAPI AccessReferenceMap provide this capability. Run your code in a "jail" or similar sandbox environment that enforces strict boundaries between the process and the operating system. This may effectively restrict all…

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

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

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

Fraquezas relacionadas

Weaknesses related to CWE-73

CWE-642 Pai

External Control of Critical State Data

This vulnerability occurs when an application stores security-sensitive state data in locations that unauthorized users can access and…

CWE-15 Irmão

External Control of System or Configuration Setting

This vulnerability occurs when an application allows users to directly modify critical system settings or configuration values from an…

CWE-426 Irmão

Untrusted Search Path

This vulnerability occurs when an application relies on an external search path, provided by a user or environment, to find and load…

CWE-472 Irmão

External Control of Assumed-Immutable Web Parameter

This vulnerability occurs when a web application incorrectly trusts data that appears to be fixed or hidden from the user, such as values…

CWE-565 Irmão

Reliance on Cookies without Validation and Integrity Checking

This vulnerability occurs when an application uses cookies to make security decisions—like granting access or changing settings—but fails…

CWE-22 Pode preceder

Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')

This vulnerability occurs when an application builds a file path using user input but fails to properly validate it, allowing an attacker…

CWE-41 Pode preceder

Improper Resolution of Path Equivalence

This vulnerability occurs when an application fails to properly handle different text representations that refer to the same file or…

CWE-98 Pode preceder

Improper Control of Filename for Include/Require Statement in PHP Program ('PHP Remote File Inclusion')

This vulnerability occurs when a PHP application uses unvalidated or insufficiently restricted user input directly within file inclusion…

CWE-434 Pode preceder

Unrestricted Upload of File with Dangerous Type

This vulnerability occurs when an application accepts file uploads without properly restricting the file types, allowing attackers to…

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.