From 67b0178f3cecdd0e68c0d78fdbf124dbdfd4ade8 Mon Sep 17 00:00:00 2001 From: Abdellah Sheikh Date: Sat, 21 Nov 2026 20:50:29 +0300 Subject: [PATCH 1/3] security: XSS corpus, bounded uploads and runtime API audit for the dashboard The rest of #118 after #160 (cross-site writes, DNS rebinding, headers). - XSS regression corpus: 56 payloads through render_report_html and through the run, SAST and secret-scanning pages that show report data; a page must not gain any script, frame, form, image, inline handler or non-http(s) URL compared with the same page built from harmless text. - Uploads: every attachment kind is capped at MAX_UPLOAD_BYTES, the copy stops at the cap, and the middleware refuses a larger Content-Length (413) or a missing one (411) before Starlette spools the body. A PDF/DOCX/PPTX whose bytes are not that format gets 415 before any parser runs. DOCX/PPTX archives that expand past 200 MB or hold more than 5,000 members are not parsed. - Fuzzing docext for 60 s with the new type check found that zipfile raises NotImplementedError for an unsupported version; fixed, and the reproducer is in fuzz/corpus/docext. - Runtime API: a test enumerates every /api/runtime route and requires 401 without a valid key; the stored key hash is compared with hmac.compare_digest; "[::1]", "LOCALHOST" and "localhost." binds count as loopback for the TLS check; --allow-insecure-runtime is documented as lifting only that check. - SECURITY.md: "Local dashboard threat model". Closes #118 --- SECURITY.md | 31 ++ docs/REFERENCE.md | 5 +- .../crash-zip-unsupported-version.docx.bin | Bin 0 -> 36572 bytes fuzz/fuzz_docext.py | 5 +- fuzz/make_seed_corpus.py | 7 + src/secfoo/docext.py | 61 +++- src/secfoo/runtime/api.py | 6 +- src/secfoo/runtime/keys.py | 11 +- src/secfoo/web/routes/assessments.py | 30 +- src/secfoo/web/security.py | 24 ++ tests/test_runtime/test_runtime_auth.py | 110 +++++++ tests/test_web/test_upload_limits.py | 184 +++++++++++ tests/test_web/test_xss_corpus.py | 288 ++++++++++++++++++ 13 files changed, 751 insertions(+), 11 deletions(-) create mode 100644 fuzz/corpus/docext/crash-zip-unsupported-version.docx.bin create mode 100644 tests/test_runtime/test_runtime_auth.py create mode 100644 tests/test_web/test_upload_limits.py create mode 100644 tests/test_web/test_xss_corpus.py diff --git a/SECURITY.md b/SECURITY.md index 2487491..0f01e2a 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -27,6 +27,8 @@ it is meant for local use. Do not expose it on a network interface without putting your own authenticating reverse proxy in front of it (`secfoo serve` prints a warning when `--host` is not loopback). +### Local dashboard threat model + Because the dashboard runs on your machine while you browse other sites, it defends against your own browser being used against it: @@ -44,6 +46,35 @@ defends against your own browser being used against it: - **Security headers** on every response: a Content-Security-Policy with `script-src 'self'` and `frame-ancestors 'none'`, `X-Frame-Options: DENY`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: same-origin`. +- **Report content cannot run script.** Reports are agent output over a + target that may be hostile, and the run page shows them as HTML. Raw HTML + in a report renders as text; links keep only `http(s)` URLs with a host + (no `javascript:`, `data:`, `file:` or protocol-relative links, no + credentials in the URL); images are removed, since loading one would be an + exfiltration channel; Mermaid source stays escaped text and Mermaid runs + with `securityLevel: "strict"`, which a `%%{init}%%` directive cannot + change. `tests/test_web/test_xss_corpus.py` puts 56 payloads (event + handlers, SVG, `javascript:` links in eleven spellings, link-title quote + breakouts, entities in headings, data URIs, Mermaid blocks with script) + through the renderer and through the run, SAST and secret-scanning pages + that show report data, and fails if a page gains anything executable. +- **Uploads are bounded.** Every attachment is capped at 25 MB: a request + declaring more is refused (`413`) before it is spooled to disk, and one + without a `Content-Length` gets `411`. A PDF, DOCX or PPTX whose bytes are + not that format is refused (`415`) before any parser sees it, and a DOCX + or PPTX that would expand past 200 MB or holds more than 5,000 archive + members is stored but not parsed. Uploaded files are never served back by + the dashboard. Text extraction still runs in the request process: a + pathological PDF can cost CPU time (see `docext.py`); `fuzz/fuzz_docext.py` + checks that each input finishes within 30 seconds. +- **The runtime ingest API** (`/api/runtime/v1/`) needs a valid API key on + every route, reads or writes; keys are random 256-bit tokens stored only + as SHA-256 hashes and compared in constant time. It is exempt from the + origin check because a page on another site cannot attach an + `Authorization` header without a CORS preflight, which the dashboard + never grants. On a non-loopback `--host` it refuses keys over plain HTTP; + `--allow-insecure-runtime` lifts that one check and nothing else (keys, + the `Host` check and rate limits still apply). `secfoo cloud login` stores an API key in `~/.secfoo/cloud.toml` (mode `0600`). This key is scoped to push completed run data to your diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index 69d831f..9e24f5b 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -714,7 +714,10 @@ A missing key, server or project is an error. There is no fallback account. it refuses API keys over plain HTTP. Put a TLS-terminating proxy in front (e.g. Caddy, nginx, or a cloud load balancer forwarding `X-Forwarded-Proto`) and run uvicorn behind it. `--allow-insecure-runtime` disables the check, for -a trusted private network only. +a trusted private network only. It disables only that check: keys are still +required on every route, the `Host` check and rate limits still apply, and +the key still crosses the network in clear text, so anyone on that network +can read it. ## Install diff --git a/fuzz/corpus/docext/crash-zip-unsupported-version.docx.bin b/fuzz/corpus/docext/crash-zip-unsupported-version.docx.bin new file mode 100644 index 0000000000000000000000000000000000000000..5c87ff53123637be992df3d26725ae606a9a0e62 GIT binary patch literal 36572 zcmagEWmsIxwl$2qOCY$ryIXK~*Wm6BjfVseBoN%)T^kRs!QI^qU_rcM@&D_DwNZs4X z+|_`|%iga3yQtC<3s(P`Uj$7OK|yaAWJ*B+0WLoq1)sgv96$!?rgrC6_m`tE?*v?R z4Hg29QO0Y>>v%QRIJ1vsEwVTp(a~mI3ikV~%SB^7oQ_1{p-Kr!1{Jv@^uv#c>iP_d zyTkTiLq3*Y58F&p)@MtV^-XK+^-*@Rp!u?+GXMt$(8^Teqot}vpS#QaYD&oFO;Fvb zCX!YcwD5jyUk4X1k0bY5ahP$lUDmrP?}?Rv0X}Y(u^^pNJ%|*}yjuIZ`A^|OFP7Fr zZrg-X5s7oLw4Aw47$W}^`{d-tofn%UnzUiRG9=~Ydw-gt`q0@2OI(lZ9xLdO6Sj|y z_TDbNyzff_47DI$Y}+^b$CzBDFH!q4@cOOT;vpyfa&NyOEJ7Il+j?RI$~*NCGf7#T zP|IHJn_6w~l>I(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k*MXEZzrUWFu*YsQJvyrMD6VdU2^-I-I*2mvlkdYgx;EJ@$X*qu z71i#+IHEevn%9r51cMMqBvjak);L~N3{A=mX<`Y9m_!aREXL}XBy3rqiAvuaUBW5K zQ| z_@1dwCDx%(&*IT7$mQ;^wWonk4BnX?s}Glf$Paq5#;nj$;KL^!TW`abdb$^N(TW5q z#(@Xr)GDq(9G*aw`?YRMe6GRc9ir-1Mk5=dLn^{Wx-eiu*wD&BTglbN&|dQ`KKldUZJzxP z09SG;fk(h!tAM#=*f*O$zkGoE01$tK`M;w3-wi{8U=_^(ADILgBL8It`0WFH0NC^Q zg-74o?$>Pe@8(xaOPI$1a|wf|MEA#yw>-Y5WAFNjI|Hb-uGWk2o@5$CbC^J5Ps`9VY n>v#L#gTa679RvPni2XY>l#>DnjG(t6jSQswHWEYM{`$WF$h1mB literal 0 HcmV?d00001 diff --git a/fuzz/fuzz_docext.py b/fuzz/fuzz_docext.py index aa540dc..209d94c 100644 --- a/fuzz/fuzz_docext.py +++ b/fuzz/fuzz_docext.py @@ -6,6 +6,8 @@ Contract: extract_text returns a string -- "" for anything it can't read -- and never raises; an upload must always succeed (docext.py's own rule). +content_matches_extension, the upload route's type check (#118), returns a +bool and never raises either. Each input must finish within PER_INPUT_SECONDS. On CI, libFuzzer's -timeout and -rss_limit_mb additionally catch hangs and decompression bombs. @@ -20,7 +22,7 @@ from _common import main -from secfoo.docext import extract_text +from secfoo.docext import content_matches_extension, extract_text SUFFIXES = (".pdf", ".docx", ".pptx") PER_INPUT_SECONDS = 30.0 @@ -37,6 +39,7 @@ def check(data: bytes) -> None: suffix, body = split(data) path = _DIR / f"upload{suffix}" path.write_bytes(body) + assert isinstance(content_matches_extension(path), bool) started = time.monotonic() text = extract_text(path) elapsed = time.monotonic() - started diff --git a/fuzz/make_seed_corpus.py b/fuzz/make_seed_corpus.py index ab1fa00..4288d97 100644 --- a/fuzz/make_seed_corpus.py +++ b/fuzz/make_seed_corpus.py @@ -152,6 +152,13 @@ def docext() -> None: buffer = io.BytesIO() document.save(buffer) _write("docext", "report.docx.bin", bytes([1]) + buffer.getvalue()) + # Crash reproducer (#118): a central-directory "version needed to + # extract" zipfile does not support makes ZipFile() itself raise + # NotImplementedError, which escaped the upload route's type check. + cd = buffer.getvalue().find(b"PK\x01\x02") + patched = bytearray(buffer.getvalue()) + patched[cd + 6:cd + 8] = (236).to_bytes(2, "little") + _write("docext", "crash-zip-unsupported-version.docx.bin", bytes([1]) + bytes(patched)) presentation = Presentation() slide = presentation.slides.add_slide(presentation.slide_layouts[5]) diff --git a/src/secfoo/docext.py b/src/secfoo/docext.py index 7795ffd..74b9b4b 100644 --- a/src/secfoo/docext.py +++ b/src/secfoo/docext.py @@ -18,11 +18,17 @@ pathological PDF object graph) could still cost more memory/CPU than its file size implies. A stronger mitigation (subprocess isolation with a hard resource/time limit) is a reasonable follow-up hardening item, not -built here. +built here. What is built (#118): a DOCX/PPTX whose archive would expand +past MAX_EXPANDED_BYTES, or holds more than MAX_ARCHIVE_MEMBERS entries, is +not parsed at all (zipfile never inflates a member past its declared +size, so the central directory is a real bound); and the upload route +refuses a file whose content does not match its extension +(content_matches_extension) before anything parses it. """ from __future__ import annotations +import zipfile from pathlib import Path SUPPORTED_EXTENSIONS = {".pdf", ".docx", ".pptx"} @@ -31,6 +37,55 @@ # certificates, and pen test reports are almost always well under this), # while bounding the worst case of the residual risk noted above. MAX_UPLOAD_BYTES = 25 * 1024 * 1024 +# Every attachment, not only vendor documents, is capped at MAX_UPLOAD_BYTES +# (web/routes/assessments.py; web/security.py refuses a larger request +# before it is spooled to disk). + +# A real 25 MB DOCX/PPTX expands to a few times its size; a zip bomb to +# thousands. Office documents have tens to a few hundred archive members. +MAX_EXPANDED_BYTES = 200 * 1024 * 1024 +MAX_ARCHIVE_MEMBERS = 5_000 + +_OOXML_MAIN_PART = {".docx": "word/document.xml", ".pptx": "ppt/presentation.xml"} + + +class UnsafeArchiveError(ValueError): + """A DOCX/PPTX whose archive is too large or too many-membered to parse.""" + + +def content_matches_extension(path: Path) -> bool: + """Whether the bytes at `path` are what its extension claims: a PDF + header for .pdf, an Office Open XML archive with its main part for + .docx/.pptx. True for any other extension (nothing to check). Never + raises.""" + suffix = path.suffix.lower() + try: + if suffix == ".pdf": + with path.open("rb") as fh: + # The spec allows junk before the header within the first 1 KiB. + return b"%PDF-" in fh.read(1024) + if suffix in _OOXML_MAIN_PART: + with zipfile.ZipFile(path) as archive: + names = set(archive.namelist()) + return "[Content_Types].xml" in names and _OOXML_MAIN_PART[suffix] in names + except Exception: # noqa: BLE001 -- a predicate: anything unreadable is "no" + # zipfile raises more than BadZipFile on hostile input: + # NotImplementedError for an unsupported version or compression, + # EOFError, struct.error, ... (found by fuzz/fuzz_docext.py). + return False + return True + + +def check_archive_bounds(path: Path) -> None: + """Raise UnsafeArchiveError when the archive at `path` would expand past + MAX_EXPANDED_BYTES or has more than MAX_ARCHIVE_MEMBERS entries.""" + with zipfile.ZipFile(path) as archive: + members = archive.infolist() + if len(members) > MAX_ARCHIVE_MEMBERS: + raise UnsafeArchiveError(f"{len(members)} archive members") + expanded = sum(member.file_size for member in members) + if expanded > MAX_EXPANDED_BYTES: + raise UnsafeArchiveError(f"expands to {expanded} bytes") def is_extractable(filename: str) -> bool: @@ -72,6 +127,8 @@ def _extract_pdf(path: Path) -> str: def _extract_docx(path: Path) -> str: import docx + check_archive_bounds(path) + document = docx.Document(str(path)) parts = [p.text for p in document.paragraphs if p.text.strip()] for table in document.tables: @@ -85,6 +142,8 @@ def _extract_docx(path: Path) -> str: def _extract_pptx(path: Path) -> str: from pptx import Presentation + check_archive_bounds(path) + presentation = Presentation(str(path)) parts = [] for slide_number, slide in enumerate(presentation.slides, start=1): diff --git a/src/secfoo/runtime/api.py b/src/secfoo/runtime/api.py index 686f464..93c97a1 100644 --- a/src/secfoo/runtime/api.py +++ b/src/secfoo/runtime/api.py @@ -32,13 +32,13 @@ from secfoo.runtime.evidence import ingest_events from secfoo.runtime.watchlist import build_watchlist from secfoo.storage.repository import RunRepository +from secfoo.web.security import is_loopback MAX_BODY_BYTES = 5 * 1024 * 1024 # compressed request body MAX_DECOMPRESSED_BYTES = 20 * 1024 * 1024 MAX_BATCH_LINES = 50_000 RATE_LIMIT_REQUESTS = 120 # per key, per window RATE_LIMIT_WINDOW_SECONDS = 60 -LOOPBACK_HOSTS = frozenset({"127.0.0.1", "localhost", "::1"}) router = APIRouter(prefix="/api/runtime/v1", tags=["runtime"]) @@ -76,7 +76,9 @@ def _require_secure_transport(request: Request) -> None: must not cross the network in clear text unless the operator opted in.""" state = request.app.state bind_host = getattr(state, "bind_host", "127.0.0.1") - if bind_host in LOOPBACK_HOSTS or getattr(state, "allow_insecure_runtime", False): + # is_loopback, not a set lookup: "[::1]", "LOCALHOST" and "localhost." + # are loopback too, and were refused here before (#118). + if is_loopback(bind_host) or getattr(state, "allow_insecure_runtime", False): return if request.url.scheme != "https": raise _error(403, "refusing an API key over plain HTTP on a non-loopback address; put TLS in front " diff --git a/src/secfoo/runtime/keys.py b/src/secfoo/runtime/keys.py index 8bce767..5c12b65 100644 --- a/src/secfoo/runtime/keys.py +++ b/src/secfoo/runtime/keys.py @@ -9,6 +9,7 @@ from __future__ import annotations import hashlib +import hmac import secrets import sqlite3 from dataclasses import dataclass @@ -85,11 +86,17 @@ def verify_key(conn: sqlite3.Connection, key: str) -> ApiKey | None: if not key or not key.startswith(KEY_PREFIX): return None row = conn.execute( - f"SELECT {_COLUMNS} FROM runtime_api_keys WHERE key_hash = ?", (hash_key(key),) # nosec B608 + f"SELECT {_COLUMNS}, key_hash FROM runtime_api_keys WHERE key_hash = ?", (hash_key(key),) # nosec B608 ).fetchone() + # The lookup is by the SHA-256 of a 256-bit random key, so how long the + # index search takes says nothing useful about the key; the stored hash + # is still compared in constant time so that holds by construction (#118). if row is None: return None - record = _row(row) + *fields, stored_hash = tuple(row) + if not hmac.compare_digest(stored_hash, hash_key(key)): + return None + record = _row(fields) if not record.active: return None conn.execute("UPDATE runtime_api_keys SET last_used_at = ? WHERE id = ?", (_now(), record.id)) diff --git a/src/secfoo/web/routes/assessments.py b/src/secfoo/web/routes/assessments.py index e5261e8..4d10439 100644 --- a/src/secfoo/web/routes/assessments.py +++ b/src/secfoo/web/routes/assessments.py @@ -426,6 +426,19 @@ def assessment_trigger_run( return RedirectResponse(url=f"/assessments/{assessment_id}", status_code=303) +def _copy_bounded(source, dest: Path, limit: int) -> bool: + """Copy `source` into `dest`, stopping as soon as more than `limit` bytes + arrive. False when the upload was over the limit.""" + written = 0 + with dest.open("wb") as fh: + while chunk := source.read(1024 * 1024): + written += len(chunk) + if written > limit: + return False + fh.write(chunk) + return True + + @router.post("/assessments/{assessment_id}/attachments") def assessment_upload(assessment_id: int, file: UploadFile): trigger_third_party_review = False @@ -452,14 +465,23 @@ def assessment_upload(assessment_id: int, file: UploadFile): dest = dest_dir / filename if dest.resolve().parent != dest_dir.resolve(): raise HTTPException(status_code=400, detail="Invalid filename") - with dest.open("wb") as fh: - shutil.copyfileobj(file.file, fh) - - if kind == "vendor_doc" and dest.stat().st_size > docext.MAX_UPLOAD_BYTES: + # Every kind is capped, and the copy stops at the cap rather than + # writing the whole upload first (#118). web/security.py already + # refuses a request whose Content-Length is over the cap; this is + # the second check, on what was actually received. + if not _copy_bounded(file.file, dest, docext.MAX_UPLOAD_BYTES): dest.unlink(missing_ok=True) max_mb = docext.MAX_UPLOAD_BYTES // (1024 * 1024) raise HTTPException(status_code=413, detail=f"File too large (max {max_mb}MB)") + # A .pdf/.docx/.pptx is handed to a parser below; refuse one whose + # bytes are something else before any parser sees it. + if kind == "vendor_doc" and not docext.content_matches_extension(dest): + dest.unlink(missing_ok=True) + raise HTTPException( + status_code=415, detail=f"{filename} is not a valid {Path(filename).suffix.lower()[1:].upper()} file" + ) + new_attachment_id = repo.add_attachment( assessment_id=assessment_id, file_path=str(dest), original_name=filename, attachment_kind=kind ) diff --git a/src/secfoo/web/security.py b/src/secfoo/web/security.py index b574213..d0583ec 100644 --- a/src/secfoo/web/security.py +++ b/src/secfoo/web/security.py @@ -13,6 +13,9 @@ report. Requests must name the dashboard by a loopback host or the --host it was started with. - Framing and content sniffing: security headers on every response. +- Oversized uploads: an attachment upload must declare a Content-Length no + larger than the attachment cap, so a huge body is refused before + Starlette spools it to a temporary file. The runtime ingest API (/api/runtime/) authenticates with an API key in the Authorization header, which a cross-site page cannot set without a CORS @@ -21,6 +24,7 @@ """ from __future__ import annotations +import re from urllib.parse import urlsplit from starlette.responses import PlainTextResponse @@ -29,6 +33,9 @@ WILDCARD_BINDS = {"", "0.0.0.0", "::"} SAFE_METHODS = {"GET", "HEAD", "OPTIONS"} MACHINE_API_PREFIX = "/api/runtime/" +UPLOAD_PATH_RE = re.compile(r"/assessments/[^/]+/attachments/?") +# The multipart envelope around the file: boundaries, part headers, filename. +MULTIPART_OVERHEAD_BYTES = 64 * 1024 CONTENT_SECURITY_POLICY = ( "default-src 'self'; " @@ -101,6 +108,23 @@ def check_request(method: str, path: str, headers, hosts: set[str] | None) -> Pl referer = headers.get("referer") if referer and not _same_origin(referer, host_header): return PlainTextResponse("Cross-origin request refused", status_code=403) + if UPLOAD_PATH_RE.fullmatch(path): + return _check_upload_size(headers) + return None + + +def _check_upload_size(headers) -> PlainTextResponse | None: + from secfoo import docext # read at call time: tests lower the cap + + limit = docext.MAX_UPLOAD_BYTES + MULTIPART_OVERHEAD_BYTES + declared = headers.get("content-length") + if declared is None: + # Browsers always send a length for a form upload; a chunked body + # could only be bounded after it was spooled. + return PlainTextResponse("Content-Length required for uploads", status_code=411) + if not declared.strip().isdigit() or len(declared.strip()) > 18 or int(declared) > limit: + max_mb = docext.MAX_UPLOAD_BYTES // (1024 * 1024) + return PlainTextResponse(f"File too large (max {max_mb}MB)", status_code=413) return None diff --git a/tests/test_runtime/test_runtime_auth.py b/tests/test_runtime/test_runtime_auth.py new file mode 100644 index 0000000..b413f21 --- /dev/null +++ b/tests/test_runtime/test_runtime_auth.py @@ -0,0 +1,110 @@ +"""Runtime ingest API audit (#118): every route needs a key, keys compare in +constant time, and --allow-insecure-runtime only lifts the TLS check.""" +from __future__ import annotations + +import pytest +from fastapi.testclient import TestClient + +from secfoo.runtime import api as runtime_api +from secfoo.runtime import keys +from secfoo.storage.repository import RunRepository +from secfoo.web.app import create_app + +PROJECT = "https://github.com/acme/payments-api" + + +@pytest.fixture +def key(tmp_path, monkeypatch): + monkeypatch.setattr("secfoo.storage.repository.DB_PATH", tmp_path / "db.sqlite") + monkeypatch.setattr("secfoo.storage.repository.ensure_store_dirs", lambda: None) + runtime_api.rate_limiter.reset() + with RunRepository() as repo: + repo.upsert_project(PROJECT, "payments-api", "github") + plaintext, _ = keys.create_key(repo.connection, name="k") + return plaintext + + +def _runtime_routes(): + for route in runtime_api.router.routes: + for method in sorted(route.methods - {"HEAD"}): + yield method, route.path + + +ROUTES = list(_runtime_routes()) + + +def test_the_audit_covers_every_runtime_route(): + """A new runtime route shows up here, and so in the tests below.""" + assert {path.rsplit("/", 1)[-1] for _m, path in ROUTES} == {"watchlist", "events", "heartbeat", "evidence"} + + +@pytest.mark.parametrize(("method", "path"), ROUTES) +@pytest.mark.parametrize("authorization", [ + None, "", "Bearer", "Bearer ", "Basic Zm9vOmJhcg==", "Bearer sfk_wrong", "Bearer not-a-key", + "Bearer sfk_" + "A" * 43, +]) +def test_every_runtime_route_refuses_a_request_without_a_valid_key(key, method, path, authorization): + client = TestClient(create_app()) + headers = {} if authorization is None else {"Authorization": authorization} + resp = client.request(method, path, params={"project": PROJECT}, headers=headers, content=b"") + assert resp.status_code == 401, resp.text + assert key not in resp.text + + +@pytest.mark.parametrize(("method", "path"), [r for r in ROUTES if r[0] == "POST"]) +def test_a_cross_site_page_cannot_write_runtime_data(key, method, path): + """/api/runtime/ is exempt from the Origin check; what protects it is + that a page on another site cannot attach the Authorization header + without a CORS preflight, which the app never grants.""" + client = TestClient(create_app()) + resp = client.request(method, path, params={"project": PROJECT}, content=b'{"type":"session","id":"x"}\n', + headers={"Origin": "https://evil.example", "Content-Type": "text/plain"}) + assert resp.status_code == 401 + preflight = client.options(path, headers={"Origin": "https://evil.example", + "Access-Control-Request-Method": "POST", + "Access-Control-Request-Headers": "authorization"}) + assert "access-control-allow-origin" not in preflight.headers + with RunRepository() as repo: + assert repo.connection.execute("SELECT COUNT(*) FROM runtime_sessions").fetchone()[0] == 0 + + +def test_a_valid_key_still_works(key): + client = TestClient(create_app()) + resp = client.get("/api/runtime/v1/watchlist", params={"project": PROJECT}, + headers={"Authorization": f"Bearer {key}"}) + assert resp.status_code == 200 + + +def test_verify_key_compares_the_stored_hash_in_constant_time(key, monkeypatch): + calls = [] + real = keys.hmac.compare_digest + monkeypatch.setattr(keys.hmac, "compare_digest", lambda a, b: calls.append((a, b)) or real(a, b)) + with RunRepository() as repo: + assert keys.verify_key(repo.connection, key) is not None + assert calls == [(keys.hash_key(key), keys.hash_key(key))] + + +@pytest.mark.parametrize("bind", ["127.0.0.1", "localhost", "LOCALHOST", "localhost.", "::1", "[::1]"]) +def test_loopback_binds_need_no_tls(key, bind): + client = TestClient(create_app(bind_host=bind), base_url="http://127.0.0.1") + resp = client.get("/api/runtime/v1/watchlist", params={"project": PROJECT}, + headers={"Authorization": f"Bearer {key}"}) + assert resp.status_code == 200, resp.text + + +@pytest.mark.parametrize("allow_insecure", [False, True]) +def test_allow_insecure_runtime_lifts_only_the_tls_check(key, allow_insecure): + """On a non-loopback bind a key over plain HTTP is refused unless the + operator opted in. Opting in changes nothing else: a bad key is still + a 401 and the Host check still applies.""" + app = create_app(bind_host="10.0.0.5", allow_insecure_runtime=allow_insecure) + client = TestClient(app, base_url="http://10.0.0.5:8787") + good = client.get("/api/runtime/v1/watchlist", params={"project": PROJECT}, + headers={"Authorization": f"Bearer {key}"}) + assert good.status_code == (200 if allow_insecure else 403) + bad = client.get("/api/runtime/v1/watchlist", params={"project": PROJECT}, + headers={"Authorization": "Bearer sfk_wrong"}) + assert bad.status_code == (401 if allow_insecure else 403) + rebound = client.get("/api/runtime/v1/watchlist", params={"project": PROJECT}, + headers={"Authorization": f"Bearer {key}", "Host": "rebind.evil.example"}) + assert rebound.status_code == 400 diff --git a/tests/test_web/test_upload_limits.py b/tests/test_web/test_upload_limits.py new file mode 100644 index 0000000..a1605b8 --- /dev/null +++ b/tests/test_web/test_upload_limits.py @@ -0,0 +1,184 @@ +"""Attachment upload limits and type checks (#118).""" +from __future__ import annotations + +import io +import zipfile + +import pytest +from fastapi.testclient import TestClient + +from secfoo import docext +from secfoo.storage.repository import RunRepository +from secfoo.web.app import create_app + + +@pytest.fixture +def client(tmp_path, monkeypatch): + monkeypatch.setattr("secfoo.storage.repository.DB_PATH", tmp_path / "db.sqlite") + monkeypatch.setattr("secfoo.storage.repository.ensure_store_dirs", lambda: None) + monkeypatch.setattr("secfoo.config.ATTACHMENTS_DIR", tmp_path / "attachments") + client = TestClient(create_app()) + client.attachments = tmp_path / "attachments" + return client + + +@pytest.fixture +def assessment_id(): + with RunRepository() as repo: + project_id = repo.upsert_project("p", "p", "local") + return repo.create_assessment(project_id=project_id, assessment_type="internal", status="ready") + + +def _attachments(assessment_id): + with RunRepository() as repo: + return [a.original_name for a in repo.list_attachments(assessment_id)] + + +def _docx(text="hello") -> bytes: + import docx + + document = docx.Document() + document.add_paragraph(text) + buf = io.BytesIO() + document.save(buf) + return buf.getvalue() + + +def _upload(client, assessment_id, name, data, **kwargs): + return client.post(f"/assessments/{assessment_id}/attachments", files={"file": (name, data)}, + follow_redirects=False, **kwargs) + + +# ---------- size ---------- + +@pytest.mark.parametrize("name", ["notes.txt", "sbom.cdx.json", "report.md", "big.pdf"]) +def test_every_kind_of_attachment_is_size_capped(client, assessment_id, monkeypatch, name): + """Before #118 only PDF/DOCX/PPTX were capped, and only after the whole + file had been written to disk.""" + monkeypatch.setattr("secfoo.docext.MAX_UPLOAD_BYTES", 1000) + monkeypatch.setattr("secfoo.web.security.MULTIPART_OVERHEAD_BYTES", 10_000) + resp = _upload(client, assessment_id, name, b"%PDF-1.4\n" + b"x" * 2000) + assert resp.status_code == 413 + assert _attachments(assessment_id) == [] + assert not any(client.attachments.rglob(name)) + + +def test_a_request_declaring_too_large_a_body_is_refused_before_it_is_read(client, assessment_id, monkeypatch): + monkeypatch.setattr("secfoo.docext.MAX_UPLOAD_BYTES", 1000) + resp = client.post(f"/assessments/{assessment_id}/attachments", content=b"x" * 10, + headers={"Content-Type": "multipart/form-data; boundary=b", "Content-Length": str(10**9)}) + assert resp.status_code == 413 + assert "max" in resp.text + + +@pytest.mark.parametrize("length", ["abc", "-1", "1" * 40]) +def test_a_malformed_content_length_is_refused(assessment_id, length): + from secfoo.web.security import check_request + + refused = check_request("POST", f"/assessments/{assessment_id}/attachments", + {"host": "127.0.0.1:8787", "content-length": length}, None) + assert refused is not None and refused.status_code == 413 + + +def test_a_chunked_upload_without_a_length_is_refused(assessment_id): + from secfoo.web.security import check_request + + refused = check_request("POST", f"/assessments/{assessment_id}/attachments", {"host": "127.0.0.1:8787"}, None) + assert refused is not None and refused.status_code == 411 + + +def test_upload_at_the_limit_is_accepted(client, assessment_id, monkeypatch): + monkeypatch.setattr("secfoo.docext.MAX_UPLOAD_BYTES", 1000) + assert _upload(client, assessment_id, "notes.txt", b"x" * 1000).status_code == 303 + assert _attachments(assessment_id) == ["notes.txt"] + + +def test_other_routes_need_no_content_length(client): + """Only the upload route is size-gated; a form POST elsewhere is unaffected.""" + from secfoo.web.security import check_request + + assert check_request("POST", "/assessments", {"host": "127.0.0.1:8787"}, None) is None + + +# ---------- type ---------- + +@pytest.mark.parametrize(("name", "data"), [ + ("soc2.pdf", b"MZ\x90\x00 this is an executable"), + ("soc2.pdf", b""), + ("soc2.docx", b"%PDF-1.4\nnot a docx"), + ("deck.pptx", b"plain text"), +]) +def test_vendor_document_whose_content_does_not_match_its_extension_is_refused(client, assessment_id, name, data): + resp = _upload(client, assessment_id, name, data) + assert resp.status_code == 415 + assert _attachments(assessment_id) == [] + assert not any(client.attachments.rglob(name)) + + +def test_docx_renamed_to_pptx_is_refused(client, assessment_id): + assert _upload(client, assessment_id, "deck.pptx", _docx()).status_code == 415 + + +def test_real_documents_are_accepted(client, assessment_id): + assert _upload(client, assessment_id, "soc2.docx", _docx("SOC 2")).status_code == 303 + assert _upload(client, assessment_id, "cert.pdf", b"%PDF-1.7\n%\xe2\xe3\xcf\xd3\n").status_code == 303 + assert sorted(_attachments(assessment_id)) == ["cert.pdf", "soc2.docx"] + + +def test_pdf_header_may_follow_leading_junk(tmp_path): + path = tmp_path / "x.pdf" + path.write_bytes(b"\xef\xbb\xbf\r\n" + b"%PDF-1.4\n") + assert docext.content_matches_extension(path) + + +def test_other_extensions_are_not_content_checked(tmp_path): + path = tmp_path / "notes.txt" + path.write_bytes(b"\x00\x01anything") + assert docext.content_matches_extension(path) + + +# ---------- archive bounds (zip bombs) ---------- + +def _bomb(tmp_path, *, members=1, member_bytes=0, suffix=".docx"): + path = tmp_path / f"bomb{suffix}" + with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED) as archive: + archive.writestr("[Content_Types].xml", "") + archive.writestr("word/document.xml" if suffix == ".docx" else "ppt/presentation.xml", "") + for i in range(members): + archive.writestr(f"word/media/{i}.bin", b"\0" * member_bytes) + return path + + +@pytest.mark.parametrize("suffix", [".docx", ".pptx"]) +def test_archive_expanding_past_the_bound_is_not_parsed(tmp_path, monkeypatch, suffix): + monkeypatch.setattr("secfoo.docext.MAX_EXPANDED_BYTES", 1_000_000) + path = _bomb(tmp_path, member_bytes=2_000_000, suffix=suffix) + assert path.stat().st_size < 10_000 # small on disk, as a bomb is + with pytest.raises(docext.UnsafeArchiveError): + docext.check_archive_bounds(path) + assert docext.extract_text(path) == "" + + +def test_archive_with_too_many_members_is_not_parsed(tmp_path, monkeypatch): + monkeypatch.setattr("secfoo.docext.MAX_ARCHIVE_MEMBERS", 50) + path = _bomb(tmp_path, members=60) + with pytest.raises(docext.UnsafeArchiveError): + docext.check_archive_bounds(path) + assert docext.extract_text(path) == "" + + +def test_a_real_docx_is_within_the_bounds(tmp_path): + path = tmp_path / "real.docx" + path.write_bytes(_docx("Vendor SOC 2 excerpt")) + docext.check_archive_bounds(path) + assert "Vendor SOC 2 excerpt" in docext.extract_text(path) + + +def test_an_unsupported_zip_version_is_refused_not_a_server_error(client, assessment_id): + """Found by fuzz/fuzz_docext.py: zipfile raises NotImplementedError, + not BadZipFile, for a version it cannot read.""" + from pathlib import Path + + corpus = Path(__file__).parents[2] / "fuzz" / "corpus" / "docext" / "crash-zip-unsupported-version.docx.bin" + resp = _upload(client, assessment_id, "vendor.docx", corpus.read_bytes()[1:]) + assert resp.status_code == 415 diff --git a/tests/test_web/test_xss_corpus.py b/tests/test_web/test_xss_corpus.py new file mode 100644 index 0000000..7ed782f --- /dev/null +++ b/tests/test_web/test_xss_corpus.py @@ -0,0 +1,288 @@ +"""XSS regression corpus for agent-written report content (#118). + +Reports are agent output over repositories that may be hostile, and the run +page renders them with `|safe`. Every payload below goes through the real +renderer and the real pages that show report data (the run page, the SAST +findings list and detail, the secret-scanning findings), and each page must +have nothing executable that the same page with harmless content lacks: no +new script, frame, object, form, base or meta element, no inline event +handler, and no link or resource URL with a scheme other than http(s). +""" + +from __future__ import annotations + +from collections import Counter +from html.parser import HTMLParser +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient + +from secfoo.report.markdown import render_report_html +from secfoo.runner import update_sast_findings, update_secret_findings +from secfoo.storage.repository import RunRepository +from secfoo.web import secret_scanning_dashboard +from secfoo.web.app import STATIC_DIR, create_app + +SAMPLE = Path(__file__).parents[2] / "examples" / "sample-output" / "nodegoat" + +# name -> Markdown. Grouped as the issue lists them; each has the marker +# alert(1) or a foreign host so a leak is easy to spot in a failure. +CORPUS = { + # raw HTML + "script": "", + "script_block": "", + "img_onerror": "", + "svg_onload": "", + "svg_script": "\n\n", + "iframe": '', + "iframe_srcdoc": '', + "object": '', + "style": "", + "meta_refresh": '', + "base": '', + "form": '
', + "inline_handler": "**x**", + "comment_breakout": " -->", + "cdata": "alert(1)]]>", + "math": "x", + # images: any image would be fetched on page load (exfiltration) + "md_image": '![x](https://evil.example/x.png "t")', + "md_image_js": "![x](javascript:alert(1))", + "md_image_data_svg": "![x](data:image/svg+xml;base64,PHN2ZyBvbmxvYWQ9YWxlcnQoMSk+)", + "md_image_ref": "![x][i]\n\n[i]: https://evil.example/x.png", + # javascript: and other schemes in links + "js_link": "[c](javascript:alert(1))", + "js_link_case": "[c](JaVaScRiPt:alert(1))", + "js_link_space": "[c](< javascript:alert(1)>)", + "js_link_entity": "[c](javascript:alert(1))", + "js_link_hex_entity": "[c](javascript:alert(1))", + "js_link_tab": "[c](java\tscript:alert(1))", + "js_link_newline": "[c](java\nscript:alert(1))", + "js_link_null": "[c](java\x00script:alert(1))", + "js_link_percent": "[c](javascript%3Aalert(1))", + "js_reference_link": "[c][r]\n\n[r]: javascript:alert(1)", + "js_autolink": "", + "vbscript": "[c](vbscript:msgbox(1))", + "data_link": "[c](data:text/html,)", + "data_autolink": "", + "file_link": "[c](file:///etc/passwd)", + "protocol_relative": "[c](//evil.example/x)", + "credentials_link": "[c](https://user:pass@evil.example)", + # quotes in link titles and URLs (attribute breakout) + "title_double_quote": '[c](https://ok.example "a\\" onmouseover=\\"alert(1)")', + "title_single_quote": "[c](https://ok.example 'x\" onclick=\"alert(1)')", + "title_paren": '[c](https://ok.example (x" onfocus="alert(1)))', + "href_quote": '[c](https://ok.example/"onmouseover="alert(1))', + "href_angle": "[c](>)", + # entities and headings (the badge post-processing rewrites

) + "entity_heading": "### [High] <script>alert(1)</script>", + "entity_double_escape": "### [High] &lt;img src=x onerror=alert(1)&gt;", + "html_heading": "### [Critical] ", + "badge_breakout": '### [High">] title', + "badge_cell": "| Severity |\n|---|\n| Critical\" onmouseover=\"alert(1) |", + "table_cell_html": "| a | b |\n|---|---|\n| | High |", + # code: diff colouring and fence info strings + "diff_block": "```diff\n+\n- \n```", + "fence_info": '```">\nx\n```', + "inline_code": "``", + # Mermaid: the source stays escaped text; mermaid.js runs in strict mode + "mermaid_label_html": '```mermaid\ngraph TD\nA[""] --> B\n```', + "mermaid_click": "```mermaid\ngraph TD\nA --> B\nclick A call alert(1)\nclick B href \"javascript:alert(1)\"\n```", + "mermaid_init_directive": '```mermaid\n%%{init: {"securityLevel": "loose"}}%%\ngraph TD\nA --> B\n```', + "mermaid_pre_breakout": "```mermaid\n\n```", + "mermaid_info_breakout": '```mermaid" onclick="alert(1)\ngraph TD\n```', +} + +_ELEMENTS = { + "script", "iframe", "frame", "frameset", "object", "embed", "applet", "base", "meta", "link", + "form", "img", "image", "svg", "math", "video", "audio", "source", "track", "style", "template", + "portal", +} +_URL_ATTRS = {"href", "src", "action", "formaction", "data", "poster", "xlink:href", "background", "ping"} + + +class _Executable(HTMLParser): + """Collects everything on a page that could run code or fetch a + resource, so two pages can be compared.""" + + def __init__(self) -> None: + super().__init__(convert_charrefs=True) + self.found: Counter = Counter() + + def handle_starttag(self, tag, attrs): + if tag in _ELEMENTS: + # A dashboard ') + for leaked in ('

