Writeup of a practice box I run in my own lab network, a small web app with a "download your report" endpoint. The lesson is about the class of bug and how to fix it, not about the specific app.
The bug. The handler joined a base directory with a name taken straight from the query string and opened the result. A name containing .. path segments climbs out of the base directory, so the endpoint can be made to read files it was never meant to serve. That is path traversal, and it is the textbook example of trusting input that crosses a boundary.
Fixes that work, in order of preference:
- Do not accept paths. Accept an identifier (
report=42) and look the file up in a table you control. - If you must take a name, resolve it and check where it ended up:
from pathlib import Path
BASE = Path("/srv/reports").resolve()
def safe_open(name: str):
p = (BASE / name).resolve()
if not p.is_relative_to(BASE):
raise PermissionError("outside base directory")
return open(p, "rb")
- Run the service as a user that can only read that directory anyway, so a bug there does not become a bug everywhere.
What does not work: removing ../ from the string. ....// becomes ../ after one pass. Blocklists lose to encodings and to creativity. Resolve, then compare.
In the lab, the "flag" was a file outside the base directory. After the fix, the same request gets a 403 and a log line. Which is also the lesson about logging: the log line is the detection.