Skip to main content
Security guideReviewed

Path traversal: check the path the file system will actually open

Path traversal happens when code builds a file path from something a visitor controls and the result lands outside the folder the code meant.

This guide shows where it hides, why stripping ../ fails, how to check the real path after links are resolved, and gives you a local Node.js lab with a canonical-path test table and a regression test.

Canonical-path lab: fixture, test table and regression test

An illustration written for this page, not client code. A Node.js lab builds a temporary folder with a served sub-folder, a marker file above it and a link pointing out, then sends twelve inputs through two flawed resolvers and a fixed one and prints the canonical-path test table.

How to use it

It also extracts an archive it builds itself, reruns a bare join under the Node.js permission model, and includes a regression test on the built-in test runner that fails for the flawed variants and passes for the fixed one. It needs Node.js only and was recorded on Node.js v26.0.0 on macOS. Use it on your own machine to learn, and to test code you own.

path-traversal.txt

ILLUSTRATION FOR LEARNING. The fixture, the three resolvers, the archive and every input below were written for this page. They are not a client's code or a client's result. Run the lab on your own machine to learn, and use its test on code you own. Do not send any of its inputs to a system you do not own or are not authorised in writing to test.

WHAT IT NEEDS
Node.js, with nothing to install. The lab uses only built-in modules: node:fs, node:os, node:path, node:url, node:child_process, node:assert and node:test. The Node.js documentation marks the test runner stable from version 20.0.0, and the permission model that Part E uses stable from versions 22.13.0 and 23.5.0. Every output below was recorded on Node.js v26.0.0, macOS 27.2.1 (arm64). It was not run on Windows or Linux.

WHAT IT TOUCHES
The lab creates one temporary folder with fs.mkdtempSync() inside your system's temporary directory, works only inside it, and deletes it at the end. The test creates and deletes its own folder the same way. The "secret" is a marker file the lab writes itself, one level above the folder it serves. No input names a real system file. The flawed resolvers and the flawed extractor run behind a guard, assertInsideLab(), that refuses any path outside the lab's temporary folder, even if you edit the inputs. Nothing opens a network connection: lab.invalid is only a base for parsing URLs, and Part E's child process only reads.

LAB IN THE OUTPUT
Temporary folder names change on every run and are local paths, so the lab prints LAB in place of the folder's absolute path (labelPath() in fixture.mjs does this). LAB/public is the folder the code serves, called the base folder below. Where an input is an absolute path, LAB/secret-marker.txt in the input stands for the full path.

THE FIXTURE
  LAB/public/readme.txt               a file the base folder serves
  LAB/public/docs/guide.txt           a served file in a subfolder
  LAB/public/linked-folder            a link the lab creates, pointing to .. (that is, to LAB)
  LAB/secret-marker.txt               the marker, one level above the base folder
  LAB/public-archive/old-note.txt     a sibling folder whose name starts with "public"
  LAB/extract-flawed, LAB/extract-fixed   empty folders for the archive extraction in Part D

The link is created in code. createFolderLink() tries a directory symbolic link first, then a Windows junction, and if both fail it records why, prints the reason and skips row R11 instead of failing. On the machine the outputs come from, the symbolic link was created; the junction fallback has not been run.

THE THREE RESOLVERS
Each receives the file name a request asked for, after the one percent-decode URLSearchParams performs on a query string value (decodeLikeUrlSearchParams() in fixture.mjs), and returns what it served.
  flawedJoin      decodes the value a second time with decodeURIComponent(), joins it onto the base folder with path.join() and reads the result.
  flawedResolve   does not decode again, but builds the path with path.resolve(), which lets an absolute value replace the base folder.
  fixedResolve    never decodes again; rejects control characters, absolute paths (POSIX or Windows) and any segment outside an allow-list (letters, digits, hyphen and underscore, with at most one dot for an extension); resolves the value against the base folder's real path; checks the result is inside; takes fs.realpathSync() of it, which resolves links; checks again; and only then opens the real path it checked.

THE ARCHIVE
Part D builds a small archive in the ustar format from the POSIX pax specification, uncompressed. It was chosen because it is simple enough to write and read exactly with built-ins: fixed 512-byte blocks, numbers stored as octal text, a checksum that is a plain sum of the header's bytes, and no compression or central directory. Each entry's name sits in its header as plain text, which is where the problem lives. Its five entries are an ordinary file, a name with parent-directory steps, an absolute name pointing into the lab's own temporary folder (never anywhere else), a symbolic link named up pointing to .., and a file written through up.

SET-UP
Make an empty folder, save the six files below into it under the names shown, and run the commands under RUN IT from that folder. The commands set LAB_VARIANT the way macOS and Linux shells do; on Windows, set it the way your shell does.

==== File 1 of 6: fixture.mjs ====
// fixture.mjs: builds the lab's own temporary folder, lists the inputs the
// lab sends, and removes the folder again. Every file the lab reads or
// writes is inside this folder. For learning, and for testing code you own.
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'

export const SECRET_MARKER = 'LAB-SECRET-MARKER: this file sits outside the served folder'

function writeText(filePath, text) {
  fs.mkdirSync(path.dirname(filePath), { recursive: true })
  fs.writeFileSync(filePath, text)
}

// The link points one level up, out of the served folder. A directory
// symbolic link is tried first, then a Windows junction. If both fail, the
// lab records why and skips the link row instead of failing.
function createFolderLink(linkPath) {
  try {
    fs.symlinkSync('..', linkPath, 'dir')
    return { created: true, note: 'symbolic link to ..' }
  } catch (firstError) {
    try {
      fs.symlinkSync(path.dirname(path.dirname(linkPath)), linkPath, 'junction')
      return { created: true, note: 'junction, because the symbolic link failed with ' + firstError.code }
    } catch (secondError) {
      return { created: false, note: 'no link: ' + firstError.code + ', then ' + secondError.code }
    }
  }
}

export function createFixture() {
  const labRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'pt-lab-'))
  const base = path.join(labRoot, 'public')
  writeText(path.join(base, 'readme.txt'), 'public file: readme')
  writeText(path.join(base, 'docs', 'guide.txt'), 'public file: guide')
  writeText(path.join(labRoot, 'secret-marker.txt'), SECRET_MARKER)
  writeText(path.join(labRoot, 'public-archive', 'old-note.txt'), 'LAB-SIBLING-MARKER: a sibling folder')
  fs.mkdirSync(path.join(labRoot, 'extract-flawed'))
  fs.mkdirSync(path.join(labRoot, 'extract-fixed'))
  const link = createFolderLink(path.join(base, 'linked-folder'))
  return {
    labRoot: labRoot,
    labRootReal: fs.realpathSync(labRoot),
    base: base,
    baseReal: fs.realpathSync(base),
    link: link,
  }
}

export function removeFixture(fixture) {
  fs.rmSync(fixture.labRoot, { recursive: true, force: true })
  return !fs.existsSync(fixture.labRoot)
}

// Replaces the temporary folder's location with LAB, so printed paths are
// the same on every run and show no local path. The real path goes first,
// because on some systems it contains the created path.
export function labelPath(fixture, text) {
  let labelled = String(text)
  for (const folder of [fixture.labRootReal, fixture.labRoot]) {
    if (labelled.startsWith(folder)) labelled = 'LAB' + labelled.slice(folder.length)
    labelled = labelled.split(folder).join(path.sep + 'LAB')
  }
  return labelled
}

// What a request handler receives: the query string value after the one
// percent-decode URLSearchParams performs, through the URL Standard's
// application/x-www-form-urlencoded parser.
export function decodeLikeUrlSearchParams(sent) {
  const url = new URL('http://lab.invalid/download?file=' + sent)
  return url.searchParams.get('file')
}

