A directory traversal attack is a web security exploit where an attacker manipulates file path input to read or write files outside the intended web root, such as configuration files, credentials, or source code. Also known as path traversal, it abuses navigation sequences like ../ (dot-dot-slash) to climb the folder structure and reach data the application never meant to serve. It stays one of the most common and damaging flaws in web applications. This guide breaks down how these attacks work, real examples, the split between relative and absolute path traversal, and the exact defenses that stop them. The tricky part is that one unvalidated parameter can quietly undo an otherwise solid security stack.

Key Takeaways:

  • A directory traversal attack (path traversal) lets attackers reach files outside the web root by tampering with a file path parameter.
  • The core technique is the ../ sequence, often disguised with URL encoding such as %2e%2e%2f or with an absolute path.
  • Frequent targets include /etc/passwd on Linux, .env secrets, web.config, and application source code.
  • Relative path traversal climbs from the current directory, while an absolute path traversal vulnerability supplies a full path to a target file.
  • The root cause is almost always user input passed straight into a filesystem call without validation or canonicalization.
  • Strong defense layers input allowlists, path canonicalization, least-privilege permissions, and a web application firewall.

How Does a Directory Traversal Attack Work?

How Does a Directory Traversal Attack Work

A directory traversal attack works by injecting path navigation characters, mainly ../, into a value the application uses to build a file path, which tricks the server into resolving a location outside the intended directory.

Picture a download feature with a link like /view?file=report.pdf. Behind the scenes the server joins a base folder to that value, for example /var/www/files/ plus report.pdf. If nothing checks the input, an attacker sends ../../../../etc/passwd, the server resolves the combined string, and it hands back the system account file instead of a report.

Think of it like a parking garage elevator that is supposed to reach only guest floors. Because no one restricts the buttons, pressing up enough times still opens onto the vault level. The application belongs to the same family of input handling flaws as an injection attack, where trusted logic acts on untrusted data.

Here is how a typical attack unfolds:

  1. The attacker finds a parameter that names or points to a file (a download, image, template, or language file).
  2. They replace the value with traversal sequences such as ../ repeated several times.
  3. If a filter blocks plain ../, they switch to encoded forms like %2e%2e%2f or double encoding.
  4. The server resolves the path and reads a file outside the web root.
  5. Sensitive contents return in the response, or get written if the endpoint accepts uploads.
Pro Tip
Search your codebase for filesystem calls that receive request data, such as readFile, fopen, include, or File.new. Every one of those lines is a candidate for a file traversal vulnerability and deserves a second look.

You might be thinking modern frameworks already handle this. Yes, but framework defaults protect only the routes you use as intended. The moment a developer builds a custom file endpoint, that safety net disappears, and the parameter is exposed again.

Directory Traversal vs Path Traversal

They are the same attack. Path traversal and directory traversal are interchangeable names for a vulnerability where untrusted input controls a file path, and both point at the same root cause.

Security teams and OWASP tend to say path traversal, while many scanners and reports label the finding directory traversal or web directory traversal. What most people miss is that treating them as two separate bugs wastes time. You are chasing one class of flaw with two labels.

It also helps to separate this from client-side web attacks. Server-side file access is very different from a UI trick such as Clickjacking, which fools a user into clicking a hidden element. Directory traversal targets the server filesystem, so the defenses live in your backend, not the browser.

So once you can spot the pattern, what does a real attack actually look like in the wild?

Directory Traversal Attack Examples You Should Recognize

Directory Traversal Attack Examples

A classic directory traversal attack example is a download endpoint like /download?file=report.pdf that an attacker rewrites to /download?file=../../../../etc/passwd to read the server account list. The same idea targets Windows with paths like ……\Windows\win.ini.

Real incidents show how far this goes. In 2021, CVE-2021-41773 in Apache HTTP Server 2.4.49 let attackers use path traversal to read files outside the document root, and in many setups it escalated to remote code execution. Enterprise products from vendors like Fortinet and GitLab have shipped emergency patches for path traversal flaws since then, several of them scoring above 9.0 on the CVSS scale.

