CWE-22: Path traversal | Causes and Fixes Skip to content

Security weaknessCWE Top 25 · #6

CWE-22 Path traversal

Attackers manipulate a file path your site accepts to read or overwrite files outside the folder you intended.

  • Senior security engineers
  • 540+ projects delivered
  • Reply within one business day

Quick answer

What is CWE-22?

Improper Limitation of a Pathname to a Restricted Directory: 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.

Business impact

What CWE-22 could cost your business

MITRE documents what this weakness can do. Here is what that means for a website, store or app.

Confidentiality

Private data exposed

Customer records, credentials, orders or internal files can be read by people who should never see them.

  • Execute Unauthorized Code or Commands
  • Read Files or Directories

Integrity

Data, pages or code changed

Prices, orders, content or the code your site runs can be altered without your approval.

  • Execute Unauthorized Code or Commands
  • Modify Files or Directories

Availability

Downtime and lost sales

Crashes, slowdowns or exhausted resources can take your site, store or app offline.

  • Execute Unauthorized Code or Commands
  • DoS: Crash, Exit, or Restart

In plain English

What Path traversal means for your business

  • 540+projects delivered
  • 9+years in business
  • 23+certified experts
Get a free security check

A senior engineer replies within one business day.

Path traversal, also called directory traversal, happens when your code builds a file path from something a user supplied. You expect a file name inside one folder, such as an uploads directory. If the input includes special sequences that mean go up one folder, or a full absolute path, the final location can end up somewhere else on the server. The code then reads, writes or deletes a file it was never meant to touch.

The files outside that folder are often the sensitive ones. Configuration files hold database passwords and API keys. Other files hold source code, backups or customer exports. If the flaw allows writing, an attacker may be able to replace a file the server later runs. For a business, that can turn a simple download feature into a route to stolen credentials, leaked data or a compromised site.

Where it shows up

  • Download and file viewer features that take a file name from the URL and read it from disk, such as invoices, reports or attachments.
  • WordPress plugins for backups, file managers, galleries and log viewers that accept a path or file parameter from the request.
  • Template, language or theme switchers that load a file based on a value in a query string, cookie or form field.
  • Upload handlers and archive extractors that keep the original file name, or unpack ZIP files whose entries contain folder-climbing paths.

Free security check

Is CWE-22 hiding in your site?

A senior engineer checks your site, store or app for this weakness and the rest of the CWE Top 25, then sends a prioritized fix plan within one business day. No obligation.

Official definition

How MITRE defines CWE-22

Improper Limitation of a Pathname to a Restricted Directory

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.

Also known as: Path traversal, Directory traversal, Path transversal

Weakness ID
CWE-22
Type
Base
Status
Stable
Likelihood of exploit
High
Applies to
Go, Python, AI/ML
Introduced during
Implementation
2025 CWE Top 25
Rank 6

Fix it

How to fix Path traversal

Practical steps in priority order. Share them with your developer or agency.

  1. Do not take paths from users

    Refer to files by an ID and look up the real path in a database or a fixed map on the server. If the set of files is small, hard-code an allowlist and reject everything else.

  2. Canonicalize, then verify the folder

    Resolve the final path with a function such as realpath in PHP or path.resolve in Node.js. Then confirm it still starts with the intended base directory before opening it. Reject the request if it does not.

  3. Validate file names strictly

    Accept only a simple name with expected characters and an allowed extension. Reject path separators, parent-directory sequences, null bytes and absolute paths. Decode input once before validating so encoded variants cannot slip past.

  4. Restrict what the server can reach

    Run the web application under an account with access only to the folders it needs. Store uploads and user files outside the web root, and keep configuration files and backups unreadable to that account where possible.

  5. Generate names for uploads and archives

    Rename uploaded files to server-generated names. When extracting archives, check each entry’s resolved destination before writing. Add web application firewall rules as a temporary safety net for third-party code you cannot patch immediately.

Signs you may be affected

  • URLs or API calls on your site include file names or folder paths as parameters.
  • Server logs show requests containing encoded dots and slashes aimed at configuration or system files.
  • Code passes request values into file read, include or delete functions without validating them.

Questions to ask your developer

  • Which features read or write files based on a value from the request?
  • Do we resolve and verify the final path before opening any file?
  • Can the web server account read configuration files, backups or other sites?

Prevention

What MITRE recommends, phase by phase

Every mitigation from the CWE entry, in the order a project runs: plan, build, test, operate.

  1. 01

    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.
    • Use 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].
    • Run 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.
    Show 3 more recommendations
    • When 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.
    • Run 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.
    • Store 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.
  2. 02

    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.
    • 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.
    • Ensure 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.
  3. 03

    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].

Detection and evidence

