highCWE-22A01:2021

Path Traversal

File paths constructed with unvalidated user input allow attackers to read or write arbitrary files on the server using ../ sequences.

How It Works

Path traversal occurs when an application uses user-supplied input to construct file paths without proper validation. An attacker can inject ../ (dot-dot-slash) sequences to navigate outside the intended directory. For example, requesting /files?name=../../../etc/passwd reads the system password file. On Windows, ..\..\..\windows\system32\config\sam achieves similar results. This vulnerability lets attackers read configuration files, source code, environment variables, and any file the server process can access. When combined with write operations, attackers can overwrite application files or inject malicious code.

Vulnerable Code
const path = require('path');
app.get('/files/:name', (req, res) => {
  const filePath = path.join(__dirname, 'uploads', req.params.name);
  res.sendFile(filePath);
});
Secure Code
const path = require('path');
app.get('/files/:name', (req, res) => {
  const uploadsDir = path.resolve(__dirname, 'uploads');
  const filePath = path.resolve(uploadsDir, req.params.name);
  if (!filePath.startsWith(uploadsDir)) {
    return res.status(403).json({ error: 'Access denied' });
  }
  res.sendFile(filePath);
});

Real-World Example

In 2021, a path traversal vulnerability in Apache HTTP Server (CVE-2021-41773) allowed attackers to access files outside the document root. Combined with CGI, it enabled remote code execution. The vulnerability was actively exploited in the wild within hours of disclosure.

How to Prevent It

  • Resolve the full path and verify it starts with the expected base directory
  • Use path.resolve() and compare with startsWith() to prevent directory escape
  • Never pass user input directly to file system operations
  • Use a UUID-based file naming system instead of user-supplied filenames

Affected Technologies

Node.jsPythonJavaPHPGo

Data Hogo detects this vulnerability automatically.

Scan Your Repo Free

Related Vulnerabilities