Path Traversal in APIs: Detection and Prevention

|
6 min
|
Path Traversal in APIs: Detection and Prevention

What happens when an attacker sends ../../etc/passwd inside a JSON request body to your file download API? Without proper input validation, the server happily returns its own password file.

A path traversal vulnerability, also called a directory traversal attack, lets attackers manipulate file path parameters to access files outside the intended scope. APIs introduce unique attack surfaces that most security guides overlook.

The Salt Labs State of API Security Report, 2024, found that 95% of organizations experienced security problems in production APIs. Path traversal falls under API8:2023 (Security Misconfiguration) in the Open Web Application Security Project (OWASP) API Security Top 10.

For a breakdown of all ten categories, see our guide to the OWASP API Top 10.

What Is a Path Traversal Attack?

A path traversal attack exploits insufficient input validation in file-handling endpoints. Attackers inject sequences like ../ (dot-dot-slash) into parameters that reference files, navigating outside the application's root directory.

Here is a directory traversal example targeting a Node.js API that serves user-uploaded documents:

app.get('/api/documents/:filename', (req, res) => {

  const filePath = path.join('/var/data/uploads/', req.params.filename);

  res.sendFile(filePath); // No validation

});

An attacker sends this request:

GET /api/documents/../../../../etc/passwd

The server resolves the path to /etc/passwd and returns the system's user file. The root cause is a missing check between the supplied filename and the base directory.

Why APIs Are Prime Targets for Directory Traversal

Web applications typically serve files through rendered HTML pages with limited user control over paths. APIs work differently, and several characteristics make directory traversal far more likely:

  • Direct file parameters in requests. RESTful APIs accept filenames or paths as URL parameters, query strings, or JSON body fields, giving attackers multiple injection points.
  • File export and download endpoints. APIs that generate reports or data exports frequently construct file paths from user input without sanitization.
  • Microservices with shared storage. Multiple services accessing a common file system expand the blast radius of a single traversal flaw.
  • Inconsistent validation across services. An API gateway may sanitize URL paths, but JSON body parameters containing file references often bypass those checks entirely.

Pairing file-handling security with REST API security best practices strengthens your foundation against traversal attacks.

Common Path Traversal Payloads in API Contexts

Attackers use a range of path traversal payloads to bypass input filters. Security teams should test file-handling endpoints against these patterns:

  • Basic traversal: ../../../etc/passwd or ..\..\..\windows\win.ini
  • URL-encoded: %2e%2e%2f decodes to ../, often bypassing basic string filters
  • Double URL-encoded: %252e%252e%252f bypasses servers that decode input once before validation
  • Null byte injection: ../../../etc/passwd%00.png terminates the string before an appended file extension
  • Nested sequences: ....//....// reverts to ../../ after a single-pass strip of ../
  • Mixed encoding: ..%c0%af or ..%ef%bc%8f exploits non-standard Unicode normalization

API endpoints are especially vulnerable to payloads in JSON body fields, multipart form data, and custom headers, since many WAFs only inspect URL paths.

Real-World Path Traversal Vulnerabilities

Path traversal is not theoretical. High-profile vulnerabilities in widely deployed software have exposed millions of systems to file disclosure and remote code execution through simple dot-dot-slash payloads.

  • CVE-2021-41773 (Apache HTTP Server). A flawed path normalization change in Apache 2.4.49 allowed URL-encoded traversal sequences to access files outside the document root. Combined with enabled CGI modules, the flaw escalated to remote code execution. Apache confirmed active exploitation in the wild.
  • CVE-2018-13379 (Fortinet FortiOS). A directory traversal flaw in the FortiGate SSL VPN allowed unauthenticated attackers to download system files, including session tokens. The Cybersecurity and Infrastructure Security Agency (CISA) listed the flaw among the top routinely exploited vulnerabilities years after disclosure.

Both vulnerabilities affected systems serving API traffic, confirming that path traversal remains a critical, actively exploited vector.

How to Detect Path Traversal in APIs

Standard Dynamic Application Security Testing (DAST) scans often miss traversal flaws in JSON payloads. Most scanners focus on URL path parameters and query strings, leaving JSON body fields, multipart form data, and custom headers completely untested.

Our API security checklist covers the full workflow, but here are key detection methods:

  • Fuzz testing with traversal payloads. 

Send encoded and nested payloads across all file-handling parameters, including URL paths, query strings, JSON fields, and headers. Start with basic ../ sequences, then escalate to URL-encoded (%2e%2e%2f), double-encoded (%252e%252e%252f), and null byte (%00) variants. Monitor responses for unexpected file contents, stack traces, or error messages that reveal internal directory structures. API fuzzing automates payload generation at scale, cycling through hundreds of encoding combinations per endpoint without manual scripting.

  • Code review for unsafe path construction. 

Flag any endpoint that concatenates user input with a base directory without canonicalization. Common culprits include document download routes, report export functions, avatar upload handlers, and log retrieval endpoints. Search the codebase for file system functions like fs.readFile(), open(), fopen(), and sendFile() that accept variables derived from request parameters. Any instance where user-controlled data flows into these functions without a resolved path check against the base directory signals a potential traversal flaw.

  • Automated API security testing. 

