From 08ed9fc37715f4206fa26c222e3a5cc24b7a5ccf Mon Sep 17 00:00:00 2001 From: noiemany <51255434+compnew2006@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:19:09 +0200 Subject: [PATCH 1/2] fix(waf): bound request body inspection while streaming --- Structure_README.md | 11 +++++ api/app.py | 104 +++++++++++++++++++++++++---------------- api/waf.py | 40 ++++++++++++++++ core/config.py | 5 +- tests/test_security.py | 87 ++++++++++++++++++++++++++++++++-- 5 files changed, 202 insertions(+), 45 deletions(-) diff --git a/Structure_README.md b/Structure_README.md index 831b9f0..68bcad1 100644 --- a/Structure_README.md +++ b/Structure_README.md @@ -777,6 +777,17 @@ 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. + ### Tailscale remote access `quota/tailscale.py` (`TailscaleManager`) manages the official `tailscale` diff --git a/api/app.py b/api/app.py index 4c23549..c3b3720 100644 --- a/api/app.py +++ b/api/app.py @@ -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, @@ -4349,18 +4351,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 + + 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) - 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 + 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 "" @@ -4385,7 +4404,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 @@ -4412,11 +4431,9 @@ 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 "" @@ -4432,10 +4449,15 @@ 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, now, 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, "too-many-headers", "request-size", "") @@ -4447,11 +4469,10 @@ async def _waf_inspect(request: Request, # -- 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, now, 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)) @@ -4479,7 +4500,7 @@ async def _waf_inspect(request: Request, async def _waf_block(request: Request, host: str, now: float, waf_mode: str, category: str, rule_id: str, - extra: str) -> Response | None: + 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} " @@ -4493,6 +4514,9 @@ async def _waf_block(request: Request, host: str, now: float, await database.add_event(message, "warn") except Exception: # noqa: BLE001 pass + if waf_mode != "strict": + return None # Log-only hits never feed the firewall auto-ban. + 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 \ @@ -4504,19 +4528,17 @@ async def _waf_block(request: Request, host: str, now: float, 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") + 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 — @@ -4526,31 +4548,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). diff --git a/api/waf.py b/api/waf.py index dea0eca..5d6efca 100644 --- a/api/waf.py +++ b/api/waf.py @@ -28,6 +28,46 @@ import ipaddress import re +from starlette.types import Message, Receive + + +class InspectionBody: + """Buffer a bounded HTTP body for inspection, then replay the same bytes.""" + + def __init__(self, receive: Receive) -> None: + self._receive = receive + self._prefix: bytearray | None = None + self._more_body = True + self._pending: Message | None = None + + async def inspect(self, limit: int) -> str | None: + """Return decoded text, or None at the first chunk that exceeds the cap.""" + prefix = self._prefix = bytearray() + while self._more_body: + message = await self._receive() + if message["type"] == "http.disconnect": + self._pending = message + return "" + chunk = message.get("body", b"") + if len(chunk) > limit - len(prefix): + # Log mode still needs to pass this event on. Keep the original + # message without copying its bytes into the inspection buffer. + self._pending = message + return None + prefix.extend(chunk) + self._more_body = message.get("more_body", False) + return prefix.decode("utf-8", "replace") + + async def receive(self) -> Message: + if self._prefix is not None: + prefix, self._prefix = self._prefix, None + return {"type": "http.request", "body": bytes(prefix), "more_body": self._more_body} + if self._pending is not None: + message, self._pending = self._pending, None + return message + return await self._receive() + + #: HTTP verbs the dashboard actually uses; everything else is rejected #: outright (TRACE/CONNECT and unused verbs are attack surface, not features). ALLOWED_METHODS = frozenset({"GET", "POST", "PUT", "PATCH", "DELETE", diff --git a/core/config.py b/core/config.py index e58d080..3854801 100644 --- a/core/config.py +++ b/core/config.py @@ -556,14 +556,15 @@ class WafConfig: enabled: bool = True #: "auto" | "strict" | "log" | "off" ("auto" = strict on WAN, log on LAN). mode: str = "auto" - #: Body size cap (bytes) — larger requests are 413'd before parsing. + #: WAF inspection cap in bytes. Strict mode returns 413 on overflow; + #: log mode records the overflow and passes the original stream through. max_body_bytes: int = 1_048_576 #: Max request header count and per-header bytes (431 on overflow). max_headers: int = 40 max_header_bytes: int = 8_192 #: "closed" (unreachable rather than unprotected) | "open" (pass through). fail_mode: str = "closed" - #: WAF hits from one source within ``ban_window_seconds`` that trigger an + #: Strict-mode WAF hits within ``ban_window_seconds`` that trigger an #: automatic firewall IP ban (``0`` disables the auto-ban). auto_ban_after: int = 8 ban_seconds: int = 1800 diff --git a/tests/test_security.py b/tests/test_security.py index 7b96634..c3e68ee 100644 --- a/tests/test_security.py +++ b/tests/test_security.py @@ -5,6 +5,7 @@ import asyncio import time +import httpx import pytest # import asyncio _cached_loop = None @@ -49,8 +50,8 @@ async def _init(): _get_loop().run_until_complete(_init()) - def _make(waf_config=None, web_config=None): - return create_app(database, service, holder, + def _make(waf_config=None, web_config=None, firewall=None): + return create_app(database, service, holder, firewall=firewall, waf_config=waf_config, web_config=web_config) yield _make, database, service, holder @@ -464,10 +465,90 @@ def test_waf_oversized_body_blocks(app_factory): c2.post("/api/login", json={"password": "admin"}) r = c2.post("/api/bundle", json={"total_gb": 1, "padding": "x" * 100}) - assert r.status_code == 403 + assert r.status_code == 413 assert "oversized-body" in str(r.json()) +async def _submit_streamed_login(app, chunks, handed_off): + async def body(): + for chunk in chunks: + handed_off.append(chunk) + yield chunk + + transport = httpx.ASGITransport(app=app, client=("192.0.2.10", 50000)) + async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client: + request = client.build_request( + "POST", "/api/login", content=body(), headers={"Content-Type": "application/json"}, + ) + assert "content-length" not in request.headers + return await client.send(request) + + +def test_waf_stops_reading_as_soon_as_body_limit_is_crossed(app_factory): + make, database, _, _ = app_factory + app = make(WafConfig(mode="strict", max_body_bytes=10, local_subnets=[])) + chunks = [b'{"pass', b'word":', b'"admin"}'] + handed_off = [] + + response = _get_loop().run_until_complete(_submit_streamed_login(app, chunks, handed_off)) + + assert response.status_code == 413 + assert "oversized-body" in response.json()["detail"] + assert handed_off == chunks[:2] + assert not _get_loop().run_until_complete(database.get_setting("session_token")) + + +@pytest.mark.parametrize("mode,exempt", [("log", False), ("off", False), ("strict", True)]) +def test_waf_preserves_body_and_forwarding_in_nonblocking_modes(app_factory, mode, exempt): + make, database, _, _ = app_factory + app = make(WafConfig( + mode=mode, max_body_bytes=10, + local_subnets=["192.0.2.0/24"] if exempt else [], + )) + chunks = [b'{"pass', b'word":', b'"admin"}'] + handed_off = [] + + response = _get_loop().run_until_complete(_submit_streamed_login(app, chunks, handed_off)) + + assert response.status_code == 200 + assert handed_off == chunks + events = _get_loop().run_until_complete(database.list_events()) + assert any("WAF oversized-body" in e["message"] for e in events) == (mode == "log") + + +@pytest.mark.parametrize("mode,status,expected_bans", [("strict", 413, 1), ("log", 200, 0)]) +def test_waf_body_limit_only_auto_bans_in_strict_mode(app_factory, mode, status, expected_bans): + make, _, _, _ = app_factory + banned = [] + + class FirewallRecorder: + async def ban_ip(self, host, seconds, reason): + banned.append(host) + + app = make( + WafConfig(mode=mode, max_body_bytes=10, local_subnets=[], auto_ban_after=1), + firewall=FirewallRecorder(), + ) + response = _get_loop().run_until_complete( + _submit_streamed_login(app, [b'{"pass', b'word":', b'"admin"}'], []), + ) + + assert response.status_code == status + assert len(banned) == expected_bans + + +def test_waf_accepts_stream_at_exact_limit_and_replays_it(app_factory): + make, _, _, _ = app_factory + app = make(WafConfig(mode="strict", max_body_bytes=20, local_subnets=[])) + chunks = [b'{"pass', b'word":', b'"admin"}'] + + response = _get_loop().run_until_complete(_submit_streamed_login(app, chunks, [])) + + assert response.status_code == 200 + assert response.headers["X-Content-Type-Options"] == "nosniff" + assert "no-store" in response.headers["Cache-Control"] + + def test_waf_endpoint_rate_limit_strict(app_factory): make, _, _, holder = app_factory holder.swap(EngineSnapshot(wan_status={"topology": "wan"})) From c78ab40850835f0799922472d7c3f36778da0556 Mon Sep 17 00:00:00 2001 From: noiemany <51255434+compnew2006@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:31:10 +0200 Subject: [PATCH 2/2] fix(waf): bound and expire rate limiter state --- Structure_README.md | 11 ++++++ api/app.py | 65 +++++++++++++++++--------------- api/waf.py | 84 +++++++++++++++++++++++++++++++----------- tests/test_security.py | 70 +++++++++++++++++++++++++++++++++++ 4 files changed, 179 insertions(+), 51 deletions(-) diff --git a/Structure_README.md b/Structure_README.md index 68bcad1..7ea772a 100644 --- a/Structure_README.md +++ b/Structure_README.md @@ -788,6 +788,17 @@ the limit was reached, without auto-banning the client. The local-subnet exempti 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` diff --git a/api/app.py b/api/app.py index c3b3720..71bd7c5 100644 --- a/api/app.py +++ b/api/app.py @@ -4258,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 @@ -4306,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: @@ -4314,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): @@ -4342,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): @@ -4437,7 +4448,6 @@ 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 ------------------------------------ @@ -4456,14 +4466,14 @@ async def _waf_inspect(request: Request, body: _waf.InspectionBody, declared = cl.lstrip("0") or "0" cap = str(max_body_bytes) if (len(declared), declared) > (len(cap), cap): - return await _waf_block(request, host, now, waf_mode, + 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 ------------------------------ @@ -4471,7 +4481,7 @@ async def _waf_inspect(request: Request, body: _waf.InspectionBody, if request.method in ("POST", "PUT", "PATCH", "DELETE"): body_text = await body.inspect(max_body_bytes) if body_text is None: - return await _waf_block(request, host, now, waf_mode, + 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, @@ -4479,28 +4489,27 @@ async def _waf_inspect(request: Request, body: _waf.InspectionBody, 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, *, status_code: int = 403) -> 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} " @@ -4517,17 +4526,13 @@ async def _waf_block(request: Request, host: str, now: float, if waf_mode != "strict": return None # Log-only hits never feed the firewall auto-ban. - 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 (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) diff --git a/api/waf.py b/api/waf.py index 5d6efca..1ed0435 100644 --- a/api/waf.py +++ b/api/waf.py @@ -27,6 +27,7 @@ import ipaddress import re +from collections import deque from starlette.types import Message, Receive @@ -210,35 +211,76 @@ def is_exempt(exceptions: list[dict], rule_id: str, path: str, return False +RATE_STATE_SWEEP_SECONDS = 5 + + class WafRateState: - """Per-source-IP request buckets + auto-ban hit counters (in-memory).""" + """Bounded endpoint buckets and rolling auto-ban history.""" - def __init__(self) -> None: - self._hits: dict[str, list[float]] = {} # ip -> WAF-block timestamps + def __init__(self, *, max_entries: int = 4096, ban_threshold: int = 8, + ban_window_seconds: float = 300) -> None: + self._max_entries = max_entries + self._ban_threshold = ban_threshold + self._ban_window = ban_window_seconds self._buckets: dict[tuple[str, str], tuple[int, float]] = {} - # (ip, path-prefix) -> (count, window_start) + self._hits: dict[str, deque[float]] = {} + self._next_sweep = 0.0 + + def expire(self, now: float) -> None: + """Remove expired entries even when their source never returns.""" + self._next_sweep = now + RATE_STATE_SWEEP_SECONDS + for key, (_, deadline) in list(self._buckets.items()): + if now > deadline: + del self._buckets[key] + for ip, stamps in list(self._hits.items()): + self._expire_hits(stamps, now) + if not stamps: + del self._hits[ip] + + def _expire_if_due(self, now: float) -> None: + if now >= self._next_sweep: + self.expire(now) def rate_limited(self, ip: str, path: str, limits: dict[str, list[int]], now: float) -> bool: - """True when ``ip`` exceeded the per-path cap for ``path``.""" + """Check the per-path cap without displacing an active bucket.""" prefix = next((p for p in limits if path.startswith(p)), None) - if not prefix: + if prefix is None: return False + self._expire_if_due(now) max_reqs, window = limits[prefix] + if max_reqs <= 0: + return True key = (ip, prefix) - count, start = self._buckets.get(key, (0, now)) - if now - start > window: - count, start = 0, now - count += 1 - self._buckets[key] = (count, start) - return count > max_reqs - - def register_block(self, ip: str, now: float) -> None: - """Record a WAF block for ``ip`` (feeds the auto-ban counter).""" - stamps = self._hits.setdefault(ip, []) - stamps.append(now) + bucket = self._buckets.get(key) + if bucket is not None and now <= bucket[1]: + count, deadline = bucket + if count >= max_reqs: + return True + self._buckets[key] = (count + 1, deadline) + else: + if bucket is None and len(self._buckets) >= self._max_entries: + return True + self._buckets[key] = (1, now + window) + return False + + def _expire_hits(self, stamps: deque[float], now: float) -> None: + cutoff = now - self._ban_window + while stamps and stamps[0] < cutoff: + stamps.popleft() - def blocks_in_window(self, ip: str, window: float, now: float) -> int: - stamps = [t for t in self._hits.get(ip, []) if now - t <= window] - self._hits[ip] = stamps - return len(stamps) \ No newline at end of file + def register_block(self, ip: str, now: float) -> bool: + """Record a block and report whether this IP has met the ban threshold.""" + if self._ban_threshold <= 0: + return False + self._expire_if_due(now) + stamps = self._hits.get(ip) + if stamps is None: + if len(self._hits) >= self._max_entries: + # The request is still blocked by the WAF. Keep the existing + # histories so a new source can't erase another source's hits. + return False + stamps = self._hits[ip] = deque(maxlen=self._ban_threshold) + self._expire_hits(stamps, now) + stamps.append(now) + return len(stamps) >= self._ban_threshold diff --git a/tests/test_security.py b/tests/test_security.py index c3e68ee..f31793f 100644 --- a/tests/test_security.py +++ b/tests/test_security.py @@ -411,6 +411,76 @@ def test_waf_rate_state_window(): assert state.rate_limited("5.6.7.8", "/api/login", limits, t) is False +def test_waf_discards_expired_state_for_clients_that_do_not_return(): + state = _waf.WafRateState() + limits = {"/api/login": [1, 60]} + state.rate_limited("192.0.2.1", "/api/login", limits, 100) + state.register_block("192.0.2.1", 100) + + assert not state.rate_limited("192.0.2.2", "/api/login", limits, 406) + + assert set(state._buckets) == {("192.0.2.2", "/api/login")} + assert not state._hits + + +def test_waf_holds_only_the_hits_needed_to_reach_ban_threshold(): + state = _waf.WafRateState() + + for timestamp in range(100, 120): + state.register_block("192.0.2.1", timestamp) + + assert len(state._hits["192.0.2.1"]) == 8 + + +def test_waf_full_rate_table_preserves_active_limits_and_recovers(): + state = _waf.WafRateState(max_entries=2) + limits = {"/api/login": [1, 60], "/api/report": [2, 30]} + assert not state.rate_limited("192.0.2.1", "/api/login", limits, 100) + assert not state.rate_limited("192.0.2.1", "/api/report", limits, 100) + + assert state.rate_limited("192.0.2.2", "/api/login", limits, 101) + assert state.rate_limited("192.0.2.1", "/api/login", limits, 101) + assert not state.rate_limited("192.0.2.2", "/unlimited", limits, 101) + assert len(state._buckets) == 2 + + # The shorter window frees a slot while the original login is still capped. + assert not state.rate_limited("192.0.2.2", "/api/login", limits, 132) + assert state.rate_limited("192.0.2.1", "/api/login", limits, 132) + + +def test_waf_hit_table_stays_bounded_and_known_clients_can_reach_threshold(): + state = _waf.WafRateState(max_entries=1, ban_threshold=2, ban_window_seconds=10) + assert not state.register_block("192.0.2.1", 100) + + assert not state.register_block("192.0.2.2", 101) + assert state.register_block("192.0.2.1", 102) + assert set(state._hits) == {"192.0.2.1"} + + assert not state.register_block("192.0.2.2", 113) + assert state.register_block("192.0.2.2", 114) + assert set(state._hits) == {"192.0.2.2"} + + +def test_waf_ban_counter_ignores_hits_outside_its_window(): + state = _waf.WafRateState(ban_threshold=2, ban_window_seconds=10) + assert not state.register_block("192.0.2.1", 100) + + assert not state.register_block("192.0.2.1", 111) + assert state.register_block("192.0.2.1", 112) + + +def test_waf_expiry_frees_state_even_when_there_are_no_new_requests(): + state = _waf.WafRateState(ban_threshold=2, ban_window_seconds=5) + limits = {"/api/login": [1, 5]} + state.rate_limited("192.0.2.1", "/api/login", limits, 100) + state.register_block("192.0.2.1", 100) + + state.expire(106) + + assert not state._buckets + assert not state._hits + + # -- WAF middleware behaviour ---------------------------------------------------