// One input per class. "sent" is the query string value exactly as sent.
export function buildInputs(fixture) {
  return [
    { id: 'R1', label: 'plain file name', sent: 'readme.txt', expected: 'public file: readme' },
    { id: 'R2', label: 'file in a subfolder', sent: 'docs/guide.txt', expected: 'public file: guide' },
    { id: 'R3', label: 'parent-directory steps', sent: '../secret-marker.txt' },
    { id: 'R4', label: 'encoded separator, single', sent: '..%2fsecret-marker.txt' },
    { id: 'R5', label: 'encoded separator, double', sent: '..%252fsecret-marker.txt' },
    { id: 'R6', label: 'encoded dots, single', sent: '%2e%2e/secret-marker.txt' },
    { id: 'R7', label: 'encoded dots, double', sent: '%252e%252e/secret-marker.txt' },
    { id: 'R8', label: 'encoded backslash', sent: '..%5csecret-marker.txt' },
    { id: 'R9', label: 'absolute path', sent: fixture.labRoot + '/secret-marker.txt' },
    { id: 'R10', label: 'sibling folder passes a prefix check', sent: '../public-archive/old-note.txt' },
    { id: 'R11', label: 'symbolic link inside the folder', sent: 'linked-folder/secret-marker.txt', needsLink: true },
    { id: 'R12', label: 'encoded NUL byte', sent: 'readme.txt%00.pdf' },
  ]
}

==== File 2 of 6: resolvers.mjs ====
// resolvers.mjs: two flawed resolvers, the fixed one, and the checks they
// share. Each resolver takes the file name a request asked for and returns
// what it served. The flawed ones are wrong on purpose: never copy them.
import fs from 'node:fs'
import path from 'node:path'

// True only for a path strictly below baseFolder. path.relative() compares
// strings, so give it two real paths, never one real and one unresolved.
export function isInside(baseFolder, target) {
  const relative = path.relative(baseFolder, target)
  if (relative === '') return false
  if (path.isAbsolute(relative)) return false
  const firstSegment = relative.split(path.sep)[0]
  return firstSegment !== '..'
}

export function nearestExistingPath(target) {
  let current = path.resolve(target)
  while (!fs.existsSync(current)) current = path.dirname(current)
  return current
}

// Safety interlock for the flawed code only: it refuses any path outside
// the lab's temporary folder, whatever a reader changes in the inputs.
export function assertInsideLab(fixture, target) {
  const resolved = path.resolve(target)
  const realExisting = fs.realpathSync(nearestExistingPath(resolved))
  const insideByName = isInside(fixture.labRoot, resolved)
  const insideReally = realExisting === fixture.labRootReal || isInside(fixture.labRootReal, realExisting)
  if (!insideByName || !insideReally) {
    throw new Error('LAB GUARD: refused a path outside the lab folder')
  }
}

function readFromDisk(filePath) {
  try {
    return { verdict: 'SERVED', servedPath: filePath, content: fs.readFileSync(filePath, 'utf8') }
  } catch (error) {
    if (error.code === 'ENOENT') return { verdict: 'NOT FOUND', detail: 'ENOENT' }
    return { verdict: 'ERROR', detail: error.code || error.message }
  }
}

// Flawed 1: decodes the value a second time, then joins it onto the base.
export function flawedJoin(fixture, requested) {
  let name
  try {
    name = decodeURIComponent(requested)
  } catch (error) {
    return { verdict: 'ERROR', detail: 'URIError' }
  }
  const filePath = path.join(fixture.base, name)
  assertInsideLab(fixture, filePath)
  return readFromDisk(filePath)
}

// Flawed 2: no second decode, but path.resolve() lets an absolute value
// replace the base folder.
export function flawedResolve(fixture, requested) {
  const filePath = path.resolve(fixture.base, requested)
  assertInsideLab(fixture, filePath)
  return readFromDisk(filePath)
}

// A name with at most one dot, such as readme.txt or docs. No leading dot,
// no separator other than / between segments, no percent sign.
const ALLOWED_SEGMENT = /^[A-Za-z0-9_-]{1,64}(\.[A-Za-z0-9]{1,10})?$/

export function findRejection(requested) {
  if (typeof requested !== 'string' || requested === '') return 'empty'
  if (/[\u0000-\u001f\u007f]/.test(requested)) return 'control character'
  if (path.posix.isAbsolute(requested) || path.win32.isAbsolute(requested)) return 'absolute path'
  for (const segment of requested.split('/')) {
    if (!ALLOWED_SEGMENT.test(segment)) return 'segment not on the allow-list'
  }
  return null
}

function reject(reason) {
  return { verdict: 'REJECTED', detail: reason }
}

// Fixed: no second decode, an allow-list, then the containment check on the
// resolved path, and again on the real path after links, before opening.
export function fixedResolve(fixture, requested) {
  const rejection = findRejection(requested)
  if (rejection) return reject(rejection)
  const candidate = path.resolve(fixture.baseReal, ...requested.split('/'))
  if (!isInside(fixture.baseReal, candidate)) return reject('outside the base folder after resolving')
  let realPath
  try {
    realPath = fs.realpathSync(candidate)
  } catch (error) {
    return { verdict: 'NOT FOUND', detail: error.code }
  }
  if (!isInside(fixture.baseReal, realPath)) return reject('real path is outside the base folder')
  return readFromDisk(realPath)
}

export const RESOLVERS = { flawedJoin, flawedResolve, fixedResolve }

==== File 3 of 6: archive.mjs ====
// archive.mjs: writes and reads uncompressed ustar archives, the tar layout
// in the POSIX pax specification: 512-byte blocks, octal number fields and a
// checksum that is a plain byte sum. Enough for the lab: regular files and
// symbolic links with names up to 100 bytes. Then a flawed and a fixed
// extractor.
import fs from 'node:fs'
import path from 'node:path'
import { assertInsideLab, findRejection, isInside, nearestExistingPath } from './resolvers.mjs'

const BLOCK = 512

function octal(value, fieldLength) {
  return value.toString(8).padStart(fieldLength - 1, '0') + '\0'
}

function sumOfBytes(header) {
  let sum = 0
  for (const byte of header) sum += byte
  return sum
}

function buildHeader(entry) {
  if (Buffer.byteLength(entry.name) > 100) throw new Error('name longer than 100 bytes: ' + entry.name)
  const isLink = entry.type === 'symlink'
  const size = isLink ? 0 : Buffer.byteLength(entry.content)
  const header = Buffer.alloc(BLOCK)
  header.write(entry.name, 0, 100)
  header.write(octal(0o644, 8), 100, 8)
  header.write(octal(0, 8), 108, 8)
  header.write(octal(0, 8), 116, 8)
  header.write(octal(size, 12), 124, 12)
  header.write(octal(0, 12), 136, 12)
  header.write('        ', 148, 8)
  header.write(isLink ? '2' : '0', 156, 1)
  header.write(entry.linkTarget || '', 157, 100)
  header.write('ustar\0', 257, 6)
  header.write('00', 263, 2)
  header.write(sumOfBytes(header).toString(8).padStart(6, '0') + '\0 ', 148, 8)
  return header
}

function padToBlock(content) {
  const padding = (BLOCK - (content.length % BLOCK)) % BLOCK
  return Buffer.concat([content, Buffer.alloc(padding)])
}

export function buildTar(entries) {
  const parts = []
  for (const entry of entries) {
    parts.push(buildHeader(entry))
    if (entry.type !== 'symlink') parts.push(padToBlock(Buffer.from(entry.content)))
  }
  parts.push(Buffer.alloc(BLOCK * 2))
  return Buffer.concat(parts)
}

function readText(header, offset, length) {
  const field = header.subarray(offset, offset + length)
  const end = field.indexOf(0)
  return field.subarray(0, end === -1 ? length : end).toString('utf8')
}

function checkChecksum(header) {
  const stored = parseInt(readText(header, 148, 8).trim(), 8)
  const copy = Buffer.from(header)
  copy.write('        ', 148, 8)
  if (sumOfBytes(copy) !== stored) throw new Error('bad header checksum')
}

function describeType(typeFlag) {
  if (typeFlag === '0' || typeFlag === '\0') return 'file'
  if (typeFlag === '2') return 'symlink'
  return 'other'
}

export function readTar(archive) {
  const entries = []
  let offset = 0
  while (offset + BLOCK <= archive.length) {
    const header = archive.subarray(offset, offset + BLOCK)
    if (header.every((byte) => byte === 0)) break
    checkChecksum(header)
    const prefix = readText(header, 345, 155)
    const shortName = readText(header, 0, 100)
    const size = parseInt(readText(header, 124, 12).trim(), 8)
    entries.push({
      name: prefix ? prefix + '/' + shortName : shortName,
      type: describeType(String.fromCharCode(header[156])),
      linkTarget: readText(header, 157, 100),
      content: archive.subarray(offset + BLOCK, offset + BLOCK + size),
    })
    offset = offset + BLOCK + Math.ceil(size / BLOCK) * BLOCK
  }
  return entries
}

