Skip to content
Closed
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
40 changes: 40 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,46 @@ that may itself be untrusted or adversarial, so it's rendered
defensively: report markdown never executes embedded HTML/scripts, and
Mermaid diagrams render with `securityLevel: "strict"`.

## Local dashboard threat model

The `secfoo serve` dashboard is designed to run locally on developer workstations and CI runners. Because it operates within reach of web browsers running untrusted public web pages, it implements defense-in-depth protections against web-based attacks targeting localhost services:

### Cross-Site Request Forgery (CSRF) Defense
All state-changing HTTP endpoints (`POST`, `PUT`, `PATCH`, `DELETE`) require cross-site request validation via `CrossSiteProtectionMiddleware`:
- Browser requests carrying `Sec-Fetch-Site: cross-site` are immediately rejected with `403 Forbidden`.
- Requests carrying an `Origin` or `Referer` header must match the expected dashboard origin (`localhost`, `127.0.0.1`, `[::1]`, or the configured host and port). Cross-origin origins/referers are blocked with `403 Forbidden`.
- Non-browser clients (such as automated scripts or curl) that omit `Origin`, `Referer`, and `Sec-Fetch-Site` are allowed without weakening browser cross-origin protection.

### DNS Rebinding Protection
To prevent malicious external websites from rebinding hostnames to loopback IP addresses (`127.0.0.1` / `::1`), the dashboard enforces Starlette's `TrustedHostMiddleware`. Only explicit local loopback hostnames (`localhost`, `127.0.0.1`, `[::1]`, `testserver`, and the explicitly configured `--host`) are accepted. Requests with unrecognized `Host` headers are rejected with `400 Bad Request`.

### Security Headers and Content Security Policy (CSP)
Every HTTP response includes standard hardening headers via `SecurityHeadersMiddleware`:
- `Content-Security-Policy`: Restricts scripts and styles to `'self'`, `'unsafe-inline'` (for UI components), and trusted CDN distributions (e.g., Tailwind, FontAwesome, Mermaid, KaTeX), while blocking unauthorized framing and object execution (`frame-ancestors 'none'; object-src 'none'`).
- `X-Frame-Options: DENY`: Prevents embedding in iframes or clickjacking attacks.
- `X-Content-Type-Options: nosniff`: Prevents browsers from MIME-sniffing responses away from the declared content type.
- `Referrer-Policy: strict-origin-when-cross-origin`: Minimizes referrer leakage on outbound links.

### XSS Prevention and Markdown Sanitization
Security assessment reports, findings, and diagrams often contain untrusted or adversarial text parsed from scanned targets:
- Assessment notes, finding titles, recommendations, and descriptions are rendered defensively. Any rendered Markdown strips dangerous HTML tags and script injections.
- Mermaid diagrams are initialized with `securityLevel: 'strict'`.
- Regression test coverage verifies that malicious inputs containing script tags, `javascript:` URIs, or iframe injections are neutralized.

### File Upload Limits and Extension Whitelist
The assessment attachment upload endpoint protects against disk exhaustion and malicious file types:
- Uploads are validated against an allowlist of permitted documentation extensions (`.pdf`, `.docx`, `.pptx`, `.md`, `.html`, `.htm`, `.txt`, `.json`, `.yaml`, `.yml`, `.csv`). Executables and arbitrary extensions are rejected with `400 Bad Request`.
- Upload size is enforced chunk-by-chunk during streaming against `MAX_UPLOAD_BYTES` (50 MB). Exceeding this limit immediately terminates the upload with `413 Payload Too Large` and cleans up any partially written files on disk.

### Safe Attachment Downloads
User-uploaded assessment attachments are served via a dedicated download endpoint (`GET /assessments/{assessment_id}/attachments/{attachment_id}/download`):
- Served with `Content-Type: application/octet-stream` and `Content-Disposition: attachment; filename="<sanitized_filename>"`.
- Accompanied by `X-Content-Type-Options: nosniff` to prevent browsers from executing active content (such as HTML or SVG) in the dashboard's origin.

