CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')

What is CWE-22?

The product uses external input to construct a pathname intended to remain under a restricted parent directory, but fails to neutralize special pathname elements that can resolve it outside that directory.

Data statistics

OWASP TOP 10:2025 RANK1 — A01:2025 — Broken Access Control
RELATED CVES (365 DAYS)1,251
ABSTRACTIONBase
LIKELIHOOD OF EXPLOITHigh

Vulnerabilities mapped to CWE-22

1,251 vulnerabilities402.4% increase year over year

Vulnerabilities in CISA KEV for CWE-22

7 vulnerabilities133.3% increase year over year

Official definition

ByMitre CWE

The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.

Many file operations are intended to take place within a restricted directory. By using special elements such as ".." and "/" separators, attackers can escape outside of the restricted location to access files or directories that are elsewhere on the system. One of the most common special elements is the "../" sequence, which in most modern operating systems is interpreted as the parent directory of the current location. This is referred to as relative path traversal. Path traversal also covers the use of absolute pathnames such as "/usr/local/bin" to access unexpected files. This is referred to as absolute path traversal.

Detailed description

Path traversal occurs when pathname processing allows an attacker-controlled path to escape its intended directory boundary. Relative traversal commonly uses .. with / separators, while absolute traversal supplies a complete pathname such as /usr/local/bin; the record also identifies the broader issue as including platform-specific path handling. The resulting operation may target files or directories elsewhere on the system instead of only the restricted location.

Characteristics

This is a base, simple weakness introduced during implementation when external input is used in file or directory operations without adequate pathname validation, decoding, canonicalization, or boundary enforcement. It can arise through relative or absolute paths, archive extraction, upload metadata, file-management commands, included files, and similar interfaces. The official record describes path traversal as preferred terminology over directory traversal, while also listing both terms and the alternate phrasing path transversal.

Common consequences

Potential consequences span confidentiality, integrity, and availability. An attacker may read unexpected files, create or overwrite programs, libraries, important data, or security-related files, potentially bypass authentication or enable unauthorized code or command execution. Overwriting, deleting, or corrupting critical files may also crash, restart, disable, or lock out users of the product.

ImpactScopeExplanation
Execute Unauthorized Code or CommandsIntegrity, Confidentiality, AvailabilityThe attacker may be able to create or overwrite critical files that are used to execute code, such as programs or libraries.
Modify Files or DirectoriesIntegrityThe attacker may be able to overwrite or create critical files, such as programs, libraries, or important data. If the targeted file is used for a security mechanism, then the attacker may be able to bypass that mechanism. For example, appending a new account at the end of a password file may allow an attacker to bypass authentication.
Read Files or DirectoriesConfidentialityThe attacker may be able read the contents of unexpected files and expose sensitive data. If the targeted file is used for a security mechanism, then the attacker may be able to bypass that mechanism. For example, by reading a password file, the attacker could conduct brute force password guessing attacks in order to break into an account on the system.
DoS: Crash, Exit, or RestartAvailabilityThe attacker may be able to overwrite, delete, or corrupt unexpected critical files such as programs, libraries, or important data. This may prevent the product from working at all and in the case of protection mechanisms such as authentication, it has the potential to lock out product users.

Risk mitigations