// Flawed: resolves each entry name against the destination and writes it,
// creating symbolic links as the archive says. The lab guard still applies.
export function flawedExtract(fixture, archive, destination) {
  const outcomes = []
  for (const entry of readTar(archive)) {
    const target = path.resolve(destination, entry.name)
    assertInsideLab(fixture, target)
    fs.mkdirSync(path.dirname(target), { recursive: true })
    if (entry.type === 'symlink') {
      fs.symlinkSync(entry.linkTarget, target)
      outcomes.push({ name: entry.name, outcome: 'CREATED A LINK to ' + entry.linkTarget + ' at', writtenTo: target })
      continue
    }
    fs.writeFileSync(target, entry.content)
    outcomes.push({ name: entry.name, outcome: 'WROTE', writtenTo: fs.realpathSync(target) })
  }
  return outcomes
}

function rejected(entry, reason) {
  return { name: entry.name, outcome: 'REJECTED: ' + reason }
}

function extractOneEntry(entry, destinationReal) {
  if (entry.type !== 'file') return rejected(entry, 'not a regular file')
  const rejection = findRejection(entry.name)
  if (rejection) return rejected(entry, rejection)
  const target = path.resolve(destinationReal, ...entry.name.split('/'))
  if (!isInside(destinationReal, target)) return rejected(entry, 'outside the destination')
  const existingFolder = fs.realpathSync(nearestExistingPath(path.dirname(target)))
  const folderIsInside = existingFolder === destinationReal || isInside(destinationReal, existingFolder)
  if (!folderIsInside) return rejected(entry, 'folder resolves outside the destination')
  fs.mkdirSync(path.dirname(target), { recursive: true })
  try {
    fs.writeFileSync(target, entry.content, { flag: 'wx' })
  } catch (error) {
    return rejected(entry, error.code)
  }
  return { name: entry.name, outcome: 'WROTE', writtenTo: fs.realpathSync(target) }
}

// Fixed: regular files only, the same allow-list as the fixed resolver,
// resolved against the destination's real path, the real folder checked
// before anything is created, and 'wx' so no existing path is overwritten.
export function fixedExtract(archive, destination) {
  const destinationReal = fs.realpathSync(destination)
  const outcomes = []
  for (const entry of readTar(archive)) outcomes.push(extractOneEntry(entry, destinationReal))
  return outcomes
}

// The archive the lab builds for itself. The absolute entry points into the
// lab's own temporary folder, never anywhere else on the machine.
export function buildLabArchive(fixture) {
  const absoluteName = fixture.labRoot.split(path.sep).join('/') + '/escaped-absolute.txt'
  return buildTar([
    { name: 'notes/hello.txt', type: 'file', content: 'archive file: hello' },
    { name: '../escaped-parent-steps.txt', type: 'file', content: 'LAB-ARCHIVE-MARKER: parent steps' },
    { name: absoluteName, type: 'file', content: 'LAB-ARCHIVE-MARKER: absolute name' },
    { name: 'up', type: 'symlink', linkTarget: '..' },
    { name: 'up/escaped-through-link.txt', type: 'file', content: 'LAB-ARCHIVE-MARKER: through a link' },
  ])
}

==== File 4 of 6: run-table.mjs ====
// run-table.mjs: usage: node run-table.mjs
// Builds the fixture, prints the canonical-path test table and the archive,
// URL parsing, strip and permission checks, then removes the fixture.
import { spawnSync } from 'node:child_process'
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { buildLabArchive, fixedExtract, flawedExtract } from './archive.mjs'
import { buildInputs, createFixture, decodeLikeUrlSearchParams, labelPath, removeFixture } from './fixture.mjs'
import { isInside, RESOLVERS } from './resolvers.mjs'

const LAB_CODE_FOLDER = path.dirname(fileURLToPath(import.meta.url))
const fixture = createFixture()
const label = (text) => labelPath(fixture, text)

function show(value) {
  return String(value).split('\u0000').join('(NUL)')
}

function line(name, value) {
  console.log('  ' + name.padEnd(30) + value)
}

function realPathOrNull(target) {
  try {
    return fs.realpathSync(target)
  } catch (error) {
    return null
  }
}

function describeResult(result) {
  if (result.verdict !== 'SERVED') return result.verdict + (result.detail ? ' (' + result.detail + ')' : '')
  const realPath = fs.realpathSync(result.servedPath)
  if (isInside(fixture.baseReal, realPath)) return 'served ' + label(realPath)
  return 'ESCAPED: served ' + label(realPath)
}

function printHeader() {
  console.log('PATH TRAVERSAL LAB: CANONICAL-PATH TEST TABLE')
  console.log('Node.js ' + process.version + ' on ' + process.platform + ' ' + process.arch)
  console.log('LAB stands for the absolute path of the temporary folder this run created.')
  console.log('The served folder (the base folder) is LAB/public.')
  console.log('Link inside the served folder: LAB/public/linked-folder, ' + fixture.link.note)
  console.log('Real path of LAB differs from the path the lab created: ' + (fixture.labRootReal !== fixture.labRoot ? 'yes' : 'no'))
  console.log('')
}

// Path targets show the URL parser's pathname; query targets show what
// URLSearchParams returns for the file parameter.
function printUrlParsingPart() {
  console.log('PART A. WHAT THE URL PARSER AND URLSearchParams DO BEFORE YOUR CODE SEES THE PATH')
  const targets = [
    '/files/readme.txt',
    '/files/../secret-marker.txt',
    '/files/%2e%2e/secret-marker.txt',
    '/files/..%2fsecret-marker.txt',
    '/files/..%5csecret-marker.txt',
    '/files/..\\secret-marker.txt',
    '/download?file=..%2fsecret-marker.txt',
    '/download?file=..%252fsecret-marker.txt',
  ]
  for (const target of targets) {
    const url = new URL(target, 'http://lab.invalid')
    const fileParameter = url.searchParams.get('file')
    const parsed = fileParameter === null ? 'pathname ' + url.pathname : 'file parameter ' + fileParameter
    console.log('  ' + target.padEnd(42) + parsed)
  }
  console.log('')
}

function printInputRow(input) {
  console.log(input.id + '  ' + input.label)
  if (input.needsLink && !fixture.link.created) {
    line('skipped', 'the folder link could not be created on this system')
    console.log('')
    return
  }
  const decoded = decodeLikeUrlSearchParams(input.sent)
  const resolvedPath = path.resolve(fixture.base, decoded)
  const realPath = realPathOrNull(resolvedPath)
  const inside = realPath ? isInside(fixture.baseReal, realPath) : isInside(fixture.base, resolvedPath)
  line('sent in the query string', label(input.sent))
  line('decoded by URLSearchParams', show(label(decoded)))
  line('path.join(base, value)', show(label(path.join(fixture.base, decoded))))
  line('path.resolve(base, value)', show(label(resolvedPath)))
  if (input.id === 'R8') line('path.win32.resolve, as text', path.win32.resolve('C:\\lab\\public', decoded))
  line('real path after links', realPath ? label(realPath) : 'none: no such file')
  line('inside LAB/public', (inside ? 'yes' : 'no') + (realPath ? '' : ', judged by the resolved path'))
  line('startsWith(base) check', resolvedPath.startsWith(fixture.base) ? 'passes' : 'fails')
  for (const name of Object.keys(RESOLVERS)) {
    const resolver = RESOLVERS[name]
    line(name, describeResult(resolver(fixture, decoded)))
  }
  console.log('')
}

function printStripPart() {
  console.log('PART C. WHY REMOVING ../ FROM THE INPUT IS NOT A FIX')
  for (const input of ['....//secret-marker.txt', '.../...//secret-marker.txt']) {
    const stripped = input.split('../').join('')
    const resolvedPath = path.resolve(fixture.base, stripped)
    console.log('  ' + input.padEnd(30) + 'after one pass: ' + stripped.padEnd(22) + 'resolves to ' + label(resolvedPath))
  }
  console.log('')
}

