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 0000000..5c87ff5 Binary files /dev/null and b/fuzz/corpus/docext/crash-zip-unsupported-version.docx.bin differ 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..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 @@ -426,6 +427,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 @@ -449,17 +463,33 @@ 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") - with dest.open("wb") as fh: - shutil.copyfileobj(file.file, fh) - - if kind == "vendor_doc" and dest.stat().st_size > docext.MAX_UPLOAD_BYTES: + 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 + # 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..fc24529 --- /dev/null +++ b/tests/test_web/test_xss_corpus.py @@ -0,0 +1,296 @@ +"""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