Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

serve: check the Host header on every request (DNS rebinding)

Niko122176a794e1453a
diff --git a/docs/DETAILS.md b/docs/DETAILS.md
index e30c2954f..2c6621c74 100644
--- a/docs/DETAILS.md
+++ b/docs/DETAILS.md
@@ -505,9 +505,22 @@ print(r.choices[0].message.content)
clients then send it as their API key. Streamed answers carry `X-Accel-Buffering: no`, so nginx-style proxies pass
each token on at once. The web app's settings and MCP tools only answer Strata's own page: when you open it through
a proxy or tunnel whose address differs, add that address, e.g. `"trusted_origins": ["https://strata.example.com"]`.
+ A tunnel or proxy that passes its own name on as `Host` needs that name allowed too (see Host names below; a
+ `trusted_origins` entry already allows its name, and a quick tunnel's random name is covered by
+ `"allowed_hosts": [".trycloudflare.com"]`).
- **From web apps in a browser (CORS).** Off by default. `"cors_origins": ["https://chat.example.com"]` lets pages of
those origins call `/v1/*` from the browser (Open WebUI's direct connections, browser extensions); `["*"]` lets any
page do it - only sensible with an API key. It never opens `/settings`, `/unload` or the MCP tools.
+- **Host names (DNS rebinding).** A web page of another site can point its own name at `127.0.0.1` and then reach
+ this server as if it were its own, so the server answers only requests whose `Host` is a name it knows:
+ `localhost` (and `*.localhost`), any IP address (`127.0.0.1`, `[::1]`, `192.168.x.x`, ...), the address it
+ listens on and, when it listens beyond this PC (`0.0.0.0` or a LAN address), this PC's name (`mypc`, `mypc.local`)
+ and `host.docker.internal`; any port. Others get **403** naming the setting, and the server window prints one line
+ for each. Reach it under another name (a reverse proxy that keeps the name, a tunnel, a DNS name on your network,
+ another container's name for it)? Add the name: `"allowed_hosts": ["strata.example.com"]` in
+ `strata-<model>.json` or `STRATA_ALLOWED_HOSTS=strata.example.com` (comma-separated); `".example.com"` allows that
+ name and every name below it, and `["*"]` turns the check off. The hosts of `trusted_origins` count as allowed.
+ Requests without a `Host` header (HTTP/1.0 clients) pass.
**Conversation cache.** A request that continues a chat reads only the part after what the engine already holds: the
live session, or one of the checkpoints it keeps in RAM (up to 6, ~118 MB each, taken at the start of each new
diff --git a/serve/server.py b/serve/server.py
index 270955606..4fc94a9ec 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -61,6 +61,7 @@ IMAGE_PAD = "<|image_pad|>"
VISION_START = "<|vision_start|>"
# #123: what closes the thinking when it reaches reasoning_budget_tokens (the model's own end-of-thinking tag after it)
REASONING_WRAP_UP = "\n\nI have thought about this long enough; time to give my answer.\n</think>\n\n"
+LOOPBACK_NAMES = ("localhost", "127.0.0.1", "::1")
CTX_SLACK = 8 # `strata --serve` rejects prompt + max_new + 8 > context: keep the same margin here
# The live tok/s is a rate over a window, not a mean since the first token: a mean reads ~1/elapsed at the first
# token (the Monitor showed five-digit numbers) and then undershoots for the first second of every answer.
@@ -960,6 +961,10 @@ class Service:
# #321: origins that count as Strata's own page for /settings and MCP tools, e.g. the web app reached through a
# reverse proxy or tunnel whose Host differs ("https://strata.example.com"); never a wildcard
self.trusted_origins: list[str] = []
+ # DNS rebinding: extra Host names this server answers to (the config's allowed_hosts, $STRATA_ALLOWED_HOSTS;
+ # "*" = any), and every name it answers to, which serve() works out from the address it listens on
+ self.allowed_hosts: list[str] = []
+ self.host_names: set[str] = set(LOOPBACK_NAMES)
self.status = {"busy": False, "queued": 0} # GET /status: what the model is doing right now
self.rate = collections.deque(maxlen=32) # (time, generated) samples for the live tok/s window
# #332: the API request monitor (/api-monitor) keeps the last 100 requests' prompts and answers in memory,
@@ -1967,6 +1972,21 @@ def make_handler(svc: Service):
def log_message(self, fmt, *args):
pass
+ def parse_request(self):
+ """Every request (any method) first passes the Host check: DNS rebinding protection (host_allowed)."""
+ if not super().parse_request():
+ return False
+ host = self.headers.get("Host")
+ if host_allowed(host, svc.host_names, "*" in svc.allowed_hosts):
+ return True
+ print(f"[strata] refused a request for Host {host!r} from {self.client_address[0]}: not a name this server "
+ f"answers to (add it to \"allowed_hosts\" in the config or STRATA_ALLOWED_HOSTS)", flush=True)
+ self._json(403, {"error": {"type": "forbidden", "message":
+ f"Host {host!r} is not allowed (DNS rebinding protection). Reaching Strata under this "
+ f"name on purpose? Add it to \"allowed_hosts\" in the config (strata-<model>.json) or to "
+ f"the STRATA_ALLOWED_HOSTS environment variable"}})
+ return False
+
def _watch_client(self, cancel: threading.Event) -> None:
"""#430 #431: cancel the request as soon as its client hangs up. A non-streamed request writes nothing
until it ends, and a streamed one only a keep-alive per prompt chunk (and the first write after a hang-up
@@ -2507,7 +2527,94 @@ def lan_addresses() -> list[str]:
return ([first] if ok(first) else []) + sorted(ip for ip in ips if ok(ip) and ip != first)
+def host_name(value) -> str:
+ """The name in a Host header (or an origin's host[:port]): "Example.com:8080" -> "example.com",
+ "[::1]:8095" -> "::1"; "" when it is malformed."""
+ v = (value or "").strip().lower()
+ if v.startswith("["):
+ name, sep, rest = v[1:].partition("]")
+ return name if sep and (not rest or (rest[:1] == ":" and rest[1:].isdigit())) else ""
+ if v.count(":") == 1:
+ v, port = v.split(":")
+ if not port.isdigit():
+ return ""
+ elif ":" in v: # a bare IPv6 address (a config entry)
+ return v
+ v = v.rstrip(".")
+ return v if v and all(c.isalnum() or c in "-._" for c in v) else ""
+
+
+def _is_ip(name: str) -> bool:
+ import ipaddress
+ try:
+ ipaddress.ip_address(name)
+ return True
+ except ValueError:
+ return False
+
+
+def _name_in(name: str, names) -> bool:
+ """`name` is one of `names`, or below an entry that starts with a dot (".example.com")."""
+ return name in names or any(n.startswith(".") and (name.endswith(n) or name == n[1:]) for n in names)
+
+
+def allowed_hosts_of(value, env: str = "") -> list[str]:
+ """The config's allowed_hosts (a name or a list) plus $STRATA_ALLOWED_HOSTS (comma-separated): host names, "*" or
+ ".example.com" (it and every name below it). A scheme, port or path is dropped ("https://a.example.com:8443/"
+ -> "a.example.com"); a wrong entry stops the start (ValueError)."""
+ items = [] if value in (None, "") else [value] if isinstance(value, str) else value
+ if not isinstance(items, list) or not all(isinstance(x, str) for x in items):
+ raise ValueError("allowed_hosts: expected a host name or a list of them")
+ out = []
+ for raw in items + [x for x in env.split(",") if x.strip()]:
+ x = raw.strip().lower()
+ if x == "*":
+ out.append(x)
+ continue
+ x = x.split("://", 1)[-1].split("/", 1)[0]
+ dot = x.startswith(".")
+ name = host_name(x[1:] if dot else x)
+ if not name:
+ raise ValueError(f"allowed_hosts: {raw!r} is not a host name like strata.example.com")
+ out.append("." + name if dot else name)
+ return list(dict.fromkeys(out))
+
+
+def host_names_for(bind_host: str, allowed_hosts=(), trusted_origins=()) -> set[str]:
+ """Every name this server answers to besides an IP address: localhost, the address it listens on, the config's
+ allowed_hosts and trusted_origins' hosts, and - listening beyond this PC (0.0.0.0 or a LAN address) - this PC's
+ name and LAN addresses (the LAN addresses matter for the Origin check, which takes no IP on trust)."""
+ names = set(LOOPBACK_NAMES)
+ bind = host_name(bind_host)
+ if bind and bind not in ("0.0.0.0", "::"):
+ names.add(bind)
+ if bind not in LOOPBACK_NAMES:
+ try:
+ pc = socket.gethostname().lower()
+ names.update((pc, pc + ".local"))
+ except OSError:
+ pass
+ names.update(("host.docker.internal", *lan_addresses()))
+ names.update(x for x in allowed_hosts if x != "*")
+ names.update(filter(None, (host_name(o.split("://", 1)[-1]) for o in trusted_origins)))
+ return names
+
+
+def host_allowed(host, names, any_host=False) -> bool:
+ """DNS rebinding: a web page of another site whose name its DNS points at 127.0.0.1 reaches this server as the
+ same origin, so the browser lets it read every answer. Its requests carry that site's name in Host, so only
+ the names this server answers to pass. An IP address passes (a page served from an IP is that IP's own page;
+ rebinding needs a name), as does "*.localhost" (browsers never ask DNS for it) and a request without a Host
+ header (HTTP/1.0 clients; browsers always send one)."""
+ if any_host or not (host or "").strip():
+ return True
+ name = host_name(host)
+ return bool(name) and (_is_ip(name) or name == "localhost" or name.endswith(".localhost")
+ or _name_in(name, names))
+
+
def serve(svc: Service, host="127.0.0.1", port=8095) -> ThreadingHTTPServer:
+ svc.host_names = host_names_for(host, svc.allowed_hosts, svc.trusted_origins)
svc.start_telemetry()
httpd = Server((host, port), make_handler(svc))
threading.Thread(target=httpd.serve_forever, daemon=True).start()
@@ -2756,6 +2863,13 @@ def main() -> int:
svc.api_key = a.api_key or cfg.get("api_key", "")
svc.cors_origins = origins_of(cfg.get("cors_origins"), "cors_origins", wildcard=True)
svc.trusted_origins = origins_of(cfg.get("trusted_origins"), "trusted_origins", wildcard=False)
+ try:
+ svc.allowed_hosts = allowed_hosts_of(cfg.get("allowed_hosts"), os.environ.get("STRATA_ALLOWED_HOSTS", ""))
+ except ValueError as e:
+ raise SystemExit(f"[strata] config {e}")
+ if svc.allowed_hosts:
+ print("[strata] Host check off: any name reaches this server (allowed_hosts \"*\")" if "*" in svc.allowed_hosts
+ else f"[strata] also answers to the host names {', '.join(svc.allowed_hosts)} (allowed_hosts)", flush=True)
svc.api_monitor = a.api_monitor or cfg.get("api_monitor") is True
if svc.api_monitor:
print("[strata] API request monitor on (/api-monitor): the last 100 requests' prompts and answers are kept in "
diff --git a/serve/test_security.py b/serve/test_security.py
new file mode 100644
index 000000000..2e137495a
--- /dev/null
+++ b/serve/test_security.py
@@ -0,0 +1,157 @@
+"""serve/test_security.py - the Host check (DNS rebinding), against the mock engine (no GPU, no pack).
+
+ python -m unittest serve.test_security -v
+"""
+from __future__ import annotations
+
+import contextlib
+import http.client
+import io
+import json
+import socket
+import sys
+import unittest
+from pathlib import Path
+from unittest import mock
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+from serve.frontend import ChatTemplate # noqa: E402
+from serve.server import (ByteTokenizer, MockEngine, Service, allowed_hosts_of, host_allowed, # noqa: E402
+ host_name, host_names_for, serve)
+
+ROOT = Path(__file__).resolve().parents[1]
+LOCAL = {"localhost", "127.0.0.1", "::1"}
+
+
+class HostNames(unittest.TestCase):
+ def test_host_name(self):
+ self.assertEqual(host_name("Example.COM:8080"), "example.com")
+ self.assertEqual(host_name("localhost"), "localhost")
+ self.assertEqual(host_name("[::1]:8095"), "::1")
+ self.assertEqual(host_name("[::1]"), "::1")
+ self.assertEqual(host_name("strata.example.com."), "strata.example.com")
+ for bad in ("", "a:b", "[::1", "[::1]x", "a b", "evil.com/x"):
+ self.assertEqual(host_name(bad), "", bad)
+
+ def test_allowed_hosts_of(self):
+ self.assertEqual(allowed_hosts_of(None), [])
+ self.assertEqual(allowed_hosts_of("Strata.Example.com"), ["strata.example.com"])
+ self.assertEqual(allowed_hosts_of(["https://a.example.com:8443/x", ".example.org", "*"], "box, nas.lan "),
+ ["a.example.com", ".example.org", "*", "box", "nas.lan"])
+ for bad in (["bad name"], 5, [3], "http://"):
+ with self.assertRaises(ValueError):
+ allowed_hosts_of(bad)
+
+ def test_names_from_the_bind_address(self):
+ with mock.patch("serve.server.lan_addresses", return_value=["192.168.1.20"]):
+ self.assertEqual(host_names_for("127.0.0.1"), LOCAL) # this PC only: nothing else
+ self.assertEqual(host_names_for("localhost"), LOCAL)
+ names = host_names_for("0.0.0.0") # other devices too
+ self.assertIn(socket.gethostname().lower(), names)
+ self.assertIn(socket.gethostname().lower() + ".local", names)
+ self.assertIn("192.168.1.20", names)
+ self.assertIn("10.0.0.7", host_names_for("10.0.0.7"))
+ names = host_names_for("127.0.0.1", ["strata.example.com", "*"], ["https://chat.example.net"])
+ self.assertTrue({"strata.example.com", "chat.example.net"} <= names)
+ self.assertNotIn("*", names)
+
+
+class HostCheck(unittest.TestCase):
+ def test_accepted(self):
+ for host in ("localhost:8095", "LOCALHOST", "127.0.0.1:1", "[::1]:8095", "192.168.1.20:8095", "[fe80::1]",
+ "app.localhost:8095", None, "", "box:8095", "a.example.org", "example.org:443"):
+ self.assertTrue(host_allowed(host, LOCAL | {"box", ".example.org"}), host)
+
+ def test_refused(self):
+ # a rebinding page sends its own name; lookalikes of allowed names stay out
+ for host in ("evil.example.com", "evil.example.com:8095", "localhost.evil.com", "127.0.0.1.nip.io",
+ "box.evil.com", "xexample.org", "bad host", "a:b:c:d:e:f:g:h:i"):
+ self.assertFalse(host_allowed(host, LOCAL | {"box", ".example.org"}), host)
+
+ def test_any_host(self):
+ self.assertTrue(host_allowed("evil.example.com", LOCAL, any_host=True))
+
+
+class OverHttp(unittest.TestCase):
+ """The checks in the running server, as a browser and as curl/the SDKs send their requests."""
+
+ def setUp(self):
+ tok = ByteTokenizer()
+ self.svc = Service(MockEngine(tok, "</think>\n\nok", max_context=4096), tok,
+ ChatTemplate(ROOT / "serve/chat_template.jinja"))
+ self.httpd = None
+
+ def start(self, **attrs):
+ for k, v in attrs.items():
+ setattr(self.svc, k, v)
+ self.httpd = serve(self.svc, port=0)
+ self.port = self.httpd.server_address[1]
+
+ def tearDown(self):
+ if self.httpd:
+ self.httpd.shutdown()
+ self.httpd.server_close()
+
+ def req(self, method, path, body=None, headers=None, host=None):
+ """(status, JSON, what the server printed); `host` replaces the Host header http.client sends."""
+ c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=30)
+ h = dict(headers or {})
+ if host is not None:
+ h["Host"] = host
+ data = body if isinstance(body, (bytes, type(None))) else json.dumps(body).encode()
+ out = io.StringIO()
+ try:
+ with contextlib.redirect_stdout(out):
+ c.request(method, path, body=data, headers=h)
+ r = c.getresponse()
+ raw = r.read()
+ return r.status, json.loads(raw) if raw[:1] in (b"{", b"[") else raw, out.getvalue()
+ finally:
+ c.close()
+
+ def chat_body(self):
+ return {"model": "m", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 64}
+
+ # --- Host
+ def test_rebinding_name_is_refused_everywhere(self):
+ self.start()
+ for method, path in (("GET", "/status"), ("GET", "/metrics"), ("GET", "/"), ("GET", "/health"),
+ ("POST", "/settings"), ("POST", "/v1/chat/completions"), ("OPTIONS", "/v1/models")):
+ code, body, log = self.req(method, path, {} if method == "POST" else None,
+ {"Content-Type": "application/json"}, host=f"evil.example.com:{self.port}")
+ self.assertEqual(code, 403, path)
+ if method != "OPTIONS":
+ self.assertIn("allowed_hosts", body["error"]["message"])
+ self.assertEqual(log.count("\n"), 1, path) # one log line each
+ self.assertIn("evil.example.com", log)
+
+ def test_local_names_and_ips_pass(self):
+ self.start()
+ for host in (f"127.0.0.1:{self.port}", f"localhost:{self.port}", f"[::1]:{self.port}",
+ f"192.168.1.20:{self.port}"):
+ self.assertEqual(self.req("GET", "/status", host=host)[0], 200, host)
+
+ def test_no_host_header_passes(self):
+ self.start()
+ with socket.create_connection(("127.0.0.1", self.port), timeout=10) as s: # an HTTP/1.0 client
+ s.sendall(b"GET /health HTTP/1.0\r\n\r\n")
+ raw = b""
+ while chunk := s.recv(65536):
+ raw += chunk
+ self.assertTrue(raw.startswith(b"HTTP/1.0 200"), raw[:40])
+
+ def test_allowed_hosts_and_wildcard(self):
+ self.start(allowed_hosts=["strata.example.com", ".home.arpa"])
+ self.assertEqual(self.req("GET", "/status", host="strata.example.com")[0], 200)
+ self.assertEqual(self.req("GET", "/status", host="nas.home.arpa:8095")[0], 200)
+ self.assertEqual(self.req("GET", "/status", host="evil.example.com")[0], 403)
+ self.svc.allowed_hosts = ["*"]
+ self.assertEqual(self.req("GET", "/status", host="evil.example.com")[0], 200)
+
+ def test_a_trusted_origin_s_host_is_allowed(self):
+ self.start(trusted_origins=["https://strata.example.com"])
+ self.assertEqual(self.req("GET", "/status", host="strata.example.com")[0], 200)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/serve/test_server.py b/serve/test_server.py
index 8f34a74b0..bb82a5239 100644
--- a/serve/test_server.py
+++ b/serve/test_server.py
@@ -676,7 +676,7 @@ class ClientHangUp(unittest.TestCase):
body = json.dumps({"model": "x", "max_tokens": 20, "stream": stream,
"messages": [{"role": "user", "content": "a long prompt"}]}).encode()
c = so.create_connection(("127.0.0.1", self.port))
- c.sendall(b"POST /v1/chat/completions HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\n"
+ c.sendall(b"POST /v1/chat/completions HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\n"
b"Content-Length: " + str(len(body)).encode() + b"\r\n\r\n" + body)
time.sleep(1.0)
c.close()