function listLabRoot() {
  return fs.readdirSync(fixture.labRoot).sort()
}

function printExtraction(name, destination, extract) {
  const before = listLabRoot()
  const outcomes = extract(destination)
  console.log('  ' + name + ' extracting into ' + label(destination))
  for (const item of outcomes) {
    const where = item.writtenTo ? ' ' + label(item.writtenTo) : ''
    console.log('    ' + label(item.name).padEnd(30) + item.outcome + where)
  }
  const added = listLabRoot().filter((entry) => !before.includes(entry))
  console.log('    new files in LAB, outside the destination: ' + (added.length ? added.join(', ') : 'none'))
}

function printArchivePart() {
  console.log('PART D. ARCHIVE EXTRACTION (an uncompressed ustar archive the lab builds itself)')
  const archive = buildLabArchive(fixture)
  console.log('  archive size: ' + archive.length + ' bytes')
  const flawedFolder = path.join(fixture.labRoot, 'extract-flawed')
  const fixedFolder = path.join(fixture.labRoot, 'extract-fixed')
  printExtraction('flawedExtract', flawedFolder, (folder) => flawedExtract(fixture, archive, folder))
  printExtraction('fixedExtract', fixedFolder, (folder) => fixedExtract(archive, folder))
  console.log('')
}

function printPermissionPart() {
  console.log('PART E. THE SAME BARE JOIN UNDER THE NODE.JS PERMISSION MODEL')
  console.log('  flags: --permission --allow-fs-read=LAB/public')
  const childPath = path.join(LAB_CODE_FOLDER, 'permission-child.mjs')
  const names = ['readme.txt', '../secret-marker.txt', '../public-archive/old-note.txt', 'linked-folder/secret-marker.txt']
  for (const name of names) {
    const flags = ['--permission', '--allow-fs-read=' + fixture.base, childPath, fixture.base, name]
    const child = spawnSync(process.execPath, flags, { encoding: 'utf8' })
    const output = (child.stdout || child.stderr || '').trim().split('\n')[0]
    console.log('  ' + name.padEnd(36) + output)
  }
  console.log('')
}

printHeader()
printUrlParsingPart()
console.log('PART B. CANONICAL-PATH TEST TABLE')
console.log('')
for (const input of buildInputs(fixture)) printInputRow(input)
printStripPart()
printArchivePart()
printPermissionPart()
console.log('Temporary folder removed: ' + (removeFixture(fixture) ? 'yes' : 'no'))

==== File 5 of 6: permission-child.mjs ====
// permission-child.mjs: usage: node permission-child.mjs BASE NAME
// A bare join with no checks at all. run-table.mjs starts it under the
// Node.js permission model, allowed to read BASE only, to see which reads
// the model stops. It only reads; it never writes.
import fs from 'node:fs'
import path from 'node:path'

const base = process.argv[2]
const requested = process.argv[3]

try {
  const content = fs.readFileSync(path.join(base, requested), 'utf8')
  console.log('READ ' + content.split(':')[0])
} catch (error) {
  console.log('REFUSED ' + (error.code || error.message))
}

==== File 6 of 6: traversal.test.mjs ====
// traversal.test.mjs: a regression test for the variant LAB_VARIANT names:
// fixed (the default), flawedJoin or flawedResolve. It asserts that every
// file served or extracted has a real path inside its intended folder, so it
// passes for the fixed resolver and extractor and fails for the flawed ones.
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import { after, test } from 'node:test'
import { buildLabArchive, fixedExtract, flawedExtract } from './archive.mjs'
import { buildInputs, createFixture, decodeLikeUrlSearchParams, labelPath, removeFixture } from './fixture.mjs'
import { fixedResolve, flawedJoin, flawedResolve, isInside } from './resolvers.mjs'

const VARIANTS = {
  fixed: { resolve: fixedResolve, extract: (fixture, archive, folder) => fixedExtract(archive, folder) },
  flawedJoin: { resolve: flawedJoin, extract: flawedExtract },
  flawedResolve: { resolve: flawedResolve, extract: flawedExtract },
}
const variantName = process.env.LAB_VARIANT || 'fixed'
const variant = VARIANTS[variantName]
const fixture = createFixture()
after(() => removeFixture(fixture))

for (const input of buildInputs(fixture)) {
  const skip = input.needsLink && !fixture.link.created ? fixture.link.note : false
  test(input.id + ' ' + input.label + ': anything served is inside LAB/public', { skip }, () => {
    const result = variant.resolve(fixture, decodeLikeUrlSearchParams(input.sent))
    if (input.expected) {
      assert.equal(result.verdict, 'SERVED')
      assert.equal(result.content, input.expected)
    }
    if (result.verdict !== 'SERVED') return
    const realPath = fs.realpathSync(result.servedPath)
    assert.ok(isInside(fixture.baseReal, realPath), variantName + ' served ' + labelPath(fixture, realPath))
  })
}

test('archive: every file written is inside the destination', () => {
  const destination = path.join(fixture.labRoot, 'extract-test')
  fs.mkdirSync(destination)
  const destinationReal = fs.realpathSync(destination)
  const outcomes = variant.extract(fixture, buildLabArchive(fixture), destination)
  for (const item of outcomes) {
    if (item.outcome !== 'WROTE') continue
    assert.ok(isInside(destinationReal, item.writtenTo), variantName + ' wrote ' + labelPath(fixture, item.writtenTo))
  }
  const escaped = fs.readdirSync(fixture.labRoot).filter((name) => name.startsWith('escaped-'))
  assert.deepEqual(escaped, [])
  assert.equal(fs.readFileSync(path.join(destination, 'notes', 'hello.txt'), 'utf8'), 'archive file: hello')
})

==== RUN IT ====
node run-table.mjs
node --test traversal.test.mjs
LAB_VARIANT=flawedJoin node --test traversal.test.mjs
LAB_VARIANT=flawedResolve node --test traversal.test.mjs

==== OUTPUT OF node run-table.mjs (Node.js v26.0.0, macOS 27.2.1 (arm64)) ====
PATH TRAVERSAL LAB: CANONICAL-PATH TEST TABLE
Node.js v26.0.0 on darwin arm64
LAB stands for the absolute path of the temporary folder this run created.
The served folder (the base folder) is LAB/public.
Link inside the served folder: LAB/public/linked-folder, symbolic link to ..
Real path of LAB differs from the path the lab created: yes

PART A. WHAT THE URL PARSER AND URLSearchParams DO BEFORE YOUR CODE SEES THE PATH
  /files/readme.txt                         pathname /files/readme.txt
  /files/../secret-marker.txt               pathname /secret-marker.txt
  /files/%2e%2e/secret-marker.txt           pathname /secret-marker.txt
  /files/..%2fsecret-marker.txt             pathname /files/..%2fsecret-marker.txt
  /files/..%5csecret-marker.txt             pathname /files/..%5csecret-marker.txt
  /files/..\secret-marker.txt               pathname /secret-marker.txt
  /download?file=..%2fsecret-marker.txt     file parameter ../secret-marker.txt
  /download?file=..%252fsecret-marker.txt   file parameter ..%2fsecret-marker.txt

PART B. CANONICAL-PATH TEST TABLE

R1  plain file name
  sent in the query string      readme.txt
  decoded by URLSearchParams    readme.txt
  path.join(base, value)        LAB/public/readme.txt
  path.resolve(base, value)     LAB/public/readme.txt
  real path after links         LAB/public/readme.txt
  inside LAB/public             yes
  startsWith(base) check        passes
  flawedJoin                    served LAB/public/readme.txt
  flawedResolve                 served LAB/public/readme.txt
  fixedResolve                  served LAB/public/readme.txt

R2  file in a subfolder
  sent in the query string      docs/guide.txt
  decoded by URLSearchParams    docs/guide.txt
  path.join(base, value)        LAB/public/docs/guide.txt
  path.resolve(base, value)     LAB/public/docs/guide.txt
  real path after links         LAB/public/docs/guide.txt
  inside LAB/public             yes
  startsWith(base) check        passes
  flawedJoin                    served LAB/public/docs/guide.txt
  flawedResolve                 served LAB/public/docs/guide.txt
  fixedResolve                  served LAB/public/docs/guide.txt

