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.

Jul 26, 2025 - 10:45
Updated: 
104.1k

Ethical Hacking in Cybersecurity & Ethical Hacking · Explainer

Web & API Security, Cyber Threats, Scams & Online Safety

Path Traversal Explained: How It Works and How to Prevent It

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?

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?

FilterBypass class
Remove ../ onceNested sequences such as ....// collapse into ../
Block ../ literallyURL encoding (%2e%2e%2f) or double encoding
Require a prefix folderinvoices/../../etc/passwd still starts with the prefix
Require a .pdf extensionOld 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, .env files, 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.jsp is 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

A vulnerability where user input in a file path lets an attacker access files outside the intended directory.

Yes. Both names describe CWE-22, where ../ sequences or absolute paths escape a restricted folder.

Yes, when it allows writing files, for example through uploads or archive extraction into a web folder.

Encoded, nested and absolute-path variants bypass string filters. Check the final resolved path instead.

Path traversal through archive entry names, which writes extracted files outside the destination folder.

Resolve the path with pathlib and confirm it is relative to the base directory before opening it.

It blocks common patterns but can be bypassed. Fix the code and treat the WAF as an extra layer.

PortSwigger Web Security Academy and deliberately vulnerable apps such as DVWA and OWASP Juice Shop.

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Wow Wow 0
Sad Sad 0
Angry Angry 0
Vaishnavi

Vaishnavi is a skilled tech professional at the Ethical Hacking Training Institute in Pune, responsible for managing and optimizing the technical infrastructure that supports advanced cybersecurity education. With deep expertise in network security, backend operations, and system performance, she ensures that practical labs, online modules, and assessments run smoothly and securely. Her behind-the-scenes contributions play a vital role in delivering a seamless and secure learning experience for aspiring ethical hackers.