Skip to content
Open
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
22 changes: 22 additions & 0 deletions Structure_README.md
Original file line number Diff line number Diff line change
Expand Up @@ -777,6 +777,28 @@ drops internet briefly) re-dials on its own. Both only run while ppp0 is
actually **up** (a dead dial has nothing to renew into), and the last-renewed
timestamp is persisted so a gateway restart never re-renews mid-schedule.

### Request body inspection by the WAF

`waf.max_body_bytes` (default 1 MiB) limits the bytes buffered to inspect
`POST`, `PUT`, `PATCH`, and `DELETE` bodies. The WAF checks the actual byte
count while reading, even when the client omits `Content-Length`. Strict mode
returns HTTP 413 for an oversized body before the route runs. Log mode records
the event and forwards the entire stream, including the bytes read before
the limit was reached, without auto-banning the client. The local-subnet exemption and WAF off mode
bypass inspection. Routes that accept large inputs still need their own limits
when WAF blocking is disabled or exempted.

In strict mode, the WAF keeps at most 4,096 active source/endpoint rate buckets
and 4,096 source histories for auto-ban. Rate buckets expire after each
endpoint's configured window. Auto-ban holds only the most recent
`waf.auto_ban_after` timestamps per source and drops hits outside
`waf.ban_window_seconds`. A five-second sweep removes expired state even
without incoming requests. When the rate table is full, an untracked source
on a rate-limited route receives 429 until a slot frees up. A full auto-ban
table keeps its active histories. New sources are still blocked for WAF
violations, but their hits do not accumulate toward a firewall ban until
space becomes available.

### Tailscale remote access

`quota/tailscale.py` (`TailscaleManager`) manages the official `tailscale`
Expand Down
163 changes: 96 additions & 67 deletions api/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@
PlainTextResponse, RedirectResponse,
StreamingResponse)
from fastapi.staticfiles import StaticFiles
from starlette.datastructures import MutableHeaders
from starlette.types import ASGIApp, Message, Receive, Scope, Send
from contextlib import asynccontextmanager