x

', "", 'x', + 'x', '', 'x'): + assert executable(f'{leaked}') != plain, leaked From 2897adafac06ef6bceef6b6b11b349966d5cc65b Mon Sep 17 00:00:00 2001 From: Abdellah Sheikh Date: Sat, 21 Nov 2026 21:12:51 +0300 Subject: [PATCH 2/3] test(web): XSS page comparison with the Mermaid bundle vendored CI has mermaid.min.js vendored, so pages showing a diagram load the Mermaid scripts and the poisoned Mermaid payloads gained two dashboard script tags over a diagram-free baseline. The baseline now has a harmless diagram, the fixture renders as if the bundle is vendored (the riskier case), and a page fails only if it gains something over the baseline. --- tests/test_web/test_xss_corpus.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/tests/test_web/test_xss_corpus.py b/tests/test_web/test_xss_corpus.py index 7ed782f..fc24529 100644 --- a/tests/test_web/test_xss_corpus.py +++ b/tests/test_web/test_xss_corpus.py @@ -176,6 +176,9 @@ def client(tmp_path, monkeypatch): monkeypatch.setattr("secfoo.storage.repository.ensure_store_dirs", lambda: None) monkeypatch.setattr("secfoo.web.routes.runs.STORE_DIR", tmp_path) monkeypatch.setattr("secfoo.web.run_status.run_dir", lambda uuid: tmp_path / "reports" / uuid) + # Render as an install with `secfoo vendor mermaid` done (CI has it): + # diagrams are then live
 blocks, the riskier case.
