Path traversal: climbing out of the folder
When a file name from the request is joined into a path, `../` lets an attacker walk up the directory tree and read configuration, secrets or system files. How it works and the two reliable fixes.
In one sentence
Never let user input decide a filesystem path. Map IDs to files, or resolve the full path and check it's still inside the allowed folder.
The idea
/download?file=invoice-1041.pdf reads uploads/invoice-1041.pdf. But file=../.env reads the app's secrets, and enough ../ reaches /etc/passwd. The operating system happily resolves the dots.
DATABASE_URL=postgres://app:FAKE-pass@db/shop STRIPE_KEY=sk_test_FAKE…
- /etc/passwd
- ▸ /srv/app/.env
- /srv/app/uploads/avatar.png
- /srv/app/uploads/invoice-1041.pdf
- base: /srv/app/uploads
Fixes that hold
Vulnerable
- fs.readFile(path.join(UPLOADS, req.query.file))
- Stripping "../" once ("....//" survives)
- Checking the extension only ("../../.env%00.pdf")
Safe
- Look up the file by ID in the DB, read its stored path
- Resolve, then require the result to start with UPLOADS + path.sep
- Serve user files from object storage with signed URLs
const full = path.resolve(UPLOADS, req.query.file);
if (!full.startsWith(UPLOADS + path.sep)) {
return new Response("Bad path", { status: 400 });
}
// and still check the user may access this fileKey takeaways
- 01
../in user input walks out of the intended folder. - 02Prefer IDs mapped to stored paths over user-supplied file names.
- 03If you must use names: resolve, then verify the prefix.
- 04Run the app as a user that can't read secrets it doesn't need.
Check your understanding
1 of 3
What does a path traversal attack use?
Related concepts
Access control & IDOR
If `/api/orders/1042` works for a user who doesn't own order 1042, that's an IDOR. Every query that loads a record by ID must also filter by who's asking.
7 min read →SSRF
Your server sits inside your network. If a user picks the URL it fetches, they borrow that position. Allowlist destinations, block private addresses after DNS resolution, and lock down cloud metadata.
7 min read →Least privilege
Assume something will get hacked. Least privilege makes sure that when it does, the attacker gets the keys to one room, not the whole building.
6 min read →