How CWE-22 is found, and where it has hit

The testing methods MITRE recommends, and real vulnerabilities this weakness has caused.

How it is detected

  • 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.
  • 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.
  • Automated Static Analysis – Binary or BytecodeAccording to SOAR [REF-1479], the following detection techniques may be useful: Bytecode Weakness Analysis – including disassembler + source code weakness analysis Binary Weakness Analysis – including disassembler + source code weakness analysis
  • Manual Static Analysis – Binary or BytecodeAccording to SOAR [REF-1479], the following detection techniques may be useful: Binary / Bytecode disassembler – then use manual analysis for vulnerabilities & anomalies
  • Dynamic Analysis with Automated Results InterpretationAccording to SOAR [REF-1479], the following detection techniques may be useful: Web Application Scanner Web Services Scanner Database Scanners

Real vulnerabilities it caused

  • CVE-2024-37032Large 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
  • CVE-2024-4315Chain: API for text generation using Large Language Models (LLMs) does not include the "\" Windows folder separator in its denylist (CWE-184) when attempting to prevent Local File Inclusion via path traversal (CWE-22).
  • CVE-2024-0520Product 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
  • CVE-2022-45918Chain: 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.
  • CVE-2019-20916Python package manager does not correctly restrict the filename specified in a Content-Disposition header, allowing arbitrary file read using path traversal sequences such as "../"
  • CVE-2022-31503Python package constructs filenames using an unsafe os.path.join call on untrusted input, allowing absolute path traversal because os.path.join resets the pathname to an absolute path that is specified as part of the.

How we fix it

From finding to fixed: how Codefreex closes CWE-22

  1. Scan and confirm

    We test your site, store or app for this weakness and the rest of the CWE Top 25 with automated scanning and manual review, and confirm what is actually exploitable.

  2. Fix at the source

    We change the code, configuration or dependency that causes it, not just the symptom, and plan the changes to avoid downtime.

  3. Verify the fix

    We retest every finding, check that nothing else broke and hand you a short report you can share with your team, client or auditor.

  4. Keep it fixed

    Updates, monitoring and maintenance so the weakness does not return with the next plugin, theme, app or code change.

Related weaknesses

FAQ

CWE-22: FAQs

Short answers for owners and developers. Not sure whether your site is affected? Ask us to check.

How serious is path traversal?

It is serious because server files often contain secrets. Reading a configuration file can reveal database credentials and API keys, which opens the door to further access. Where writing is possible, the attacker may overwrite files the server executes. MITRE rates the likelihood of exploitation as high. Impact depends on what the server account is permitted to read and write.

Is path traversal only a risk for file downloads?

No. Any feature that turns outside input into a file location can be affected. That includes uploads, image resizing, template or language loading, log viewers, backup tools and archive extraction. APIs are affected in the same way as web pages. Review every place your code opens, includes, writes or deletes a file.

How do I prevent path traversal?

Avoid passing user input to file functions at all. Map IDs to known files instead. Where a name must be accepted, validate it against an allowlist, resolve the full path, and confirm it stays inside the intended folder. Limit the server account’s file permissions, and keep plugins that handle files updated.

What is CWE-22?

CWE-22, “Improper Limitation of a Pathname to a Restricted Directory”, is a software weakness catalogued by MITRE in the Common Weakness Enumeration. 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.

How serious is CWE-22?

MITRE rates the likelihood of exploit as High. It can affect integrity, confidentiality, availability, with impacts such as execute unauthorized code or commands, modify files or directories, read files or directories. It ranks number 6 on the 2025 CWE Top 25 Most Dangerous Software Weaknesses. The real risk depends on where the weakness sits and what data or functions it exposes.

How do you prevent CWE-22?

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. 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.

Can Codefreex check my site for CWE-22?

Yes. A senior engineer reviews your site, store or app for CWE-22 and the rest of the CWE Top 25, confirms what is exploitable and sends a prioritized fix plan within one business day. Start with the free security check form on this page.

Free security check

Find out if CWE-22 affects your site

Send your URL. A senior engineer checks for this weakness and the rest of the CWE Top 25, and replies within one business day with what to fix first.

  • A senior strategist reviews your request, not a sales bot
  • Clear scope, timeline and estimate within one business day
  • Free 30-minute discovery call, no obligation
  • NDA available on request

Weakness data from the Common Weakness Enumeration (CWE®) version 5.0, Copyright © 2006–2026, The MITRE Corporation. CWE is free to use by any organization or individual for any research, development, and/or commercial purposes under the CWE Terms of Use. CWE is a registered trademark of The MITRE Corporation. The business impact, risk profile and plain-English guidance on this page are written by Codefreex and are general information, not a security assessment of your system.