BackendBench
Coffee
Spot the Bug #117

A download that can reach any file

A medium Java puzzle in the security mistakes family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.

mediumSecurity mistakesbuggy line: 8

Highlighted: line 8. Play this one as a puzzle without the answer.

What is wrong

A filename like ../../etc/passwd resolves outside the base directory. Joining paths does not confine them. An attacker can read any file the process can access.

The fix

Path p = BASE.toPath().resolve(filename).normalize(); if (!p.startsWith(BASE.toPath())) throw new SecurityException("bad path");

How to avoid it next time

Normalize the resolved path and verify it still starts with the allowed directory, or accept only generated ids.

Want the background? Read NIO.2: Path and Files in practice in the Java concepts library.

About security mistakes

Predictable random numbers, secrets in source code, unvalidated file paths and weak hashes turn working features into vulnerabilities. They pass every functional test.

In code review: Search for java.util.Random in security contexts, literals that look like keys, paths built from user input, and MD5 or SHA-1 used for passwords.

More puzzles in this family

๐Ÿž Play today's puzzleAll 132 bugsโ† #116#118 โ†’

Frequently asked questions

What is the bug in "A download that can reach any file"?

A filename like ../../etc/passwd resolves outside the base directory. Joining paths does not confine them. An attacker can read any file the process can access. The faulty line is line 8: File f = new File(BASE, filename);

How do I fix it?

Replace it with: Path p = BASE.toPath().resolve(filename).normalize(); if (!p.startsWith(BASE.toPath())) throw new SecurityException("bad path");. Normalize the resolved path and verify it still starts with the allowed directory, or accept only generated ids.

How do I catch security mistakes in code review?

Search for java.util.Random in security contexts, literals that look like keys, paths built from user input, and MD5 or SHA-1 used for passwords.

Is there a new puzzle every day?

Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.

More tools you might need