+    monkeypatch.setattr("secfoo.web.app.mermaid_bundle_available", lambda: True)
     client = TestClient(create_app())
     client.store = tmp_path
     return client
@@ -218,7 +221,9 @@ def _baseline_and_poisoned(client, payload, build_report, pages):
     """`pages(run_uuid, repo)` -> list of URLs. Returns (baseline, poisoned)
     executable counters for each page, harmless content first."""
     results = []
-    for content in ("plain text", payload):
+    # The baseline has a harmless diagram, so pages that load Mermaid for
+    # one (with the bundle vendored, as in CI) load it in the baseline too.
+    for content in (HARMLESS, payload):
         client.store.joinpath("db.sqlite").unlink(missing_ok=True)
         repo, project_id, run_id, run_uuid = _completed_run(client.store, *build_report(content))
         update = update_sast_findings if build_report is _sast_report else update_secret_findings
@@ -234,6 +239,9 @@ def _baseline_and_poisoned(client, payload, build_report, pages):
     return results
 
 
+HARMLESS = "plain text\n\n```mermaid\ngraph TD\n  A --> B\n```\n"
+
+
 def _sast_report(content):
     return "sast", _poison_sast(content)
 
@@ -269,14 +277,14 @@ def _secret_pages(run_uuid, repo):
 def test_sast_pages_with_a_poisoned_report_have_nothing_new_that_executes(client, name):
     baseline, poisoned = _baseline_and_poisoned(client, CORPUS[name], _sast_report, _sast_pages)
     for url_index, (plain, bad) in enumerate(zip(baseline, poisoned)):