Common targets attackers reach for include:

  • /etc/passwd and /etc/shadow on Linux servers
  • .env files holding API keys and database credentials
  • web.config and appsettings.json on Windows and .NET stacks
  • SSH private keys under a user home directory
  • Application source code that reveals more vulnerabilities

A mid-size retailer we reviewed leaked its full database credentials through an image-resizing endpoint that accepted a path parameter. The endpoint looked harmless, yet a single crafted request returned the .env file. No alarms fired because the request looked like ordinary image traffic.

Numbers like that raise an obvious question: how bad can one of these get?

Relative vs Absolute Path Traversal Vulnerabilities

Relative path traversal uses ../ to move up from the current folder, while an absolute path traversal vulnerability lets an attacker supply a complete path such as /etc/shadow or C:\boot.ini directly, with no climbing required.

The distinction matters because the two need different fixes. Blocking ../ does nothing against an absolute path, and rejecting drive letters does nothing against a relative climb. You need both checks.

Aspect Relative path traversal Absolute path traversal vulnerability
How it moves Climbs up from the current folder using ../ sequences Supplies a full path to the target file from the filesystem root
Typical payload shape file=../../../../etc/passwd file=/etc/passwd or C:\Windows\win.ini
When it works When the app builds a path by joining a base folder with user input When the app uses user input as the whole path with no base folder
Common target Files a few levels above the web root Any file the app process is allowed to read
First-line fix Canonicalize the resolved path and confirm it stays inside the base folder Reject absolute paths and drive letters before any file call
Pro Tip
Canonicalization is your strongest single control. Resolve the final path (for example with realpath) and confirm it still starts with your approved base directory. This one check neutralizes relative climbs, absolute paths, and most encoding tricks at once.

What Can Attackers Actually Access?

A successful path traversal vulnerability can expose credentials, private keys, customer records, and source code, and in the worst cases it escalates to remote code execution and full server takeover.

The damage usually moves through three stages. First an attacker reads files, then finds an endpoint that writes files, then plants a script or poisons a log to gain code execution. What starts as a quiet read of a config file can end as a compromised host.

  • Data exposure that turns into full breaches, which is exactly why teams study how to prevent data breaches as a standing priority
  • Credential theft that hands attackers a path deeper into the network
  • Source code disclosure that reveals other weaknesses to chain
  • Log poisoning and file writes that escalate to remote code execution

You might argue this is just a read bug, so the risk is limited. Yes, but a read that exposes a signing key or a cloud token is often more valuable to an attacker than code execution, because it grants quiet, long-lived access. Keeping hacker-free servers depends on closing these quiet leaks, not only the loud ones.

How to Detect a File Traversal Vulnerability

You detect a file traversal vulnerability by testing every file-handling parameter with traversal sequences and watching logs for ../, encoded dot-dot patterns, and unexpected file access outside the web root.

Detection works best in layers, mixing automated scanning with human review and runtime monitoring:

  1. Run a DAST scanner and a static analysis tool that flags tainted input reaching filesystem calls.
  2. Manually test each file parameter with ../, encoded variants, and absolute paths in a safe environment.
  3. Add a canary file outside the web root and alert if it is ever accessed.
  4. Watch server logs for repeated dot-dot patterns and sudden spikes from a single source.

Automated scanners hammer endpoints with thousands of probes, so a rate-limiter is a practical early-warning signal. When one client sends hundreds of odd path requests per minute, that is rarely a real user. Pairing that with a customized waf rule set lets you flag and block traversal signatures the moment they appear.

Pro Tip
Log the fully resolved path, not just the raw request. A log line showing that /var/www/files/../../../etc/passwd resolved to /etc/passwd is a clear, greppable signal that someone probed you, even when the attempt failed.

Finding the flaw is half the job. Closing it for good is where most teams either win or slip.

Directory Traversal Attack Prevention: Defenses That Work

Directory Traversal Attack Prevention

The most reliable directory traversal attack prevention is to stop passing user input to filesystem APIs, and where you must, validate against an allowlist and canonicalize the resolved path so it always stays inside the intended directory.