Use layered controls grounded in the official record:

  • Validate strictly: Assume input is malicious and use accept-known-good allowlists covering length, type, syntax, allowed values, related-field consistency, and business rules. For filenames, restrict the character set, preferably allow only one . when feasible, exclude directory separators, and constrain extensions. Do not rely solely on denylists or dangerous-character removal, because alternate separators and other bypasses may remain.
  • Normalize before validation: Decode and canonicalize input once into the application’s internal representation before validation. Use a built-in canonicalization function such as realpath in C or PHP, getCanonicalPath in Java, GetFullPath in ASP.NET, or abs_path in Perl, while accounting for .. sequences and symbolic links.
  • Enforce checks server-side: Duplicate security checks on the server when client-side checks also exist, because clients can be modified or bypassed.
  • Prefer safer designs: Use vetted libraries or frameworks. When acceptable filenames or URLs are known, map fixed identifiers to those objects and reject other inputs, such as mapping numeric IDs to fixed filenames.
  • Reduce impact and exposure: Run with the lowest necessary privileges, use isolated limited-purpose accounts, and place library, include, and utility files outside the web document root when possible. Otherwise, use server access controls and safeguards against direct requests.
  • Add operational defenses: An application firewall can provide emergency or defense-in-depth protection, especially when code cannot immediately be fixed, but it may miss vectors, be bypassed, reject legitimate requests, or require customization. Sandboxes or jails such as Unix chroot, AppArmor, SELinux, or Java java.io.FilePermission can restrict accessible files or commands, but their effectiveness is limited and depends on the specific implementation; they may only reduce scope and require care to avoid jail-related weaknesses.
  • Limit disclosure: Keep error messages minimally detailed and avoid revealing filesystem path information or validation methods. Record necessary detail in logs with care, and do not store highly sensitive information such as passwords in logs.
  • PHP-specific measure: Do not use register_globals, and do not create an unsafe emulation of it.
  1. Input Validation · ImplementationAssume 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.
  2. Architecture and DesignFor 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.
  3. Input Validation · ImplementationInputs 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
  4. Libraries or Frameworks · Architecture and DesignUse a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid [REF-1482].
  5. Firewall · Operation · Effectiveness: ModerateUse 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].An application firewall might not cover all possible input vectors. In addition, attack techniques might be available to bypass the protection mechanism, such as using malformed inputs that can still be processed by the component that receives those inputs. Depending on functionality, an application firewall might inadvertently reject or modify legitimate requests. Finally, some manual effort may be required for customization.
  6. Environment Hardening · Architecture and Design, OperationRun your code using the lowest privileges that are required to accomplish the necessary tasks [REF-76]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations.
  7. Enforcement by Conversion · Architecture and DesignWhen the set of acceptable objects, such as filenames or URLs, is limited or known, create a mapping from a set of fixed input values (such as numeric IDs) to the actual filenames or URLs, 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 [REF-185] provide this capability.
  8. Sandbox or Jail · Architecture and Design, Operation · Effectiveness: LimitedRun the code in a "jail" or similar sandbox environment that enforces strict boundaries between the process and the operating system. This may effectively restrict which files can be accessed in a particular directory or which commands can be executed by the software. OS-level examples include the Unix chroot jail, AppArmor, and SELinux. In general, managed code may provide some protection. For example, java.io.FilePermission in the Java SecurityManager allows the software to specify restrictions on file operations. This may not be a feasible solution, and it only limits the impact to the operating system; the rest of the application may still be subject to compromise. Be careful to avoid CWE-243 and other weaknesses related to jails.The effectiveness of this mitigation depends on the prevention capabilities of the specific sandbox or jail being used and might only help to reduce the scope of an attack, such as restricting the attacker to certain system calls or limiting the portion of the file system that can be accessed.
  9. Attack Surface Reduction · Architecture and Design, OperationStore library, include, and utility files outside of the web document root, if possible. Otherwise, store them in a separate directory and use the web server's access control capabilities to prevent attackers from directly requesting them. One common practice is to define a fixed constant in each calling program, then check for the existence of the constant in the library/include file; if the constant does not exist, then the file was directly requested, and it can exit immediately. This significantly reduces the chance of an attacker being able to bypass any protection mechanisms that are in the base program but not in the include files. It will also reduce the attack surface.
  10. ImplementationEnsure that error messages only contain minimal details that are useful to the intended audience and no one else. The messages need to strike the balance between being too cryptic (which can confuse users) or being too detailed (which may reveal more than intended). The messages should not reveal the methods that were used to determine the error. Attackers can use detailed information to refine or optimize their original attack, thereby increasing their chances of success. If errors must be captured in some detail, record them in log messages, but consider what could occur if the log messages can be viewed by attackers. Highly sensitive information such as passwords should never be saved to log files. Avoid inconsistent messaging that might accidentally tip off an attacker about internal state, such as whether a user account exists or not. In the context of path traversal, error messages which disclose path information can help attackers craft the appropriate attack strings to move through the file system hierarchy.
  11. Environment Hardening · Operation, ImplementationWhen using PHP, configure the application so that it does not use register_globals. During implementation, develop the 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.

Detection methods

The official record identifies several complementary detection approaches:

  • Source and code analysis: Automated static analysis and automated source-code weakness analyzers, including context-configured analyzers, are highly effective but may require tuning. Manual source review and focused spot checks can provide high-value coverage; manual static analysis may reduce false positives when all file-access operations can be assessed within available time.
  • Binary and bytecode analysis: Automated bytecode weakness analysis, including disassembly with source-code weakness analysis, is highly cost effective. Binary weakness analysis and manual binary or bytecode disassembly followed by manual review provide cost-effective partial coverage.
  • Dynamic testing: Web application, web services, and database scanners, as well as fuzz testers and framework-based fuzzers, are identified as highly cost effective. Their results still depend on the paths, inputs, and functionality exercised.
  • Architecture and design review: Formal methods or correct-by-construction techniques are highly cost effective, while IEEE 1028 inspections can provide cost-effective partial coverage across requirements, design, and source code.

Automated techniques may need customization to distinguish administrator-only or otherwise privileged behavior from exploitable weaknesses. No single approach is stated to provide complete coverage.

