Path Traversal
A download endpoint like /files?name=report.pdf maps a request parameter to a file on disk. If the application glues the name onto a directory and opens the result, the name ../../etc/passwd walks out of that directory, and the attacker reads whatever the server's account can read: configuration files with database passwords, private keys, source code, other users' uploads. This is path traversal (directory traversal, CWE-22), part of A01 Broken Access Control in the OWASP Top 10 2025. The same bug in the other direction, writing to a path built from input (an upload's file name, an entry in a zip archive), can overwrite code or configuration. This lesson attacks a file server in your sandbox that serves its own public/ folder, then fixes it with path resolution rather than string filtering.
Definitions
- Traversal sequence:
../(and..\on Windows) moves up one directory. Variants that slip past naive filters: URL-encoded (%2e%2e%2f), double-encoded (%252e%252e%252f), overlong UTF-8 in old servers,....//after a filter that deletes../once, and absolute paths (/etc/hostname,C:\Windows\win.ini). - Canonical path: the absolute path after resolving
.,..and symbolic links (os.path.realpath,Path.resolve(), Java'stoRealPath()). The only reliable check compares canonical paths. os.path.joinand absolute components:os.path.join("public", "/etc/passwd")returns/etc/passwd; the base is discarded. Java'sPath.resolveand Node'spath.join/path.resolvehave their own versions of this surprise.- Zip Slip: an archive entry named
../../app/config.pywritten by an extractor that trusts entry names.
The attack and the fix, in the sandbox
The session creates public/ (with a docs/ subfolder) and two files the app is meant to serve, and private/api-keys.txt (lab-only fake keys) next to it, outside the served folder. The vulnerable app joins and opens; the fixed app resolves the path and checks that it is still inside public/.
mkdir -p public/docs private
printf 'Q3 report: revenue up\n' > public/report.txt
printf 'welcome\n' > public/readme.txt
printf 'PAYMENT_API_KEY=lab-not-a-real-key\n' > private/api-keys.txt
cat > files.py <<'PY'
import os, sys
from pathlib import Path
from urllib.parse import parse_qs
from wsgiref.simple_server import make_server, WSGIRequestHandler
FIXED = sys.argv[1] == "fixed"
BASE = Path("public").resolve()
class Quiet(WSGIRequestHandler):
def log_message(self, *args):
pass
def app(environ, start_response):
name = parse_qs(environ.get("QUERY_STRING", "")).get("name", [""])[0] # parse_qs decodes %xx once
with open("access.log", "a") as log:
log.write(f"GET /files?{environ.get('QUERY_STRING', '')}\n")
try:
if FIXED:
target = (BASE / name).resolve()
if not target.is_relative_to(BASE) or not target.is_file():
raise FileNotFoundError
else:
target = os.path.join("public", name)
data, status = open(target, "rb").read(), "200 OK"
except OSError:
data, status = b"not found\n", "404 Not Found"
start_response(status, [("Content-Type", "text/plain")])
return [data]
make_server("127.0.0.1", 8000, app, handler_class=Quiet).serve_forever()
PY
ask() { printf ' %-44s -> ' "$1"; curl -s --path-as-is -w ' [%{http_code}]' "http://127.0.0.1:8000/files?name=$1" | tr -d '\n'; echo; }
for mode in vulnerable fixed; do
: > access.log
python3 files.py $mode &
for i in $(seq 50); do curl -s -o /dev/null http://127.0.0.1:8000/ && break; sleep 0.1; done
echo "=== $mode"
ask 'report.txt'
ask '../private/api-keys.txt'
ask '..%2fprivate%2fapi-keys.txt'
ask "$PWD/private/api-keys.txt"
ask 'docs/../../private/api-keys.txt'
kill %1; wait 2>/dev/null
done
echo "=== detection: traversal patterns in the access log (decoded once, as the app sees them)"
python3 - <<'DETECT'
import re
from urllib.parse import unquote
SIGNS = re.compile(r"(\.\./|\.\.\\|^/|^[A-Za-z]:\\)")
for line in open("access.log"):
if "name=" not in line:
continue # the session's readiness check
name = unquote(line.split("name=", 1)[1].strip())
print((" ALERT " if SIGNS.search(name) else " ok ") + name)
DETECT=== vulnerable
report.txt -> Q3 report: revenue up [200]
../private/api-keys.txt -> PAYMENT_API_KEY=lab-not-a-real-key [200]
..%2fprivate%2fapi-keys.txt -> PAYMENT_API_KEY=lab-not-a-real-key [200]
/home/learner/private/api-keys.txt -> PAYMENT_API_KEY=lab-not-a-real-key [200]
docs/../../private/api-keys.txt -> PAYMENT_API_KEY=lab-not-a-real-key [200]
=== fixed
report.txt -> Q3 report: revenue up [200]
../private/api-keys.txt -> not found [404]
..%2fprivate%2fapi-keys.txt -> not found [404]
/home/learner/private/api-keys.txt -> not found [404]
docs/../../private/api-keys.txt -> not found [404]
=== detection: traversal patterns in the access log (decoded once, as the app sees them)
ok report.txt
ALERT ../private/api-keys.txt
ALERT ../private/api-keys.txt
ALERT /home/learner/private/api-keys.txt
ALERT docs/../../private/api-keys.txt
The vulnerable app served the private key file four ways: with a plain ../, URL-encoded (the framework decoded %2f before the app saw it, so a filter on the raw query string would have missed it), as an absolute path, which os.path.join accepted by discarding public, and through a subfolder (docs/../../), which a check for a leading ../ would miss. The fixed app resolved every candidate to its canonical path and refused anything outside public/, including the subfolder variant. The detection script decodes the logged parameter once, as the application does, and flags traversal sequences and absolute paths.
How path traversal is detected
- Testing (in scope): every parameter that names a file, template, language, theme or include (
file=,page=,lang=,template=,download=), plus upload file names and archive imports. Try../sequences with a file that exists on every system of that kind (in a lab:/etc/hostname,/etc/passwd,C:\Windows\win.ini), the encodings above, absolute paths, and a valid file name followed by/../. - Code review: file APIs (
open,send_file,FileInputStream,fs.readFile,include) receiving request data; checks withstartswithon non-canonical strings;replace("../", ""). - Logs and WAF:
../,..%2f,%2e%2e,%252e,..\, absolute paths in parameters; 200 responses with unusual sizes on download endpoints. - File-integrity and access monitoring on sensitive files (keys,
.env) read by the web server process.
How it is fixed
- Don't use names from the client. Store files under random ids and keep the original name only as metadata:
/files/7f3e9a…looks up the path in a database. - If names are needed, resolve and compare canonical paths:
target = (BASE / name).resolve(); target.is_relative_to(BASE)(Python 3.9+), Javabase.resolve(name).normalize().toRealPath().startsWith(base), Nodepath.resolve(base, name)thenstartsWith(base + path.sep). - Validate the name with an allow-list pattern (
^[A-Za-z0-9_-]+\.(pdf|txt)$) as an extra layer. - Least privilege: the web server account can't read keys and configuration it doesn't need; secrets come from a secret manager, not files beside the code.
- For archives, apply the same canonical-path check to every entry before writing it (Python's
tarfilehas extraction filters since 3.12, also backported to security releases of 3.8–3.11: usefilter="data").
Pitfalls
- String filters: removing
../once turns....//into../. - Checking before decoding (or decoding twice): validate exactly the string you will open.
- Prefix checks without a separator:
/srv/public-old/xstarts with/srv/public.is_relative_toand comparisons withbase + os.sepavoid it. - Symbolic links inside the served folder pointing outside it:
resolve()follows them, which is why the check is done after resolving.
Practice
1. A Node handler does res.sendFile(path.join(__dirname, 'public', req.query.f)). Is it safe?
No: path.join normalises .., so f=../server.js resolves outside public. Use res.sendFile(req.query.f, { root: path.join(__dirname, 'public') }), which Express checks against the root, or resolve and compare yourself; better, map ids to files.
2. Why did the fixed app also require is_file()?
So that directories and special files inside public/ aren't opened (a directory would raise an error that might leak a stack trace or behave differently per platform), and the answer for "not a regular file" is the same 404 as for "outside".
Practice problem in 21 languages: Resolve a Request Path Safely.
Test yourself
What does os.path.join('public', '/home/learner/private/keys.txt') return?
- public/home/learner/private/keys.txt
- /home/learner/private/keys.txt
- An error
- public/keys.txt
Which check reliably keeps a path inside the base directory?
- name.startswith('..') is false
- name.replace('../', '')
- Resolve the joined path to its canonical form and check it is inside the canonical base
- A regex on the URL
Why did ..%2fprivate%2fapi-keys.txt work against the vulnerable app?
- curl decoded it
- The framework decoded %2f to / before the app joined the path
- It is a different file
- The fixed app was running
What is Zip Slip?
- A compression bomb
- Archive entries with ../ in their names written outside the extraction directory
- A slow zip
- A zip password attack