Security

What is Path Traversal (CWE-31)?

Path Traversal (CWE-31) occurs when an application uses external input to construct a pathname that should be within a restricted directory, but it does not...

SP
Shreya Pillai July 27, 2026 5 min read Security
AI-friendly summary

What it is: Path Traversal (CWE-31) is a type of vulnerability that occurs when an application uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences that can resolve to a location outside of that directory.

Why it matters: Path Traversal is a critical vulnerability because it allows attackers to access sensitive files and directories, potentially leading to unauthorized data modification or deletion. This can have significant business impacts, including financial losses, compliance issues, and reputational damage.

How to fix it: To fix Path Traversal vulnerabilities, developers should implement input validation, canonicalization, and proper use of allowlists to restrict directory access.

TL;DR: Path Traversal (CWE-31) is a critical vulnerability that occurs when an application fails to properly validate external input used in constructing pathnames. To fix this issue, developers should implement input validation, canonicalization, and proper use of allowlists.

At-a-Glance Table

Field Value
CWE ID CWE-31
OWASP Category Not directly mapped
CAPEC None known
Typical Severity Critical
Affected Technologies Web applications, file systems
Detection Difficulty Moderate
Last Updated 2026-07-27

What is Path Traversal?

Path Traversal (CWE-31) is a type of vulnerability that occurs when an application uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences that can resolve to a location outside of that directory. As defined by the MITRE Corporation under CWE-31, and classified by the OWASP Foundation as Not directly mapped, Path Traversal is a critical vulnerability that allows attackers to access sensitive files and directories.

Quick Summary

Path Traversal (CWE-31) is a critical vulnerability that occurs when an application fails to properly validate external input used in constructing pathnames. This can have significant business impacts, including financial losses, compliance issues, and reputational damage. To fix this issue, developers should implement input validation, canonicalization, and proper use of allowlists.

Jump to: Quick Summary · Path Traversal Overview · How Path Traversal Works · Business Impact of Path Traversal · Path Traversal Attack Scenario · How to Detect Path Traversal · How to Fix Path Traversal · Framework-Specific Fixes for Path Traversal · How to Ask AI to Check Your Code for Path Traversal · Path Traversal Best Practices Checklist · Path Traversal FAQ · Vulnerabilities Related to Path Traversal · References · Scan Your Own Site

Path Traversal Overview

What: Path Traversal (CWE-31) is a type of vulnerability that occurs when an application uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences that can resolve to a location outside of that directory.

Why it matters: Path Traversal is a critical vulnerability because it allows attackers to access sensitive files and directories, potentially leading to unauthorized data modification or deletion. This can have significant business impacts, including financial losses, compliance issues, and reputational damage.

Where it occurs: Path Traversal vulnerabilities typically occur in web applications that use external input to construct pathnames.

Who is affected: Any organization that uses web applications with external input used in constructing pathnames may be affected by Path Traversal vulnerabilities.

Who is NOT affected: Organizations that do not use web applications or do not use external input in constructing pathnames are not affected by Path Traversal vulnerabilities.

How Path Traversal Works

Root Cause

The root cause of Path Traversal is the failure to properly validate and sanitize external input used in constructing pathnames.

Attack Flow

  1. An attacker submits malicious input to the application, which is then used to construct a pathname.
  2. The application fails to properly validate the input, allowing the attacker to traverse directories outside of the intended restricted directory.
  3. The attacker gains access to sensitive files and directories, potentially leading to unauthorized data modification or deletion.

Prerequisites to Exploit

  • External input must be used in constructing pathnames
  • Application must fail to properly validate and sanitize external input

Vulnerable Code

import os

path = request.args.get('path')
os.chdir(path)

This code is vulnerable because it uses external input (request.args.get('path')) to construct a pathname without proper validation.

Secure Code

import os

base_dir = '/restricted_directory'
path = request.args.get('path')

if not os.path.abspath(path).startswith(base_dir):
    raise ValueError('Invalid path')
else:
    os.chdir(path)

This code is secure because it properly validates the input using os.path.abspath() and checks if the path starts with the base directory.

Business Impact of Path Traversal

Confidentiality: Unauthorized access to sensitive files and directories can lead to confidentiality breaches, potentially exposing sensitive information.

Integrity: Unauthorized modification or deletion of data can lead to integrity breaches, potentially causing financial losses or reputational damage.