R3  parent-directory steps
  sent in the query string      ../secret-marker.txt
  decoded by URLSearchParams    ../secret-marker.txt
  path.join(base, value)        LAB/secret-marker.txt
  path.resolve(base, value)     LAB/secret-marker.txt
  real path after links         LAB/secret-marker.txt
  inside LAB/public             no
  startsWith(base) check        fails
  flawedJoin                    ESCAPED: served LAB/secret-marker.txt
  flawedResolve                 ESCAPED: served LAB/secret-marker.txt
  fixedResolve                  REJECTED (segment not on the allow-list)

R4  encoded separator, single
  sent in the query string      ..%2fsecret-marker.txt
  decoded by URLSearchParams    ../secret-marker.txt
  path.join(base, value)        LAB/secret-marker.txt
  path.resolve(base, value)     LAB/secret-marker.txt
  real path after links         LAB/secret-marker.txt
  inside LAB/public             no
  startsWith(base) check        fails
  flawedJoin                    ESCAPED: served LAB/secret-marker.txt
  flawedResolve                 ESCAPED: served LAB/secret-marker.txt
  fixedResolve                  REJECTED (segment not on the allow-list)

R5  encoded separator, double
  sent in the query string      ..%252fsecret-marker.txt
  decoded by URLSearchParams    ..%2fsecret-marker.txt
  path.join(base, value)        LAB/public/..%2fsecret-marker.txt
  path.resolve(base, value)     LAB/public/..%2fsecret-marker.txt
  real path after links         none: no such file
  inside LAB/public             yes, judged by the resolved path
  startsWith(base) check        passes
  flawedJoin                    ESCAPED: served LAB/secret-marker.txt
  flawedResolve                 NOT FOUND (ENOENT)
  fixedResolve                  REJECTED (segment not on the allow-list)

R6  encoded dots, single
  sent in the query string      %2e%2e/secret-marker.txt
  decoded by URLSearchParams    ../secret-marker.txt
  path.join(base, value)        LAB/secret-marker.txt
  path.resolve(base, value)     LAB/secret-marker.txt
  real path after links         LAB/secret-marker.txt
  inside LAB/public             no
  startsWith(base) check        fails
  flawedJoin                    ESCAPED: served LAB/secret-marker.txt
  flawedResolve                 ESCAPED: served LAB/secret-marker.txt
  fixedResolve                  REJECTED (segment not on the allow-list)

R7  encoded dots, double
  sent in the query string      %252e%252e/secret-marker.txt
  decoded by URLSearchParams    %2e%2e/secret-marker.txt
  path.join(base, value)        LAB/public/%2e%2e/secret-marker.txt
  path.resolve(base, value)     LAB/public/%2e%2e/secret-marker.txt
  real path after links         none: no such file
  inside LAB/public             yes, judged by the resolved path
  startsWith(base) check        passes
  flawedJoin                    ESCAPED: served LAB/secret-marker.txt
  flawedResolve                 NOT FOUND (ENOENT)
  fixedResolve                  REJECTED (segment not on the allow-list)

R8  encoded backslash
  sent in the query string      ..%5csecret-marker.txt
  decoded by URLSearchParams    ..\secret-marker.txt
  path.join(base, value)        LAB/public/..\secret-marker.txt
  path.resolve(base, value)     LAB/public/..\secret-marker.txt
  path.win32.resolve, as text   C:\lab\secret-marker.txt
  real path after links         none: no such file
  inside LAB/public             yes, judged by the resolved path
  startsWith(base) check        passes
  flawedJoin                    NOT FOUND (ENOENT)
  flawedResolve                 NOT FOUND (ENOENT)
  fixedResolve                  REJECTED (segment not on the allow-list)

R9  absolute path
  sent in the query string      LAB/secret-marker.txt
  decoded by URLSearchParams    LAB/secret-marker.txt
  path.join(base, value)        LAB/public/LAB/secret-marker.txt
  path.resolve(base, value)     LAB/secret-marker.txt
  real path after links         LAB/secret-marker.txt
  inside LAB/public             no
  startsWith(base) check        fails
  flawedJoin                    NOT FOUND (ENOENT)
  flawedResolve                 ESCAPED: served LAB/secret-marker.txt
  fixedResolve                  REJECTED (absolute path)

R10  sibling folder passes a prefix check
  sent in the query string      ../public-archive/old-note.txt
  decoded by URLSearchParams    ../public-archive/old-note.txt
  path.join(base, value)        LAB/public-archive/old-note.txt
  path.resolve(base, value)     LAB/public-archive/old-note.txt
  real path after links         LAB/public-archive/old-note.txt
  inside LAB/public             no
  startsWith(base) check        passes
  flawedJoin                    ESCAPED: served LAB/public-archive/old-note.txt
  flawedResolve                 ESCAPED: served LAB/public-archive/old-note.txt
  fixedResolve                  REJECTED (segment not on the allow-list)

R11  symbolic link inside the folder
  sent in the query string      linked-folder/secret-marker.txt
  decoded by URLSearchParams    linked-folder/secret-marker.txt
  path.join(base, value)        LAB/public/linked-folder/secret-marker.txt
  path.resolve(base, value)     LAB/public/linked-folder/secret-marker.txt
  real path after links         LAB/secret-marker.txt
  inside LAB/public             no
  startsWith(base) check        passes
  flawedJoin                    ESCAPED: served LAB/secret-marker.txt
  flawedResolve                 ESCAPED: served LAB/secret-marker.txt
  fixedResolve                  REJECTED (real path is outside the base folder)

R12  encoded NUL byte
  sent in the query string      readme.txt%00.pdf
  decoded by URLSearchParams    readme.txt(NUL).pdf
  path.join(base, value)        LAB/public/readme.txt(NUL).pdf
  path.resolve(base, value)     LAB/public/readme.txt(NUL).pdf
  real path after links         none: no such file
  inside LAB/public             yes, judged by the resolved path
  startsWith(base) check        passes
  flawedJoin                    ERROR (ERR_INVALID_ARG_VALUE)
  flawedResolve                 ERROR (ERR_INVALID_ARG_VALUE)
  fixedResolve                  REJECTED (control character)

PART C. WHY REMOVING ../ FROM THE INPUT IS NOT A FIX
  ....//secret-marker.txt       after one pass: ../secret-marker.txt  resolves to LAB/secret-marker.txt
  .../...//secret-marker.txt    after one pass: ../secret-marker.txt  resolves to LAB/secret-marker.txt

PART D. ARCHIVE EXTRACTION (an uncompressed ustar archive the lab builds itself)
  archive size: 5632 bytes
  flawedExtract extracting into LAB/extract-flawed
    notes/hello.txt               WROTE LAB/extract-flawed/notes/hello.txt
    ../escaped-parent-steps.txt   WROTE LAB/escaped-parent-steps.txt
    LAB/escaped-absolute.txt      WROTE LAB/escaped-absolute.txt
    up                            CREATED A LINK to .. at LAB/extract-flawed/up
    up/escaped-through-link.txt   WROTE LAB/escaped-through-link.txt
    new files in LAB, outside the destination: escaped-absolute.txt, escaped-parent-steps.txt, escaped-through-link.txt
  fixedExtract extracting into LAB/extract-fixed
    notes/hello.txt               WROTE LAB/extract-fixed/notes/hello.txt
    ../escaped-parent-steps.txt   REJECTED: segment not on the allow-list
    LAB/escaped-absolute.txt      REJECTED: absolute path
    up                            REJECTED: not a regular file
    up/escaped-through-link.txt   WROTE LAB/extract-fixed/up/escaped-through-link.txt
    new files in LAB, outside the destination: none

PART E. THE SAME BARE JOIN UNDER THE NODE.JS PERMISSION MODEL
  flags: --permission --allow-fs-read=LAB/public
  readme.txt                          READ public file
  ../secret-marker.txt                REFUSED ERR_ACCESS_DENIED
  ../public-archive/old-note.txt      REFUSED ERR_ACCESS_DENIED
  linked-folder/secret-marker.txt     READ LAB-SECRET-MARKER

Temporary folder removed: yes
run-table exit code: 0

