Skip to content

Path Traversal via User Input in Path Construction

Description

The code constructs a path using user input, which can lead to a Path Traversal vulnerability. This allows an attacker to access files outside the intended directory by manipulating the input.

Examples

Insecure Code

javascript
const path = require('path');
app.get('/', (req, res) => {
  const filePath = path.join(__dirname, req.query.file);
  res.sendFile(filePath);
});

Secure Code

javascript
const path = require('path');
app.get('/', (req, res) => {
  const allowedFiles = ['file1.txt', 'file2.txt'];
  const filePath = path.join(__dirname, 'files', allowedFiles.includes(req.query.file) ? req.query.file : 'index.txt');
  res.sendFile(filePath);
});

Remediation

Validate and sanitize user input before using it to construct paths. Use a whitelist approach to ensure only allowed paths are accessible.

Rule Details

FieldValue
IDCODE-0420
CategoryInjection
SeverityMEDIUM
CWECWE-22
ConfidenceHIGH
ImpactHIGH
LikelihoodMEDIUM
ExploitabilityEASY
TagsPath Traversal, User Input Validation
OWASPA5:2017-Broken Access Control, A01:2021-Broken Access Control