← Lessons

quiz vs the machine

Silver1100

Security

Path Traversal Prevention

How dot dot slash escapes your folder and how to keep file access inside bounds.

4 min read · intro · beat Silver to climb

The Risk

Many apps build a file path from user input, such as a download name or a template id. If you simply join that input to a base folder, an attacker can include sequences like dot dot slash to climb out of the intended directory. This is path traversal, and it can let someone read configuration files, credentials, or source code that should never be served.

The danger comes from trusting a name to stay within a folder when the operating system happily resolves parent directory references.

The Defense

  • Canonicalize the path by resolving it to its real absolute form, then check that it still starts with the allowed base directory.
  • Reject input that contains separators or parent references when only a plain filename is expected.
  • Prefer an allowlist of known identifiers that map to safe paths internally.
  • Run the file serving process with least privilege so even an escape reaches little.

Key idea

Resolve the final path and verify it stays inside the approved directory rather than trusting the raw name a user sends.

Check yourself

Answer to earn rating on the learn ladder.

1. What lets path traversal escape a folder?

2. Which check best prevents traversal?