How-To Guide

How to Prevent Path Traversal Attacks

Stop path traversal: reject .. and absolute paths, resolve against a fixed base, verify the result stays inside it, and test with encoded payloads.

On this page

  1. Introduction
  2. Build paths by resolving, not concatenating
  3. Verify containment on resolved paths
  4. Reject dangerous components early too
  5. Handle encoding and symlinks
  6. Test with the payloads attackers use
  7. Common pitfalls
  8. Conclusion

Introduction

A path traversal attack uses input intended to name a file to reach a file it should not, such as a configuration file or another user’s document. If the application builds a path by concatenating a base with user input, the input can contain .. segments or an absolute path and escape the base. Encoded and double-encoded forms, and symlinks, add more ways to slip past a check that only looks for the literal two dots.

This tutorial shows the reliable defense: resolve the user component against a fixed base to an absolute, normalized path, then verify the resolved path is inside the base. It covers rejecting dangerous components, handling encoding, dealing with symlinks, and testing with the payloads attackers use. The examples use Node.js path handling, but the resolve-and-verify pattern is universal.

Build paths by resolving, not concatenating

The root mistake is string concatenation: joining a base and user input with a slash and trusting that the result is under the base. Instead, treat the base as an absolute path, join the user component to it, and resolve the result to a normalized absolute path. Resolution collapses .. segments and removes redundancies, so the check operates on the same path the filesystem will open.

Resolve the base itself to an absolute, canonical form first, so the containment check compares like with like. If the base is relative to the process working directory, resolve it once at startup and use that absolute value, rather than letting it change with the working directory. Then every check compares two absolute paths resolved the same way.

import { resolve, join, sep } from 'node:path';

const BASE = resolve('/srv/app/uploads'); // resolved once, absolute

function resolveInsideBase(userPath) {
  const target = resolve(join(BASE, userPath));
  // must be the base itself or a path strictly inside it
  if (target !== BASE && !target.startsWith(BASE + sep)) {
    throw new Error('path escapes base');
  }
  return target;
}

Verify containment on resolved paths

The containment check must compare resolved absolute paths, and it must use a path separator in the comparison. Checking startsWith(BASE) without the separator admits a sibling directory whose name begins with the base’s name, such as /srv/app/uploads_backup when the base is /srv/app/uploads. Comparing against BASE + separator, or equality with the base itself, closes that gap.

Do the check after resolution so that encoded input has already been normalized by the filesystem semantics of resolve. A raw ..%2f string is not decoded by resolve, so if the input arrives percent-encoded you must decode it first, then resolve. The order is decode, join, resolve, verify, and the verify step is what makes the result safe regardless of how the input was spelled.

Reject dangerous components early too

As a fast, explicit rejection, refuse input containing a .. segment, an absolute path, a null byte, or a path separator where a single filename is expected. This is not the primary defense, because encoding can hide these, but it gives a clear error for the obvious attempts and keeps a well-behaved client from sending a path when a name is meant.

Decide whether the input is a single filename or a relative path. If it is a single filename, reject any separator at all, which is the strictest and simplest rule. If a relative path is genuinely needed, allow separators but still resolve and verify containment, and reject absolute paths and .. segments. The narrower the accepted shape, the smaller the attack surface.

function safeFilename(name) {
  if (typeof name !== 'string') throw new Error('bad name');
  if (name.includes('\0')) throw new Error('null byte');
  if (name.includes('/') || name.includes('\\')) throw new Error('separator');
  if (name === '.' || name === '..') throw new Error('reserved');
  return name;
}

Input may arrive percent-encoded or double-encoded. Decode once, and be aware that a double-encoded value decodes to an encoded value that later decoding could turn into ..; if your framework decodes again later, the check must run on the final decoded value. The resolve-and-verify pattern handles this if the check runs after all decoding, on the value the filesystem will finally use.

A path can resolve inside the base yet reach outside through a symlink inside the base. If the base can contain symlinks you do not control, resolve the real path with realpath, which follows symlinks, and verify containment against the real path. Where possible, avoid symlinks inside the served tree, and store uploads with generated names so user input never selects a path at all.

import { realpath } from 'node:fs/promises';
import { resolve, sep } from 'node:path';

async function resolveRealInsideBase(userPath) {
  const realBase = await realpath(BASE);
  const target = await realpath(resolve(join(BASE, userPath))); // follows symlinks
  if (target !== realBase && !target.startsWith(realBase + sep)) {
    throw new Error('path escapes base');
  }
  return target;
}

Test with the payloads attackers use

Test the traversal check with payloads an attacker would use: ../, ..%2f, %2e%2e%2f, a double-encoded form, an absolute path such as /etc/passwd, a null byte, a sibling directory name that shares the base prefix, and a symlink inside the base pointing out. Assert each either is rejected or, if a relative path is allowed, resolves to a location inside the base. Test the check after decoding, since that is where the encoded forms are caught.

for P in "../secret" "..%2fsecret" "%2e%2e%2fsecret" "/etc/passwd" "uploads_backup/x" ; do
  curl -s -o /dev/null -w "%{http_code} $P\n" "http://localhost:3000/file?name=$P"
done
# expect 400 for each: rejected or contained inside the base

Common pitfalls

Concatenating base and input with a slash, checking only for the literal two dots and missing encoded forms, a startsWith check without a path separator so a sibling directory passes, verifying before decoding, and ignoring symlinks inside the base are the recurring mistakes. Resolve and verify on decoded paths with a separator-aware check, reject dangerous components early, and use realpath where symlinks matter.

Conclusion

Path traversal is defeated by never trusting a constructed path. Resolve the user component against a fixed base to an absolute normalized path, verify it is inside the base using a separator-aware comparison, reject .., absolute paths, and null bytes early, and resolve symlinks where they matter. Self-check by trying encoded, double-encoded, absolute, and sibling-prefix payloads and asserting each is rejected or contained. Then user input can name only files you intend.

Sources: OWASP: Path traversal, OWASP: File path traversal cheat sheet, Node.js: path module.

FAQ

Is rejecting .. enough?
No. Encoded forms such as %2e%2e%2f, double-encoded variants, absolute paths, symlinks, and null bytes can all escape a naive check. Resolve the path against a fixed base and verify the resolved result is inside it, which catches every form because the filesystem normalization happens before the check.
What about symlinks inside the base?
A path that resolves inside the base can still point through a symlink to a file outside. If the base may contain symlinks you do not control, resolve the real path with the symlink resolved too, and re-check containment against the real path.

Related Examples