==== OUTPUT OF node --test traversal.test.mjs (Node.js v26.0.0, macOS 27.2.1 (arm64)) ====
✔ R1 plain file name: anything served is inside LAB/public (1.403916ms)
✔ R2 file in a subfolder: anything served is inside LAB/public (0.21525ms)
✔ R3 parent-directory steps: anything served is inside LAB/public (0.060416ms)
✔ R4 encoded separator, single: anything served is inside LAB/public (0.060833ms)
✔ R5 encoded separator, double: anything served is inside LAB/public (0.045375ms)
✔ R6 encoded dots, single: anything served is inside LAB/public (0.036292ms)
✔ R7 encoded dots, double: anything served is inside LAB/public (0.045875ms)
✔ R8 encoded backslash: anything served is inside LAB/public (0.046042ms)
✔ R9 absolute path: anything served is inside LAB/public (0.059959ms)
✔ R10 sibling folder passes a prefix check: anything served is inside LAB/public (0.094834ms)
✔ R11 symbolic link inside the folder: anything served is inside LAB/public (0.114958ms)
✔ R12 encoded NUL byte: anything served is inside LAB/public (0.037917ms)
✔ archive: every file written is inside the destination (1.98575ms)
ℹ tests 13
ℹ suites 0
ℹ pass 13
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 88.594833
exit code: 0

==== REGRESSION TEST RESULTS FOR ALL THREE VARIANTS ====
The counts and exit codes are copied from each run's summary lines. Each failure message below was followed by a stack trace naming a local file path, cut here.
LAB_VARIANT              tests  pass   fail   exit code
fixed (default)          13     13     0      0
flawedJoin               13     5      8      1
flawedResolve            13     6      7      1

Failure messages, in order, without repeats:
flawedJoin:
  AssertionError [ERR_ASSERTION]: flawedJoin served LAB/secret-marker.txt
  AssertionError [ERR_ASSERTION]: flawedJoin served LAB/public-archive/old-note.txt
  AssertionError [ERR_ASSERTION]: flawedJoin wrote LAB/escaped-parent-steps.txt
flawedResolve:
  AssertionError [ERR_ASSERTION]: flawedResolve served LAB/secret-marker.txt
  AssertionError [ERR_ASSERTION]: flawedResolve served LAB/public-archive/old-note.txt
  AssertionError [ERR_ASSERTION]: flawedResolve wrote LAB/escaped-parent-steps.txt

==== READING THE TABLE ====
sent in the query string: the value exactly as the request carried it.
decoded by URLSearchParams: what URLSearchParams returned for the file parameter, which is what a request handler receives. (NUL) stands for a NUL character.
path.join and path.resolve: what each function returned for that value. Neither opens a file.
real path after links: fs.realpathSync() of the path.resolve() result, or "none" when no such file exists.
inside LAB/public: whether that real path sits below the base folder's real path, using isInside() from resolvers.mjs. Where no file exists, the resolved path is judged instead.
startsWith(base) check: what a plain prefix comparison of the resolved path with the base folder's path would have said. Compare it with the line above.
flawedJoin, flawedResolve, fixedResolve: what each resolver did. ESCAPED means it served a file whose real path is outside LAB/public. NOT FOUND and ERROR mean nothing was served. REJECTED means the resolver refused before opening anything, and names the check that refused it.

==== WHAT WAS NOT TESTED ====
The lab ran on macOS only. On Windows the path functions treat a backslash as a separator, so the R8 input could behave like R3 there; the table shows path.win32.resolve() only as text, computed on macOS against a made-up base, C:\lab\public. Drive-letter paths, UNC paths, the NT device namespace, the junction fallback for the link and Windows' handling of trailing dots and spaces were not tested. Case variants of file names were not tested on any system.

==== USING THE TEST ON YOUR OWN CODE ====
1. Find each place your code builds a file path from a request: downloads by name, template, theme or language selectors, image resizers, log viewers, backup and export features, upload handlers and archive imports. Include values your application stored earlier and reads back.
2. Wrap each one in a function shaped like the resolvers above: it takes the value your handler receives and returns what it served.
3. Copy fixture.mjs, resolvers.mjs, archive.mjs and traversal.test.mjs, add your function to VARIANTS in the test, and run it with LAB_VARIANT set to its name. Keep the assertion: any file served or written has a real path inside its intended folder.
4. Add rows for the names your feature really accepts, such as a real invoice number, so the test also shows when validation is stricter than it needs to be.
5. Keep the test in your suite, so a later change that loosens the check fails a build instead of reaching production.

What path traversal is

Path traversal, also called directory traversal, is what happens when an application builds a file path from part of a request and the request decides where that path ends up.

OWASP's Path Traversal page describes an attack that aims to access files and directories stored outside the web root folder, by manipulating variables that reference files with dot-dot-slash (../) sequences and their variations, or by using absolute file paths. It also lists dot-dot-slash, directory climbing and backtracking as names for the same attack.

MITRE catalogues the weakness as CWE-22, Improper Limitation of a Pathname to a Restricted Directory. The product uses external input to construct a pathname meant to identify a file or directory underneath a restricted parent directory, but does not properly neutralise special elements that can make the pathname resolve to a location outside it.

CWE-22 calls the ../ form relative path traversal, catalogued as CWE-23, and the use of an absolute pathname such as /usr/local/bin absolute path traversal, catalogued as CWE-36.

The consequences CWE-22 lists run in both directions. An attacker may be able to read unexpected files and expose sensitive data, create or overwrite critical files such as programs, libraries or important data, or delete and corrupt files so the product stops working.

Writing can go further: CWE-22 lists executing unauthorised code among its consequences, where the attacker may be able to create or overwrite critical files that are used to execute code, such as programs or libraries.

In the standards, OWASP's Top 10:2025 lists CWE-22, CWE-23, CWE-36 and CWE-59, the link-following weakness this guide returns to below, among the CWEs mapped to A01:2025 Broken Access Control. ASVS 5.0 requirement 5.3.2, a Level 1 requirement, asks that when the application creates file paths for file operations, it uses internally generated or trusted data instead of user-submitted file names, or applies strict validation and sanitisation where user-submitted file names or file metadata must be used, to protect against path traversal, local or remote file inclusion and server-side request forgery.

This guide covers one thing: a file path built from input, how a name or path supplied by a user ends up outside the folder the code meant, and how to test that yours stays inside it. What an upload may contain and where the server keeps it is the subject of the file upload security guide in this library.

Where path traversal hides in an ordinary application

Any feature that turns part of a request into a file name is a candidate.

The WSTG test for this flaw, WSTG-ATHZ-01, notes that many web applications use server-side scripts to include different kinds of files, and calls it quite common to use this method to manage images, templates and static texts.

Such applications are exposed, it says, if input parameters such as form parameters and cookie values are not correctly validated. Its first stage is to enumerate every part of the application that accepts content from the user, including GET and POST queries, file uploads and HTML forms, and to ask whether a request parameter could be used for a file operation and whether cookies drive the dynamic generation of pages or templates.

These are the features to look for in your own application:

  • Downloads by file name: an invoice, report or document fetched as download?file=invoice-17.pdf, where the value is joined onto a folder.
  • Template, theme and language selectors. OWASP's advice for templating and language files is to use indexes rather than portions of file names, and CWE-22's observed examples include a case where external control of a user's desired language and theme enables path traversal.
  • Image resizers and thumbnail endpoints that read an original image by name.
  • Log viewers and admin screens that show a file chosen from a list.
  • Backup, export and report features that write a file whose name or folder comes from the request.
  • Upload handlers that keep the name the browser sent. CWE-22's fifth example is a Java upload servlet that writes to its upload folder using the file name from the request, which it says lets ../ sequences write files outside the intended directory.
  • Archive imports, where every entry in a zip or tar file carries its own path. They have their own section below.
  • Values the application stored earlier and reads back. The WSTG says path traversal strings may be inserted when the application adds data to the database, and that the problem is difficult to discover because the parameters inside the inclusion functions seem internal and safe.

The two conditions that make it a flaw

CWE-73, External Control of File Name or Path, reduces all of these to two conditions: an attacker can specify a path used in an operation on the file system, and by specifying the resource, the attacker gains a capability that would not otherwise be permitted.

