Path Traversal: Directory Escape Mechanics, Symlink Bypasses, and Safe Canonicalization
Learn how path traversal turns relative segments, encodings, and symlinks into arbitrary file access, and why realpath plus openat stops directory escapes.

A customer clicks a button to download their monthly invoice PDF from an export service. Under the hood, the web handler takes a query parameter like report=march-2026.pdf, glues it onto an internal folder string such as /srv/app/exports/, and hands the combined string to the operating system's file-reading API. Everything works cleanly until someone replaces march-2026.pdf with ../../config.ini, and the server cheerfully streams back database credentials instead of a PDF.
Imagine handing a warehouse clerk a note that says, "Go to Aisle 4, then walk out the back door, go up two flights of stairs, and grab the binder on the manager's desk." If the clerk follows walking directions literally without checking whether the final destination is still inside Aisle 4, your warehouse security boundary evaporates. Operating system file APIs behave just like that literal-minded clerk: when an application passes a string containing relative navigation tokens like .., the filesystem resolves those steps from the starting folder and returns whatever file sits at the end of the walk.
Path traversal (also known as directory traversal or directory escape) happens whenever untrusted input influences a filesystem path without canonical verification after resolution. Although the bug looks deceptively simple in introductory examples, production vulnerabilities survive because of parser disagreements between proxies and application runtimes, sibling-prefix bugs in naive boundary checks, symlink escapes, archive extraction flaws, and race conditions between validation and file opening.
How Does Path Resolution Turn Relative Segments Into Arbitrary File Access?
Operating system path APIs treat / (and \ on Windows) as hierarchy separators and treat . and .. as navigation operators meaning "current directory" and "parent directory." Unless a program explicitly enforces a jail or verifies the resolved destination, the kernel evaluates every component from left to right and opens whatever inode sits at the final location.
In a typical web stack, a path string does not travel straight from the browser to the disk. It passes through multiple parsing layers, each applying its own decoding and normalization rules before the kernel ever inspects an inode.
mermaid\nflowchart LR\n A[\"HTTP Client (Query or Path Param)\"] --> B[\"Reverse Proxy or WAF (URL Decode and Clean)\"]\n B --> C[\"App Runtime (Concatenation or Lexical Resolve)\"]\n C --> D[\"OS Kernel VFS (Parent Links and Symlinks)\"]\n D --> E[\"Backing Storage (/srv/app/config.ini)\"]\n
The core danger sits at the handoff between lexical path arithmetic and virtual filesystem (VFS) lookup. When a Node.js, Python, or Go handler concatenates /srv/app/exports/ with ../../config.ini, the resulting string /srv/app/exports/../../config.ini looks like it starts inside the exports folder if you only inspect its prefix. When the kernel walks that path component by component, however, the first .. climbs from /srv/app/exports to /srv/app, the second .. climbs to /srv, and config.ini resolves to /srv/config.ini (or /srv/app/config.ini depending on depth).
Absolute path injection works even faster when string-combining helpers ignore the base directory. In Python, for example, combining a base folder with a leading slash argument discards the base folder completely and jumps straight to the supplied root path. Even when a developer expects a relative filename, passing /var/app/tenant-secrets.json bypasses .. filters altogether because no parent traversal tokens appear in the payload.
Why Do Naive Filters and String Normalization Fail Against Real Payloads?
Once engineers discover a traversal bug, the first instinct is almost always to sanitize the input string by stripping ../ or checking startsWith. Both approaches fail in production because lexical string inspection operates on an uncanonicalized representation that attackers and intermediate parsers can reshape.
Consider a vulnerable handler running on app.example that naively concatenates a query parameter:
javascript\nconst fs = require('fs');\nconst express = require('express');\nconst app = express();\n\napp.get('/api/v1/exports', (req, res) => {\n const filename = String(req.query.file || '');\n const target = '/srv/app/exports/' + filename;\n\n fs.readFile(target, (err, data) => {\n if (err) return res.status(404).send('Not found');\n res.send(data);\n });\n});\n
Suppose a well-meaning patch adds filename.replaceAll('../', '') before concatenation, or a WAF blocks literal ../ sequences. Attackers bypass those defenses using several recurring classes of parser differentials.
http\nGET /api/v1/exports?file=....//....//config.ini HTTP/1.1\nHost: app.example\n\nGET /api/v1/exports?file=%252e%252e%252f%252e%252e%252fconfig.ini HTTP/1.1\nHost: app.example\n
In the first request, a single-pass non-recursive sanitizer strips the inner ../ from ....//, collapsing the outer characters into a fresh ../ sequence that reaches the filesystem intact. In the second request, the reverse proxy or WAF URL-decodes once (seeing the harmless literal %2e%2e%2f), passes the request through, and a framework controller URL-decodes a second time before opening the file.
Three additional bypass mechanics catch teams off guard across heterogeneous environments:
- Backslash normalization mismatch: Linux treats
\as a valid filename character, whereas Windows APIs and some cross-platform web servers treat\as a directory separator. A Linux-based WAF checking only for../will wave through..\..\tenant-secrets.jsonaimed at a Windows backend, and certain HTTP servers normalize\to/after routing checks. - Partial prefix confusion: Checking
resolvedPath.startsWith('/srv/app/exports')without a trailing directory separator lets/srv/app/exports-private/keys.jsonpass the check because its string prefix matches character for character. - Overlong UTF-8 and Unicode normalization: Legacy decoders or NFKC normalization layers can fold fullwidth dots (
\uFF0E) or fullwidth slashes (\uFF0F) into ASCII.and/after validation has already executed.
How Canonicalization Works and Where Purely Lexical Checks Still Break
Canonicalization resolves every relative segment, redundant separator, encoding, and filesystem link into one unique, unambiguous absolute path before comparing it against a trusted root directory. Crucially, there are two completely different levels of canonicalization, and confusing them leaves a gaping hole in multi-tenant and upload-enabled applications.
Lexical normalization functions (such as path.resolve in Node.js or os.path.normpath in Python) operate purely on strings in memory without touching the disk. They collapse a/b/../c into a/c, which stops pure .. arithmetic escapes. However, lexical functions know nothing about symbolic links or mount points on the actual filesystem.
If an extraction job, a user tarball, or a neighboring service creates a symbolic link inside /srv/app/exports/latest pointing to /var/app/tenant-secrets.json, a lexical check sees /srv/app/exports/latest and declares it safely inside /srv/app/exports. The moment the application opens that path, the kernel follows the symlink out of the sandbox and reads the secret file.
Real filesystem canonicalization (fs.realpathSync in Node.js, os.path.realpath in Python, filepath.EvalSymlinks in Go) walks every component on disk, resolves every symlink, and returns the true physical location. Pairing real canonicalization with a trailing-separator boundary check stops both .. escapes and symlink escapes on existing files.
javascript\nconst fs = require('fs');\nconst path = require('path');\n\nconst EXPORT_ROOT = fs.realpathSync('/srv/app/exports');\nconst EXPORT_PREFIX = EXPORT_ROOT.endsWith(path.sep)\n ? EXPORT_ROOT\n : EXPORT_ROOT + path.sep;\n\nfunction resolveSafeExport(userInput) {\n if (typeof userInput !== 'string' || userInput.length === 0 || userInput.includes('\\0')) {\n throw new Error('Invalid filename');\n }\n\n // Reject absolute paths or alternate separators early before resolution\n if (path.isAbsolute(userInput) || userInput.includes('\\\\')) {\n throw new Error('Relative path required');\n }\n\n const lexicalCandidate = path.resolve(EXPORT_ROOT, userInput);\n const canonicalTarget = fs.realpathSync(lexicalCandidate);\n\n if (!canonicalTarget.startsWith(EXPORT_PREFIX)) {\n throw new Error('Path traversal detected');\n }\n\n return canonicalTarget;\n}\n
Notice three subtle invariants in that snippet. First, EXPORT_ROOT itself is passed through fs.realpathSync at startup; on systems where /srv or /var/tmp is itself a symlink, comparing a canonicalized target against an uncanonicalized base path causes false rejections on every valid request. Second, EXPORT_PREFIX guarantees a trailing separator, preventing /srv/app/exports-private from matching /srv/app/exports and also preventing a request for the root directory itself from passing as a file. Third, null bytes are explicitly rejected because older C-backed libraries truncate paths at \0, reading a different filename than the extension validator inspected.
There is one major operational caveat with realpath: it requires the target path to exist on disk. When validating a path for a new file write or upload where the file does not exist yet, calling realpathSync on the full target throws ENOENT. In that scenario, you must canonicalize the deepest existing ancestor directory with realpath, verify that ancestor sits inside EXPORT_PREFIX, and ensure the remaining new path components contain no .., ., or symlink-creating operations.
Why Archive Extraction and File Uploads Trigger Hidden Traversal (Zip Slip)
Path traversal does not only enter through HTTP query parameters; it routinely arrives inside .zip, .tar, or .docx archives and multipart file upload headers. Whenever a service unpacks user-supplied archives or honors a client-provided filename inside Content-Disposition, each archive entry name acts as a separate path input.
In the classic Zip Slip pattern, an attacker crafts an archive whose entry header literally names a file ../../../../srv/app/config.ini or embeds a symlink entry pointing outside the extraction directory followed by a regular file written through that symlink. Extraction loops that blindly prepend the output directory to entry.filename overwrite application binaries, configuration files, or cron jobs on disk.
Python's os.path.commonpath provides a cleaner boundary check than raw string prefix matching because it compares parsed path components rather than characters and raises ValueError if paths sit on different Windows drives.
python\nimport os\nimport zipfile\n\ndef safe_extract_zip(archive_path: str, dest_dir: str) -> list[str]:\n real_dest = os.path.realpath(dest_dir)\n extracted = []\n\n with zipfile.ZipFile(archive_path, \"r\") as zf:\n for info in zf.infolist():\n # Skip directory entries and reject Unix symlinks encoded in external_attr\n if info.is_dir():\n continue\n mode = (info.external_attr >> 16) & 0o170000\n if mode == 0o120000:\n raise ValueError(f\"Symlink entry blocked: {info.filename}\")\n\n norm_member = os.path.normpath(info.filename.replace(\"\\\\\", \"/\"))\n if os.path.isabs(norm_member) or norm_member.startswith(\"..\"):\n raise ValueError(f\"Unsafe archive member: {info.filename}\")\n\n candidate = os.path.realpath(os.path.abspath(f\"{real_dest}/{norm_member}\"))\n if os.path.commonpath([real_dest, candidate]) != real_dest or candidate == real_dest:\n raise ValueError(f\"Archive escape detected: {info.filename}\")\n\n os.makedirs(os.path.dirname(candidate), exist_ok=True)\n with zf.open(info, \"r\") as src, open(candidate, \"wb\") as dst:\n dst.write(src.read())\n extracted.append(candidate)\n\n return extracted\n
Checking external_attr for 0o120000 (S_IFLNK) closes a subtle two-step attack in archives. Without that check, entry one could extract a harmless-looking symlink inside dest_dir pointing to /var/app, and entry two could write symlink/tenant-secrets.json, bypassing purely lexical member-name checks.
For general HTTP file uploads, relying on client-supplied filenames at all is fragile defense. Beyond traversal sequences, user filenames carry double extensions (.jpg.php), NTFS Alternate Data Streams (report.pdf::$DATA), or active HTML/SVG payloads if served inline. The durable architectural fix is to store uploaded blobs outside the webroot under a server-generated UUID, record the original display name strictly as database metadata, and serve downloads with Content-Disposition: attachment and X-Content-Type-Options: nosniff.
The Subtle Trap: TOCTOU Races and Kernel-Enforced Directory Sandboxes
Even when an application runs realpath and verifies the boundary check properly, a gap in time exists between checking the path string and actually opening the file. Security engineers call this a Time-of-Check to Time-of-Use (TOCTOU) race condition.
mermaid\nflowchart TD\n A[\"App calls realpath(target)\"] --> B[\"Verified inside /srv/app/exports\"]\n B --> C[\"Race Window (Concurrent Thread Swaps Symlink)\"]\n C --> D[\"App calls open(target) by String Path\"]\n D --> E[\"Kernel Follows New Symlink Outside Root\"]\n F[\"App holds dirfd on /srv/app/exports\"] --> G[\"Single Syscall openat2 with RESOLVE_BENEATH\"]\n G --> H[\"Kernel Atomically Blocks Escapes and Symlinks\"]\n
On single-purpose read endpoints with root-owned static assets, a local attacker cannot swap a symlink mid-flight. In multi-tenant CI runners, container build workers, shared scratch volumes, or parallel archive extractors, however, another thread or unprivileged process can replace a benign directory with a symlink during the microseconds between realpath and open.
The modern systems solution eliminates string-path re-resolution altogether by pinning a file descriptor to the root directory (dirfd) and asking the kernel to enforce confinement atomically during the open syscall itself. On Linux 5.6 and newer, openat2(2) accepts RESOLVE_BENEATH and RESOLVE_NO_SYMLINKS, instructing the kernel VFS never to cross above dirfd and never to follow symbolic links during lookup.
c\n#define _GNU_SOURCE\n#include <fcntl.h>\n#include <linux/openat2.h>\n#include <sys/syscall.h>\n#include <unistd.h>\n\nint open_confined_readonly(int root_dir_fd, const char *rel_path) {\n struct open_how how = {\n .flags = O_RDONLY | O_CLOEXEC,\n .resolve = RESOLVE_BENEATH | RESOLVE_NO_SYMLINKS | RESOLVE_NO_MAGICLINKS,\n };\n return (int)syscall(SYS_openat2, root_dir_fd, rel_path, &how, sizeof(how));\n}\n
Because open_confined_readonly passes a kernel-held root_dir_fd and forbids both upward .. escapes (RESOLVE_BENEATH) and symlink traversal (RESOLVE_NO_SYMLINKS plus RESOLVE_NO_MAGICLINKS for /proc magic links), there is zero TOCTOU window between validation and access. Languages like Rust expose equivalent capability-oriented primitives via crates like cap-std, while Go 1.24 added os.Root (os.OpenRoot) to enforce traversal-safe operations anchored to a directory handle across platforms.
Comparing Path Traversal Defenses and Production Tradeoffs
Choosing the right control depends on whether your endpoint truly needs arbitrary nested paths or only needs to fetch one object from a known collection. Over-engineering a filesystem sandbox when an opaque database identifier solves the problem adds unnecessary syscall overhead and operational fragility.
| Defense Strategy | Stops Encoded .. |
Stops Symlink Escape | Immune to TOCTOU | Operational Tradeoffs |
|---|---|---|---|---|
Regex or replace('../', '') |
No | No | No | Breaks legitimate filenames; bypassed by ....// or double encoding |
Lexical path.resolve + prefix check |
Partial | No | No | Fast (no disk I/O), but vulnerable to symlinks and sibling prefix bugs without trailing slash |
realpath + trailing sep / commonpath |
Yes | Yes | No | Adds lstat I/O per path component; fails with ENOENT on non-existent write targets |
dirfd + openat2 (RESOLVE_BENEATH) / os.Root |
Yes | Yes | Yes | Kernel-enforced atomic safety; requires modern OS/runtime support or per-component O_NOFOLLOW fallback |
| Opaque ID indirection (UUID lookup) | Yes | Yes | Yes | Eliminates user-controlled paths entirely; requires metadata store mapping IDs to storage keys |
From an operations and performance standpoint, calling realpath on every static asset request inside a deeply nested NFS or container overlay mount triggers a chain of lstat calls for every directory segment, inflating tail latency under high concurrency. Caching the canonicalized base directory once at startup (assuming the mount topology is static) and reserving user-space realpath or kernel openat2 for dynamic user-supplied paths keeps I/O overhead negligible.
Web Application Firewalls (WAFs) provide useful defense-in-depth telemetry, yet relying on them as a primary fix creates friction. Broad WAF rules blocking .. anywhere in query parameters routinely trigger false positives when users search for phrases with ellipses or pass markdown snippets. Treat WAF alerts as anomaly signals for triage rather than a boundary guarantee, and monitor application logs for spikes in HTTP 400 or 403 rejections from canonicalization guards alongside kernel auditd or eBPF telemetry flagging unexpected openat targets outside designated data directories.
Engineering Checklist for Hardening File Endpoints
When reviewing an existing service or designing a new file-handling API, apply controls in order from strongest architectural elimination down to safe filesystem confinement:
- Remove user strings from filesystem paths wherever possible. Map an opaque UUID or signed token to an internal object key in your database, or store user files in an object store where keys are flat strings rather than OS directory hierarchies.
- Canonicalize both root and target on disk when relative paths are unavoidable. Use
realpath(oros.path.realpath) on an existing target, or on the deepest existing ancestor for new writes, after URL-decoding once at a single trusted boundary. - Enforce component-aware containment. Always append a trailing path separator to the canonical root before prefix comparison, or use
os.path.commonpathand reject equality with the root itself when opening files. - Eliminate symlinks and TOCTOU races in untrusted workspaces. Use
openat2(RESOLVE_BENEATH | RESOLVE_NO_SYMLINKS), Goos.Root, or component-by-componentO_NOFOLLOWdirectory walking whenever concurrent writers or archives can plant links. - Isolate storage and response headers. Keep upload and export directories outside the webroot, disable directory listing, and send
Content-Disposition: attachmentwithX-Content-Type-Options: nosniffso downloaded files cannot execute active content in a user's browser.
References & Sources
Related Security Reads

Rate Limiting and Brute-Force Defense: Blocking Attackers, Not Users
Build multi-dimensional rate limiting with GCRA token buckets, trusted proxy parsing, and HTTP 429 cooldowns to block brute force without self-DoS.

TLS Handshake in HTTPS: How Browsers Negotiate Encrypted Web Connections
Explore how TLS 1.3 and 1.2 handshakes verify server identity, derive forward-secret AEAD keys, prevent downgrade attacks, and handle 0-RTT replay tradeoffs.

LLM Output Security: Preventing XSS and SQL Injection at Sink Boundaries
Treat LLM responses as untrusted input. See how prompt injection turns generated text into XSS or SQLi, and enforce context encoding and parameterized queries.

Software Bill of Materials (SBOM): Internals, Formats, and CVE Response
Learn how SBOMs map transitive dependencies via CycloneDX, SPDX, and PURLs, integrate with VEX and SLSA attestations, and cut CVE triage from hours to seconds.
Get new posts by email
No ads, no tracking. Just new posts, unsubscribe any time.
Comments
No comments yet.