SecPrep logoSecPrep

Write `isPathTraversal(path)` that returns `true` when the path contains a `../` directory traversal sequence, and `false` otherwise.

Reference Solution

javascript
/**
 * Returns true if `path` contains a path-traversal sequence.
 * Normalises both forward-slash and backslash variants.
 * @param {string} path
 * @returns {boolean}
 */
function isPathTraversal(path) {
  // Normalise backslashes, then check for the ../ or /.. patterns.
  const normalised = path.replace(/\\/g, '/');
  return normalised.split('/').some((segment) => segment === '..');
}

Path traversal (also called directory traversal) is when user-controlled input that forms a file path contains ../ sequences to 'climb' up the directory tree beyond the intended root. For example, if the server appends a user-supplied filename to ./uploads/, an attacker can supply ../../etc/passwd to read the system password file.

Detecting it: normalise path separators (replace \ with /) then check whether any path segment equals ... The fix in production code: use path.resolve() to compute the absolute path and verify it starts with the allowed root directory — reject any path that escapes that root, regardless of what sequences were used to get there.

Practice this in the app →