Skip to content

Path Traversal: How ../ Reads Files You Never Meant to Share

Path traversal lets an attacker climb out of an intended directory with dot-dot-slash sequences and read arbitrary files on the server. Here is how it works, the encodings that defeat naive filters, and the canonicalization fix that stops it.

SelfSec Team 7 min read

Part 1 of 3From the Path Traversal series

At a glance

CWE-22
Interpreter
Filesystem path resolution
Required condition
Request data becomes part of a filesystem path that is opened without canonicalizing and checking the result.
Potential impact
Disclosure of configuration, secrets and source code, and file overwrite where the sink writes.
Primary defense
Map identifiers to server-owned paths, or canonicalize and verify the path stays under a fixed base directory.

Safe practice: use benign proof only, in a disposable local lab or on a system you are explicitly authorized to test.

Path traversal — also called directory traversal — happens when an application builds a filesystem path out of user input and never checks that the result stays where it is supposed to. By injecting ../ sequences, an attacker walks up and out of the intended folder and reaches files anywhere the application can read: /etc/passwd, configuration secrets, application source, even credentials.

It is one of the oldest bugs on the web and still one of the most common, because the vulnerable pattern looks so reasonable: take a filename, open it, return it. The OWASP Top 10:2025 maps path traversal (CWE-22) to A01 Broken Access Control, because the flaw lets a request reach files the application never meant to grant. This post shows how that single missing check turns into arbitrary file disclosure, and how to close it for good.

The mental model: the filesystem resolves the path, not your string check

The application thinks in strings; the operating system thinks in resolved paths. A string that starts with the right folder name can still resolve somewhere else entirely once the filesystem has processed .. segments, absolute prefixes and decoded separators.

Request value Path the code builds Path the filesystem opens
invoice.pdf /var/www/uploads/invoice.pdf /var/www/uploads/invoice.pdf
../../../etc/passwd /var/www/uploads/../../../etc/passwd /etc/passwd
/etc/passwd /etc/passwd with Python os.path.join or .NET Path.Combine /etc/passwd
..%2f..%2f..%2fetc/passwd Decoded to ../../../etc/passwd by a later layer /etc/passwd

The third row surprises many developers: several path-joining APIs discard the base directory when the second argument is absolute. The only check that holds is one made against the final, resolved path.

How it happens

The root cause is concatenating user input straight into a path. A download endpoint that serves files from a fixed folder is the classic example:

$file = $_GET['file'];
$path = "/var/www/uploads/" . $file;

readfile($path);

For a normal request like ?file=invoice.pdf, the path resolves to /var/www/uploads/invoice.pdf and everything works. The developer assumes file is just a name. But it is data the attacker controls, and / and . are perfectly valid characters in it — so the input can describe a journey out of the uploads directory.

A concrete attack

Instead of a filename, the attacker sends a chain of parent-directory hops:

GET /download?file=../../../etc/passwd HTTP/1.1
Host: app.example

The path the application opens becomes:

/var/www/uploads/../../../etc/passwd  ->  /etc/passwd

Each ../ cancels one directory level. Three of them climb from uploads past www and var to the filesystem root, and the server happily returns the contents of /etc/passwd. Extra ../ segments are harmless to the attacker, because the root directory is its own parent, so a payload with eight hops reaches the root from any base folder up to eight levels deep. On Windows the same idea uses backslashes, as in ..\..\..\windows\win.ini, or an absolute drive path such as C:\Windows\win.ini.

When a filter naively strips the literal string ../, attackers reach for encoded and malformed variants that decode back to the same sequence later in the pipeline:

..%2f..%2f..%2fetc/passwd        # URL-encoded slash
..%252f..%252f..%252fetc/passwd  # double-encoded
....//....//....//etc/passwd     # survives a single "../" -> "" strip
..%c0%af..%c0%afetc/passwd       # overlong UTF-8 slash
..%00/etc/passwd                 # null-byte truncation of an appended suffix

The encoding bypass post walks through why each of these slips past a blocklist.

The application thought it was choosing the file. The attacker only had to phrase the filename as directions, and the filesystem followed them right out of the sandbox.

What an attacker gains

Arbitrary read access to the server's filesystem is a deep foothold:

  • Credential and config theft — .env files, database passwords, API keys and private keys.
  • Source code disclosure — reading the application's own code to find more vulnerabilities.
  • System reconnaissance — /etc/passwd, /proc/self/environ and process data that map out the host.
  • Escalation to code execution — when the same flaw allows writing files, an attacker can drop a web shell or poison a config. When the path reaches an include rather than a read, traversal becomes local or remote file inclusion.

Where path traversal appears

Download and preview endpoints are the textbook case, but any value that names a file can carry the same flaw: language or theme selectors such as ?lang=en, template names, report exporters, image resizers, log viewers and REST routes that map a path segment straight onto a folder. Upload handlers that keep the client's filename, and archive extraction that writes each entry's stored path, turn the read primitive into a write primitive.

The review question is the same everywhere: after every decoding and join, can the final path point outside the folder this feature is allowed to touch?

