What Is Directory Traversal (Path Traversal)?

Directory traversal (path traversal) is a vulnerability where an attacker manipulates file path inputs to access files outside the intended directory. By using ../ sequences, the attacker can read sensitive files like /etc/passwd, application configuration files, source code, and environment variables containing database credentials and API keys.

Types of Directory Traversal (Path Traversal)?

Basic traversal

Using ../ to navigate up directories.

GET /api/file?name=../../../etc/passwd

Encoded traversal

URL-encoding or double-encoding ../ to bypass filters.

GET /api/file?name=%2e%2e%2f%2e%2e%2fetc%2fpasswd

Null byte injection

Appending %00 to truncate file extensions (legacy, mostly fixed).

GET /api/file?name=../../../etc/passwd%00.png

How to Prevent It

# 1. Use basename() — strip all path components
import os
filename = os.path.basename(user_input)  # "../../etc/passwd" → "passwd"

# 2. Resolve and validate the full path
base_dir = os.path.realpath('/app/uploads')
requested = os.path.realpath(os.path.join(base_dir, user_input))
if not requested.startswith(base_dir):
    raise ValueError("Path traversal detected")

# 3. Node.js equivalent
const path = require('path');
const base = path.resolve('/app/uploads');
const requested = path.resolve(base, userInput);
if (!requested.startsWith(base)) {
  throw new Error('Path traversal detected');
}

# 4. Chroot or containerization — OS-level isolation
# Run the application in a container with only necessary files mounted

Real-World Impact

Reading source code reveals business logic and other vulnerabilities. Reading .env or config files exposes database credentials, API keys, and secrets. In severe cases, writing to the filesystem enables remote code execution.

Related Questions

Scan your system prompt with LochBot — free, client-side, no data sent anywhere.

Frequently Asked Questions

What is directory traversal?

Directory traversal is when an attacker manipulates file path inputs (using ../ sequences) to access files outside the intended directory. This can expose sensitive system files, application source code, and configuration files containing secrets.

How do I prevent directory traversal?

Use basename() to strip directory components, resolve the full path and verify it stays within the allowed directory, reject inputs containing ../ or encoded variants, and run applications in containers with minimal file access.

What files do attackers target with directory traversal?

Common targets: /etc/passwd (user accounts), .env files (secrets), config files (database credentials), application source code, SSH keys (~/.ssh/id_rsa), and cloud credential files (~/.aws/credentials).