Security

What is Path Traversal (CWE-22)?

Path Traversal (CWE-22) lets attackers escape a restricted directory via unsanitized input. See real vulnerable/secure code and the canonicalization fix.

SP
Shreya Pillai July 27, 2026 7 min read Security
AI-friendly summary

What it is: Path Traversal (CWE-22) is a type of broken access control vulnerability where unsanitized input lets an attacker construct a file path that escapes its intended restricted directory.

Why it matters: It can expose credentials, source code, and configuration files, or let an attacker overwrite files used to execute code — MITRE rates its likelihood of exploit as High.

How to fix it: Canonicalize the input path and verify the resolved absolute path is still inside the allowed base directory before granting access.

TL;DR: Path Traversal lets an attacker read or write files outside a restricted directory by manipulating unsanitized path input; the fix is canonicalization plus a base-directory allowlist check, never a denylist substring check.

Field Value
CWE ID CWE-22
OWASP Category A01:2025 - Broken Access Control
CAPEC CAPEC-126, CAPEC-64, CAPEC-76, CAPEC-78, CAPEC-79
Typical Severity Critical
Affected Technologies Web applications, file systems, operating systems
Detection Difficulty Easy
Last Updated 2026-07-27

What is Path Traversal?

Path Traversal (CWE-22) is a type of broken access control vulnerability that occurs when an application uses external input to construct a pathname intended to stay within a restricted parent directory, but fails to neutralize special elements that let the resolved path escape that directory. As defined by the MITRE Corporation under CWE-22, and classified by the OWASP Foundation under A01:2025 - Broken Access Control, this is one of the most consistently high-likelihood weaknesses in MITRE’s own exploitability ratings.

Quick Summary

Path Traversal turns any file-serving or file-processing feature into a potential window onto the entire filesystem the application process can reach. Because the attack requires nothing more than manipulating a request parameter, and the payloads are well-known and easy to automate, MITRE rates its likelihood of exploit as High — this is not a theoretical or hard-to-reach weakness.

Jump to: Quick Summary · Path Traversal Overview · How Path Traversal Works · Business Impact of Path Traversal · Path Traversal Attack Scenario · How to Detect Path Traversal · How to Fix Path Traversal · Framework-Specific Fixes for Path Traversal · How to Ask AI to Check Your Code for Path Traversal · Path Traversal Best Practices Checklist · Path Traversal FAQ · Vulnerabilities Related to Path Traversal · References · Scan Your Own Site

Path Traversal Overview

What: An application builds a file path from external input without confirming the resolved path stays inside its intended restricted directory.

Why it matters: The weakness directly exposes the filesystem itself — not just application data — including configuration files, credentials, and source code.

Where it occurs: Any file-download, file-upload, template-include, or log-viewer feature that accepts a filename or path fragment from the client.

Who is affected: Any application that constructs filesystem paths from request parameters, form fields, or query strings.

Who is NOT affected: Applications that never construct paths from external input at all — e.g. serving files exclusively via fixed, hardcoded paths or opaque database-stored IDs mapped server-side to a fixed file.

How Path Traversal Works

Root Cause

The application concatenates a restricted base directory with untrusted input and uses the result directly in a file operation, without verifying the final resolved path is still inside that base directory.

Attack Flow

  1. The attacker identifies a parameter that is used to build a file path (e.g. a “file” or “template” query parameter).
  2. The attacker submits a value containing traversal sequences (e.g. ../../../../etc/passwd).
  3. The application resolves the path, which now points outside the intended directory.
  4. The file operation (read, and sometimes write) executes against the unintended target.
  5. The attacker receives sensitive file contents, or successfully overwrites a file the application later trusts.

Prerequisites to Exploit

  • External input reaches a file-path-constructing operation.
  • The application does not canonicalize the resolved path before using it.
  • The application does not verify the resolved path is still inside the intended base directory.

Vulnerable Code

import os

def read_report(filename):
    base_dir = "/var/app/reports"
    path = os.path.join(base_dir, request.args.get("file"))
    with open(path) as f:
        return f.read()

The filename comes directly from the request with no validation at all, so a value like ../../../../etc/passwd resolves outside /var/app/reports entirely.

Secure Code

import os

def read_report(filename):
    base_dir = "/var/app/reports"
    requested = request.args.get("file")
    full_path = os.path.abspath(os.path.join(base_dir, requested))
    if not full_path.startswith(os.path.abspath(base_dir) + os.sep):
        raise ValueError("Invalid path")
    with open(full_path) as f:
        return f.read()

The path is canonicalized with os.path.abspath() and then explicitly checked against the real base directory before the file is opened, so any traversal attempt is rejected instead of silently resolved.

Business Impact of Path Traversal

Confidentiality: Attackers can read unexpected files and expose sensitive data, including password files, source code, or configuration secrets.

Integrity: Attackers may create or overwrite critical files, including programs or libraries used to execute code, potentially bypassing security mechanisms entirely.

