From ec53bce5dc565403b600614efe398ad09f315046 Mon Sep 17 00:00:00 2001 From: fl0l0u Date: Fri, 30 Oct 2026 11:33:42 +0000 Subject: [PATCH] server: stop treating the loopback socket as identity Three guards read a loopback peer plus a matching Origin as "this is the machine's operator". Two real topologies forge exactly that: DNS rebinding hands a hostile page its victim's own browser, so the peer IS loopback, and the page is same-origin with the server, so the Origin/Host compare stays silent. Only the Host still says which name the client asked for, and the attacker's domain cannot be made to read as the loopback. The documented TLS-proxy topology puts every remote client behind a loopback socket, and a non-browser client sends no Origin at all; the proxy passes the public Host, which the new check refuses. Server::local_operator now guards the keyless routes: the socket, the Origin, and a Host naming the loopback, --allow-host, or a concrete bind address. GET /admin/control-vector takes the guard POST already had, placed before the 404-that-means-no-vector so a remote page can probe neither; keyless DELETE /sessions and /reset_prefix_cache -- which destroy other clients' cached conversations -- answer the machine only. --allow-host (repeatable) admits names an operator reaches the box by from the box itself. A local user at the console stays admitted; nothing about a key-set server changes. GUIDE 6.6 states the new posture. --- core/config.cpp | 12 +++++ core/engine.cpp | 1 + core/rad_core.h | 3 ++ core/server/admin.cpp | 20 +++++-- core/server/dashboard.cpp | 35 +++++++----- core/server/http.cpp | 25 +++++++++ core/server/http.h | 9 ++++ core/server/oai.cpp | 8 +++ core/server/oai.h | 1 + core/server/server.cpp | 31 +++++++++-- core/server/server.h | 11 ++++ docs/GUIDE.md | 22 +++++--- tests/config_test.cpp | 11 ++++ tests/server_test.cpp | 111 ++++++++++++++++++++++++++++++++------ 14 files changed, 257 insertions(+), 43 deletions(-) diff --git a/core/config.cpp b/core/config.cpp index 178f5fd7..2df429f0 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -213,6 +213,9 @@ static const Flag g_flags[] = { { "--port", "N", "listen port" }, { "--api-key", "KEY", "require `Authorization: Bearer KEY` or `X-Api-Key: KEY` on every request but /health,\n" " /v1/health, /ping and the dashboard page" }, + { "--allow-host", "NAME", "a Host name the keyless loopback-only routes (/diagnostics,\n" + " /admin/control-vector, the LoRA and session admin) accept besides\n" + " localhost; repeatable" }, { "--served-model-name", "NAME", "the model id /v1/models lists and responses carry; default the container's name" }, { "--mm-max-patches", "N", "patches one encoder pass carries, and so the largest image (a patch is 16x16\n" "pixels). Default `auto`: 16384 when the container carries a vision tower. 0\n" @@ -820,6 +823,11 @@ int config_parse(int argc, char** argv, Config* c) { return RAD_E_INVAL; } c->api_key = v; } + else if (S("--allow-host")) { + if (!(v = need(i))) return RAD_E_INVAL; + if (!*v) { RAD_ERR("--allow-host takes a non-empty name"); return RAD_E_INVAL; } + c->allow_hosts.emplace_back(v); + } else if (S("--served-model-name")) { if (!(v = need(i))) return RAD_E_INVAL; if (!*v) { RAD_ERR("--served-model-name takes a non-empty name"); return RAD_E_INVAL; } @@ -1344,6 +1352,10 @@ const ShowRow kShow[] = { { "--port", [](const Config& c) { return num(c.port); } }, /* Never print the secret, only whether it is set. */ { "--api-key", [](const Config& c) { return std::string(c.api_key.empty() ? "not set" : "set"); } }, + { "--allow-host", [](const Config& c) { + std::string o; + for (const std::string& h : c.allow_hosts) o += (o.empty() ? "" : ",") + h; + return o.empty() ? std::string("the loopback names only") : o; } }, { "--served-model-name", [](const Config& c) { return or_none(c.served_model_name, "the container's name"); } }, { "--mm-max-patches", [](const Config& c) { return c.mm_max_patches < 0 ? std::string("auto") : num(c.mm_max_patches); } }, { "--image-gen-max-pixels", [](const Config& c) { return c.image_gen_max_pixels > 0 ? num(c.image_gen_max_pixels) : std::string("the model's"); } }, diff --git a/core/engine.cpp b/core/engine.cpp index 1b916a35..27788414 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -2620,6 +2620,7 @@ int Engine::run_server() { o.host = cfg_.host; o.port = cfg_.port; o.api_key = cfg_.api_key; + o.local_hosts = cfg_.allow_hosts; o.max_seqs = cfg_.max_seqs; /* `n` fans one request out over the batch, so the default scales with --max-num-seqs; the * floor of 8 keeps a small batch from refusing what it would queue. */ diff --git a/core/rad_core.h b/core/rad_core.h index 8edf84a2..7efca3ec 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -1049,6 +1049,9 @@ struct Config { /* --api-key: the bearer key every request but the probes and the dashboard page must carry. * Empty serves without one. */ std::string api_key; + /* --allow-host, repeatable: Host names the keyless loopback-only routes accept beside the + * loopback names themselves, for operators who reach the box by another name. */ + std::vector allow_hosts; /* --served-model-name: the id /v1/models lists, a response names when its request named none, * and the metrics carry. Empty takes the container's own name. A request may still name any * model: one model is loaded and every request is served by it. */ diff --git a/core/server/admin.cpp b/core/server/admin.cpp index b46b4a06..8e6969b9 100644 --- a/core/server/admin.cpp +++ b/core/server/admin.cpp @@ -509,14 +509,15 @@ HttpResponse Server::handle_diagnostics(const HttpRequest& req) { return error_response(err_not_implemented( "the server was not given a diagnostics provider; this build has no engine attached"), req.peer); - if (opt_.api_key.empty() && (!req.peer_is_loopback() || req.is_cross_origin())) { - /* A cross-origin browser is not a loopback client even when its own machine serves - * this port: the drive-by that guard exists to refuse. */ + if (opt_.api_key.empty() && !local_operator(req)) { + /* A cross-origin browser is not a loopback client even when the victim's own machine + * serves this port, and under rebinding or a localhost proxy the socket alone says + * loopback for anyone: the Host is what still names who the client asked. */ ApiError e; e.status = 403; e.type = "permission_error"; - e.message = "without --api-key, /diagnostics answers only loopback clients; start the " - "server with --api-key to read it from elsewhere"; + e.message = "without --api-key, /diagnostics answers only a loopback client naming this " + "machine; start the server with --api-key to read it from elsewhere"; return error_response(e, req.peer); } metrics_.observe_http(200); @@ -530,6 +531,15 @@ HttpResponse Server::handle_reset_prefix_cache(const HttpRequest& req) { if (!deps_.sched) return error_response(err_not_implemented("the server has no engine attached"), req.peer); + /* Wiping every client's cached prefix is an operator act: keyless, it belongs to the + * machine, not to whichever browser or page can reach the port. */ + if (opt_.api_key.empty() && !local_operator(req)) + return error_response( + err_forbidden("without --api-key, /reset_prefix_cache runs only from a loopback " + "client naming this machine; start the server with --api-key to run " + "it from elsewhere"), + req.peer); + const int64_t n = deps_.sched->reset_prefix_cache(); if (n < 0) return error_response(err_not_implemented( diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index 2c09fc35..3510e60a 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -43,6 +43,18 @@ namespace server { * and answers with the same object. A deployment with no vector loaded answers 404 on both: it has * no such feature, and its requests refuse `control_vector: true` by name. */ HttpResponse Server::handle_control_vector(const HttpRequest& req) { + /* Keyless, the vector and its switch belong to the machine: a rebinding page, a page on + * any origin a localhost proxy fronts, or a plain remote client reads neither the state + * nor the 404-that-means-no-vector. With --api-key both verbs are behind the key anyway. */ + if (opt_.api_key.empty() && !local_operator(req)) { + ApiError e; + e.status = 403; + e.type = "permission_error"; + e.message = "without --api-key, the control vector is read and its default changed only " + "from a loopback client naming this machine; start the server with --api-key " + "to reach it from elsewhere"; + return error_response(e, req.peer); + } const bool have = deps_.control_vector.available && deps_.control_vector.available(); if (!have) { /* 404, like a model the server does not serve: the route exists, this deployment has nothing @@ -56,20 +68,6 @@ HttpResponse Server::handle_control_vector(const HttpRequest& req) { } if (req.method == "POST") { - /* The default applies to every client's requests that name no choice, so a server - * started without --api-key takes the change from a loopback client only, as it does a - * runtime adapter load. A browser page on another origin does not qualify even when the - * victim's own browser makes it loopback: that is the drive-by this guard must refuse. - */ - if (opt_.api_key.empty() && (!req.peer_is_loopback() || req.is_cross_origin())) { - ApiError e; - e.status = 403; - e.type = "permission_error"; - e.message = "without --api-key, the control-vector default is changed only from a " - "loopback client; start the server with --api-key to change it from " - "elsewhere"; - return error_response(e, req.peer); - } bool over = false, deep = false; json body = parse_json_bounded(req.body.empty() ? "{}" : req.body, 0, &over, &deep); if (body.is_discarded()) return error_response(err_bad("body", "not JSON"), req.peer); @@ -195,6 +193,15 @@ HttpResponse Server::handle_session_release(const HttpRequest& req) { if (!deps_.sched) return error_response(err_not_implemented("the server has no engine attached"), req.peer); + /* Releasing a session destroys another client's cached conversation: keyless, that is an + * operator act, not something any page or client that reaches the port may do. */ + if (opt_.api_key.empty() && !local_operator(req)) + return error_response( + err_forbidden("without --api-key, sessions are released only from a loopback client " + "naming this machine; start the server with --api-key to do it from " + "elsewhere"), + req.peer); + const std::string label = req.param("label"); uint64_t id = 0; const std::string id_s = req.param("id"); diff --git a/core/server/http.cpp b/core/server/http.cpp index 3a15b6db..725cb8d1 100644 --- a/core/server/http.cpp +++ b/core/server/http.cpp @@ -441,6 +441,31 @@ bool HttpRequest::is_cross_origin() const { return lower_ascii(auth) != lower_ascii(header("Host")); } +std::string HttpRequest::host_authority() const { + std::string h = lower_ascii(header("Host")); + if (h.empty()) return h; + if (h.front() == '[') { + /* "[::1]:8000": the address is what the brackets hold. */ + const size_t close = h.find(']'); + return close == std::string::npos ? h.substr(1) : h.substr(1, close - 1); + } + const size_t colon = h.rfind(':'); + if (colon != std::string::npos && h.find(':') == colon && + h.find_first_not_of("0123456789", colon + 1) == std::string::npos) + h.erase(colon); /* "localhost:8000" -> "localhost"; a bare "::1" keeps its colons */ + return h; +} + +bool HttpRequest::host_is_loopback() const { + const std::string h = host_authority(); + if (h.empty()) return peer.empty(); /* no Host: an in-process dispatch, never a socket */ + if (h == "localhost" || h == "ip6-localhost" || h == "ip6-loopback") return true; + in_addr v4{}; + if (inet_pton(AF_INET, h.c_str(), &v4) == 1) return (ntohl(v4.s_addr) >> 24) == 127; + in6_addr v6{}; + return inet_pton(AF_INET6, h.c_str(), &v6) == 1 && IN6_IS_ADDR_LOOPBACK(&v6); +} + /* The API key a browser's socket carries. A browser cannot set a header on a WebSocket, so * OpenAI's browser clients offer it as a subprotocol, `openai-insecure-api-key.`, beside * `realtime`; the subprotocol chosen is never that one. Compared in constant time, as the header diff --git a/core/server/http.h b/core/server/http.h index 46bc165e..f475546d 100644 --- a/core/server/http.h +++ b/core/server/http.h @@ -57,6 +57,15 @@ struct HttpRequest { * SDK. Through a proxy that rewrites Host, every browser reads as cross-origin -- which is * exactly the case the "loopback-only" guards must not wave through. */ bool is_cross_origin() const; + /* The Host header's authority, lowercased with the port stripped; "" when there is no Host. + * The name a browser believes it is talking to — under DNS rebinding the attacker's own, and + * through a proxy the public one, neither of which the peer's address shows. */ + std::string host_authority() const; + /* True when the Host names this machine as the loopback: "localhost", 127.0.0.1/8, [::1]. + * A rebinding page is same-origin with the server and its victim's browser is the loopback + * peer — only the Host still says what page asked for it. An absent Host reads as local for + * an in-process dispatch and as remote for a socket, which always carries one. */ + bool host_is_loopback() const; }; struct HttpResponse { diff --git a/core/server/oai.cpp b/core/server/oai.cpp index 47f3fd7f..bcefbbd3 100644 --- a/core/server/oai.cpp +++ b/core/server/oai.cpp @@ -186,6 +186,14 @@ ApiError err_unsupported(const std::string& param, const std::string& why) { return e; } +ApiError err_forbidden(const std::string& why) { + ApiError e; + e.status = 403; + e.type = "permission_error"; + e.message = why; + return e; +} + ApiError err_not_implemented(const std::string& what) { ApiError e; e.status = 501; diff --git a/core/server/oai.h b/core/server/oai.h index 8ceacf2e..61459b65 100644 --- a/core/server/oai.h +++ b/core/server/oai.h @@ -44,6 +44,7 @@ struct ApiError { ApiError err_bad(const std::string& param, const std::string& why); ApiError err_unsupported(const std::string& param, const std::string& why); +ApiError err_forbidden(const std::string& why); ApiError err_not_implemented(const std::string& what); ApiError err_overloaded(const std::string& why); ApiError err_internal(const std::string& why); diff --git a/core/server/server.cpp b/core/server/server.cpp index 72cc04f5..8b488a4a 100644 --- a/core/server/server.cpp +++ b/core/server/server.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -57,6 +58,27 @@ Server::Server(const Deps& d, const ServerOptions& o) register_routes(); } +bool Server::local_operator(const HttpRequest& req) const { + if (!req.peer_is_loopback() || req.is_cross_origin()) return false; + if (req.host_is_loopback()) return true; + const std::string host = req.host_authority(); + if (host.empty()) return false; /* a socket always carries a Host; the in-process case + passed host_is_loopback on its empty peer */ + for (const std::string& a : opt_.local_hosts) { + std::string want = a; + for (char& ch : want) ch = (char)std::tolower((unsigned char)ch); + if (want == host) return true; + } + /* Bound to one concrete address, the box answers to that name on itself. */ + std::string bind = opt_.host; + for (char& ch : bind) ch = (char)std::tolower((unsigned char)ch); + if (!bind.empty() && bind.front() == '[' && bind.back() == ']') + bind = bind.substr(1, bind.size() - 2); + if (!bind.empty() && bind != "0.0.0.0" && bind != "::" && bind != "*") + return bind == host; + return false; +} + Server::~Server() { stop(); } /* A sink may be freed only after the scheduler reports its request terminal, since @@ -2251,12 +2273,15 @@ HttpResponse Server::handle_lora_admin(const HttpRequest& req, bool load) { if (!opt_.lora_load || !opt_.lora_unload) return fail(404, "not_found_error", "this server was started without runtime LoRA (--lora or " "--max-loras)"); - if (opt_.api_key.empty() && (!req.peer_is_loopback() || req.is_cross_origin())) + if (opt_.api_key.empty() && !local_operator(req)) /* A cross-origin browser counts as neither loopback nor local: the victim's own browser - * is loopback to this port, and that is exactly how a hostile page would reach here. */ + * is loopback to this port, and that is exactly how a hostile page would reach here — + * under DNS rebinding it even arrives with a matching Host unless the Host names the + * loopback, and through a localhost proxy every remote client does. Reading a path on + * this machine is a local operator's act. */ return fail(403, "permission_error", "loading an adapter reads a path on this machine, and a " "server started without --api-key takes it only from a " - "loopback client"); + "loopback client naming this machine"); /* Bounded like a generation body: this parses client text the same way, and a deep bracket * nest would overflow this worker's stack when the tree is torn down. */ bool over = false, deep = false; diff --git a/core/server/server.h b/core/server/server.h index 7809814a..dc5a332f 100644 --- a/core/server/server.h +++ b/core/server/server.h @@ -183,6 +183,9 @@ struct ServerOptions { std::function()> gen_lora_names; std::string api_key; + /* Extra Host authorities the keyless "loopback only" guards accept (--allow-host): names an + * operator reaches the box by that the loopback IP check cannot know. Case-insensitive. */ + std::vector local_hosts; bool cors = true; /* The transport's timeouts and body bound. See TransportOptions. */ @@ -227,6 +230,14 @@ public: /* Renders each --reasoning-effort-map target as a request's effort. Empty when the template * takes all of them; otherwise the first refusal, naming the target. */ std::string check_reasoning_effort_map() const; + /* The identity the keyless "loopback only" guards accept: the socket is loopback, the + * request carries no foreign Origin, and the Host names the loopback, one of + * ServerOptions::local_hosts, or the address --host names. Two ways forge the socket alone: + * a DNS-rebinding page is same-origin with the server and its victim's browser *is* the + * loopback peer — only the Host still tells which page asked for it — and a localhost TLS + * proxy puts every remote client behind the loopback socket, carrying the public Host. An + * attacker at the console of this machine is a local user either way, and stays admitted. */ + bool local_operator(const HttpRequest& req) const; void stop(); int port() const { return transport_.port(); } /* 0 until run() is accepting */ diff --git a/docs/GUIDE.md b/docs/GUIDE.md index d27455cf..af760829 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -2121,6 +2121,7 @@ by 0.002-0.003 nats. | `--host ADDR` | 0.0.0.0 | listen address | | `--port N` | 8000 | listen port | | `--api-key KEY` | none | require `Authorization: Bearer KEY` or `X-Api-Key: KEY` on every request but `/health`, `/v1/health`, `/ping` and the dashboard page (§6.6); the key must be non-empty | +| `--allow-host NAME` | — | a `Host` name the keyless loopback-only routes accept besides the loopback names; repeatable (§6.6) | | `--served-model-name NAME` | container's name | the model id `/v1/models` lists, the metrics carry and a response names when its request named none. A request may name any model; the loaded one serves it | | `--mm-max-patches N` | auto | patches one vision-encoder pass carries, and so the largest image (a patch is 16x16 pixels, 14x14 on GLM-5.3). `auto` is 16384 when the container carries a vision tower; 0 serves text only and keeps the tower off the card. A pass is not one tower invocation: inside it the tower batches at most 8 tiles per weight read, and the pass size may reduce that (4 tiles at the 64-pixel grid with the default 16384 patches); a picture contributes a separate pass per grid. See the concurrency notes for Unlimited-OCR (§5.17) | | `--override-chat-template PATH` | container's | a Jinja chat template file served in place of the container's. The reply format (reasoning markers, tool calls) is derived from it too, unless the architecture plugin declares one. An unreadable or empty file stops startup | @@ -3811,12 +3812,21 @@ and sends it on every data fetch. The exemption follows those paths' methods -- `POST /ping` of the health-check convention -- so it cannot follow a method no route answers. An empty `--api-key` value is a startup error: it would guard nothing. -Without a key, `/diagnostics` answers only loopback clients (others get 403), because it describes -the host: kernel, boot parameters, PCI layout, memory limits. Read it on the machine, or start the -server with `--api-key`. The same loopback-only rule covers the control-vector default and runtime -LoRA loads, and a browser page on another origin does not qualify as a loopback client even when -its own machine serves the port: that is how a hostile web page would reach these routes through a -victim's browser, and a request that says `Origin: http://evil` is refused the way a remote one is. +Without a key, the routes that see the machine or change its state answer the machine itself only: +`/diagnostics` (it describes the host — kernel, boot parameters, PCI layout, memory limits), +`GET|POST /admin/control-vector`, `/v1/load_lora_adapter` and `/v1/unload_lora_adapter` (they read +paths from disk), `DELETE /sessions/...` and `/reset_prefix_cache` (they destroy other clients' +cached conversations). Others get 403. "The machine itself" means the socket comes from loopback, +carries no foreign `Origin` — a browser page on another origin does not qualify even when its own +machine serves the port, which is how a hostile web page would reach these routes through a +victim's browser — **and its `Host` names the loopback** (`localhost`, `127.0.0.1`, +`[::1]`): a DNS-rebinding page is same-origin with your server and its victim's own browser *is* +the loopback peer, and behind a localhost TLS proxy every remote client arrives on a loopback +socket — only the `Host` still tells which machine the client asked for. A browser that typed your +public name into the address bar is therefore refused; `localhost`, a `127.x` address and an SSH +tunnel pass. If you reach the box by another name from the box itself, list it: `--allow-host box` +(repeatable). A local user on the server's own console is admitted either way — the boundary is +against remote callers, not against whoever owns the machine. The key is not encrypted in transit. On a network you do not control, bind to localhost behind a TLS-terminating reverse proxy: diff --git a/tests/config_test.cpp b/tests/config_test.cpp index 7aea8d94..53d25b66 100644 --- a/tests/config_test.cpp +++ b/tests/config_test.cpp @@ -102,6 +102,16 @@ TEST(an_empty_api_key_is_refused) { CHECK(c.api_key == "k"); } +/* --allow-host repeats: the loopback-only routes take the set of names, and an empty one is + * a hole cut by a typo, so it is refused like the empty key. */ +TEST(allow_host_repeats_and_refuses_the_empty_name) { + CHECK_EQ(parse_fresh({ "--allow-host", "" }), RAD_E_INVAL); + Config c; + CHECK_EQ(parse({ "--allow-host", "box", "--allow-host", "box.example" }, &c), 0); + CHECK(c.allow_hosts.size() == 2); + CHECK(c.allow_hosts[0] == "box" && c.allow_hosts[1] == "box.example"); +} + /* A flag written last with no argument is refused rather than reading past argv. */ TEST(a_flag_missing_its_argument_is_refused_rather_than_read_past) { Config c; @@ -482,6 +492,7 @@ const std::map>& legal_values() { { "--draft-window", { "fixed" } }, { "--draft-short-from", { "4" } }, { "--draft-coupling", { "on" } }, { "--host", { "127.0.0.1" } }, { "--port", { "8001" } }, { "--api-key", { "k" } }, + { "--allow-host", { "box" } }, { "--served-model-name", { "m" } }, { "--mm-max-patches", { "1024" } }, { "--control-vector", { "off" } }, { "--generation-config", { "/g.json" } }, { "--override-chat-template", { "/t.jinja" } }, diff --git a/tests/server_test.cpp b/tests/server_test.cpp index 8bdeb682..e7d0a1e0 100644 --- a/tests/server_test.cpp +++ b/tests/server_test.cpp @@ -3041,8 +3041,10 @@ TEST(server_info_drops_an_engine_blob_that_is_not_an_object) { CHECK(has(r2.body, "\"arch\":\"testarch\"")); } -/* /diagnostics describes the host, so without a key it answers this machine only. With a key the - * transport's gate has already checked the caller, and any address may ask. */ +/* /diagnostics describes the host, so without a key it answers this machine only — and the Host + * must name it, since a rebinding victim's browser or a localhost proxy's every remote client + * arrives with a loopback socket. With a key the transport's gate has already checked the + * caller, and any address may ask. */ TEST(diagnostics_without_a_key_answers_loopback_only) { FakeScheduler sched; FakeTokenizer tok; @@ -3051,29 +3053,91 @@ TEST(diagnostics_without_a_key_answers_loopback_only) { d.tok = &tok; ServerOptions o; o.model_id = "test-model"; + o.local_hosts = { "box" }; o.diagnostics_json = [] { return std::string(R"({"findings":[]})"); }; Server srv(d, o); - auto from = [](Server& s, const char* peer) { + auto from = [](Server& s, const char* peer, const char* host = nullptr, + const char* origin = nullptr) { HttpRequest q; q.path = "/diagnostics"; q.peer = peer; + if (host) q.headers["Host"] = host; + if (origin) q.headers["Origin"] = origin; return s.router().dispatch(q).status; }; - CHECK_EQ(from(srv, "127.0.0.1:50122"), 200); - CHECK_EQ(from(srv, "127.8.9.10:50122"), 200); - CHECK_EQ(from(srv, "::1:50122"), 200); - CHECK_EQ(from(srv, "[::1]:50122"), 200); - CHECK_EQ(from(srv, "::ffff:127.0.0.1:50122"), 200); + CHECK_EQ(from(srv, "127.0.0.1:50122", "localhost:8000"), 200); + CHECK_EQ(from(srv, "127.8.9.10:50122", "127.8.9.10:8000"), 200); + CHECK_EQ(from(srv, "::1:50122", "127.0.0.1:8000"), 200); + CHECK_EQ(from(srv, "[::1]:50122", "[::1]:8000"), 200); + CHECK_EQ(from(srv, "::ffff:127.0.0.1:50122", "127.0.0.1:8000"), 200); + CHECK_EQ(from(srv, "127.0.0.1:50122", "localhost:8000", "http://localhost:8000"), 200); + CHECK_EQ(from(srv, "127.0.0.1:50122", "BOX:8000"), 200); /* --allow-host, any case */ CHECK_EQ(from(srv, ""), 200); /* in-process */ - CHECK_EQ(from(srv, "192.168.1.20:50122"), 403); - CHECK_EQ(from(srv, "::ffff:10.0.0.7:50122"), 403); - CHECK_EQ(from(srv, "fe80::1:50122"), 403); - CHECK_EQ(from(srv, "128.0.0.1:50122"), 403); + /* Loopback socket, foreign Host: the rebinding page (Origin matching its Host, so the + * cross-origin check stays silent) and the localhost proxy handing over the public name + * (no Origin at all). Neither names the machine, and a socket that carries no Host does + * not either. */ + CHECK_EQ(from(srv, "127.0.0.1:50122", "evil.test:8000", "http://evil.test:8000"), 403); + CHECK_EQ(from(srv, "127.0.0.1:50122", "api.example.com"), 403); + CHECK_EQ(from(srv, "127.0.0.1:50122", "192.168.1.20:8000"), 403); + CHECK_EQ(from(srv, "127.0.0.1:50122"), 403); + CHECK_EQ(from(srv, "127.0.0.1:50122", "other.box:8000"), 403); + CHECK_EQ(from(srv, "127.0.0.1:50122", "localhost:8000", "http://evil.test"), 403); + CHECK_EQ(from(srv, "192.168.1.20:50122", "localhost:8000"), 403); + CHECK_EQ(from(srv, "::ffff:10.0.0.7:50122", "localhost:8000"), 403); + CHECK_EQ(from(srv, "fe80::1:50122", "localhost:8000"), 403); + CHECK_EQ(from(srv, "128.0.0.1:50122", "localhost:8000"), 403); ServerOptions ok = o; ok.api_key = "k"; Server keyed(d, ok); - CHECK_EQ(from(keyed, "192.168.1.20:50122"), 200); + CHECK_EQ(from(keyed, "192.168.1.20:50122", "api.example.com"), 200); +} + +/* Destroying cache is an operator act: without a key, session release and prefix-cache reset + * answer the machine only, judged with the same identity as /diagnostics. The statuses below + * say the guard passed (the handler's own answers) rather than the 403 it refuses with. */ +TEST(state_changing_routes_without_a_key_answer_the_machine_only) { + FakeScheduler sched; + FakeTokenizer tok; + Deps d; + d.sched = &sched; + d.tok = &tok; + ServerOptions o; + o.model_id = "test-model"; + Server srv(d, o); + auto del = [](Server& s, const char* peer, const char* host) { + HttpRequest q; + q.method = "DELETE"; + q.path = "/sessions"; + q.query["label"] = "conv-1"; + q.peer = peer; + if (host) q.headers["Host"] = host; + return s.router().dispatch(q).status; + }; + auto reset = [](Server& s, const char* peer, const char* host) { + HttpRequest q; + q.method = "POST"; + q.path = "/reset_prefix_cache"; + q.peer = peer; + if (host) q.headers["Host"] = host; + return s.router().dispatch(q).status; + }; + CHECK_EQ(del(srv, "", nullptr), 501); /* no prefix cache: past the guard */ + CHECK_EQ(del(srv, "127.0.0.1:50122", "localhost:8000"), 501); + CHECK_EQ(del(srv, "127.0.0.1:50122", "evil.test:8000"), 403); /* rebinding */ + CHECK_EQ(del(srv, "127.0.0.1:50122", "api.example.com"), 403); /* proxy */ + CHECK_EQ(del(srv, "192.168.1.20:50122", "localhost:8000"), 403); /* remote */ + CHECK_EQ(reset(srv, "", nullptr), 501); /* no cache to reset: past the guard */ + CHECK_EQ(reset(srv, "127.0.0.1:50122", "127.0.0.1:8000"), 501); + CHECK_EQ(reset(srv, "127.0.0.1:50122", "evil.test:8000"), 403); + CHECK_EQ(reset(srv, "192.168.1.20:50122", "localhost:8000"), 403); + + ServerOptions ok = o; + ok.api_key = "k"; + Server keyed(d, ok); + CHECK_EQ(del(keyed, "192.168.1.20:50122", "api.example.com"), 501); + CHECK_EQ(reset(keyed, "192.168.1.20:50122", "api.example.com"), 501); } TEST(tokenize_takes_a_prompt_or_messages_and_never_both) { @@ -4800,17 +4864,28 @@ TEST(the_control_vector_field_overrides_the_default_or_is_refused) { * tear down, parsed bounded and refused. */ CHECK_EQ(f.post("/admin/control-vector", std::string(20000, '[') + std::string(20000, ']')).status, 400); - /* Without --api-key a change comes from loopback only; reading it is not restricted. */ + /* Without --api-key the vector is read and changed by the machine itself, and its Host + * must still name it: under DNS rebinding the victim's browser IS the loopback peer and + * its Origin matches its Host — only the dialled name tells the two apart. */ HttpRequest q; q.method = "POST"; q.path = "/admin/control-vector"; q.body = R"({"enabled":true})"; q.peer = "192.168.1.20:50122"; + q.headers["Host"] = "127.0.0.1:8080"; CHECK_EQ(f.srv->router().dispatch(q).status, 403); CHECK(!def); q.peer = "127.0.0.1:50122"; + q.headers["Host"] = "localhost:8000"; CHECK_EQ(f.srv->router().dispatch(q).status, 200); CHECK(def); + /* The rebinding page: loopback peer, Origin and Host both the attacker's domain, the + * pair no `Origin != Host` check can see. */ + q.body = R"({"enabled":false})"; + q.headers["Host"] = "evil.test:8000"; + q.headers["Origin"] = "http://evil.test:8000"; + CHECK_EQ(f.srv->router().dispatch(q).status, 403); + CHECK(def); /* A browser page on another origin is not a loopback client, even though its own * browser makes the request arrive loopback: defeating the guard that way is exactly * what the drive-by would do. Same-origin browser traffic still passes. */ @@ -4826,10 +4901,16 @@ TEST(the_control_vector_field_overrides_the_default_or_is_refused) { x.headers["Origin"] = "http://127.0.0.1:8080"; CHECK_EQ(f.srv->router().dispatch(x).status, 200); CHECK(!def); + /* Reading is guarded like the change: what a keyless deployment carries — that it has + * a vector at all, its family and range — is no remote caller's business. */ HttpRequest g2; g2.path = "/admin/control-vector"; g2.peer = "192.168.1.20:50122"; - CHECK_EQ(f.srv->router().dispatch(g2).status, 200); + g2.headers["Host"] = "box.example:8000"; + CHECK_EQ(f.srv->router().dispatch(g2).status, 403); + HttpRequest g3; + g3.path = "/admin/control-vector"; + CHECK_EQ(f.srv->router().dispatch(g3).status, 200); /* in-process */ } }