TExcelTAD

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's toRealPath()). The only reliable check compares canonical paths.
  • os.path.join and absolute components: os.path.join("public", "/etc/passwd") returns /etc/passwd; the base is discarded. Java's Path.resolve and Node's path.join/path.resolve have their own versions of this surprise.
  • Zip Slip: an archive entry named ../../app/config.py written 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/.

bash · try it yourself
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 with startswith on 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

  1. 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.
  2. If names are needed, resolve and compare canonical paths: target = (BASE / name).resolve(); target.is_relative_to(BASE) (Python 3.9+), Java base.resolve(name).normalize().toRealPath().startsWith(base), Node path.resolve(base, name) then startsWith(base + path.sep).
  3. Validate the name with an allow-list pattern (^[A-Za-z0-9_-]+\.(pdf|txt)$) as an extra layer.
  4. 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.
  5. For archives, apply the same canonical-path check to every entry before writing it (Python's tarfile has extraction filters since 3.12, also backported to security releases of 3.8–3.11: use filter="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/x starts with /srv/public. is_relative_to and comparisons with base + os.sep avoid 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?

  1. public/home/learner/private/keys.txt
  2. /home/learner/private/keys.txt
  3. An error
  4. public/keys.txt

Which check reliably keeps a path inside the base directory?

  1. name.startswith('..') is false
  2. name.replace('../', '')
  3. Resolve the joined path to its canonical form and check it is inside the canonical base
  4. A regex on the URL

Why did ..%2fprivate%2fapi-keys.txt work against the vulnerable app?

  1. curl decoded it
  2. The framework decoded %2f to / before the app joined the path
  3. It is a different file
  4. The fixed app was running

What is Zip Slip?

  1. A compression bomb
  2. Archive entries with ../ in their names written outside the extraction directory
  3. A slow zip
  4. A zip password attack