from api.schemas import (BundleUpdate, ConsumptionSpoofRequest, DeviceCreate,
Expand Down Expand Up @@ -4256,6 +4258,11 @@ async def _push_loop() -> None:
except Exception: # noqa: BLE001
active_ws.discard(ws)

async def _expire_waf_state() -> None:
while True:
await asyncio.sleep(_waf.RATE_STATE_SWEEP_SECONDS)
waf_state.expire(time.monotonic())

@asynccontextmanager
async def _lifespan(_app: FastAPI):
# startup
Expand Down Expand Up @@ -4304,6 +4311,7 @@ async def _disk_heal_loop():

disk_restore_task = asyncio.get_running_loop().create_task(_restore_disk_shares())
disk_heal_task = asyncio.get_running_loop().create_task(_disk_heal_loop())
waf_expiry_task = asyncio.create_task(_expire_waf_state())
try:
yield
finally:
Expand All @@ -4312,6 +4320,8 @@ async def _disk_heal_loop():
share_cleanup_task.cancel()
disk_restore_task.cancel()
disk_heal_task.cancel()
waf_expiry_task.cancel()
await asyncio.gather(waf_expiry_task, return_exceptions=True)
try:
await push_task
except (asyncio.CancelledError, Exception):
Expand Down Expand Up @@ -4340,7 +4350,10 @@ async def _disk_heal_loop():
# (blocking) on WAN, log-only on LAN; fail-closed on WAN if the layer
# itself errors.

waf_state = _waf.WafRateState()
waf_state = _waf.WafRateState(
ban_threshold=int(getattr(waf_cfg, "auto_ban_after", 8) or 0),
ban_window_seconds=float(getattr(waf_cfg, "ban_window_seconds", 300) or 300),
)

def _waf_mode() -> str:
if not getattr(waf_cfg, "enabled", True):
Expand All @@ -4349,18 +4362,35 @@ def _waf_mode() -> str:
if holder else "lan"
return _waf.resolve_mode(getattr(waf_cfg, "mode", "auto"), topology)

@app.middleware("http")
async def _security_middleware(request: Request,
call_next) -> Response:
"""WAF inspection + CSRF custom-header guard + security headers.
def _security_middleware(app: ASGIApp) -> ASGIApp:
async def dispatch(scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await app(scope, receive, send)
return

body = _waf.InspectionBody(receive)
request = Request(scope, receive=body.receive)
response = await _security_response(request, body)
if response is not None:
await response(scope, body.receive, send)
return

Order: WAF first (reject the request before any handler runs), then
CSRF (a session-bearing cross-site mutation must carry ``X-QM-CSRF``),
then the response is stamped with the security headers. A WAF crash
async def send_with_security_headers(message: Message) -> None:
if message["type"] == "http.response.start":
_stamp_security_headers(request.url.path, MutableHeaders(scope=message))
await send(message)

await app(scope, body.receive, send_with_security_headers)
return dispatch

async def _security_response(request: Request,
body: _waf.InspectionBody) -> Response | None:
"""Return an early response for captive guests, WAF, or CSRF checks.

WAF runs before CSRF and can reject the request before the handler. A WAF crash
fails CLOSED in strict mode (503) — the dashboard becomes unreachable
rather than silently unprotected — and OPEN (pass + log) in log mode.
"""
response: Response | None = None
try:
# Captive portal redirection for pending guests
host = request.client.host if request.client else ""
Expand All @@ -4385,7 +4415,7 @@ async def _security_middleware(request: Request,

waf_mode = _waf_mode()
if waf_mode != "off":
blocked = await _waf_inspect(request, waf_mode)
blocked = await _waf_inspect(request, body, waf_mode)
if blocked is not None:
return blocked
# CSRF: a state-changing request carrying a valid session cookie
Expand All @@ -4412,15 +4442,12 @@ async def _security_middleware(request: Request,
return JSONResponse(
{"detail": "security layer unavailable"},
status_code=503)
response = await call_next(request)
_stamp_security_headers(request.url.path, response)
return response
return None

async def _waf_inspect(request: Request,
async def _waf_inspect(request: Request, body: _waf.InspectionBody,
waf_mode: str) -> Response | None:
"""Run the WAF checks; return a Response to short-circuit, else None."""
host = request.client.host if request.client else ""
now = time.monotonic()
cfg = waf_cfg

# -- local-management exemption ------------------------------------
Expand All @@ -4432,54 +4459,57 @@ async def _waf_inspect(request: Request,
return None

# -- cheap whole-request caps (before touching the body) --------------
max_body_bytes = getattr(cfg, "max_body_bytes", 1_048_576)
cl = request.headers.get("content-length", "")
if cl.isdigit() and int(cl) > getattr(cfg, "max_body_bytes", 1_048_576):
return await _waf_block(request, host, now, waf_mode,
"oversized-body", "request-size", cl)
if cl.isascii() and cl.isdecimal():
# Compare decimal strings so even a long header needs no bigint.
declared = cl.lstrip("0") or "0"
cap = str(max_body_bytes)
if (len(declared), declared) > (len(cap), cap):
return await _waf_block(request, host, waf_mode,
"oversized-body", "request-size", "", status_code=413)
if len(request.headers) > getattr(cfg, "max_headers", 40):
return await _waf_block(request, host, now, waf_mode,
return await _waf_block(request, host, waf_mode,
"too-many-headers", "request-size", "")
for key, value in request.headers.items():
if len(value) > getattr(cfg, "max_header_bytes", 8192):
return await _waf_block(request, host, now, waf_mode,
return await _waf_block(request, host, waf_mode,
"oversized-header", "request-size", key)

# -- signatures over path / query / body ------------------------------
body_text = ""
if request.method in ("POST", "PUT", "PATCH", "DELETE"):
try:
raw = await request.body()
except Exception: # noqa: BLE001
raw = b""
body_text = raw.decode("utf-8", "replace")
body_text = await body.inspect(max_body_bytes)
if body_text is None:
return await _waf_block(request, host, waf_mode,
"oversized-body", "request-size", "", status_code=413)
rule = _waf.classify(
request.method, request.url.path, request.url.query,
body_text, dict(request.headers))
if rule is not None and not _waf.is_exempt(
getattr(cfg, "exceptions", []), rule[0],
request.url.path, host):
return await _waf_block(request, host, now, waf_mode,
return await _waf_block(request, host, waf_mode,
rule[1], rule[0], "")

# -- scanner User-Agent -----------------------------------------------
if _waf.classify_ua(request.headers.get("user-agent", "")):
return await _waf_block(request, host, now, waf_mode,
return await _waf_block(request, host, waf_mode,
"scanner-ua", "scanner", "")

# -- per-endpoint request-rate cap (strict only; logged otherwise) ----
# -- per-endpoint request-rate cap (strict only) -----------------------
limits = getattr(cfg, "endpoint_limits", {}) or {}
if limits and waf_state.rate_limited(host, request.url.path,
limits, now):
if waf_mode == "strict":
return JSONResponse(
{"detail": "request rate limit exceeded"},
status_code=429,
headers={"Retry-After": "30"})
if waf_mode == "strict" and limits and waf_state.rate_limited(
host, request.url.path, limits, time.monotonic()):
return JSONResponse(
{"detail": "request rate limit exceeded"},
status_code=429,
headers={"Retry-After": "30"})
return None

async def _waf_block(request: Request, host: str, now: float,
waf_mode: str, category: str, rule_id: str,
extra: str) -> Response | None:
async def _waf_block(request: Request, host: str, waf_mode: str,
category: str, rule_id: str, extra: str,
*, status_code: int = 403) -> Response | None:
"""Log a WAF hit, feed the auto-ban, and (in strict mode) reject."""
where = f"{request.url.path}" + (f"?{extra}" if extra else "")
message = (f"WAF {category} ({rule_id}) from {host} "
Expand All @@ -4493,30 +4523,27 @@ async def _waf_block(request: Request, host: str, now: float,
await database.add_event(message, "warn")
except Exception: # noqa: BLE001
pass
waf_state.register_block(host, now)
auto_after = int(getattr(waf_cfg, "auto_ban_after", 8) or 0)
if auto_after and firewall is not None and \
hasattr(firewall, "ban_ip"):
window = float(getattr(waf_cfg, "ban_window_seconds", 300) or 300)
if waf_state.blocks_in_window(host, window, now) >= auto_after:
seconds = int(getattr(waf_cfg, "ban_seconds", 1800) or 1800)
try:
await firewall.ban_ip(host, seconds, "waf")
except Exception: # noqa: BLE001
log.exception("waf auto-ban failed")
if waf_mode == "strict":
return JSONResponse(
{"detail": f"blocked by WAF ({category})"},
status_code=403)
return None # log-only (LAN): record + pass through

def _stamp_security_headers(path: str, response: Response) -> None:
response.headers.setdefault("X-Content-Type-Options", "nosniff")
response.headers.setdefault("X-Frame-Options", "DENY")
response.headers.setdefault("Referrer-Policy", "no-referrer")
if waf_mode != "strict":
return None # Log-only hits never feed the firewall auto-ban.

if (firewall is not None and hasattr(firewall, "ban_ip")
and waf_state.register_block(host, time.monotonic())):
seconds = int(getattr(waf_cfg, "ban_seconds", 1800) or 1800)
try:
await firewall.ban_ip(host, seconds, "waf")
except Exception: # noqa: BLE001
log.exception("waf auto-ban failed")
return JSONResponse(
{"detail": f"blocked by WAF ({category})"},
status_code=status_code)

def _stamp_security_headers(path: str, headers: MutableHeaders) -> None:
headers.setdefault("X-Content-Type-Options", "nosniff")
headers.setdefault("X-Frame-Options", "DENY")
headers.setdefault("Referrer-Policy", "no-referrer")
# If the dashboard ever sits on a public address, search engines must
# never index the admin UI (robots.txt + this header both say so).
response.headers.setdefault("X-Robots-Tag", "noindex, nofollow")
headers.setdefault("X-Robots-Tag", "noindex, nofollow")
# Sensitive-data protection (anti-replay / anti-cache): every DATA
# response (API + the HTML pages) is marked no-store so the browser
# never writes the payloads — MACs, usage, history, events, log lines —
Expand All @@ -4526,31 +4553,33 @@ def _stamp_security_headers(path: str, response: Response) -> None:
# Without a header browsers cache them heuristically for days, so after an
# update the dashboard kept running the OLD app.js against the NEW API.
if path.startswith(("/assets/", "/js/", "/css/", "/fonts/")) or path == "/logo.svg":
response.headers.setdefault("Cache-Control", "no-cache")
headers.setdefault("Cache-Control", "no-cache")
if path.startswith(("/api", "/report", "/milestone", "/share", "/guest-pending", "/guest/pending", "/spoof")) or path == "/":
response.headers.setdefault("Cache-Control",
"no-store, no-cache, must-revalidate, max-age=0")
response.headers.setdefault("Pragma", "no-cache")
response.headers.setdefault("Expires", "0")
headers.setdefault("Cache-Control",
"no-store, no-cache, must-revalidate, max-age=0")
headers.setdefault("Pragma", "no-cache")
headers.setdefault("Expires", "0")
# Strict CSP for the dashboard + API. /report, /milestone, /share, the guest
# portal and the calibration page carry inline scripts, so they get the
# looser (still-useful) profile (a strict script-src blocked the guest
# page's status polling and its "Check now" button).
if path.startswith(("/report", "/milestone", "/share", "/guest/pending", "/spoof")):
response.headers.setdefault(
headers.setdefault(
"Content-Security-Policy",
"default-src 'self'; style-src 'self' 'unsafe-inline'; "
"img-src 'self' data: blob:; connect-src 'self' ws: wss:; "
"script-src 'self' 'unsafe-inline'; base-uri 'self'; "
"frame-ancestors 'none'; form-action 'self'")
else:
response.headers.setdefault(
headers.setdefault(
"Content-Security-Policy",
"default-src 'self'; script-src 'self'; "
"style-src 'self' 'unsafe-inline'; img-src 'self' data:; "
"connect-src 'self' ws: wss:; font-src 'self'; "
"base-uri 'self'; frame-ancestors 'none'; form-action 'self'")

app.add_middleware(_security_middleware)

# The dashboard used to live under /ui/ while the classic one sat at "/".
# Old bookmarks and any cached page still point there: send them to the same
# file at the root (so /ui/ -> /, /ui/js/main.js -> /js/main.js).
Expand Down
Loading
Loading