#71 · Errors and security

Find the bug · #71 · Errors and security Hard JavaScript

The download link can read any file

A download endpoint meant for uploaded files can be tricked into serving the server’s secrets.

On this page

The report

Bug report

Users download their uploaded files through /download?file=report.pdf. A bug-bounty report shows that /download?file=../config/secrets.env downloads the server’s secrets.

The code

Read it first: what should it do? Then click the line where you think the bug is.

JavaScriptClick the line you think is wrong
import path from 'node:path';

const UPLOADS = '/srv/app/uploads';

// The file on disk for a download link like /download?file=report.pdf
function fileFor(requested) {
  return path.join(UPLOADS, requested);
}

Read it, then pick a line.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
console.log(fileFor('report.pdf'));
try {
  console.log(fileFor('../config/secrets.env'));
} catch (e) {
  console.log('blocked: ' + e.message);
}

It prints

/srv/app/uploads/report.pdf
/srv/app/config/secrets.env

It should print

/srv/app/uploads/report.pdf
blocked: Not allowed
Show the answer: the bug, the fix, and how you’d find it

The bug (line 7)

Line 7 joins the requested name onto the uploads folder without checking where the result ends up. .. means “the folder above”, so ../config/secrets.env walks out of the uploads folder into the rest of the server. This is path traversal. Resolve the full path, then refuse anything that isn’t inside the uploads folder.

The fix

4 5// The file on disk for a download link like /download?file=report.pdf6function fileFor(requested) {7  return path.join(UPLOADS, requested);7  const full = path.resolve(UPLOADS, requested);8  if (!full.startsWith(UPLOADS + path.sep)) throw new Error('Not allowed');9  return full;8}

How you’d find it

  1. Reproduce with the reported link: the path comes out as /srv/app/config/secrets.env.
  2. path.join tidies up .., it doesn’t forbid it. Nothing checks that the result is still under UPLOADS.
  3. Check the tricky cases too: an absolute path, and a sibling folder whose name starts the same (uploads-old), which is why the check adds path.sep.

The test that catches it

It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.

assert.throws(() => fileFor('../../etc/passwd'));
assert.throws(() => fileFor('/etc/passwd'));
assert.throws(() => fileFor('../uploads-old/x.pdf'));
assert.equal(fileFor('a/b.pdf'), '/srv/app/uploads/a/b.pdf');

Where else this bites

  • Zip files with ../ in their entry names (“zip slip”).
  • Any API that takes a file name, template name or log name from the user.
Your progress stays on this device.