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.