The WSTG adds the condition on the other side: the attack works only if the validation checkpoint fails and, according to the file system privileges, the web application itself is able to read the file. Both halves matter, and the sections below deal with each.

Why stripping ../ from the input is not a fix

The tempting fix is to remove ../ from the value and carry on.

CWE-22 warns against relying exclusively on a filter that removes potentially dangerous characters, because that is equivalent to a denylist, which may be incomplete. Its example: if ../ sequences are removed from the string .../...// in a sequential fashion, two instances are removed and the remaining characters still form ../.

The WSTG describes the same pattern from the tester's side. Some developers try to change invalid input to make it valid, it says, these functions are usually prone to security flaws, and it tests a filter that replaces a parent-directory sequence with nothing using values such as ....//.

Part C of the lab on this page runs both strings through a single pass that removes every ../ it finds. Each came out as ../secret-marker.txt, which resolves to the marker file one level above the served folder. OWASP's own guidance on the Path Traversal page is to validate the input by only accepting known good, and not to sanitise it.

Encoded separators and dots

Encoding changes where the dots and slashes appear, not whether they arrive. 1 min read

What the URL parser decides before your code runs

Some of this happens before your handler sees anything. 1 min read

Windows separators

CWE-22 points out that filtering / is insufficient if the file system also supports \ as a separator. 1 min read

Canonical path validation: check the final path

The check that holds is made on the path the file system will open, not on the text that arrived.

CWE-22 recommends a built-in path canonicalisation function, such as realpath() in C, that produces the canonical version of the pathname, which effectively removes .. sequences and symbolic links. In Node.js that is fs.realpath(), which its documentation says computes the canonical pathname by resolving ., .. and symbolic links.

Resolve the requested value against your base folder, take the real path of the result, and accept it only if it sits inside the real path of the base folder.

What the Node.js path functions do and do not do

The node:path functions build and tidy path strings, and each answers a narrower question than "is this inside my folder". path.join() joins its segments with the platform separator and then normalises the result. path.resolve() processes its arguments from right to left, prepending each until it has an absolute path, so an absolute value replaces whatever came before it. path.normalize() resolves .. and . segments, and its documentation warns that on POSIX, substitutions such as removing .. segments may change how the underlying system resolves the path. path.isAbsolute() determines whether the literal path is absolute, and the documentation says it is therefore not safe for mitigating path traversals. path.relative() returns the relative path from one path to another, based on the current working directory. 1 min read

A prefix check is not containment

Checking that the resolved path starts with the base folder's path fails in two ways the lab shows. 1 min read

Resolve symbolic links before you check

CWE-59, Improper Link Resolution Before File Access, covers code that accesses a file by name without preventing that name from identifying a link or shortcut that resolves to an unintended resource. 1 min read

Keep the check and the open together

A check and an open are two separate steps. 1 min read

Path traversal prevention, strongest measure first

The lab's fixedResolve puts several of these in one function, but the first two remove the problem rather than checking for it, and they are worth reaching for before any check.

  • Keep request data out of file paths. OWASP's first protection is to prefer working without user input when using file system calls, and the WSTG's remediation for file inclusion calls avoiding user-submitted input in any filesystem or framework API the most effective solution. Store each file under a name your code generates.
  • Map an identifier to a file. Under enforcement by conversion, CWE-22 says that when the set of acceptable objects such as file names is limited or known, map fixed input values such as numeric IDs to the actual file names and reject all other inputs. A language selector that sends 5 and looks up the file in a table never handles a file name at all.
  • Where a name must come from the request, accept known good. For file names CWE-22 advises a stringent allowlist that limits the character set, only a single dot where feasible, no directory separators and a list of allowable file extensions. The lab allows subfolders, so it applies that pattern to each segment between slashes and rejects a leading slash and control characters.
  • Build the path around the value. OWASP's guidance is to ensure the user cannot supply all parts of the path, surrounding it with your own path code. The base folder is a constant in your code, not a value read from the request.
  • Decode once, then validate, and never decode again after the check, as CWE-22 advises.
  • Resolve, check, then open what you checked: resolve against the base folder's real path, take fs.realpath() of the result, confirm it is inside the base folder, and open that real path.
  • Keep what must not be served out of the served folder. OWASP says not to store sensitive configuration files inside the web root, and CWE-22 advises storing library, include and utility files outside the web document root where possible.
  • Say little in errors. CWE-22 notes that error messages which disclose path information can help attackers craft the attack strings to move through the file system. Return a plain not-found, and log the detail on the server.

What least privilege on the file system adds

Validation decides which path your code asks for.

File system permissions decide what the operating system hands over when the validation is wrong. The WSTG makes the dependency explicit: the attack depends on the web application itself being able to read the file. CWE-22's environment hardening advice is to run code with the lowest privileges required and, where possible, in isolated accounts used for a single task, so a successful attack does not immediately give the attacker the rest of the software or its environment.

For a file feature that means a process that can read the folder it serves and little else, can write only to the folders it writes, and does not own its own code. CWE-59 adds a reason specific to links: denying access to a file can prevent an attacker from replacing that file with a link to a sensitive file.

Sandboxes help less than they sound. CWE-22 rates a jail such as chroot, AppArmor or SELinux as limited in effectiveness, depending on the sandbox, and says it only limits the impact to the operating system.

What a whole process can reach, its user, container and secrets, is covered in the remote code execution guide in this library.

Node.js has its own backstop. Started with --permission, a process has its file system access through the fs module restricted, and --allow-fs-read and --allow-fs-write grant access back. Part E of the lab runs a bare join with no checks at all under --permission and --allow-fs-read=LAB/public.

The parent-directory and sibling-folder reads were refused with ERR_ACCESS_DENIED. The read through linked-folder succeeded, which is the limitation the documentation lists: symbolic links are followed even to locations outside the paths access has been granted to.

The documentation also says the permission model does not protect against malicious code. Treat it as a seat belt for code you trust, and keep the real-path check as the control.

Archive extraction and Zip Slip

An archive import is path traversal with the input inside a file.

Snyk, which published the research under the name Zip Slip, describes it as a form of directory traversal exploited by extracting files from an archive: a specially crafted archive holds directory traversal file names such as ../../evil.sh, and extraction code that omits validation on the file paths writes them outside the target folder.

Snyk lists tar, jar, war, cpio, apk, rar and 7z among the formats it can affect, says the attacker can overwrite executable or configuration files, and notes that archive creation tools do not typically allow users to add files with these paths, so a test archive has to be built on purpose.

MITRE lists Zip Slip as an alternate term under CWE-23 and CWE-59, and says it is most commonly used for relative path traversal and link following.

Two Level 3 requirements in ASVS 5.0 bear on it. Requirement 5.3.3 asks that server-side file processing, such as file decompression, ignores user-provided path information to prevent vulnerabilities such as zip slip. Requirement 5.2.5 asks that the application does not allow uploading compressed files containing symlinks unless this is specifically required, in which case an allowlist of the files that can be symlinked to is needed.

If you extract with a library, read what its documentation says about these cases, because defaults differ between libraries and versions. Python's tarfile documentation is one example. It says extracting a tar file can overwrite arbitrary files in various ways, for example through absolute paths, .. path components or symlinks that affect later members.

From Python 3.14 its default extraction filter is data, which strips leading slashes from member names and refuses any name that is still absolute, refuses files whose path after following symlinks would end up outside the destination, and refuses links that point to absolute paths or outside the destination; before 3.14 the default was equivalent to fully_trusted.

It also says none of the available filters blocks all dangerous archive features, and never to extract archives from untrusted sources without prior inspection.

Part D of the lab builds its own archive in the ustar format from the POSIX pax specification: 512-octet records, a header with the entry name as plain text, numbers stored in octal and a checksum that is the simple sum of the header's octets.

With no compression, a few lines of Buffer code write and read it exactly. flawedExtract, which resolves each name against its destination and creates links as the archive says, wrote three files outside its folder: one through ../, one through the absolute name and one through the link named up. fixedExtract refused the ../ name, the absolute name and the link, and wrote the other two entries inside its folder; with the link refused, the last entry landed in an ordinary folder named up.

The lab's fixed extractor keeps the folders inside an archive when every check passes; requirement 5.3.3 at Level 3 goes further and asks for user-provided path information to be ignored altogether.