Availability: DDoS attacks or other forms of disruption can lead to availability breaches, potentially causing significant business impacts.

Path Traversal Attack Scenario

  1. An attacker submits malicious input to the application, which is then used to construct a pathname.
  2. The application fails to properly validate the input, allowing the attacker to traverse directories outside of the intended restricted directory.
  3. The attacker gains access to sensitive files and directories, potentially leading to unauthorized data modification or deletion.

How to Detect Path Traversal

Manual Testing

  • Test external input used in constructing pathnames
  • Verify proper validation and sanitization of external input
  • Check for allowlists to restrict directory access

Automated Scanners (SAST/DAST)

Automated scanners can detect Path Traversal vulnerabilities by analyzing code and identifying potential issues.

Note: While automated scanners can catch some instances of Path Traversal, they may not catch all cases. Manual testing is still necessary to ensure proper validation and sanitization of external input.

PenScan Detection

PenScan’s scanner engines actively test for this issue.

False Positive Guidance

A finding on a filename that’s canonicalized and verified to stay inside an allowed base directory before use is a false positive — confirm the check happens on the resolved absolute path, not just a substring check of the raw input, before treating it as real.

How to Fix Path Traversal

  • Implement input validation using os.path.abspath() or similar methods
  • Properly sanitize external input using allowlists or other techniques
  • Restrict directory access using allowlists or other techniques

Framework-Specific Fixes for Path Traversal

Java

import java.io.File;

String path = request.getParameter("path");
File baseDir = new File("/restricted_directory");

if (!new File(path).getAbsolutePath().startsWith(baseDir.getAbsolutePath())) {
    throw new RuntimeException("Invalid path");
} else {
    // proceed with secure code
}

Node.js

const express = require('express');
const fs = require('fs');

app.get('/path', (req, res) => {
  const path = req.query.path;
  const baseDir = '/restricted_directory';

  if (!fs.existsSync(baseDir + '/' + path)) {
    res.status(404).send({ message: 'Invalid path' });
  } else {
    // proceed with secure code
  }
});

Python/Django

import os

path = request.args.get('path')
base_dir = '/restricted_directory'

if not os.path.abspath(path).startswith(base_dir):
    raise ValueError('Invalid path')
else:
    # proceed with secure code

How to Ask AI to Check Your Code for Path Traversal

You can ask AI to review your code for potential CWE-31 Path Traversal vulnerabilities by using a copy-pasteable prompt that includes the relevant language and fix technique.

Copy-paste prompt

Review the following Python/Django code block for potential CWE-31 Path Traversal vulnerabilities and rewrite it using input validation:

```python import os path = request.args.get('path') base_dir = '/restricted_directory' if not os.path.abspath(path).startswith(base_dir): raise ValueError('Invalid path') else: # proceed with secure code ```

Path Traversal Best Practices Checklist

✅ Implement input validation using os.path.abspath() or similar methods ✅ Properly sanitize external input using allowlists or other techniques ✅ Restrict directory access using allowlists or other techniques

Path Traversal FAQ

How does Path Traversal occur?

Path Traversal occurs when an application uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences that can resolve to a location outside of that directory.

What is the root cause of Path Traversal?

The root cause of Path Traversal is the failure to properly validate and sanitize external input used in constructing pathnames.

How do attackers exploit Path Traversal?

Attackers exploit Path Traversal by manipulating external input to traverse directories outside of the intended restricted directory, potentially leading to unauthorized access or data modification.

What are the common consequences of a successful Path Traversal attack?

The common consequences of a successful Path Traversal attack include unauthorized access to sensitive files and directories, as well as potential data modification or deletion.

How can I detect Path Traversal vulnerabilities in my application?

You can detect Path Traversal vulnerabilities using manual testing, automated scanners (SAST/DAST), and PenScan’s detection capabilities.

What are the primary prevention techniques for Path Traversal?

The primary prevention techniques for Path Traversal include input validation, canonicalization, and proper use of allowlists to restrict directory access.

How can I ask AI to check my code for Path Traversal vulnerabilities?

You can ask AI to review your code for potential CWE-31 Path Traversal vulnerabilities by using a copy-pasteable prompt that includes the relevant language and fix technique.

CWE Name Relationship
CWE-23 Relative Path Traversal ChildOf

References

Scan Your Own Site

Manual code review catches what you know to look for. An automated scan catches what you didn’t. Scan your own website using PenScan to find Path Traversal and other risks before an attacker does.