Skip to content

Path Traversal Vulnerability Fix

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about Path Traversal Vulnerability Fix. We cover key concepts, practical examples, and best practices.

An attacker can read arbitrary files outside the intended directory by using ../ sequences — path traversal allows access to /etc/passwd, application source code, or configuration files.

Step-by-Step Fix

1. Validate and sanitize file paths

import os

# Wrong — directly using user input as file path
filename = request.args.get("file")
with open(f"/var/data/{filename}") as f:
    content = f.read()
# User can access: /var/data/../../etc/passwd

# Right — resolve and validate the path
BASE_DIR = "/var/data"
filename = request.args.get("file")
safe_path = os.path.normpath(os.path.join(BASE_DIR, filename))
if not safe_path.startswith(os.path.realpath(BASE_DIR)):
    raise ValueError("Invalid path")
with open(safe_path) as f:
    content = f.read()

2. Fix in Node.js

const path = require('path');
const fs = require('fs');

// Wrong — allowing path traversal
app.get('/files/:name', (req, res) => {
  const filePath = path.join(__dirname, 'files', req.params.name);
  res.sendFile(filePath);
  // /files/../../../etc/passwd works!

// Right — validate resolved path
app.get('/files/:name', (req, res) => {
  const baseDir = path.resolve(__dirname, 'files');
  const filePath = path.resolve(baseDir, req.params.name);
  if (!filePath.startsWith(baseDir)) {
    return res.status(403).send('Forbidden');
  }
  res.sendFile(filePath);
});

3. Use a whitelist approach

# Wrong — blacklist approach (easily bypassed)
filename = request.args.get("file")
if ".." in filename or "/" in filename:
    raise ValueError("Invalid filename")

# Right — whitelist known safe files
ALLOWED_FILES = {
    "report1", "report2", "config"
}
filename = request.args.get("file")
if filename not in ALLOWED_FILES:
    raise ValueError("File not allowed")
with open(f"/var/data/{filename}.txt") as f:
    content = f.read()

Common Mistakes

Mistake Fix
Using blacklist filters for ../ Attackers can use URL-encoded variants: %2e%2e%2f, ..%252f
Not normalizing the path before validation Always use os.path.normpath() or path.resolve() first
Checking prefix on unsanitized input path.startswith(BASE_DIR) on a joined path, not the resolved path
Allowing symbolic links Use os.path.realpath() to resolve symlinks before validation
Using user input in os.path.join without validation Validate after joining and resolving, not before

Prevention

  • Use a whitelist of allowed filenames when possible.
  • Resolve the full absolute path and verify it starts with the allowed base directory.
  • Use os.path.realpath() to resolve all symlinks.
  • Avoid reading files based on user input — use IDs mapped to files instead.
  • Store files outside the webroot and serve through a controlled endpoint.

DodaTech Tools

Doda Browser's file access monitor tracks all file read operations and flags path traversal attempts. DodaZIP safely extracts archives without following directory traversal symlinks. Durga Antivirus Pro detects path traversal patterns in HTTP request parameters.

Common Mistakes with traversal fix

  1. Using foldl instead of foldl' causing stack overflow on large lists
  2. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  3. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable

These mistakes appear frequently in real-world PATH code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

What is a path traversal attack?

Path traversal (directory traversal) is an attack where the attacker manipulates file paths using ../ sequences or absolute paths to access files and directories outside the intended directory. ||| Can URL encoding bypass path traversal filters? Yes. Attackers can use URL encoding, double encoding, or Unicode encoding to bypass simple blacklist filters. Always resolve the path to its canonical form before validation. ||| Is it safe to use an allowlist for file access? Yes, whitelisting (allowlisting) is the most secure approach. Map user-facing identifiers to actual files on the server, so the user never directly specifies a file path.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro