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
21 changes: 20 additions & 1 deletion SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,26 @@ way you'd treat opening it in your agent CLI in the first place.

`secfoo serve` binds to `127.0.0.1` by default and has no authentication —
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.
putting your own authenticating reverse proxy in front of it (`secfoo serve`
prints a warning when `--host` is not loopback).

Because the dashboard runs on your machine while you browse other sites, it
defends against your own browser being used against it:

- **Cross-site writes are refused.** Every state-changing request (start an
agent run, delete a case file, review a finding) must come from the
dashboard's own origin; a request whose `Origin`, `Sec-Fetch-Site` or
`Referer` names another site gets `403`. Clients that send none of these
(curl, scripts) are unaffected. The runtime ingest API is authenticated by
its API key instead.
- **DNS rebinding is refused.** Requests must name the dashboard by
`localhost`, `127.0.0.1`, `[::1]` or its `--host`; any other `Host` gets
`400`. Reaching it through a port-forwarding or proxy name? Add that name
with `secfoo serve --allow-host NAME`. A wildcard `--host 0.0.0.0` accepts
any name.
- **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`.

`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
16 changes: 15 additions & 1 deletion src/secfoo/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -873,6 +873,11 @@ def serve(
"--runtime-recheck-hours",
help="Re-check running package versions against OSV this often (#68). 0 disables.",
)] = 6.0,
allow_host: Annotated[Optional[list[str]], typer.Option(
"--allow-host",
help="Also answer to this host name (repeatable), e.g. a port-forwarding or reverse-proxy name. "
"Requests naming any other host are refused, which blocks DNS rebinding.",
)] = None,
) -> None:
"""Launch the local web dashboard."""
if ctx.invoked_subcommand is not None:
Expand All @@ -885,7 +890,16 @@ def serve(
if runtime_recheck_hours > 0:
_start_runtime_recheck(runtime_recheck_hours)
console.print(f"Serving dashboard at [bold]http://{host}:{port}[/]")
uvicorn.run(create_app(bind_host=host, allow_insecure_runtime=allow_insecure_runtime), host=host, port=port)
from secfoo.web.security import is_loopback

if not is_loopback(host):
err_console.print(
f"[yellow]Warning:[/] --host {host} is reachable from other machines. The dashboard has no login: "
"anyone who can reach it can read every report and start agent runs. Prefer 127.0.0.1 "
"(or an SSH tunnel / authenticating reverse proxy)."
)
app = create_app(bind_host=host, allow_insecure_runtime=allow_insecure_runtime, allow_hosts=allow_host or ())
uvicorn.run(app, host=host, port=port)


def _start_runtime_recheck(hours: float) -> None:
Expand Down
11 changes: 10 additions & 1 deletion src/secfoo/web/app.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

from collections.abc import Iterable
from pathlib import Path

from fastapi import FastAPI
Expand All @@ -8,6 +9,7 @@

from secfoo.config import STORE_DIR
from secfoo.runtime import api as runtime_api
from secfoo.web import security
from secfoo.web.routes import (
activities,
agents,
Expand Down Expand Up @@ -35,7 +37,9 @@ 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, allow_hosts: Iterable[str] = ()
) -> 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.
Expand All @@ -58,6 +62,11 @@ async def revalidate_static(request, call_next):
if request.url.path.startswith("/static/"):
response.headers["Cache-Control"] = "no-cache"
return response

# Added last so it is the outermost layer: Host/Origin checks run before
# any route, and security headers land on every response, rejections included.
security.install(app, bind_host=bind_host, allow_hosts=allow_hosts)

# Mounted BEFORE /static: Starlette matches mounts in registration
# order, so the broader /static would otherwise swallow /static/vendor.
VENDOR_DIR.mkdir(parents=True, exist_ok=True)
Expand Down
122 changes: 122 additions & 0 deletions src/secfoo/web/security.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
"""Browser-facing protections for the local dashboard (#118).

`secfoo serve` binds 127.0.0.1 and has no login, so the threat is the user's
own browser: any page they visit can send requests to http://127.0.0.1:8787.

- Cross-site writes: a page can POST a form (or `fetch(..., {mode: "no-cors"})`)
to start a paid agent run, delete a case file or flip a finding review.
Unsafe methods must come from the dashboard's own origin. Browsers always
send `Origin` (and modern ones `Sec-Fetch-Site`) on such requests, so a
request carrying neither is a non-browser client (curl, the CLI, tests).
- DNS rebinding: an attacker's hostname that resolves to 127.0.0.1 makes the
dashboard same-origin with the attacker's page, which could then read every
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.

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
preflight the app never grants, so it is exempt from the origin check (sensors
are not browsers) but not from the Host check.
"""
from __future__ import annotations

from urllib.parse import urlsplit

from starlette.responses import PlainTextResponse

LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1"}
WILDCARD_BINDS = {"", "0.0.0.0", "::"}
SAFE_METHODS = {"GET", "HEAD", "OPTIONS"}
MACHINE_API_PREFIX = "/api/runtime/"

CONTENT_SECURITY_POLICY = (
"default-src 'self'; "
"script-src 'self'; "
# Mermaid writes <style> into the SVGs it renders; no script is inline.
"style-src 'self' 'unsafe-inline'; "
"img-src 'self' data:; "
"font-src 'self' data:; "
"connect-src 'self'; "
"object-src 'none'; "
"base-uri 'none'; "
"form-action 'self'; "
"frame-ancestors 'none'"
)
SECURITY_HEADERS = {
"Content-Security-Policy": CONTENT_SECURITY_POLICY,
"X-Frame-Options": "DENY",
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "same-origin",
"Cross-Origin-Opener-Policy": "same-origin",
"Cross-Origin-Resource-Policy": "same-origin",
}


def _hostname(netloc: str) -> str:
"""'127.0.0.1:8787' -> '127.0.0.1', '[::1]:8787' -> '::1', 'LocalHost.' -> 'localhost'."""
netloc = netloc.strip().lower()
if netloc.startswith("["):
return netloc[1:netloc.find("]")] if "]" in netloc else ""
if netloc.count(":") == 1:
netloc = netloc.rsplit(":", 1)[0]
return netloc.rstrip(".")


def is_loopback(host: str) -> bool:
return _hostname(host) in LOOPBACK_HOSTS


def allowed_hosts(bind_host: str, extra=()) -> set[str] | None:
"""Host names the dashboard answers to; None means any (a wildcard bind,
where the operator already chose to expose it to the network)."""
bind = _hostname(bind_host)
if bind in WILDCARD_BINDS:
return None
return set(LOOPBACK_HOSTS) | {bind} | {_hostname(name) for name in extra}


def _same_origin(url: str, host_header: str) -> bool:
parts = urlsplit(url)
return parts.scheme in {"http", "https"} and parts.netloc.lower() == host_header.strip().lower()


def check_request(method: str, path: str, headers, hosts: set[str] | None) -> PlainTextResponse | None:
"""Return a rejection response, or None to let the request through."""
host_header = headers.get("host", "")
if hosts is not None and _hostname(host_header) not in hosts:
return PlainTextResponse(
"Invalid Host header. secfoo serve only answers to loopback names and its --host; "
"add another name with --allow-host NAME.", status_code=400)
if method.upper() in SAFE_METHODS or path.startswith(MACHINE_API_PREFIX):
return None
fetch_site = headers.get("sec-fetch-site")
if fetch_site is not None and fetch_site not in {"same-origin", "none"}:
return PlainTextResponse("Cross-site request refused", status_code=403)
origin = headers.get("origin")
if origin is not None:
if not _same_origin(origin, host_header): # includes Origin: null
return PlainTextResponse("Cross-origin request refused", status_code=403)
elif fetch_site is None:
referer = headers.get("referer")
if referer and not _same_origin(referer, host_header):
return PlainTextResponse("Cross-origin request refused", status_code=403)
return None


def install(app, *, bind_host: str, allow_hosts=()) -> None:
hosts = allowed_hosts(bind_host, allow_hosts)

@app.middleware("http")
async def dashboard_security(request, call_next):
# Read at request time so tests can add TestClient's "testserver".
current = None if hosts is None else hosts | EXTRA_ALLOWED_HOSTS
refused = check_request(request.method, request.url.path, request.headers, current)
response = refused or await call_next(request)
for name, value in SECURITY_HEADERS.items():
response.headers.setdefault(name, value)
return response


# Empty in production; tests/conftest.py adds Starlette TestClient's default host.
EXTRA_ALLOWED_HOSTS: set[str] = set()
7 changes: 7 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ def _isolated_custom_skills(tmp_path_factory, monkeypatch):
loader._reset_for_tests()


@pytest.fixture(autouse=True)
def _testclient_host_is_allowed(monkeypatch):
"""The dashboard refuses foreign Host headers (DNS rebinding, #118);
Starlette's TestClient sends "Host: testserver" by default."""
monkeypatch.setattr("secfoo.web.security.EXTRA_ALLOWED_HOSTS", {"testserver"})


class FakePopen:
"""Stand-in for subprocess.Popen used by AgentAdapter.run()."""

Expand Down
153 changes: 153 additions & 0 deletions tests/test_web/test_dashboard_security.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
"""Cross-site writes, DNS rebinding and security headers on the local dashboard (#118)."""
from __future__ import annotations

import re

import pytest
from fastapi.testclient import TestClient

from secfoo.storage.repository import RunRepository
from secfoo.web import security
from secfoo.web.app import create_app

DASHBOARD = "http://127.0.0.1:8787"
EVIL = "https://evil.example"


@pytest.fixture
def app(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")
monkeypatch.setattr("secfoo.web.security.EXTRA_ALLOWED_HOSTS", set()) # behave like `secfoo serve`
return create_app(bind_host="127.0.0.1")


@pytest.fixture
def client(app, tmp_path):
client = TestClient(app, base_url=DASHBOARD, follow_redirects=False)
client.target = tmp_path / "project"
client.target.mkdir()
return client


def _assessment_count():
with RunRepository() as repo:
return len(repo.list_assessments())


def _create(client, **headers):
return client.post("/assessments", data={"project_name": "p", "project": str(client.target),
"assessment_type": "internal"}, headers=headers)


def _routes(routes):
"""Flatten FastAPI's included routers into (method, path) pairs."""
for route in routes:
inner = getattr(route, "original_router", None)
if inner is not None:
yield from _routes(inner.routes)
else:
for method in getattr(route, "methods", None) or ():
yield method, route.path


# ---------- cross-site writes ----------

@pytest.mark.parametrize("headers", [
{"Origin": EVIL},
{"Origin": "null"}, # sandboxed iframe, data: URL, file://
{"Origin": "http://127.0.0.1:9999"}, # another local server: same site, different origin
{"Origin": "http://localhost:8787"}, # same port, but not the host this page was loaded from
{"Sec-Fetch-Site": "cross-site"},
{"Sec-Fetch-Site": "same-site"},
{"Referer": EVIL + "/attack.html"}, # no Origin/Sec-Fetch-Site: an old browser
])
def test_cross_site_form_post_is_refused_and_has_no_effect(client, headers):
resp = _create(client, **headers)
assert resp.status_code == 403
assert _assessment_count() == 0


def test_same_origin_browser_post_is_accepted(client):
resp = _create(client, Origin=DASHBOARD, **{"Sec-Fetch-Site": "same-origin", "Referer": DASHBOARD + "/assessments/new"})
assert resp.status_code == 303
assert _assessment_count() == 1


def test_non_browser_clients_without_origin_headers_still_work(client):
"""curl, scripts and the CLI send neither Origin nor Sec-Fetch-Site."""
assert _create(client).status_code == 303


def test_every_state_changing_dashboard_route_is_covered(app, client):
"""Any POST/PUT/PATCH/DELETE route added later is protected too."""
unsafe = [(method, path) for method, path in _routes(app.routes)
if method not in security.SAFE_METHODS and not path.startswith(security.MACHINE_API_PREFIX)]
assert len(unsafe) >= 6
for method, path in unsafe:
concrete = re.sub(r"\{[^}]+\}", "1", path)
resp = client.request(method, concrete, headers={"Origin": EVIL})
assert resp.status_code == 403, (method, path)


def test_runtime_api_is_exempt_from_the_origin_check_but_still_needs_its_key(client):
resp = client.post("/api/runtime/v1/events", params={"project": "p"}, content="{}\n", headers={"Origin": EVIL})
assert resp.status_code == 401


def test_reads_are_not_blocked_by_origin(client):
assert client.get("/assessments", headers={"Origin": EVIL, "Sec-Fetch-Site": "cross-site"}).status_code == 200


# ---------- DNS rebinding ----------

@pytest.mark.parametrize("host", ["rebind.evil.example", "rebind.evil.example:8787", "127.0.0.1.evil.example",
"localhost.evil.example", "", "8787"])
def test_foreign_host_header_is_refused(client, host):
resp = client.get("/", headers={"Host": host})
assert resp.status_code == 400


@pytest.mark.parametrize("host", ["127.0.0.1:8787", "localhost:8787", "LOCALHOST:8787", "localhost.:8787",
"[::1]:8787", "127.0.0.1"])
def test_loopback_host_headers_are_served(client, host):
assert client.get("/", headers={"Host": host}).status_code == 200


def test_the_bind_host_is_allowed_and_a_wildcard_bind_allows_any_host(monkeypatch, tmp_path):
monkeypatch.setattr("secfoo.storage.repository.DB_PATH", tmp_path / "db.sqlite")
monkeypatch.setattr("secfoo.web.security.EXTRA_ALLOWED_HOSTS", set())
lan = TestClient(create_app(bind_host="10.0.0.5"), base_url="http://10.0.0.5:8787")
assert lan.get("/").status_code == 200
assert lan.get("/", headers={"Host": "rebind.evil.example"}).status_code == 400
anyhost = TestClient(create_app(bind_host="0.0.0.0"), base_url="http://secfoo.internal:8787")
assert anyhost.get("/").status_code == 200
# ...but cross-site writes are still refused on a wildcard bind.
assert anyhost.post("/assessments", data={}, headers={"Origin": EVIL}).status_code == 403


def test_allow_host_adds_a_forwarded_name(monkeypatch, tmp_path):
monkeypatch.setattr("secfoo.storage.repository.DB_PATH", tmp_path / "db.sqlite")
monkeypatch.setattr("secfoo.web.security.EXTRA_ALLOWED_HOSTS", set())
app = create_app(bind_host="127.0.0.1", allow_hosts=["Dash.Example.Dev"])
forwarded = TestClient(app, base_url="https://dash.example.dev")
assert forwarded.get("/").status_code == 200
refused = forwarded.get("/", headers={"Host": "other.example.dev"})
assert refused.status_code == 400 and "--allow-host" in refused.text


# ---------- headers ----------

def test_security_headers_on_pages_static_files_and_rejections(client):
for resp in (client.get("/"), client.get("/static/js/theme.js"), client.get("/", headers={"Host": "evil"})):
assert resp.headers["X-Frame-Options"] == "DENY"
assert resp.headers["X-Content-Type-Options"] == "nosniff"
csp = resp.headers["Content-Security-Policy"]
assert "script-src 'self'" in csp and "frame-ancestors 'none'" in csp and "'unsafe-eval'" not in csp
assert "'unsafe-inline'" not in csp.split("script-src", 1)[1].split(";", 1)[0]


def test_serve_warns_when_bound_beyond_loopback():
assert security.is_loopback("127.0.0.1") and security.is_loopback("[::1]") and security.is_loopback("localhost")
assert not security.is_loopback("0.0.0.0") and not security.is_loopback("10.0.0.5")
Loading