What Is a Path Traversal Attack?
Path traversal—also called directory traversal—occurs when user-controlled path input lets an application access files outside the intended directory. OWASP’s Web Security Testing Guide describes the risk in applications that use insufficient input validation around file operations, potentially enabling unintended read, write or include behavior.
The vulnerability usually comes from concatenating a trusted base directory with an untrusted filename or path and then assuming the resulting string remains inside the intended root. Encoding, platform path separators, symbolic links and archive extraction can make naive filtering unreliable.
Path Traversal Attack Example: Unsafe Filename-to-Path Mapping
A vulnerable download endpoint might conceptually construct a local path from a user-supplied filename:
// Risky design: user input becomes a path
String requested = request.getParameter("file");
Path p = Paths.get("/srv/reports/" + requested);
return readFile(p);A safer design accepts an opaque report ID, looks up the authorized storage object server-side, resolves the path to a canonical location, verifies it remains under the approved root, and then opens it with least-privileged filesystem permissions.
// Safer design concept
Report r = repository.findAuthorized(reportId, currentUser);
Path root = Paths.get("/srv/reports").toRealPath();
Path file = root.resolve(r.serverControlledName()).normalize();
if (!file.startsWith(root)) reject();
return readFile(file);Common Path Traversal Variants
| Variant | Risk |
|---|---|
| Relative traversal segments | Attempts to move to parent directories |
| Encoded traversal | Alternative encodings can bypass string filters |
| Absolute path injection | Input selects a path outside the application root directly |
| Symlink/junction escape | A seemingly safe child path resolves elsewhere |
| Archive traversal / ZIP Slip | Archive entry names escape the extraction directory |
| File include traversal | Traversal reaches templates, source or executable content |
Do not build a blacklist around a handful of traversal strings. Normalize and constrain the actual resolved path, and preferably remove user-controlled paths from the interface entirely.
How to Prevent Path Traversal
- Prefer opaque IDs over paths. Map a report/document ID to a server-controlled storage object after authorization.
- Allowlist expected resources. If the set of files is finite, select from known server-side names instead of accepting arbitrary filenames.
- Canonicalize before enforcing containment. Resolve the final candidate path and verify it remains under the intended root using platform-aware path APIs.
- Do not “sanitize” by deleting
../. Encodings, alternate separators and repeated normalization can bypass blacklist replacements. - Separate authorization from path validation. A syntactically safe path may still point to an object the caller is not permitted to access.
- Run with least filesystem privilege. The application account should not be able to read secrets or write executable/configuration locations it never needs.
Where possible, use storage APIs that operate on object IDs or handles rather than constructing operating-system paths from request parameters. This removes the traversal grammar from the public API entirely.
Uploads, Archive Extraction and Path Traversal
File upload and archive workflows add another traversal surface. Never trust an uploaded filename as a storage path. Generate server-side object names and store the original filename only as metadata if the product needs it.
Before extracting an archive, validate every entry path against the extraction root and enforce archive size/count/decompression limits. A malicious archive can contain nested entry names intended to write outside the chosen directory. Related reading: API security testing vs runtime monitoring.
Secure File Download APIs
A robust download API generally exposes a stable resource identifier rather than a filesystem path:
GET /v1/reports/rpt_8F4J2/content
Authorization: Bearer <token>- Authorize the caller against
rpt_8F4J2before resolving storage. - Fetch the server-controlled storage key from a database or object store.
- Do not allow the client to replace the storage key with an arbitrary path.
- Apply appropriate response headers and authorization again for every download.
Path Traversal Detection and Testing
- Alert on repeated file requests containing unexpected path separators, encoded dot segments or platform-specific path syntax.
- Test download, import, export, template, log-viewer and archive endpoints—not only obvious “file” routes.
- Review application code for string concatenation used to build file paths from request input.
- Log the logical resource ID and decision outcome rather than raw sensitive filesystem paths where possible.
- Use SAST and DAST to complement manual tests around normalization and symlink behavior.
Related Ammune reading: API security testing vs runtime monitoring and API security in CI/CD pipelines.
Common Path Traversal Prevention Mistakes
- Blocking only the literal sequence
../. - Checking the path before URL decoding or framework normalization.
- Using
startsWithon raw strings instead of resolved path objects. - Trusting an uploaded filename.
- Assuming object storage keys cannot have traversal-like semantics in downstream processing.
- Running the web process with broad filesystem access.
Canonicalization, Decoding and Symlink Edge Cases
Path validation is frequently defeated by checking the wrong representation. Frameworks, proxies and operating systems may decode or normalize input at different stages. A filter that examines the raw URL before percent-decoding may see a different string than the filesystem API eventually receives. The application should define one normalization sequence and make the security decision on the final resolved path object.
Symbolic links and junctions deserve separate attention. A path can lexically begin under an approved directory yet resolve to a target elsewhere. Sensitive applications should use filesystem APIs that can constrain traversal, avoid following links where possible and consider race conditions between validation and file open operations.
- Decode once using the framework’s documented behavior; reject malformed or double-encoded input.
- Normalize separators and dot segments with platform path APIs.
- Resolve against a trusted root and verify the final path remains inside it.
- Control or reject symlinks in directories that hold user-controlled content.
Why URL Encoding and String Replacement Do Not Fix Path Traversal
Blocking the literal sequence ../ is fragile because the application stack may decode, normalize or reinterpret input at different stages. Alternate separators, repeated encoding, Unicode handling, archive entry names, symlinks and framework normalization can all make string-based filters disagree with the filesystem’s final interpretation.
A stronger design validates the resource at the semantic boundary: accept an opaque identifier, map it to a server-controlled object, authorize that object, resolve the resulting path with platform-aware APIs and verify containment under the intended root. For upload or extraction workflows, validate every generated destination after normalization rather than trusting the archive-provided name.
Runtime Visibility Around File-Oriented API Abuse
Path traversal is prevented by safe resource mapping, canonical containment checks and authorization—not by runtime monitoring alone. Ammune can complement those controls by identifying repeated suspicious file-oriented API requests and correlating them with the affected endpoints and services.
Path Traversal Security Checklist
- Do not expose raw server paths in APIs.
- Use server-side ID-to-object mapping.
- Normalize and verify resolved paths remain under an approved root.
- Authorize the logical object before file access.
- Generate upload/storage names server-side.
- Validate archive entry paths before extraction.
- Run services with minimal filesystem permissions.
- Test encoded, platform-specific and symlink edge cases.
Frequently Asked Questions
What is path traversal?
Path traversal is a vulnerability where user-controlled input influences a file path and reaches files outside the directory the application intended to expose.
Is directory traversal the same as path traversal?
The terms are commonly used interchangeably in web application security.
Is blocking ../ enough?
No. Encoding, alternate separators, absolute paths, symlinks and normalization differences make simple string blacklists unreliable.
What is the safest API design for file downloads?
Expose an opaque resource ID, authorize that object, and map it to a server-controlled storage location rather than accepting filesystem paths from the client.
Can ZIP files cause path traversal?
Yes. Archive entry names can escape the extraction directory if every resolved entry path is not validated before extraction.
Primary References
Identify Repeated Attacks on File-Oriented APIs
Prevent traversal through secure path design and least privilege. Ammune can add runtime visibility into suspicious requests reaching download, upload and file-processing endpoints.
