Path traversal is a web security vulnerability that allows an attacker to access files or directories outside the location an application was designed to use.
It is also known as directory traversal, directory climbing, file path traversal, or the dot-dot-slash attack. The vulnerability usually appears when an application places user-controlled information, such as a filename, document ID, image name, or download path, into a filesystem operation without enforcing a safe boundary.
A vulnerable application may intend to retrieve a profile image or downloadable report. An attacker may manipulate the requested path so that the application reads a configuration file, source-code file, system record, credential store, or another user’s private document instead.
Some path traversal flaws permit only file reading. More severe versions may allow an attacker to create, replace, move, or delete files, potentially changing application behavior or gaining deeper control over the server.
How Does a Path Traversal Attack Work?
Applications often need to interact with files stored on a server. Common examples include:
- Displaying images
- Serving downloadable documents
- Loading language files
- Opening report templates
- Retrieving user attachments
- Processing uploaded archives
- Reading application themes
- Creating backups
- Exporting account data
- Loading configuration files
- Accessing log files
- Generating invoices
The application might accept a filename and combine it with a server-controlled directory.
For example, an image feature may be designed to retrieve a selected file from an approved images folder. The security problem begins when the application trusts the supplied filename and fails to verify where the completed path actually leads.
A typical directory traversal attack follows this pattern:
- The application accepts a user-controlled filename or path.
- It combines that input with an intended base directory.
- The input contains path-navigation characters or another unexpected path format.
- The operating system resolves the resulting path.
- The resolved location falls outside the approved directory.
- The application reads, writes, or deletes the unintended file.
- The attacker receives the content or observes another result.
OWASP describes path traversal as an attack that manipulates file references to reach data stored outside the web root or another intended directory. This can expose application source code, configuration information, and critical system files. OWASP’s Path Traversal overview explains the underlying weakness.
Why Is Path Traversal Dangerous?
Files stored outside a public web directory are not necessarily safe if the application itself can access them.
The vulnerable application may have permission to read or modify:
- Application configuration
- Environment files
- Database credentials
- API keys
- Encryption keys
- Source code
- Authentication records
- Customer documents
- System logs
- Backup archives
- Cloud credentials
- Service-account tokens
- Administrative scripts
- Operating-system files
Exposed configuration or source-code files may reveal additional vulnerabilities, internal endpoints, database details, and security controls.
Potential consequences include:
- Disclosure of sensitive information
- Credential theft
- Exposure of personal data
- Source-code theft
- Access to other users’ files
- Authentication bypass
- Application configuration changes
- Destruction or corruption of data
- Malware placement
- Unauthorized code execution
- Service disruption
- Movement into connected systems
- Complete server compromise in severe cases
The impact depends on whether the application can only read files or can also create, overwrite, include, move, or execute them.
Common Types of Path Traversal
Relative Path Traversal
Relative path traversal uses path-navigation behavior to move away from the application’s intended folder.
Operating systems use special path components to represent the current directory or a parent directory. If an application accepts these components without validating the final location, a supplied filename may escape the approved directory tree.
This is the classic form of the vulnerability and the reason path traversal is sometimes called a directory-climbing attack.
Absolute Path Traversal
Some applications expect only a filename but unintentionally accept a complete filesystem path.
Instead of navigating outward from the intended directory, an attacker supplies an absolute location pointing directly to another part of the filesystem.
A filter that blocks only parent-directory sequences will not prevent this variation. The application must reject absolute paths unless they are explicitly required and safely controlled.
Encoded Path Traversal
Web applications frequently decode URL values, form data, filenames, and other input before using them.
An attacker may encode path separators or navigation characters in an attempt to bypass a filter. Problems occur when:
- Validation happens before decoding
- Data is decoded more than once
- Different components normalize input differently
- The filter and filesystem interpret characters differently
- Unicode or alternative encodings are handled inconsistently
The safe approach is to decode input exactly as required, normalize it consistently, and then validate the resolved path.
Nested or Repeated Traversal
A weak security filter may remove one suspicious sequence but fail to examine the result again.
When parts of the input overlap or are nested, removing one pattern may accidentally create another dangerous path. This is one reason developers should not depend on repeated string replacement as a security control.
Mixed-Separators Traversal
Operating systems and software libraries may accept different directory separators.
A validation rule designed for only one separator may fail when the application is deployed on another operating system or when an underlying library accepts multiple formats.
Cross-platform applications must account for the path behavior of the actual runtime and filesystem.
Path Traversal Through File Uploads
Upload features can become vulnerable when users control:
- The original filename
- The destination folder
- An archive’s internal paths
- A document-extraction location
- A media-processing output path
An unsafe upload may overwrite an existing application file or place content in an unintended directory.
Files extracted from ZIP and similar archives require special attention. A malicious archive can contain entries whose paths escape the intended extraction folder. This variation is sometimes called Zip Slip.
Path Traversal in File Downloads
Download endpoints often accept a filename, document path, or report identifier.
If the endpoint directly converts that value into a filesystem path, an attacker may request a private file instead of the intended download.
The safer design is to accept an opaque record identifier, confirm the user is authorized to access the record, and map that identifier to a server-controlled storage location.
Write-Based Path Traversal
Some path traversal vulnerabilities allow the attacker to select where the application writes a file.
Depending on filesystem permissions, the attacker might:
- Replace an application configuration
- Corrupt stored data
- Modify a startup file
- Overwrite a script
- Change a template
- Place content in a public directory
- Interfere with logs
- Affect another user’s files
Write access is often more dangerous than read access because it may alter application behavior or create a route to code execution.
Delete or Move Path Traversal
Applications that rename, move, archive, or delete files may also be affected.
A user-controlled path can cause the application to act on a resource outside the intended storage area. This could delete important files, move private documents, or disrupt the application.
Second-Order Path Traversal
Second-order path traversal occurs when the dangerous value is stored before it is used.
An application may save an uploaded filename, report name, or export destination in a database. A background worker later uses that stored value in a filesystem operation without validating it again.
The delay between submission and execution can make the vulnerability harder to discover and investigate.
Where Do Path Traversal Vulnerabilities Appear?
Directory traversal can affect any software that builds file paths using information an attacker can influence.
Common locations include:
- Image-loading endpoints
- File-download functions
- Document-management platforms
- Cloud storage gateways
- Backup and restoration tools
- Archive extractors
- Content-management systems
- Log viewers
- Template engines
- Localization systems
- Theme managers
- Media-processing services
- Report generators
- Source-code browsers
- Developer tools
- Administrative dashboards
- Mobile application backends
- Desktop applications
- Internet of Things devices
- File-sharing platforms
Developers should examine paths derived from URLs, forms, API fields, cookies, headers, uploaded metadata, database values, message queues, and background jobs.
What Causes Path Traversal?
The root cause is allowing untrusted input to influence a filesystem location without reliably enforcing the intended directory boundary.
Common development mistakes include:
- Appending a user-supplied filename to a directory
- Accepting complete paths from a client
- Relying only on blocked characters
- Removing suspicious strings without normalization
- Validating before decoding
- Decoding input multiple times
- Ignoring alternative path separators
- Trusting an uploaded filename
- Extracting archives without checking every entry
- Performing only a prefix string comparison
- Following symbolic links unexpectedly
- Using inconsistent path libraries
- Running the application with excessive filesystem permissions
- Assuming authenticated users are trustworthy
- Failing to authorize access to the requested file
MITRE classifies improper path restriction as CWE-22. The weakness occurs when software does not properly limit a pathname to a restricted directory. MITRE’s CWE-22 entry provides the formal classification.
What Is the Difference Between Path Traversal and File Inclusion?
The terms are related but describe different behavior.
Path traversal allows an attacker to reach a file outside the intended directory.
File inclusion causes an application to load or execute a file as part of its program flow. Depending on the language and configuration, this may involve a local file or a remote resource.
A path traversal weakness may help an attacker choose which file is included, but not every traversal vulnerability executes files. Many only disclose their contents.
What Is the Difference Between Path Traversal and Forced Browsing?
Forced browsing involves requesting hidden or unlinked resources that are still reachable through the web server.
Path traversal manipulates a filesystem path to escape an intended directory.
With forced browsing, the resource may already have a valid public URL that is simply not displayed. With path traversal, the attacker attempts to make the application access a location that should not be exposed through the feature at all.
What Is the Difference Between Path Traversal and IDOR?
An insecure direct object reference, or IDOR, occurs when an application exposes an object identifier but fails to verify whether the current user is authorized to access that object.
Path traversal focuses on unsafe filesystem path construction.
The two problems may overlap. A file-download feature might safely resolve a path but still allow one user to download another user’s document because authorization is missing. Conversely, an authorization check may exist, but unsafe path construction could let the request escape the authorized storage directory.
Applications need both safe path handling and object-level authorization.
What Is the Difference Between Path Traversal and Command Injection?
Path traversal manipulates the location of a file or directory. Command injection manipulates an instruction executed by the operating system.
A path traversal vulnerability normally provides unintended filesystem access. Command injection may give an attacker the ability to execute system commands.
However, the vulnerabilities can be combined. For example, an attacker might use traversal to overwrite a script that is later executed by the application.
Warning Signs of a Path Traversal Attack
Users may not see obvious symptoms, but developers and security teams may notice:
- Requests containing unusual path-navigation patterns
- Repeated requests for configuration or system filenames
- Encoded directory separators
- Unexpected absolute paths
- Requests for files outside normal content folders
- Download errors involving sensitive server paths
- Unexplained access to configuration files
- File reads performed by a public application endpoint
- Unexpected files appearing in application directories
- Modified templates or scripts
- Failed archive extractions
- Uploaded filenames containing directory components
- Abnormal file-permission errors
- Sensitive file content appearing in responses
- Application processes accessing unrelated directories
- Attempts to retrieve backup or source-code files
- Unusual filesystem activity from a web-server account
Security teams should compare suspicious requests with application, proxy, filesystem, endpoint, and authentication logs.
How Can Developers Prevent Path Traversal?
Avoid Accepting File Paths From Users
The strongest approach is to prevent users from supplying paths or filenames that are passed directly to the filesystem.
Instead, the application can accept:
- A database record ID
- A generated file identifier
- A selection from an approved list
- A random storage key
- A server-defined resource name
The server should map that value to a controlled storage location.
Use an Allowlist of Permitted Files
When only a limited set of files is required, create a server-side mapping.
For example, a language selection can map to an approved language file. The user selects the language code, but the server chooses the actual path.
Reject any value that is not explicitly supported.
Generate Internal Filenames
Uploaded files should normally receive application-generated names.
The original filename may be stored separately as display metadata after it has been safely processed, but it should not determine the file’s storage location.
Random or opaque storage identifiers also reduce filename collisions and make direct guessing more difficult.
Resolve and Validate the Final Path
When path construction is unavoidable, the application should use a maintained platform path library to:
- Construct the candidate path.
- Normalize or canonicalize it.
- Resolve it against the approved base directory.
- Confirm the final path remains inside that directory.
- Perform the filesystem operation only after validation.
String concatenation alone is not safe.
A simple text check that the path “starts with” an approved directory can also fail if directory boundaries, case sensitivity, separators, or symbolic links are handled incorrectly.
Validate After Decoding
Security checks must operate on the same effective value the filesystem will receive.
Applications should establish a consistent processing order:
- Reject malformed encoding
- Decode only as required
- Avoid repeated decoding
- Normalize the path
- Validate the final resolved location
- Perform the filesystem operation
Validation performed on an earlier representation may miss what the path becomes later.
Reject Absolute Paths
If the feature requires only a simple filename or identifier, reject absolute paths and directory components.
The accepted format should be as narrow as possible. A file type, name length, and character allowlist can provide additional protection, but these checks should support—not replace—final path validation.
Enforce Filesystem Boundaries
The application should verify that the resolved destination is a child of the approved directory.
This boundary must account for:
- Platform-specific separators
- Case sensitivity
- Symbolic links
- Junctions or mount points
- Existing and newly created files
- Race conditions
- Archive entries
- Network-mounted storage
Security-sensitive code should use established framework or language functions rather than custom path parsing.
Handle Symbolic Links Carefully
A path may appear to remain inside the approved directory while a symbolic link points somewhere else.
Applications should avoid following untrusted links. Depending on the platform and use case, developers may need to:
- Resolve real filesystem locations
- Reject symbolic links
- Open files using safer directory-relative APIs
- Restrict link creation
- Revalidate immediately before use
- Use operating-system protections against link following
Protect Archive Extraction
Before extracting an archive, inspect every entry.
For each file, the application should:
- Reject absolute paths
- Normalize the destination
- Confirm it remains inside the extraction folder
- Reject unsafe symbolic links
- Enforce size and file-count limits
- Prevent overwriting important files
- Use an isolated temporary directory
The check must occur for every archive entry, not just the archive’s name.
Apply Object-Level Authorization
A safe file path does not prove that the user is entitled to access the file.
Before reading, writing, moving, or deleting a resource, verify:
- The user’s identity
- Ownership of the object
- Required role or permission
- Tenant or organization boundary
- Requested operation
- Current object status
Path validation and authorization solve different problems, so both are necessary.
Use Least Privilege
The application process should have access only to the directories and operations it genuinely needs.
A public-facing service should not normally be able to read:
- Operating-system secrets
- Other applications’ configuration
- Deployment credentials
- Private administrator files
- Unrelated customer storage
- Backup repositories
- Cloud identity files
Where possible, provide read-only access to content that does not need modification.
Isolate File-Processing Services
High-risk file operations can run in a restricted environment with:
- A dedicated service account
- A limited filesystem view
- Read-only system directories
- A temporary working directory
- No unnecessary network access
- Resource limits
- Container or sandbox controls
- Minimal credentials
Isolation limits the damage if path validation fails.
Keep Sensitive Files Outside Public Storage
Configuration files, credentials, database exports, source archives, and backups should not be stored inside publicly served directories.
This does not fix path traversal, but it reduces exposure through web-server mistakes and direct URL access.
Use Framework Security Features
Modern frameworks and storage libraries may provide secure resource-serving functions, safe upload handling, or directory-bound file APIs.
Developers should use these established features correctly and keep their dependencies updated.
Custom file-serving implementations require careful review because small differences in normalization and encoding can create serious vulnerabilities.
Why Character Blocklists Are Not Enough
A blocklist attempts to remove or reject a few known path patterns.
This approach is unreliable because paths can be represented through:
- Different separators
- Absolute locations
- Encoded characters
- Repeated decoding
- Unicode variations
- Nested sequences
- Platform-specific prefixes
- Symbolic links
- Parser inconsistencies
The application should define exactly which resources are permitted and confirm the final resolved path remains within the approved boundary.
PortSwigger similarly recommends avoiding direct use of user input in filesystem operations. When this cannot be avoided, the input should be validated and the canonicalized path must remain under the expected base directory. PortSwigger’s path traversal guidance describes this defensive model.
Can a Web Application Firewall Prevent Path Traversal?
A web application firewall, or WAF, may block obvious traversal patterns, encoded separators, and requests for known sensitive files.
However, it cannot reliably understand every application’s path-building logic, decoding order, operating system, storage design, and authorization rules.
A WAF can provide temporary containment or additional detection, but the application must still:
- Avoid user-controlled paths
- Resolve paths safely
- Enforce directory boundaries
- Validate authorization
- Restrict filesystem permissions
How Should Path Traversal Be Tested?
Testing must be performed only with authorization and in a controlled environment.
A security assessment should identify every feature that:
- Reads a file
- Writes a file
- Accepts an upload
- Extracts an archive
- Generates a report
- Loads a template
- Serves an image
- Creates a backup
- Opens a log
- Moves or deletes stored content
- Accepts a filename or path
- Uses stored input in a later filesystem operation
Reviewers should examine:
- Input decoding
- Path normalization
- Absolute-path handling
- Alternative separators
- Symbolic links
- Archive entries
- Authorization checks
- Filesystem permissions
- Background jobs
- Error messages
- Framework configuration
- Differences between operating systems
OWASP’s testing guidance recommends systematically identifying all relevant input vectors and evaluating whether path-manipulation techniques can escape the intended directory. OWASP Web Security Testing Guide provides a structured methodology.
How Can Organizations Detect Path Traversal?
Security teams should monitor both incoming requests and server-side file activity.
Useful data sources include:
- Web server logs
- Application audit logs
- API gateway records
- WAF events
- Endpoint detection
- File-integrity monitoring
- Operating-system audit logs
- Storage access logs
- Container runtime alerts
- Authentication records
- Cloud audit events
High-value alerts may include:
- A public endpoint reading configuration files
- A web process accessing system directories
- Unexpected changes to scripts or templates
- Archive extraction outside a temporary directory
- Sensitive filenames appearing in requests
- Repeated encoded path patterns
- File operations inconsistent with the user’s permissions
Logs should record enough context to support an investigation without unnecessarily storing file contents or secrets.
What Should an Organization Do After Detecting Path Traversal?
Disable or Restrict the Vulnerable Feature
Temporarily disable the affected endpoint or limit it to trusted administrative access.
A reverse-proxy or WAF rule may help block known attack patterns while developers prepare a complete fix.
Preserve Evidence
Collect relevant information before rebuilding or modifying affected systems.
Evidence may include:
- Application requests
- Authentication activity
- File access logs
- Filesystem changes
- WAF and proxy events
- Process execution records
- Cloud audit logs
- Uploaded archives
- Background-job activity
- Database records containing filenames
Follow the organization’s incident-response and legal procedures.
Determine Which Files Were Accessed
Investigators should establish:
- Which paths were requested
- Whether requests succeeded
- What the application account could access
- Whether files were read, created, changed, or deleted
- Whether customer information was exposed
- Whether credentials or keys were accessible
- Whether source code was disclosed
- Whether uploaded content reached an executable location
Do not rely only on the HTTP response. Blind or write-based traversal may cause an effect without returning file content.
Rotate Exposed Credentials
If configuration files, environment data, cloud identity files, or application secrets may have been accessed, rotate the affected credentials.
These may include:
- Database passwords
- API tokens
- Cloud credentials
- Encryption keys
- Signing secrets
- Service-account credentials
- Administrative passwords
- Deployment keys
Review how the old credentials were used before and after the suspected incident.
Restore Modified or Deleted Files
Compare the system with a known-good version.
Restore affected files from trusted backups and verify:
- Application code
- Templates
- Configuration
- Scheduled tasks
- Startup entries
- User-upload directories
- Access permissions
If attackers could overwrite executable or configuration files, rebuilding the affected workload from a trusted image may be safer than repairing individual files.
Correct the Root Cause
Replace client-supplied paths with server-controlled identifiers whenever possible.
Otherwise, implement:
- Safe path-library functions
- Normalization and canonicalization
- Final directory-boundary checks
- Authorization
- Generated filenames
- Secure archive extraction
- Least-privilege filesystem access
- Isolation
Review similar file-handling code across the entire application.
Monitor After Recovery
Continue monitoring for:
- Repeated requests to the vulnerable endpoint
- Use of exposed credentials
- Modified files
- Unexpected process execution
- New accounts or persistence
- Unusual downloads
- Access to related storage
- Attempts against similar endpoints
Can Path Traversal Lead to Remote Code Execution?
Yes, under certain conditions.
A read-only path traversal vulnerability usually exposes files rather than executing code. It may still reveal credentials or source code that helps an attacker compromise another system.
Remote code execution becomes more likely when an attacker can:
- Write into an executable directory
- Replace a script or template
- Modify application configuration
- Plant a file that another service later executes
- Combine traversal with an upload vulnerability
- Access administrative credentials
- Manipulate a scheduled job
The result depends on filesystem permissions and how other application components use the affected files.
Does HTTPS Prevent Path Traversal?
No.
HTTPS encrypts traffic between the user and the server. It does not determine whether the application is authorized to access a particular file.
A directory traversal request can be transmitted through a correctly encrypted HTTPS connection.
Can Path Traversal Affect Cloud Applications?
Yes. Cloud-hosted applications still use local disks, attached volumes, container filesystems, object-storage gateways, and shared file services.
A traversal flaw may expose:
- Workload credentials
- Service configuration
- Mounted secrets
- Deployment files
- Container data
- Shared customer documents
- Cloud-storage access tokens
Cloud applications should use least-privilege identities, isolated storage, secret-management services, and tightly controlled filesystem mounts.
Is Path Traversal Only a Web Vulnerability?
No. Any software that creates filesystem paths from untrusted data may be affected.
Potential targets include:
- Desktop applications
- Mobile backends
- File synchronization software
- Backup utilities
- Archive extractors
- Network services
- Build pipelines
- Developer tools
- Embedded devices
- Administrative scripts
The underlying problem is unsafe path construction, not the presence of a browser.