### Runtime Key Comparison and Insecure Runtime Opt-in
- Runtime API keys used for authentication are compared using constant-time string comparison (`hmac.compare_digest`) via SQLite candidate lookups, preventing timing side-channel attacks.
- When `secfoo serve` binds to an external, non-loopback network interface, runtime key authentication requires HTTPS by default. The `--allow-insecure-runtime` CLI flag provides an explicit opt-in for deployments running behind TLS-terminating reverse proxies, without weakening CSRF or host header protections.

## Supported versions

Only the latest published release on PyPI is supported. Please upgrade
Expand Down
52 changes: 52 additions & 0 deletions fuzz/fuzz_docext.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"""Coverage-guided fuzzing of secfoo's document parsers (docext) with Atheris.

docext parses PDF, DOCX, and PPTX files for vendor security documents.
Extraction must never raise an unhandled exception or crash on malformed data (#118).

Run locally (Linux or macOS with clang):

pip install atheris
python fuzz/fuzz_docext.py -max_total_time=60

Any crash is written to the current directory as crash-<sha1>; reproduce
with `python fuzz/fuzz_docext.py crash-<sha1>`.
"""

from __future__ import annotations

import sys
import tempfile
from pathlib import Path

import atheris

with atheris.instrument_imports():
from secfoo.docext import extract_text, is_extractable

EXTENSIONS = [".pdf", ".docx", ".pptx"]


def test_one_input(data: bytes) -> None:
if not data:
return
# Use the first byte to pick the extension
ext = EXTENSIONS[data[0] % len(EXTENSIONS)]
content = data[1:]

assert is_extractable(f"sample{ext}")

with tempfile.TemporaryDirectory() as tmp_dir:
tmp_file = Path(tmp_dir) / f"fuzz_input{ext}"
tmp_file.write_bytes(content)
# extract_text must never raise unhandled exceptions on malformed files
result = extract_text(tmp_file)
assert isinstance(result, str)


def main() -> None:
atheris.Setup(sys.argv, test_one_input)
atheris.Fuzz()


if __name__ == "__main__":
main()
5 changes: 4 additions & 1 deletion src/secfoo/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,7 @@ def run_dir(run_uuid: str) -> Path:


def attachment_dir(assessment_id: int) -> Path:
return ATTACHMENTS_DIR / str(assessment_id)
safe_id = int(assessment_id)
if safe_id <= 0:
raise ValueError(f"Invalid assessment_id: {assessment_id}")
return ATTACHMENTS_DIR / str(safe_id)
25 changes: 15 additions & 10 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 @@ -81,17 +82,21 @@ def revoke_key(conn: sqlite3.Connection, key_id: int) -> bool:


def verify_key(conn: sqlite3.Connection, key: str) -> ApiKey | None:
"""The active key record for `key`, or None (unknown or revoked)."""
"""The active key record for `key`, or None (unknown or revoked). Constant-time check (#118)."""
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
).fetchone()
if row is None:
candidate_hash = hash_key(key)
rows = conn.execute(
f"SELECT {_COLUMNS}, key_hash FROM runtime_api_keys WHERE key_prefix = ? AND revoked_at IS NULL", # nosec B608
(key[:10],),
).fetchall()
matched = None
for row in rows:
stored_hash = row[-1]
if hmac.compare_digest(stored_hash, candidate_hash):
matched = _row(row[:-1])
if matched is None:
return None
record = _row(row)
if not record.active:
return None
conn.execute("UPDATE runtime_api_keys SET last_used_at = ? WHERE id = ?", (_now(), record.id))
conn.execute("UPDATE runtime_api_keys SET last_used_at = ? WHERE id = ?", (_now(), matched.id))
conn.commit()
return record
return matched
7 changes: 7 additions & 0 deletions src/secfoo/storage/repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -894,6 +894,13 @@ def list_attachments(self, assessment_id: int) -> list[AttachmentRecord]:
).fetchall()
return [AttachmentRecord(**dict(row)) for row in rows]

