mirror of
https://github.com/maziggy/bambuddy.git
synced 2026-08-11 00:30:12 -04:00
Two attacker-controlled strings were being joined to library_dir with no
resolve + containment check in the project ZIP import endpoint:
- linked_folders[*].name from the request's project.json
- per-entry zf.namelist() paths from the ZIP itself
An absolute path in either field collapsed the join (Path("/lib") / "/etc"
becomes Path("/etc") because pathlib discards the left side when the right
is absolute) and the next write_bytes landed wherever the attacker chose.
Adjacent finding from the routes audit: GET /archives/{id}/photos/{filename}
had NO validation on filename and FileResponse-served arbitrary paths -
the DELETE counterpart at least gated on the photos membership check.
Adjacent finding from the services audit: ArchiveService.attach_timelapse
wrote archive_dir / filename where filename ultimately came from a printer's
FTP listing (compromised-printer threat model) or the /timelapse/select
query param. A malicious printer that exposes a directory entry with ..
segments could write the timelapse outside the archive directory.
New backend/app/utils/safe_path.py::safe_join_under(parent, *parts) is the
single source of truth: rejects empty / null-byte / absolute parts up-front,
joins under parent, resolves both sides, asserts is_relative_to. Returns the
resolved canonical path on success, raises HTTPException(400) on escape, or
PathTraversalError when http=False (for service-layer callers that need to
match a non-HTTP return contract).
Wired into the import vectors, both archive photo handlers, and the
attach_timelapse service. The full audit sweep inspected every Path/Name
join in backend/app/api/routes/ AND backend/app/services/ - 25 route-layer
sites + 8 service-layer sites confirmed safe and tagged with
# SEC-PATH-OK: <reason> so future audits trust the inline guard at a glance.
Fifth CI backstop test_route_path_arithmetic_is_safe_joined_or_marked
AST-walks both layers and fails the build on any <dir-like>/<bare variable>
join that doesn't either route through safe_join_under or carry the marker.
The services layer is in scope because it receives values verbatim from the
routes AND from external sources Bambuddy has no control over (the printer
FTP-listing case above).
SECURITY.md gets a fifth rule + a fifth row in the CI test mapping table;
the rule now names the printer FTP-listing case explicitly so future
services-layer audits set the right expectation.
--------------
fix(library): suppress warning storm when bulk-uploading ZIPs of empty/stub STL files
Uploading a ZIP of stub or empty STL files (e.g. the 24-byte
"solid test\nendsolid test" shape) produced one WARNING per file in
stl_thumbnail.py::generate_stl_thumbnail. The warnings were technically
correct - trimesh returns a valid Mesh with zero vertices, the safeguard
matches, and the function returns None so the library entry is still
created without a thumbnail - but the volume turned a successful upload
into thousands of WARNING lines in the journal.
Two changes:
1. The per-file "Failed to load STL or empty mesh" message in
stl_thumbnail.py is now logger.debug instead of logger.warning. It's
a per-file content observation, not an actionable error; the caller
already handles None correctly. The branch now catches the rare
"large enough but trimesh still can't parse it" case, visible in
debug logs without spamming production.
2. New module constant MIN_USABLE_STL_BYTES = 200 (smallest binary STL
with one triangle is 134B, smallest ASCII ~150B; 200 is a safe floor
below any real STL). The three thumbnail call sites in library.py
(extract_zip_file, single-file upload, _backfill_external_stl_thumbnails)
pre-skip files below this size before calling generate_stl_thumbnail.
Stubs never enter the trimesh pipeline at all.
Behavior is unchanged for real STLs: any file >=200 bytes runs through
the existing pipeline, MAX_VERTICES still triggers simplification at
100k vertices for the 256x256 thumbnail render, large files still get
thumbnails.
------------
fix(stl-thumbnail): silence matplotlib first-import noise (writable cache + font_manager log level)
On first STL upload, three matplotlib-internal log lines surfaced:
WARNING [matplotlib] /opt/claude/.config/matplotlib is not a writable directory
INFO [matplotlib.font_manager] Failed to extract font properties from NotoColorEmoji.ttf
INFO [matplotlib.font_manager] generated new fontManager
The writable-dir warning fired because Bambuddy's $HOME isn't writable for
matplotlib's default config path; matplotlib fell back to /tmp/matplotlib-XXX
which lost the font cache on every host reboot, so font_manager rebuilt it
each cold start - producing another batch of INFO lines.
Fix is two small additions in stl_thumbnail.py before the matplotlib import:
1. New _configure_matplotlib_cache() sets MPLCONFIGDIR to
settings.base_dir/.cache/matplotlib (mkdir if missing) so the cache
persists across container restarts and the writable-dir warning never
fires. Respects an externally-set MPLCONFIGDIR so operators who chose
their own path aren't overridden. Best-effort with a debug fallback if
settings can't be imported or the mkdir fails.
2. logging.getLogger("matplotlib.font_manager").setLevel(WARNING) at module
import demotes the per-font INFO scan that fires when font_manager
builds its cache cold. Real font warnings (>= WARNING) still surface.
3 new tests: font_manager logger at WARNING after module import;
_configure_matplotlib_cache creates the directory under base_dir and sets
MPLCONFIGDIR; an externally-set MPLCONFIGDIR is preserved verbatim.
5516 backend tests green, frontend gates clean.
114 lines
4.5 KiB
Python
114 lines
4.5 KiB
Python
"""Containment-checked path joining.
|
|
|
|
Single source of truth for joining a user-controlled string under a trusted
|
|
parent directory. The two-vector arbitrary-file-write reported against
|
|
``backend/app/api/routes/projects.py::import_project_file`` traced to plain
|
|
``Path / user_string`` arithmetic with no resolve + containment check —
|
|
attacker passed an absolute path, ``Path("/lib") / "/etc"`` collapsed to
|
|
``Path("/etc")``, and the next ``write_bytes`` landed wherever the attacker
|
|
chose. This module is the answer.
|
|
|
|
Every site that joins a path component coming from a request body, a ZIP
|
|
``namelist()``, an ``UploadFile.filename``, or any other attacker-controlled
|
|
source MUST route through ``safe_join_under``. Sites that join trusted
|
|
constants (settings paths, hardcoded subdirs) are not in scope — those should
|
|
carry a ``# SEC-PATH-OK: <reason>`` marker so the CI backstop knows.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
|
|
from fastapi import HTTPException
|
|
|
|
|
|
class PathTraversalError(ValueError):
|
|
"""Raised when a join attempt would escape the trusted parent.
|
|
|
|
Callers in API-route context catch this and translate to ``HTTPException``
|
|
via ``safe_join_under`` (which already raises HTTPException directly when
|
|
invoked with ``http=True``). Non-route callers can catch the
|
|
``PathTraversalError`` and decide their own response shape.
|
|
"""
|
|
|
|
|
|
def safe_join_under(parent: Path, *parts: str, http: bool = True) -> Path:
|
|
"""Join *parts* under *parent* and assert the result stays under it.
|
|
|
|
Rejects:
|
|
- empty / None / non-str parts;
|
|
- parts containing NUL (``\\x00``);
|
|
- parts starting with ``/`` or ``\\`` (absolute paths;
|
|
``Path("/lib") / "/etc"`` discards ``/lib``);
|
|
- any sequence whose resolved form is not a descendant of *parent*'s
|
|
resolved form (defeats ``..`` traversal even when the literal join
|
|
doesn't look suspicious).
|
|
|
|
Returns the resolved absolute path on success.
|
|
|
|
When ``http=True`` (default; suitable for FastAPI routes), failures raise
|
|
``HTTPException(400, "Invalid path in upload")``. Set ``http=False`` to
|
|
raise ``PathTraversalError`` instead — for non-route callers that need
|
|
finer control over the response.
|
|
"""
|
|
if not parts:
|
|
_fail("safe_join_under called with no parts", http)
|
|
|
|
for part in parts:
|
|
if not isinstance(part, str):
|
|
_fail(f"Path part has type {type(part).__name__}, expected str", http)
|
|
if not part:
|
|
_fail("Empty path part", http)
|
|
if "\x00" in part:
|
|
_fail("NUL byte in path part", http)
|
|
# Reject literal absolute markers: pathlib collapses ``Path("/a") /
|
|
# "/b"`` to ``Path("/b")`` so the catch-after-resolve below would also
|
|
# fire, but rejecting up-front gives a clearer error and avoids
|
|
# touching the filesystem.
|
|
if part.startswith("/") or part.startswith("\\"):
|
|
_fail("Absolute path part not allowed", http)
|
|
|
|
parent_resolved = parent.resolve()
|
|
candidate = parent
|
|
for part in parts:
|
|
candidate = candidate / part
|
|
candidate_resolved = candidate.resolve()
|
|
|
|
if not _is_relative_to(candidate_resolved, parent_resolved):
|
|
_fail("Path escapes the parent directory", http)
|
|
|
|
return candidate_resolved
|
|
|
|
|
|
def assert_under(parent: Path, candidate: Path, *, http: bool = True) -> Path:
|
|
"""Assert that an already-joined *candidate* path is under *parent*.
|
|
|
|
Use when you have an existing ``Path`` (e.g. from another helper that
|
|
builds the path itself) and need a containment check before writing or
|
|
deleting. Equivalent to ``safe_join_under`` minus the per-part input
|
|
validation.
|
|
"""
|
|
parent_resolved = parent.resolve()
|
|
candidate_resolved = candidate.resolve()
|
|
if not _is_relative_to(candidate_resolved, parent_resolved):
|
|
_fail("Path escapes the parent directory", http)
|
|
return candidate_resolved
|
|
|
|
|
|
def _is_relative_to(child: Path, parent: Path) -> bool:
|
|
# ``Path.is_relative_to`` exists in Python 3.9+. Bambuddy targets 3.11+
|
|
# (per pyproject and the bug-report system info) so this is safe.
|
|
try:
|
|
return child.is_relative_to(parent)
|
|
except AttributeError: # pragma: no cover - defensive
|
|
try:
|
|
child.relative_to(parent)
|
|
return True
|
|
except ValueError:
|
|
return False
|
|
|
|
|
|
def _fail(reason: str, http: bool) -> None:
|
|
if http:
|
|
raise HTTPException(status_code=400, detail="Invalid path in upload")
|
|
raise PathTraversalError(reason)
|