MethodApproachEffectiveness
Automated Static AnalysisAutomated techniques can find areas where path traversal weaknesses exist. However, tuning or customization may be required to remove or de-prioritize path-traversal problems that are only exploitable by the product's administrator - or other privileged users - and thus potentially valid behavior or, at worst, a bug instead of a vulnerability.High
Manual Static AnalysisManual white box techniques may be able to provide sufficient code coverage and reduction of false positives if all file access operations can be assessed within limited time constraints.High
Automated Static Analysis - Binary or BytecodeAccording to SOAR [REF-1479], the following detection techniques may be useful: ``` Highly cost effective: ``` Bytecode Weakness Analysis - including disassembler + source code weakness analysis ``` Cost effective for partial coverage: ``` Binary Weakness Analysis - including disassembler + source code weakness analysisHigh
Manual Static Analysis - Binary or BytecodeAccording to SOAR [REF-1479], the following detection techniques may be useful: ``` Cost effective for partial coverage: ``` Binary / Bytecode disassembler - then use manual analysis for vulnerabilities & anomaliesSOAR Partial
Dynamic Analysis with Automated Results InterpretationAccording to SOAR [REF-1479], the following detection techniques may be useful: ``` Highly cost effective: ``` Web Application Scanner Web Services Scanner Database ScannersHigh
Dynamic Analysis with Manual Results InterpretationAccording to SOAR [REF-1479], the following detection techniques may be useful: ``` Highly cost effective: ``` Fuzz Tester Framework-based FuzzerHigh
Manual Static Analysis - Source CodeAccording to SOAR [REF-1479], the following detection techniques may be useful: ``` Highly cost effective: ``` Manual Source Code Review (not inspections) ``` Cost effective for partial coverage: ``` Focused Manual Spotcheck - Focused manual analysis of sourceHigh
Automated Static Analysis - Source CodeAccording to SOAR [REF-1479], the following detection techniques may be useful: ``` Highly cost effective: ``` Source code Weakness Analyzer Context-configured Source Code Weakness AnalyzerHigh
Architecture or Design ReviewAccording to SOAR [REF-1479], the following detection techniques may be useful: ``` Highly cost effective: ``` Formal Methods / Correct-By-Construction ``` Cost effective for partial coverage: ``` Inspection (IEEE 1028 standard) (can apply to requirements, design, source code, etc.)High

Representative vulnerabilities

The official record lists the following representative examples, not an exhaustive set:

  • CVE-2024-37032: An LLM management tool enabled relative traversal through an unvalidated digest from an untrusted model registry.
  • CVE-2024-4315: An LLM text-generation API omitted the Windows \ separator from a denylist, allowing arbitrary file deletion on Windows.
  • CVE-2024-0520: An AI dataset-management product allowed relative and absolute traversal through Content-Disposition to overwrite files.
  • CVE-2022-45918: A learning-management debugger used an insufficiently validated path to locate session logs through ../ sequences.
  • CVE-2019-20916: A Python package manager allowed arbitrary file reads through traversal in a Content-Disposition filename.
  • CVE-2022-31503: An unsafe Python os.path.join use allowed an absolute input path to replace the intended pathname.
  • CVE-2022-24877: A Go Kubernetes operator allowed access to files in its controller pod through ../ in YAML.
  • CVE-2021-21972: An unauthenticated archive upload combined with .. traversal to access unexpected files, and was exploited in the wild according to the record.
  • CVE-2020-4053 and CVE-2019-10743: Go package or archive handling allowed files from malicious plugin or ZIP archives to be copied or extracted outside the intended directory, known as Zip Slip.
  • CVE-2020-3452: Improper input validation in a security product led to directory traversal and was exploited in the wild according to the record.
  • CVE-2010-0467: A newsletter module allowed arbitrary file reads through ../.
  • CVE-2006-7079: A PHP compatibility layer using extract for register_globals compatibility enabled traversal.
  • CVE-2009-4194, CVE-2009-4053, and CVE-2009-0244: FTP-related services allowed arbitrary deletion, directory creation, directory listing, or file reading through .. sequences.
  • CVE-2009-4013 and CVE-2010-0012: Package or torrent processing allowed arbitrary file overwriting through .. or ../.
  • CVE-2010-0013: A chat program allowed file overwriting through a custom smiley request.
  • CVE-2009-4449: A bulletin board allowed attackers to determine whether files existed.
  • CVE-2009-4581: A PHP program allowed arbitrary code execution when .. appeared in filenames passed to include.
  • CVE-2008-5748: External control of language and theme values enabled traversal.
  • CVE-2009-1936: A library-file redirect check still allowed execution when the file was directly requested, enabling remote file inclusion and traversal.

Below are representative vulnerabilities related to this CWE, prioritized by severity.

Sources (12)

CWE™ Program, operated by The MITRE Corporation. Copyright © 2006–2026, The MITRE Corporation. The MITRE Corporation hereby grants you a non-exclusive, royalty-free license to use CWE for research, development, and commercial purposes. CWE Terms of Use.

Learn more

Run an in-depth assessment with complete web risk management

CyStack VulnScan continuously discovers assets, validates vulnerabilities, and helps security teams prioritize remediation across the organization.

Explore CyStack VulnScan