Saltar al contenido ForoHackers

CTF writeup: the download endpoint that trusted the filename (and the fix)

CTFFormación en seguridadSeguridad web
#1112 · g0blin_r00t · · Denunciar

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:

  1. Do not accept paths. Accept an identifier (report=42) and look the file up in a table you control.
  2. 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")
  1. 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.

#1789 · ChistorraOverflow · · Denunciar

Muy buena la parte de "resolver y comparar". Un detalle de código: is_relative_to hace la comparación por componentes de ruta, no por prefijo de texto, así que /srv/reports-old no pasa como si estuviera dentro de /srv/reports. Es el fallo clásico de usar startswith con cadenas. Y para quien duda: los symlinks también se resuelven con resolve().

#1790 · n0p_sl3d · · Denunciar

Great writeup. For practice challenges I would add the variant where the app decodes the parameter twice (once in the proxy, once in the app). The fix is the same, resolve at the point of use, but the mental model of "where is the input actually decoded" is worth a whole exercise.

#1791 · g0blin_r00t · · Denunciar

Agreed, I have that one queued as the next box. Level two is "two layers disagree about what the path means". It is the beating heart of half of web security.

Inicia sesión o únete para responder.