Purpose-built API security testing platforms simulate traversal attacks across every endpoint, testing payloads that WAFs and generic scanners miss. Automated platforms parse API specifications to identify file-handling parameters, then generate targeted attack sequences for each one. Results include proof-of-exploitation details showing exactly which parameter accepted the traversal payload and what file contents were returned, giving developers the context needed for immediate remediation.

5 Strategies for Path Traversal Attack Prevention

Use our vulnerability scanning guide alongside these five strategies to harden your APIs:

1. Never pass raw user input to file system APIs. 

Replace direct filename parameters with indirect references like database IDs or hash-based lookups. When a user requests a file, the API resolves the actual path server-side without exposing the directory structure to the client:

javascript

// Instead of: /api/files?name=report.pdf

// Use: /api/files?id=a1b2c3d4

const filePath = db.getFilePath(req.query.id);

Even if an attacker guesses or enumerates IDs, no traversal payload can reach the file system because the filename never comes from user input. Store the mapping between IDs and file paths in a database table, and return a 404 for any ID that does not exist.

2. Canonicalize and validate resolved paths. 

Resolve the full path before granting access, then verify the result stays within the allowed directory. Canonicalization strips ../ sequences, symbolic links, and encoded characters so the final resolved path reflects the true location on disk:

java

File file = new File(BASE_DIRECTORY, userInput);

String canonicalPath = file.getCanonicalPath();

if (!canonicalPath.startsWith(BASE_DIRECTORY)) {

    throw new SecurityException("Path traversal blocked");

}

In Python, the equivalent uses os.path.realpath() to resolve the absolute path, followed by a prefix check against the base directory. Always perform validation after decoding, not before, since attackers layer multiple encoding rounds to bypass pre-decode filters.

3. Enforce a strict allowlist. 

Restrict accepted filenames to a predefined set of values. Reject any input that does not match rather than attempting to filter dangerous characters. Blocklists fail because attackers constantly find new encoding tricks, Unicode variations, and null byte injections to evade pattern matching. An allowlist flips the model so that only known-safe values pass through. For APIs with dynamic file uploads, store uploaded filenames in a database and assign a sanitized, server-generated name to the actual file on disk. The original filename becomes metadata, never a path component.

4. Sandbox file access with containers. 

Running API services in isolated Docker containers limits the files an attacker can reach. Restrict container mounts to only the directories the service requires, and set the file system to read-only where possible:

yaml

# docker-compose.yml

volumes:

  - ./uploads:/app/uploads:ro

read_only: true

Even if a traversal flaw exists, the attacker cannot escape the container's restricted view of the host file system. Pair containerization with the principle of least privilege by running the API process as a non-root user inside the container, further limiting access to sensitive system files.

5. Integrate continuous API security testing. 

Path traversal flaws often appear when new file-handling endpoints are added. A single overlooked download route or export function can reintroduce the vulnerability after months of clean scans. Running automated API security testing within a Continuous Integration/Continuous Deployment (CI/CD) pipeline catches vulnerabilities before code reaches production. Automated platforms send traversal payloads, including encoded and nested variants, across every parameter type on every endpoint with each build, ensuring that no file-handling logic ships without validation.

Secure Your APIs Before Attackers Walk Through the Gaps

Path traversal vulnerabilities persist because developers trust user-supplied file paths without validation. Indirect references, path canonicalization, allowlists, and continuous testing close those gaps.

APIsec tests every endpoint for OWASP API Top 10 vulnerabilities, including security misconfigurations like directory traversal.

Start a free scan and uncover what your current tools miss.

FAQs

What is the difference between path traversal and local file inclusion?

Path traversal accesses files outside the intended directory using dot-dot-slash sequences, while local file inclusion (LFI) reads or executes files within the web root. Both exploit poor input validation but differ in scope.

Can a WAF prevent all directory traversal attacks?

WAFs catch many common path traversal payloads in URL paths, but attackers bypass them using double encoding, Unicode tricks, or payloads embedded in JSON body parameters that WAFs do not inspect.

What is the most common path traversal attack example in APIs?

File download endpoints accepting filenames as URL or query parameters are the most frequent target, where attackers inject encoded traversal sequences to read configuration files or credentials.

How does path traversal relate to the OWASP API Security Top 10?

Path traversal falls under API8:2023 (Security Misconfiguration) because misconfigured file-handling endpoints and missing input validation allow attackers to navigate outside intended directories.

What are the most effective path traversal payloads to test against?

Start with basic ../ sequences, then test URL-encoded (%2e%2e%2f), double-encoded (%252e%252e%252f), null byte (%00), and nested (....//) variants across URL paths, JSON body fields, and multipart parameters.


Start Protecting Your APIs Today

Partner with a team that does more than scan — experience real, continuous protection with APIsec.

Get started for FREE

You Might Also Like