CWE-23 Base Rascunho

Relative Path Traversal

This vulnerability occurs when an application builds file paths using user-supplied input without properly validating or sanitizing it. Attackers can exploit this by inserting special directory…

Definição

What is CWE-23?

This vulnerability occurs when an application builds file paths using user-supplied input without properly validating or sanitizing it. Attackers can exploit this by inserting special directory traversal sequences like '..' to access files and directories outside the intended restricted folder.
Path traversal, often called directory traversal, is a critical security flaw where an attacker manipulates file path inputs to break out of the application's intended directory. By using sequences like '../' (or its encoded equivalents), they can navigate to sensitive system files, configuration files, source code, or other restricted data. This typically happens when file operations—such as reading, writing, or deleting—rely on unsanitized user input from URLs, form fields, or cookies to construct the final path. To prevent this, developers must implement strict validation using allowlists of permitted files or directories, rather than trying to block malicious patterns. All user input used in file system operations should be canonicalized and then checked against a base directory path to ensure the final resolved path stays within the intended safe location. Server configuration should also enforce proper permissions, limiting the application's access to only necessary directories.
Vulnerability Diagram CWE-23
Relative Path Traversal User input name=../secret.cfg Intended dir: /app/data/ /app/data/user.json ✓ /app/data/../secret.cfg ✗ → /app/secret.cfg Sibling secrets disclosed Relative segments escape the intended directory boundary.
Impacto no mundo real

Real-world CVEs caused by CWE-23

  • Large language model (LLM) management tool does not validate the format of a digest value (CWE-1287) from a private, untrusted model registry, enabling relative path traversal (CWE-23), a.k.a. Probllama

  • Product for managing datasets for AI model training and evaluation allows both relative (CWE-23) and absolute (CWE-36) path traversal to overwrite files via the Content-Disposition header

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

  • Python package manager does not correctly restrict the filename specified in a Content-Disposition header, allowing arbitrary file read using path traversal sequences such as "../"

  • directory traversal in Go-based Kubernetes operator app allows accessing data from the controller's pod file system via ../ sequences in a yaml file

  • a Kubernetes package manager written in Go allows malicious plugins to inject path traversal sequences into a plugin archive ("Zip slip") to copy a file outside the intended directory

  • Chain: Cloud computing virtualization platform does not require authentication for upload of a tar format file (CWE-306), then uses .. path traversal sequences (CWE-23) in the file to access unexpected files, as exploited in the wild per CISA KEV.

  • Go-based archive library allows extraction of files to locations outside of the target folder with "../" path traversal sequences in filenames in a zip file, aka "Zip Slip"

Como os atacantes a exploram

Trajeto do atacante passo a passo

  1. 1

    The following URLs are vulnerable to this attack:

  2. 2

    A simple way to execute this attack is like this:

  3. 3

    The following code could be for a social networking application in which each user's profile information is stored in a separate file. All files are stored in a single directory.

  4. 4

    While the programmer intends to access files such as "/users/cwe/profiles/alice" or "/users/cwe/profiles/bob", there is no verification of the incoming user parameter. An attacker could provide a string such as:

  5. 5

    The program would generate a profile pathname like this:

Exemplo de código vulnerável

Vulnerable Other

The following URLs are vulnerable to this attack:

Vulnerável Other
http://example.com/get-files.jsp?file=report.pdf
  http://example.com/get-page.php?home=aaa.html
  http://example.com/some-page.asp?page=index.html
Payload do atacante

A simple way to execute this attack is like this:

Payload do atacante Other
http://example.com/get-files?file=../../../../somedir/somefile
  http://example.com/../../../../etc/shadow
  http://example.com/get-files?file=../../../../etc/passwd
Exemplo de código seguro

Secure HTML

The following code demonstrates the unrestricted upload of a file with a Java servlet and a path traversal vulnerability. The action attribute of an HTML form is sending the upload file request to the Java servlet.

Seguro HTML
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
  Choose a file to upload:
  <input type="file" name="filename"/>
  <br/>
  <input type="submit" name="submit" value="Submit"/>
  </form>
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-23

  • 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 Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180). Make sure that the application does not decode the same input twice (CWE-174). Such errors could be used to bypass allowlist validation schemes by introducing dangerous inputs after they have been checked. 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). This includes: - realpath() in C - getCanonicalPath() in Java - GetFullPath() in ASP.NET - realpath() or abs_path() in Perl - realpath() in PHP
  • Operation Use an application firewall that can detect attacks against this weakness. It can be beneficial in cases in which the code cannot be fixed (because it is controlled by a third party), as an emergency prevention measure while more comprehensive software assurance measures are applied, or to provide defense in depth [REF-1481].
Sinais de deteção

How to detect CWE-23

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

This vulnerability occurs when an application builds file paths using user-supplied input without properly validating or sanitizing it. Attackers can exploit this by inserting special directory traversal sequences like '..' to access files and directories outside the intended restricted folder.

Qual a gravidade do CWE-23?

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

MITRE lists the following affected platforms: AI/ML.

Como posso prevenir o CWE-23?

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

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

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

Fraquezas relacionadas

Weaknesses related to CWE-23

CWE-22 Pai

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-36 Irmão

Absolute Path Traversal

This vulnerability occurs when an application builds file paths using user input without properly blocking absolute paths like…

CWE-24 Filho

Path Traversal: '../filedir'

Path traversal, often called directory traversal, occurs when an application builds a file path using user input without properly blocking…

CWE-25 Filho

Path Traversal: '/../filedir'

This vulnerability, often called directory traversal, occurs when an application builds a file path using user input without properly…

CWE-26 Filho

Path Traversal: '/dir/../filename'

This vulnerability occurs when an application builds a file path using user input but fails to properly block directory traversal…

CWE-27 Filho

Path Traversal: 'dir/../../filename'

This vulnerability occurs when an application builds file paths using user input but fails to properly block sequences like…

CWE-28 Filho

Path Traversal: '..\filedir'

This vulnerability occurs when an application builds a file path using user input but fails to block or properly handle '..\' sequences.…

CWE-29 Filho

Path Traversal: '\..\filename'

This vulnerability occurs when an application builds file paths using user input but fails to block '\..\filename' sequences. Attackers…

CWE-30 Filho

Path Traversal: '\dir\..\filename'

This vulnerability occurs when an application builds file paths using user input but fails to properly sanitize sequences like…

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.