Files
SQLBot/backend/common/core/host_validation.py
T
fit2cloud-chenywandClaude bbfc4cc8f5 fix(Security): Host header injection auth bypass and forged admin embedded token (CNVD)
- TokenMiddleware/ResponseMiddleware/audit logger use scope['path']
  instead of request.url.path for whitelist checks: a crafted Host
  header (e.g. x/api/v1/mcp) was concatenated into Starlette's URL
  and made protected routes match the /mcp* whitelist entry
- validateEmbedded rejects admin accounts and non-type-4 apps, so a
  self-signed token with account=admin can no longer impersonate the
  administrator
- Add HostValidationMiddleware rejecting malformed Host headers at the
  outermost layer (defense in depth)
- Add regression tests for host validation, whitelist matching and
  source-level guards

Co-Authored-By: Claude <[email protected]>
2026-08-31 11:05:05 +08:00

22 lines
875 B
Python

import re
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import JSONResponse
# 合法 Host:域名 / IPv4 / IPv6(含端口),排除 '/'、'@'、空白等非法字符。
# Starlette 的 URL(scope) 会把 Host 头原始值拼进 URL,Host 携带路径片段会污染
# request.url.path 等派生属性(历史上被用于绕过认证白名单),因此请求入口处直接拒绝。
_HOST_RE = re.compile(r'^[A-Za-z0-9.\-:\[\]]{1,255}$')
class HostValidationMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
host = request.headers.get("host")
if not host or not _HOST_RE.match(host):
return JSONResponse(
{"code": 400, "data": None, "msg": "invalid host header"},
status_code=400,
)
return await call_next(request)