Files
romm/backend/utils/nginx.py
Georges-Antoine Assi 0abff94157 security: strip control characters from names reaching the mod_zip manifest
The mod_zip manifest that streams multi-file downloads is line-oriented, and
the NAME field of each record was interpolated from a rom file's full_path
verbatim. A line feed in that path would split the record and forge an extra
archive entry pointing at any internal nginx location.

sanitize_filename now drops the whole C0 range plus DEL instead of only null
bytes, so a control character cannot enter fs_name through a rename or an
upload. ZipContentLine scrubs the same range from the entry name, which is a
path and so cannot go through sanitize_filename, and rejects a location that
was not URL-encoded.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 11:17:52 -04:00

101 lines
3.4 KiB
Python

import dataclasses
from collections.abc import Collection
from pathlib import PurePath
from typing import Any
from urllib.parse import quote
from anyio import Path
from fastapi.responses import Response
from utils.filesystem import CONTROL_CHARS
@dataclasses.dataclass(frozen=True)
class ZipContentLine:
"""Dataclass for lines returned in the response body, for usage with the `mod_zip` module.
Reference:
https://github.com/evanmiller/mod_zip?tab=readme-ov-file#usage
"""
crc32: str | None
size_bytes: int
encoded_location: str
filename: str
def __post_init__(self) -> None:
"""Keep the rendered line parseable as exactly one mod_zip record.
The manifest is line-oriented, so a line feed in a name taken off disk
would otherwise let that name forge an extra archive entry.
"""
location = self.encoded_location
if " " in location or CONTROL_CHARS.search(location):
raise ValueError(f"mod_zip location must be URL-encoded, got {location!r}")
object.__setattr__(self, "filename", CONTROL_CHARS.sub("_", self.filename))
def __str__(self) -> str:
crc32 = self.crc32 or "-"
return f"{crc32} {self.size_bytes} {self.encoded_location} {self.filename}"
class ZipResponse(Response):
"""Response class for returning a ZIP archive with multiple files, using the `mod_zip` module."""
def __init__(
self,
*,
content_lines: Collection[ZipContentLine],
filename: str,
**kwargs: Any,
):
if kwargs.get("content"):
raise ValueError(
"Argument 'content' must not be provided, as it is generated from 'content_lines'"
)
kwargs["content"] = "\n".join(str(line) for line in content_lines)
kwargs.setdefault("headers", {}).update(
{
"Content-Disposition": f"attachment; filename*=UTF-8''{filename}; filename=\"{filename}\"",
"X-Archive-Files": "zip",
"X-Archive-Charset": "UTF-8",
}
)
super().__init__(**kwargs)
class FileRedirectResponse(Response):
"""Response class for serving a file download by using the X-Accel-Redirect header."""
def __init__(
self,
*,
download_path: Path | PurePath,
filename: str | None = None,
disposition: str = "attachment",
**kwargs: Any,
):
"""
Arguments:
- download_path: Path to the file to be served. Only its name and string
form are read, so either flavour of Path works.
- filename: Name of the file to be served. If not provided, the file name from the
download_path is used.
- disposition: "attachment" (default) forces a download; "inline" lets the
browser render/stream the file (required for <audio> to issue Range
requests and seek). Nginx itself still handles the Range parsing.
"""
media_type = kwargs.pop("media_type", "application/octet-stream")
filename = filename or download_path.name
kwargs.setdefault("headers", {}).update(
{
"Content-Disposition": f"{disposition}; filename*=UTF-8''{quote(filename)}; filename=\"{quote(filename)}\"",
"X-Accel-Redirect": quote(str(download_path)),
}
)
super().__init__(media_type=media_type, **kwargs)