-        assert bad == plain, (url_index, bad - plain)
+        assert not bad - plain, (url_index, bad - plain)
 
 
 @pytest.mark.parametrize("name", CORPUS)
 def test_secret_scanning_pages_with_a_poisoned_report_have_nothing_new_that_executes(client, name):
     baseline, poisoned = _baseline_and_poisoned(client, CORPUS[name], _secret_report, _secret_pages)
     for url_index, (plain, bad) in enumerate(zip(baseline, poisoned)):
-        assert bad == plain, (url_index, bad - plain)
+        assert not bad - plain, (url_index, bad - plain)
 
 
 def test_the_comparison_would_catch_a_leak():

From aa9e194b26b14244bb7e7fe84dfded8f48009229 Mon Sep 17 00:00:00 2001
From: Abdellah Sheikh 
Date: Sun, 22 Nov 2026 00:50:12 +0300
Subject: [PATCH 3/3] fix(web): write the upload containment check in a form
 CodeQL recognizes

CodeQL flagged the new bounded copy and type check (py/path-injection)
although the filename was already reduced to a basename and checked
against the attachment directory. Use os.path.normpath plus a prefix
check on the real directory, which the query treats as a barrier, and
keep the resolve() check for an existing symlink pointing out.
---
 src/secfoo/web/routes/assessments.py | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)

