Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand All @@ -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
Expand Down
5 changes: 4 additions & 1 deletion docs/REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Binary file not shown.
5 changes: 4 additions & 1 deletion fuzz/fuzz_docext.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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
Expand All @@ -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
Expand Down
7 changes: 7 additions & 0 deletions fuzz/make_seed_corpus.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
61 changes: 60 additions & 1 deletion src/secfoo/docext.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"}
Expand All @@ -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:
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
# 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:
Expand Down Expand Up @@ -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:
Expand All @@ -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):
Expand Down
6 changes: 4 additions & 2 deletions src/secfoo/runtime/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"])

Expand Down Expand Up @@ -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 "
Expand Down
11 changes: 9 additions & 2 deletions src/secfoo/runtime/keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from __future__ import annotations

import hashlib
import hmac
import secrets
import sqlite3
from dataclasses import dataclass
Expand Down Expand Up @@ -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))
Expand Down
42 changes: 36 additions & 6 deletions src/secfoo/web/routes/assessments.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import os
import shutil
import tempfile
import threading
Expand Down Expand Up @@ -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:
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
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
Expand All @@ -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)
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
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
)
Expand Down
24 changes: 24 additions & 0 deletions src/secfoo/web/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -21,6 +24,7 @@
"""
from __future__ import annotations

import re
from urllib.parse import urlsplit

from starlette.responses import PlainTextResponse
Expand All @@ -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'; "
Expand Down Expand Up @@ -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


Expand Down
Loading
Loading