def get_attachment(self, attachment_id: int) -> AttachmentRecord | None:
row = self._conn.execute(
"SELECT * FROM assessment_attachments WHERE id = ?",
(attachment_id,),
).fetchone()
return AttachmentRecord(**dict(row)) if row is not None else None

def add_ai_bom_items(self, attachment_id: int, items: list[dict[str, str | None]]) -> None:
if not items:
return
Expand Down
25 changes: 23 additions & 2 deletions src/secfoo/web/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from starlette.responses import PlainTextResponse
from starlette.middleware.trustedhost import TrustedHostMiddleware

from secfoo.config import STORE_DIR
from secfoo.runtime import api as runtime_api
Expand All @@ -18,6 +18,11 @@
runs,
third_party,
)
from secfoo.web.security import (
LOOPBACK_HOSTS,
CrossSiteProtectionMiddleware,
SecurityHeadersMiddleware,
)

STATIC_DIR = Path(__file__).parent / "static"

Expand All @@ -35,13 +40,29 @@ def mermaid_bundle_available() -> bool:
return MERMAID_BUNDLE.is_file()


def create_app(*, bind_host: str = "127.0.0.1", allow_insecure_runtime: bool = False) -> FastAPI:
def create_app(
*,
bind_host: str = "127.0.0.1",
allow_insecure_runtime: bool = False,
allowed_hosts: list[str] | None = None,
) -> FastAPI:
app = FastAPI(title="secfoo dashboard")
# Read by the runtime ingest API (#66): on a non-loopback bind it refuses
# API keys over plain HTTP unless the operator opted in.
app.state.bind_host = bind_host
app.state.allow_insecure_runtime = allow_insecure_runtime

# Host allowlisting for DNS rebinding protection (#118)
hosts = list(LOOPBACK_HOSTS)
if bind_host and bind_host not in hosts:
hosts.append(bind_host)
if allowed_hosts:
hosts = list(allowed_hosts)

app.add_middleware(SecurityHeadersMiddleware)
app.add_middleware(CrossSiteProtectionMiddleware, allowed_hostnames=set(hosts))
app.add_middleware(TrustedHostMiddleware, allowed_hosts=hosts)

@app.middleware("http")
async def revalidate_static(request, call_next):
# Make the browser re-check stylesheets/scripts on each load (a cheap
Expand Down
101 changes: 87 additions & 14 deletions src/secfoo/web/routes/assessments.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

import os
import re
import shutil
import tempfile
import threading
Expand All @@ -8,7 +10,7 @@
from urllib.parse import urlencode

from fastapi import APIRouter, Form, HTTPException, Request, UploadFile
from fastapi.responses import RedirectResponse
from fastapi.responses import FileResponse, RedirectResponse

from secfoo import docext
from secfoo.agents.registry import ADAPTERS, get_adapter
Expand All @@ -22,12 +24,20 @@
from secfoo.storage.repository import RunRepository
from secfoo.targets.resolver import TargetResolutionError, resolve_target
from secfoo.web.run_status import assessment_pipeline
from secfoo.web.templating import SIDEBAR_ACTIVITY_IDS, ordered_skills, severity_rows, templates
from secfoo.web.templating import (
SIDEBAR_ACTIVITY_IDS,
ordered_skills,
severity_rows,
templates,
)
from secfoo.web.third_party_dashboard import SKILL_ID as THIRD_PARTY_RISK_SKILL_ID

router = APIRouter()

_ACTIVE_RUN_STATUSES = {"pending", "running"}
ALLOWED_ATTACHMENT_EXTENSIONS = frozenset(
{".pdf", ".docx", ".pptx", ".md", ".html", ".htm", ".txt", ".json", ".yaml", ".yml", ".csv"}
)