Availability: Attackers may overwrite, delete, or corrupt critical files, preventing the application from functioning and potentially locking out legitimate users.

  • Direct exposure of credentials and secrets stored in configuration files
  • Potential full remote code execution if writable, executable paths are reachable
  • Regulatory and compliance exposure from unauthorized data disclosure

Path Traversal Attack Scenario

  1. An attacker finds a report-download endpoint that accepts a file parameter.
  2. They request file=../../../../etc/passwd and observe the response contains the system’s password file.
  3. Encouraged, they probe further and request file=../../config/database.yml, exposing database credentials.
  4. Using those credentials, the attacker pivots to the database directly, well beyond the original file-download feature’s intended scope.

How to Detect Path Traversal

Manual Testing

  • Identify every parameter that influences a file path (filename, template, path, document, page).
  • Submit ../ sequences, URL-encoded (%2e%2e%2f), and absolute-path payloads against each.
  • Confirm whether the response contains content from outside the expected directory.
  • Test upload features for path traversal in the stored filename itself.

Automated Scanners (SAST / DAST)

Static analysis can flag file operations built from unsanitized request data directly in source, while dynamic testing is required to confirm the live server actually resolves and returns content from outside the intended directory.

PenScan Detection

PenScan’s scanner engines send real traversal payloads against file-related parameters across common frameworks and confirm whether out-of-directory content is returned.

False Positive Guidance

A parameter that looks path-like but is actually mapped server-side to a fixed, allowlisted set of files (e.g. an enum-style ID) is not vulnerable even though the parameter name suggests a filename — confirm the value is used directly in a filesystem call before treating it as exploitable.

How to Fix Path Traversal

  • Canonicalize the resolved path (realpath(), getCanonicalPath(), GetFullPath()) before any validation or use.
  • Verify the canonicalized path still starts with the intended base directory; reject anything that doesn’t.
  • Prefer mapping user-supplied IDs to fixed filenames server-side instead of accepting raw filenames at all.
  • Run the application with the lowest filesystem privileges required for its task, limiting the blast radius of any bypass.

Framework-Specific Fixes for Path Traversal

  • Java: use Paths.get(baseDir, userInput).normalize() combined with startsWith(Paths.get(baseDir)) before any file access.
  • Node.js: use path.join() and path.resolve(), then verify the result with .startsWith(path.resolve(baseDir)).
  • Python/Django: use os.path.abspath() combined with a startswith() check against the resolved base directory, as shown above.
  • PHP: use realpath() on the constructed path and verify it still starts with realpath($baseDir) before any fopen()/include() call.

How to Ask AI to Check Your Code for Path Traversal

Copy-paste prompt

Review the following [language] code block for potential CWE-22 Path Traversal vulnerabilities and rewrite it using path canonicalization plus a base-directory allowlist check: [paste code here]

Path Traversal Best Practices Checklist

✅ Canonicalize every user-influenced path before use ✅ Verify the canonicalized path is still inside the intended base directory ✅ Prefer ID-to-fixed-filename mapping over accepting raw filenames ✅ Never rely on a denylist substring check like blocking “../” alone ✅ Run file-serving processes with least-privilege filesystem access

Path Traversal FAQ

How does Path Traversal actually let an attacker read arbitrary files?

When an application builds a file path by concatenating a restricted base directory with unsanitized user input, sequences like “../” let the resolved path climb out of that base directory to anywhere the process can read.

How is Path Traversal different from Relative Path Traversal (CWE-23)?

CWE-22 is the general parent weakness covering any failure to keep a constructed pathname inside a restricted directory; CWE-23 is the specific case where the attack uses relative “../” sequences to do it.

How dangerous is Path Traversal compared to other injection issues?

MITRE rates its likelihood of exploit as High, and successful exploitation can expose credentials, source code, or configuration files, and in some cases allow overwriting files used to execute code.

How do I detect Path Traversal in my own application?

Test any endpoint that accepts a filename or path parameter with payloads containing “../” sequences, URL-encoded variants, and absolute paths, and confirm whether the response returns content from outside the intended directory.

How do I fix Path Traversal without breaking legitimate file access?

Canonicalize the input path with a function like realpath() or getCanonicalPath(), then verify the resolved absolute path still starts with the intended base directory before allowing access — reject anything that resolves outside it.

How does denylisting “..” fail to prevent Path Traversal?

Attackers can bypass a simple substring check with URL encoding (%2e%2e%2f), double encoding, alternate separators like backslash, or by exploiting inconsistent normalization, all of which a denylist alone does not catch.

How can PenScan help find Path Traversal issues?

PenScan tests file-related parameters with real traversal payloads across common frameworks and flags endpoints that return content from outside the expected directory.

CWE Name Relationship
CWE-706 Use of Incorrectly-Resolved Name or Reference ChildOf
CWE-668 Exposure of Resource to Wrong Sphere CanPrecede

References

Scan Your Own Site

Manual code review catches what you know to look for. An automated scan catches what you didn’t. Scan your own website using PenScan to find Path Traversal and other risks before an attacker does.