Apply these controls in order of impact:

  1. Do not use raw user input in file paths. Map an ID to a filename on the server instead.
  2. Validate input against an allowlist of known-good filenames, not a blocklist of bad ones.
  3. Canonicalize the resolved path and confirm it starts with your approved base directory.
  4. Reject absolute paths, drive letters, and null bytes before any file operation.
  5. Decode input fully first, then validate, so encoded ../ cannot slip past filters.
  6. Run the app with least-privilege permissions so a leak reaches as little as possible.
  7. Disable directory listing and store sensitive files outside the web root entirely.
  8. Add a web application firewall as an outer layer that filters traversal payloads.

Prevention is also about shrinking exposure. Every extra file endpoint is another door, so mitigating attack surface by removing unused download and upload routes cuts risk before you write a single validation check. At the network edge, a hardened firewall solution adds a further barrier between attackers and the file system.

Pro Tip
Prefer library functions built for safe path joining that reject traversal by design over hand-rolled string checks. Custom regex filters miss creative encodings far more often than a well-tested path resolver does.

Secure code is the foundation, yet attackers still probe from the outside every day. That is where an outer defensive layer earns its keep.

Where a WAF, Firewall, and Edge Security Fit In

A web application firewall and edge security add a critical outer layer that filters traversal payloads before they reach your code, though they complement secure coding rather than replace it.

An advanced web application firewall inspects incoming requests and blocks known traversal signatures, encoded dot-dot patterns, and requests aimed at files like /etc/passwd. Because the check happens at the edge, malicious requests never touch your origin server. This is also where the classic waf vs firewall question matters, since a network firewall filters ports and IPs while a WAF understands the actual HTTP payload.

Layering matters. defense-grade edge security combines WAF filtering, DDoS mitigation, and TLS at globally distributed nodes, so traversal probes are absorbed far from your infrastructure. The result is fewer requests reaching code, faster blocking, and clearer signals about who is testing you.

You might expect a WAF to solve the problem outright. Yes, but a WAF tuned too loosely lets creative encodings through, and one tuned too tightly blocks real users. Treat it as a strong outer wall that buys time, while canonicalization and allowlists remain your real lock on the door.

Final Thought on Directory Traversal Attack

Directory traversal keeps working for one reason: applications still trust user input near the filesystem. The single principle that stops it is simple to state and worth repeating. Never let untrusted input decide which file gets opened, and when you must, canonicalize the resolved path and confirm it stays inside a folder you approved.

Treat prevention as layered rather than binary. Combine clean input handling, least-privilege permissions, and a filtering layer at the edge, and you close both the loud attacks and the quiet ones that leak a single dangerous file. Solid engineering and a strong outer wall together are what keep sensitive data where it belongs.

Frequently Asked Questions About Directory Traversal Attack

What is an example of a directory traversal attack?

Changing a download link like /download?file=report.pdf to /download?file=../../../../etc/passwd. If the server builds the path without validation, it returns the system account file instead of the report. CVE-2021-41773 in Apache 2.4.49 is a real-world case.

What may cause a path traversal vulnerability?

Using untrusted input to build a file path without proper validation. It usually comes from passing a request parameter straight into a filesystem call, trusting a blocklist that misses encoded ../ sequences, and never canonicalizing the final path.

What is the recommended solution for path traversal?

Stop passing user input to filesystem APIs. When a user must pick a file, map an ID to a known filename, validate against an allowlist, then canonicalize the resolved path and confirm it stays inside the intended base directory.

How can developers mitigate the risk of path traversal vulnerabilities?

Layer defenses: decode input before validating, reject absolute paths and null bytes, run with least-privilege permissions, keep sensitive files outside the web root, and put a web application firewall in front to filter traversal payloads.

What is the difference between directory traversal and path traversal?

There is no real difference. Directory traversal and path traversal describe the same vulnerability, where untrusted input controls a file path. OWASP and most security tools use the terms interchangeably, though scanners may label the same finding either way.

Is directory traversal the same as local file inclusion?

They are closely related but not identical. Directory traversal reads or writes files outside the intended folder. Local file inclusion (LFI) uses a similar path manipulation but causes the server to include and sometimes execute the file, which can escalate to remote code execution.