diff --git a/src/secfoo/web/routes/assessments.py b/src/secfoo/web/routes/assessments.py
index 4d10439..1ad8932 100644
--- a/src/secfoo/web/routes/assessments.py
+++ b/src/secfoo/web/routes/assessments.py
@@ -1,5 +1,6 @@
 from __future__ import annotations
 
+import os
 import shutil
 import tempfile
 import threading
@@ -462,8 +463,15 @@ def assessment_upload(assessment_id: int, file: UploadFile):
         kind = infer_attachment_kind(filename)
         dest_dir = attachment_dir(assessment_id)
         dest_dir.mkdir(parents=True, exist_ok=True)
-        dest = dest_dir / filename
-        if dest.resolve().parent != dest_dir.resolve():
+        # normpath + a prefix check on the resolved directory: the same
+        # containment check as before, written in the form CodeQL's
+        # py/path-injection query recognizes as a barrier.
+        base = os.path.realpath(dest_dir)
+        dest_path = os.path.normpath(os.path.join(base, filename))
+        if not dest_path.startswith(base + os.sep) or os.path.dirname(dest_path) != base:
+            raise HTTPException(status_code=400, detail="Invalid filename")
+        dest = Path(dest_path)
+        if dest.resolve().parent != Path(base):  # an existing symlink pointing out
             raise HTTPException(status_code=400, detail="Invalid filename")
         # Every kind is capped, and the copy stops at the cap rather than
         # writing the whole upload first (#118). web/security.py already