Path Traversal Explained: How It Works and How to Prevent It
Path traversal (also called directory traversal, CWE-22) happens when an application builds a file path from user input without making sure the result stays inside the intended folder. Input such as../../etc/passwd or an absolute path makes the server read, or sometimes write, files elsewhere, exposing configuration files, source code and credentials.
Topic: Ethical Hacking in Cybersecurity & Ethical Hacking · Explainer
Also covers: Web & API Security, Cyber Threats, Scams & Online Safety
Quick answer: Path traversal (also called directory traversal, CWE-22) happens when an application builds a file path from user input without making sure the result stays inside the intended folder. Input such as ../../etc/passwd or an absolute path makes the server read, or sometimes write, files elsewhere, exposing configuration files, source code and credentials. The reliable fix is to avoid using user input in paths at all (use an ID mapped to a file), or to resolve the full canonical path and check it starts with the allowed base directory before opening it.
Key takeaways
../moves up one directory; enough of them reach the filesystem root.- Blocklist filters fail against encoding, absolute paths and platform differences.
- Canonicalise, then compare with the base directory: that is the core defence.
- Archive extraction (zip slip) is path traversal too.
- CISA issued a Secure by Design alert in 2024 calling this class of bug avoidable.
Table of Contents
- What Is Path Traversal?
- How Does It Work?
- Why Do Simple Filters Fail?
- What Is the Impact?
- What Are Real-World Examples?
- How Do You Prevent It in Code?
- How Do Authorised Testers Check for It?
- How Do You Detect Attempts?
- References
What Is Path Traversal?
Many applications serve files based on a parameter: /download?file=invoice-1043.pdf. If the code joins that parameter to a folder such as /var/app/invoices/ without validation, an attacker controls which file is opened. OWASP describes the attack and its variants.
How Does It Work?
# vulnerable Python (do not use)
@app.get("/download")
def download():
name = request.args["file"]
return send_file("/var/app/invoices/" + name)
# request
GET /download?file=../../../etc/passwd
# path opened: /var/app/invoices/../../../etc/passwd => /etc/passwd
On Windows, both ..\ and ../ usually work, and drive letters such as C:\ give an absolute path.
Why Do Simple Filters Fail?
| Filter | Bypass class |
|---|---|
Remove ../ once | Nested sequences such as ....// collapse into ../ |
Block ../ literally | URL encoding (%2e%2e%2f) or double encoding |
| Require a prefix folder | invoices/../../etc/passwd still starts with the prefix |
Require a .pdf extension | Old runtimes truncated at a null byte; other code may strip extensions |
Block only / | Backslashes on Windows; absolute paths |
This is why the fix must check the final resolved path, not the input string. PortSwigger's path traversal labs let you see each bypass legally.
What Is the Impact?
- Reading secrets: configuration files,
.envfiles, private keys, cloud credentials. - Source code disclosure, which reveals further bugs.
- Writing files: where uploads or archive extraction are affected, attackers can overwrite configuration or place a web shell, leading to code execution.
- Zip slip: an archive entry named
../../app/shell.jspis written outside the extraction folder.
What Are Real-World Examples?
Path traversal appears regularly in CISA's Known Exploited Vulnerabilities catalogue, which prompted CISA and the FBI to publish a Secure by Design alert on directory traversal in May 2024. Recent examples on this blog include the absolute path traversal flaw in Tableau Server (CVE-2025-52452) and the ZipVim flaw in Vim (CVE-2025-53906).
How Do You Prevent It in Code?
Best option: do not accept file names. Store files under generated IDs and look them up in a database that also checks ownership.
Otherwise, canonicalise and check the prefix:
# Python 3.9+
from pathlib import Path
BASE = Path("/var/app/invoices").resolve()
def safe_path(name: str) -> Path:
p = (BASE / name).resolve()
if not p.is_relative_to(BASE):
raise PermissionError("path outside base directory")
return p
// Node.js
const path = require('path');
const BASE = path.resolve('/var/app/invoices');
function safePath(name) {
const p = path.resolve(BASE, name);
if (p !== BASE && !p.startsWith(BASE + path.sep)) throw new Error('blocked');
return p;
}
// Java
Path base = Paths.get("/var/app/invoices").toRealPath();
Path p = base.resolve(name).normalize();
if (!p.startsWith(base)) throw new SecurityException("blocked");
// PHP
$base = realpath('/var/app/invoices');
$p = realpath($base . DIRECTORY_SEPARATOR . $name);
if ($p === false || strpos($p, $base . DIRECTORY_SEPARATOR) !== 0) { http_response_code(404); exit; }
Also: allow only expected characters (for example ^[A-Za-z0-9_-]+\.pdf$), run the application as a low-privilege user, and when extracting archives, apply the same check to every entry name. Note that resolve() follows symbolic links, which is what you want for this check.
How Do Authorised Testers Check for It?
Following the OWASP testing guide, testers identify every parameter that names a file, template or path, then try relative sequences, absolute paths and encoded forms against a harmless known file such as /etc/hostname or C:\Windows\win.ini. Tools such as Burp Suite Intruder or ffuf with a traversal wordlist speed this up. Test only applications you own or are authorised to assess.
How Do You Detect Attempts?
# search web server logs for traversal patterns (raw and encoded)
grep -Ei "(\.\./|\.\.%2f|%2e%2e%2f|%252e%252e|\.\.\\)" /var/log/nginx/access.log | head
Web application firewalls block common patterns, but treat that as a backup: encoded variants and application-specific parameters can slip through. Read about web application firewalls, or ask WebAsha about secure coding and web application security courses.
References
Frequently Asked Questions
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Wow
0
Sad
0
Angry
0