Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')

ID

javascript.path_traversal

Severity

critical

Resource

Path Resolution

Language

JavaScript

Tags

CWE:22, CWE:73, NIST.SP.800-53, OWASP:2021:A4, OWASP:2021:A5, PCI-DSS:6.5.8

Description

Improper limitation of a pathname to a restricted directory.

Path Traversal vulnerabilities exploit improper validation of user inputs when constructing file paths. Attackers can manipulate input to navigate the directory structure and access files outside the intended file directory. This typically involves injecting special characters such as ../, which, when processed, traverse the directory hierarchy.

Rationale

Allowing external input to control paths used in file system operations could allow an attacker to access or modify unintended files.

If the software concatenates external input into a path used during file operations, an attacker could "escape" from the directory reserved for such operations. Depending on the file operations performed by the software, an attacker could read or write arbitrary files, including sensitive application or operating system files, with the permissions granted to the process running the software.

Threat actors can:

  • Exfiltrate sensitive files from the software or the operating system.

  • Modify application configuration files for removing security controls and gaining further access.

  • Upload executable code (typically forcing execution of the uploaded code), which could install malware, open a reverse shell, or perform other malicious actions.

The following is an example of a path traversal vulnerability in JavaScript:

var express = require('express');
var fs = require('fs');
var path = require('path');

var app = express();
// ...

const UPLOAD_DIR = '/var/tmp/upload';
var dir = fs.mkdirSync(UPLOAD_DIR);

app.post('/product/:product', function(req, res) {
  let productName = req.params.product;
  let content = req.body.content;

  // simple join with unsanitized input allows path manipulation
  let fname = path.join(UPLOAD_DIR, productName);

  /*
    FLAW - path traversal, user may choose productName as
    ../../../path/to/important/file to overwrite any file of interest
  */
  fs.writeFile(fname, content, 'utf-8', function(err) {
    if(err) return handleError(err, res);
    onSavedProduct({product: productName, content: content, file: fname}, res);
  })
});

Remediation

To protect against Path Traversal vulnerabilities in applications, consider the following remediation strategies:

  1. Canonicalize the Path: Normalize file paths before processing them using file functions. This ensures that any navigational characters are resolved and the path refers to the correct location. Perform any checks on path after canonicalization.

  2. Whitelisting: Maintain a whitelist of allowed file names or extensions that users can access, rejecting any requests for files not in the whitelist.

  3. Input Validation: Validate incoming parameters rigorously. Reject or safely encode inputs containing harmful patterns, such as .., or control characters.

  4. Least Privilege: Ensure that applications run with the least privilege necessary. Restrict file permissions to prevent unauthorized file access even if paths are manipulated.

  5. Security Audits and SAST: Conduct regular security audits and integrate Static Application Security Testing tools to identify and mitigate Path Traversal vulnerabilities early during development.

By implementing these preventive measures, you can significantly reduce the risk of Path Traversal vulnerabilities, safeguarding your application against unauthorized file access and potential data breaches.

To fix the vulnerability in the example before, a path validation function such as isPathInDirectory() should be used:

var path = require('path');

function isPathInDirectory(basedir, filepath) {
  var abspath = path.resolve(filepath);
  var absdir = path.resolve(basedir) + path.sep;
  return abspath.substring(0, absdir.length) === absdir;
}

So the fixed code goes like this:

app.post('/product/:product', function(req, res) {
  let productName = req.params.product;
  let content = req.body.content;

  // simple join with unsanitized input allows path manipulation
  let fname = path.join(UPLOAD_DIR, productName);

  // FIXED - path validation
  // Another possibility is to check for e.g. alphanumeric productName with a regex
  // const regex = /^[a-zA-Z][a-zA-Z0-9_]*$/;
  if(!isPathInDirectory(UPLOAD_DIR, fname)) {
    return handleError(new Error('Illegal product name'), res);
  }

  fs.writeFile(fname, content, 'utf-8', function(err) {
    if(err) return handleError(err, res);
    onSavedProduct({product: productName, content: content, file: fname}, res);
  })
});

Configuration

The detector has the following configurable parameters:

  • sources, that indicates the source kinds to check.

  • neutralizations, that indicates the neutralization kinds to check.

Unless you need to change the default behavior, you typically do not need to configure this detector.

References