def _extracted_text_path(file_path: Path) -> Path:
Expand Down Expand Up @@ -396,25 +406,57 @@ def assessment_upload(assessment_id: int, file: UploadFile):
# using the raw filename directly here would be a path-traversal /
# arbitrary-file-write bug (confirmed by a real threat-assessment
# run against this exact route).
filename = Path(file.filename or "upload").name
raw_name = os.path.basename(file.filename or "upload")
clean_name = re.sub(r"[^\w.-]", "_", raw_name).strip("._")
filename = os.path.basename(clean_name or "upload")
if not filename or filename in (".", ".."):
raise HTTPException(status_code=400, detail="Invalid filename")

ext = Path(filename).suffix.lower()
if ext not in ALLOWED_ATTACHMENT_EXTENSIONS:
raise HTTPException(
status_code=400,
detail=f"Unsupported file type '{ext}'. Allowed types: {', '.join(sorted(ALLOWED_ATTACHMENT_EXTENSIONS))}",
)

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():
safe_assessment_id = int(assessment_id)
if safe_assessment_id <= 0:
raise HTTPException(status_code=400, detail="Invalid assessment ID")

dest_dir = attachment_dir(safe_assessment_id)
dest_dir_str = os.path.realpath(os.path.normpath(str(dest_dir)))
os.makedirs(dest_dir_str, exist_ok=True)
dest_path_str = os.path.realpath(os.path.normpath(os.path.join(dest_dir_str, filename)))
if not dest_path_str.startswith(dest_dir_str + os.sep):
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.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)")
dest = Path(dest_path_str)

# Stream chunk-by-chunk to enforce size limit before writing entire file to disk (#118)
bytes_written = 0
chunk_size = 64 * 1024
max_bytes = docext.MAX_UPLOAD_BYTES
try:
with open(dest_path_str, "wb") as fh:
while True:
chunk = file.file.read(chunk_size)
if not chunk:
break
bytes_written += len(chunk)
if bytes_written > max_bytes:
if os.path.exists(dest_path_str):
os.unlink(dest_path_str)
max_mb = max_bytes // (1024 * 1024)
raise HTTPException(status_code=413, detail=f"File too large (max {max_mb}MB)")
fh.write(chunk)
except Exception:
if os.path.exists(dest_path_str) and bytes_written > max_bytes:
os.unlink(dest_path_str)
raise

new_attachment_id = repo.add_attachment(
assessment_id=assessment_id, file_path=str(dest), original_name=filename, attachment_kind=kind
assessment_id=assessment_id, file_path=dest_path_str, original_name=filename, attachment_kind=kind
)

if kind == "ai_bom":
Expand Down Expand Up @@ -464,3 +506,34 @@ def assessment_delete(assessment_id: int):
raise HTTPException(status_code=404, detail="Assessment not found")
repo.delete_assessment(assessment_id)
return {"ok": True}


@router.get("/assessments/{assessment_id}/attachments/{attachment_id}/download")
def assessment_attachment_download(assessment_id: int, attachment_id: int):
safe_assessment_id = int(assessment_id)
safe_attachment_id = int(attachment_id)
if safe_assessment_id <= 0 or safe_attachment_id <= 0:
raise HTTPException(status_code=400, detail="Invalid ID")

with RunRepository() as repo:
attachment = repo.get_attachment(safe_attachment_id)
if attachment is None or attachment.assessment_id != safe_assessment_id:
raise HTTPException(status_code=404, detail="Attachment not found")

expected_dir_str = os.path.realpath(os.path.normpath(str(attachment_dir(safe_assessment_id))))
target_file_str = os.path.realpath(os.path.normpath(str(attachment.file_path)))
if not target_file_str.startswith(expected_dir_str + os.sep):
raise HTTPException(status_code=403, detail="Invalid attachment path")
if not os.path.isfile(target_file_str):
raise HTTPException(status_code=404, detail="Attachment file not found")

filename = os.path.basename(attachment.original_name)
return FileResponse(
path=target_file_str,
media_type="application/octet-stream",
filename=filename,
headers={
"Content-Disposition": f'attachment; filename="{filename}"',
"X-Content-Type-Options": "nosniff",
},
)
Loading
Loading