The fix: canonicalize, then verify the path stays inside

The dependable fix is not to filter bad strings — it is to resolve the final path and confirm it still lives under your base directory. Canonicalize first (so every ../, symlink and encoding is collapsed to one real path), then compare:

$base = realpath("/var/www/uploads");
$requested = realpath($base . "/" . $_GET['file']);

if ($requested === false || !str_starts_with($requested, $base . DIRECTORY_SEPARATOR)) {
    http_response_code(404);
    exit;
}

readfile($requested);

realpath() resolves the path to its true location on disk; the str_starts_with check rejects anything that escaped the base folder. The trailing DIRECTORY_SEPARATOR matters: without it, a sibling folder such as /var/www/uploads-old would pass a bare prefix check.

The same pattern in C# uses Path.GetFullPath to normalize .. segments. Path.Combine returns an absolute second argument unchanged, so a request for /etc/passwd resolves outside the base and also fails the prefix check:

static readonly string Root = Path.GetFullPath("/var/app/files") + Path.DirectorySeparatorChar;

static string? ResolveInside(string name)
{
    if (name.Contains('\0'))
    {
        return null;
    }

    var fullPath = Path.GetFullPath(Path.Combine(Root, name));
    return fullPath.StartsWith(Root, StringComparison.Ordinal) ? fullPath : null;
}

Unlike realpath(), Path.GetFullPath does not follow symbolic links, so keep links out of the served directory or resolve them before comparing. In Python, pathlib resolves links and offers a containment test directly:

from pathlib import Path

BASE = Path("/var/app/files").resolve()

def resolve_inside(name: str) -> Path | None:
    if "\x00" in name:
        return None
    candidate = (BASE / name).resolve()
    return candidate if candidate.is_relative_to(BASE) else None

Both helpers return nothing for a path that escapes the base, and the caller answers with a 404. Flask's send_from_directory applies the same kind of safe join for you, so prefer it over building paths for send_file.

Layer extra defenses on top: where you can, avoid user-controlled paths entirely and map an opaque ID to a known filename in a lookup table; validate filenames against a strict allowlist (^[a-zA-Z0-9._-]+$, no slashes); and run the service with least privilege so even a successful traversal reads as little as possible.

Fixes that do not hold

  • Stripping ../ once: ....// collapses into ../ after the strip, and backslashes or encoded separators never match the pattern at all.
  • Filtering before decoding: a later URL decode, framework rewrite or second decoding layer reintroduces the separators the filter never saw.
  • Checking the prefix of the raw string: /var/www/uploads/../../etc/passwd starts with the base directory and still escapes it.
  • Prefix checks without a trailing separator: /var/www/uploads is a string prefix of /var/www/uploads-backup.
  • Appending a fixed extension: legacy runtimes truncate at a null byte, and the attacker may simply target a sensitive file that already has that extension.
  • Relying on a WAF: it recognizes common traversal strings but cannot know which resolved paths the application is allowed to serve.

A developer review checklist

  1. Find every file API that receives request-influenced data: reads, writes, includes, file responses, archive extraction and upload storage.
  2. Replace user-supplied paths with identifiers mapped to server-owned filenames wherever possible.
  3. Join, canonicalize, then verify containment against the base directory plus a trailing separator.
  4. Reject absolute paths, drive letters, null bytes and separators where a bare filename is expected.
  5. Treat archive entry names and uploaded filenames as untrusted paths.
  6. Run the service under an account that can read only the directories it serves, and mount them read-only where possible.

References

Module: Path Traversal. How it probes: Unix and Windows traversal sequences at depths one to eight, absolute paths, null-byte suffix truncation and URL-encoded, double-encoded, overlong UTF-8 and doubled-separator forms in query, form, JSON, path-segment and WebSocket values. How it confirms: A passwd or win.ini signature has to be absent from the baseline and survive a benign control, then reappear on a fresh request while a control that sends the signature text itself does not, which rules out simple reflection. A finding moves from Possible to Confirmed only after this check. Reported as CWE-22 · ATT&CK T1190, T1083 · SARIF 2.1.0.
How SelfSec proves this one
Module
Path Traversal
How it probes
Unix and Windows traversal sequences at depths one to eight, absolute paths, null-byte suffix truncation and URL-encoded, double-encoded, overlong UTF-8 and doubled-separator forms in query, form, JSON, path-segment and WebSocket values.
How it confirms
A passwd or win.ini signature has to be absent from the baseline and survive a benign control, then reappear on a fresh request while a control that sends the signature text itself does not, which rules out simple reflection.
Reported as CWE-22 · ATT&CK T1190, T1083 · SARIF 2.1.0

A reflected response alone is not enough to promote a Path Traversal finding. The classical engine has to confirm the behavior before it reaches the report. See the detection engine

SelfSec scanner

Find Path Traversal in your own app

Reading about the class is one thing. SelfSec tests for it against an application you are authorized to assess, and only calls it real when independent evidence agrees.

Join the launch list