Local file inclusion and path traversal

The WSTG's file inclusion test defines local file inclusion (LFI) as the process of including files that are already locally present on the server, through vulnerable inclusion procedures implemented in the application.

It occurs, for example, when a page receives as input the path to the file to be included and the input is not properly sanitised, allowing directory traversal characters such as dot-dot-slash to be injected. Depending on the case, the WSTG says file inclusion can lead from outputting the contents of a file to code execution on the web server.

MITRE's CWE-98 covers the PHP form of the weakness, input used without proper restriction in require, include or similar functions, and lists local file inclusion as a common name for cases where remote download is disabled or the first part of the file name is not under the attacker's control, which it says forces use of relative path traversal (CWE-23) techniques.

Path traversal is the route; inclusion is what the application then does with the file it reached, and reading returns the contents where including or rendering it may run them.

The WSTG's remediation is the same as for any file path: avoid passing user-submitted input to any filesystem or framework API, and where that is not possible, keep an allow list of files that may be included and select one with an identifier such as an index number, rejecting any request with an invalid identifier.

In a Node.js application, ask the same question of any module, template or view whose name comes from a request.

When the path is an object storage key

Files kept in object storage change the shape of the problem.

Amazon's S3 documentation describes its data model as a flat structure: a bucket stores objects, there is no hierarchy of subbuckets or subfolders, and the console and SDKs infer folders from key name prefixes and the / delimiter.

A ../ inside a key does not climb out of a folder on a disk, because there is no folder to climb out of. The boundary becomes the key your code builds: if one customer's files share a prefix, a key assembled from that prefix and a name from the request reaches whichever object the resulting text names, so the check moves to the final key and to who may read that prefix.

Dot segments still matter at the edges. The same documentation says keys containing relative path elements such as ../ are valid if, parsed left to right, the count of relative segments never exceeds the non-relative elements before them; that keys with period-only segments can cause unexpected behaviour in applications, SDKs or tools that interpret them as relative path references; and it recommends avoiding period-only path segments in key names.

Code that copies objects to a local disk, by syncing a bucket or unpacking an export, builds file paths from keys, and the rest of this guide applies to it.

Path traversal testing in code and on a running build

WSTG-ATHZ-01 sets two objectives: identify the injection points that pertain to path traversal, and assess bypassing techniques and the extent of the traversal.

It works in two stages: a systematic evaluation of each input vector, then a methodical evaluation of each attack technique.

In code, the WSTG's grey-box advice is to search for inclusion functions and file system operations. Its examples cover PHP, JSP and ASP, so for a Node.js code base add the calls this guide has covered: every fs call that reads, streams, writes or deletes a file, every path.join() or path.resolve() that takes a value from a request, and any archive extraction.

Trace each value back to the request, a cookie or a stored record. CWE-22 rates automated static analysis as high in effectiveness for this weakness, and notes that tuning or customisation may be needed to remove or de-prioritise path traversal problems that only the product's administrator or other privileged users can exploit.

Against a running build, use the lab's method: a marker file you placed yourself, inputs that can only reach that marker, and only an application you own or are authorised in writing to test. The WSTG's own examples request well-known system files; proving the flaw does not need them.

Then keep the case in a regression test like traversal.test.mjs, asserting that anything served or written has a real path inside its intended folder.

Some neighbouring questions have their own guides in this library. A secure code review traces these values across a whole code base. Backups, repository metadata and other files that should never sit in a served folder are a security misconfiguration question. What an escaped read exposes is covered by the sensitive data exposure guide. A file name or working directory handed to another program is also a command injection question.

Walking through the canonical-path lab

The lab is an illustration written for this page, not a client's code.

It creates one temporary folder, serves LAB/public from it, places a marker file one level above, a sibling folder whose name starts with public, and a link inside the served folder that points to the folder above.

Every path it prints says LAB in place of the temporary folder's location, because that location changes on every run. It needs Node.js and nothing else, and the outputs were recorded on Node.js v26.0.0 on macOS.

Three resolvers receive the same twelve inputs, each after the one percent-decode URLSearchParams performs on a query string value. flawedJoin decodes again and uses path.join(). flawedResolve uses path.resolve(). fixedResolve rejects control characters, absolute paths and anything outside its allow-list, resolves against the base folder's real path, checks, resolves links, checks again and only then opens the file.

For each input the table prints what the path functions returned, the real path, whether that real path is inside LAB/public, what a startsWith check would have said, and what each resolver did.

What the table showed

Both flawed resolvers served the two ordinary files and escaped on the parent-directory steps, the single-encoded rows, the sibling folder and the link. flawedJoin also escaped on both double-encoded rows, because of its second decode, but not on the absolute path. flawedResolve escaped on the absolute path but not on the double-encoded rows.

Neither escaped on the encoded backslash, which is an ordinary character in a macOS file name. fixedResolve served the two ordinary files and refused the other ten inputs: nine at its first checks for control characters, absolute paths and the allow-list, and the link only at the real-path check.

The NUL byte row never reached a file in any resolver: both flawed ones failed with ERR_INVALID_ARG_VALUE when Node.js was handed a path containing a NUL character, and fixedResolve rejected it as a control character.

The regression test

traversal.test.mjs runs thirteen checks against the variant LAB_VARIANT names: one per input, asserting that anything served has a real path inside LAB/public, and one for the archive, asserting that nothing is written outside the destination and the ordinary entry arrives.

The fixed variant passed all thirteen. flawedJoin failed eight and flawedResolve failed seven, each failure naming the file that escaped, and both runs exited with code 1, which the Node.js test runner documentation says it sets when any test fails.

The lab was not run on Windows, so backslash separators, drive letters, UNC paths and the junction fallback for the link are untested there.

Where an outside test fits

The lab checks the file paths you already know about.

A review is for the ones you do not. A secure code review from Clever Ops follows the paths in scope with read-only access to the repository, looking at untrusted input along the way, and code findings are confirmed against a running build where the scope allows, with the report marking any that rest on the code alone.

A web application and API penetration test exercises the running application, file uploads are in scope, and read-only code access to named areas can be added to confirm how a control is enforced. If Clever Ops built or hosts your application, the work is a security review rather than an independent test, and the report says who built it and who hosts it.

Frequently asked questions

Yes, for practical purposes. OWASP's Path Traversal page says the attack is also known as directory traversal, and MITRE lists both as alternate terms for CWE-22, preferring "path traversal" and calling both terms attack-focused. CWE-22's terminology note adds that some people use "directory traversal" only for .. sequences, though absolute pathnames and drive letters have the effect of directory traversal.

No. path.normalize() resolves .. and . segments in the text, and path.join() joins and then normalises, so both can return a path outside your folder. In the lab, path.join() turned ../secret-marker.txt into the marker's path one level above the served folder. They are steps for building a path. The check comes after: take fs.realpath() of the result and confirm it sits inside the real path of your base folder.

Because a path can be inside your folder by its text and outside it on disk. In row R11 of the lab, path.resolve() returned a path inside the served folder, and fs.realpathSync() showed it pointed one level up, through a link. CWE-22 recommends a canonicalisation function such as realpath() because it removes .. sequences and symbolic links. Check the real path, then open the real path you checked.

They overlap. The WSTG defines local file inclusion as including files already present on the server through vulnerable inclusion procedures, and gives as an example a page that receives the path of the file to include as input, without proper sanitisation, so directory traversal characters such as dot-dot-slash can be injected. Path traversal is the route to the file; inclusion is what the application does with it, and including or rendering a file can run it where reading only returns its contents.

It changes it. Amazon's S3 documentation describes a flat structure with no folders, only key prefixes and a delimiter. That leaves no directory on a disk for a ../ in a key to climb out of. The same documentation says many systems resolve . and .. in keys, which can change the effective path. The check moves to the final key your code builds and to who may read each prefix. The same documentation recommends avoiding period-only segments in keys, because tools that treat them as relative paths can behave unexpectedly. Any code that copies objects to a disk builds file paths again.

Use a marker file you created yourself and inputs that can only reach it, as the lab on this page does, and test only an application you own or are authorised in writing to test. Then keep the case as a regression test that asserts anything served or written has a real path inside its intended folder, so a later change that loosens the check fails a build.

Scope the right test for your application

Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.