# 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)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.sec1.io/user-docs/4-sast/3-javascript/unsanitized-dynamic-input-in-file-path-traversal.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
