# Unsanitized dynamic input in file path traversal

## Overview

* **Rule ID**: `javascript_lang_path_traversal`
* **Applicable Languages**: Javascript
* **Weakness ID**: CWE-22

## Description

Using unsanitized dynamic input to determine file paths can enable attackers to access files and directories outside the intended scope. This vulnerability arises when user-provided input is directly used to interact with the filesystem without adequate validation or sanitization.

## Remediation Guidelines

* **Do not** directly use user input to build file paths. This can result in unauthorized file access.
* **Do** sanitize user input used in file paths. Replace patterns that could allow navigation out of intended directories, such as `..\..`, to prevent path traversal attacks.

  ```javascript
  var folder = target.replace(/^(\.\.(\/|\\|$))+/, '');

  ```
* **Do** check for and remove any occurrences of the NULL byte (%00) in user input to protect against NULL byte injection attacks.

  ```java
  if (target.indexOf('\0') !== -1) {
    // Handle or reject the input
  }

  ```
* **Do** use path concatenation methods provided by your programming environment to securely combine user input with your base directory path. This ensures the final path remains within the intended scope.

  ```java
  const path = require("path");
  var pathname = path.join("/public/", folder);
  if (pathname.indexOf("/public/") !== 0) {
    // Handle or reject the input
  }

  ```

## References

* [**OWASP Path Traversal**](https://owasp.org/www-community/attacks/Path_Traversal)
* [**CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')**](https://cwe.mitre.org/data/definitions/22.html)
* [**OWASP Top 10: A01:2021 - Broken Access Control**](https://owasp.org/Top10/A01_2021-Broken_Access_Control/)

## Configuration

To omit this rule during a scan, and to provide you with continuous 24/7 code-level scanning, you can employ our [**SAST TOOL**](https://scopy.sec1.io/login)
