logo

Database

Javascript Path Traversal Vulnerability

Description

Detects potential path traversal vulnerabilities in JavaScript code where file system operations may allow unauthorized access to files outside the intended directory structure. This occurs when user-controlled input can manipulate file paths without proper validation, potentially allowing access to sensitive files using "../" traversal sequences.

Weakness:

063 - Lack of data validation - Path Traversal

Category: Unexpected Injection

Detection Strategy

    • Check for file system operations (like fs.readFile, path.join) that accept dynamic path arguments

    • Identify path variables or parameters that may contain user-controlled input

    • Look for missing path normalization or validation before using paths in file operations

    • Flag instances where path strings could include '../' or similar directory traversal sequences

    • Verify if absolute paths are enforced or if relative paths are properly restricted

Vulnerable code example

const fs = require('fs');

function readUserFile(userPath) {
  // Vulnerable: Direct use of user input in file operations without path sanitization
  const data = fs.readFileSync(userPath);
  return data;
}

✅ Secure code example

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

function readUserFile(userPath) {
  try {
    // Sanitize and resolve the full path
    const resolvedPath = path.resolve(userPath);
    ...