From 21d34b13ed4967c0815d2626beaade777e1619f1 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Thu, 26 Nov 2026 11:05:35 +0100 Subject: [PATCH] http: bodies end at 64 KiB, and the checkout limit counts per IPv6 /48 Two limits that were not limiting. The listener's default body limit is 512 MiB and nothing set another, with no cap on connections: one 64 MiB POST took the server from 7 MB to 72 MB before the handler's own 16 KiB check answered 413. The limit is now 64 KiB. A request that announces more in Content-Length is answered 400 from its headers, with none of its body read: a 64 MiB upload is refused after 786 KB and the server's peak memory does not move. That is a limit on the decoded body, and the comment says so. A chunked request sent straight to the port can pad its chunk framing and still make one connection hold hundreds of megabytes; the parser that allows it is Crafter.Network's. Behind Caddy an oversized body is refused by request_body before it gets here, so this is one more thing that rests on port 8081 being private. The per-peer checkout limit was kept per address. Over IPv6 one subscriber holds a whole prefix, a /56 or a /48, and can submit from a fresh address every time, so the per-peer cap did nothing and the global cap was the only limit an IPv6 client met. The key is now the IPv4 address or the IPv6 /48 (RateLimitKeyFor). An IPv4-mapped address is keyed as the IPv4 client it is, and something that does not read as an address is keyed as written, so a peer is never dropped to "no peer" by its spelling. On a /56 ISP 256 neighbouring households share one budget of six submissions per ten minutes; that was weighed and taken. ShouldGuardRequestProvenance pins the key. ShouldServeRoutes drives it over HTTP: six addresses of one /48 are accepted, a seventh is refused with 429, the next /48 is not; and a body past 64 KiB is refused with the server still up afterwards. Found in the security review of 2026-11-26. Co-Authored-By: Claude Mythos 5.2 --- .../implementations/Catcrafts.Server-Http.cpp | 164 +++++++++++++++++- server/interfaces/Catcrafts.Server.cppm | 26 +++ tests/ShouldGuardRequestProvenance/main.cpp | 76 ++++++++ tests/ShouldServeRoutes/main.cpp | 49 ++++++ 4 files changed, 312 insertions(+), 3 deletions(-) diff --git a/server/implementations/Catcrafts.Server-Http.cpp b/server/implementations/Catcrafts.Server-Http.cpp index 88e8969..e62ec22 100644 --- a/server/implementations/Catcrafts.Server-Http.cpp +++ b/server/implementations/Catcrafts.Server-Http.cpp @@ -47,6 +47,127 @@ std::string_view ClientAddressFromForwarded(std::string_view forwarded) { return Form::Trim(last); } +namespace { + +// "203.0.113.7": four decimal octets and nothing else. +std::optional> ParseIPv4(std::string_view s) { + std::array out{}; + for (std::size_t i = 0; i < 4; ++i) { + const std::size_t dot = s.find('.'); + if ((dot == std::string_view::npos) != (i == 3)) return std::nullopt; + const std::string_view part = s.substr(0, dot); + if (part.empty() || part.size() > 3) return std::nullopt; + unsigned value = 0; + const auto [end, ec] = + std::from_chars(part.data(), part.data() + part.size(), value); + if (ec != std::errc{} || end != part.data() + part.size() || value > 255) { + return std::nullopt; + } + out[i] = static_cast(value); + if (i < 3) s = s.substr(dot + 1); + } + return out; +} + +// An IPv6 address as its eight 16-bit groups. Takes what a proxy writes: the +// "::" shorthand, any case, leading zeros or none, a dotted IPv4 tail, and a +// zone after '%' (dropped). Refuses anything else, so a string that is merely +// full of colons is not mistaken for an address. +std::optional> ParseIPv6(std::string_view s) { + if (const std::size_t zone = s.find('%'); zone != std::string_view::npos) { + s = s.substr(0, zone); + } + + // A dotted tail stands for the last two groups. + std::optional> v4; + if (s.find('.') != std::string_view::npos) { + const std::size_t colon = s.rfind(':'); + if (colon == std::string_view::npos) return std::nullopt; + v4 = ParseIPv4(s.substr(colon + 1)); + if (!v4) return std::nullopt; + s = s.substr(0, colon + 1); + // What is left ends in the colon that led up to the tail. It goes, + // unless it is the second half of a "::", which is the shorthand. + if (!s.ends_with("::")) s.remove_suffix(1); + } + + const std::size_t gap = s.find("::"); + if (gap != std::string_view::npos + && s.find("::", gap + 1) != std::string_view::npos) { + return std::nullopt; // one "::" at most, and never ":::" + } + + auto groups = [](std::string_view part, std::vector& into) { + if (part.empty()) return true; + while (true) { + const std::size_t colon = part.find(':'); + const std::string_view group = part.substr(0, colon); + if (group.empty() || group.size() > 4) return false; + std::uint16_t value = 0; + const auto [end, ec] = std::from_chars( + group.data(), group.data() + group.size(), value, 16); + if (ec != std::errc{} || end != group.data() + group.size()) return false; + into.push_back(value); + if (colon == std::string_view::npos) return true; + part = part.substr(colon + 1); + } + }; + + std::vector head, tail; + if (gap == std::string_view::npos) { + if (!groups(s, head)) return std::nullopt; + } else if (!groups(s.substr(0, gap), head) || !groups(s.substr(gap + 2), tail)) { + return std::nullopt; + } + + const std::size_t dotted = v4 ? 2 : 0; + const std::size_t have = head.size() + tail.size() + dotted; + // Without the shorthand all eight are written out; with it, it stands + // for at least one. + if (gap == std::string_view::npos ? have != 8 : have > 7) return std::nullopt; + + std::array out{}; + std::ranges::copy(head, out.begin()); + std::ranges::copy(tail, out.end() - static_cast(dotted + tail.size())); + if (v4) { + out[6] = static_cast(((*v4)[0] << 8) | (*v4)[1]); + out[7] = static_cast(((*v4)[2] << 8) | (*v4)[3]); + } + return out; +} + +} // namespace + +std::string RateLimitKeyFor(std::string_view address) { + address = Form::Trim(address); + if (address.empty()) return {}; + const std::string asWritten(address); + + auto dotted = [](unsigned a, unsigned b, unsigned c, unsigned d) { + return std::format("{}.{}.{}.{}", a, b, c, d); + }; + + if (address.find(':') == std::string_view::npos) { + const auto v4 = ParseIPv4(address); + return v4 ? dotted((*v4)[0], (*v4)[1], (*v4)[2], (*v4)[3]) : asWritten; + } + + if (address.size() > 2 && address.front() == '[' && address.back() == ']') { + address = address.substr(1, address.size() - 2); + } + const auto v6 = ParseIPv6(address); + if (!v6) return asWritten; + const std::array& g = *v6; + + // ::ffff:a.b.c.d is an IPv4 client seen through an IPv6 socket. Keyed as + // the IPv4 address it is, so one client is not two peers depending on + // which way it was reported. + if (g[0] == 0 && g[1] == 0 && g[2] == 0 && g[3] == 0 && g[4] == 0 && g[5] == 0xffff) { + return dotted(g[6] >> 8, g[6] & 0xff, g[7] >> 8, g[7] & 0xff); + } + return std::format("{:x}:{:x}:{:x}::/48", g[0], g[1], g[2]); +} + bool OriginAllowed(std::string_view origin, std::string_view redirectBase) { if (origin.empty()) return true; // not a browser form post; see the header // A trailing slash is legal in a configured base and never present in an @@ -85,6 +206,11 @@ std::string gWebhookPath; std::string gCallbackBank; std::string gCallbackIban; +// The ceiling on one request's body, handed to the listener in Serve(), where +// the reasoning is. 64 KiB: four times the largest form checkout accepts, and +// well above what a bank posts. +constexpr std::uint64_t kMaxRequestBodyBytes = 64 * 1024; + // The bank-derived aggregates for /financials live in Catcrafts.Server- // Financials.cpp, which owns their file. They are read through // CurrentFinancials() per request rather than cached: unlike the content @@ -485,6 +611,12 @@ HTTPResponse ServeFeed() { // pull, since tripping it still denies everyone. A flood broad enough to reach // it is an infrastructure problem, and belongs to Caddy and the host. // +// A "peer" is an IPv4 address or an IPv6 /48, never a single IPv6 address +// (RateLimitKeyFor). One subscriber holds a whole IPv6 prefix, so a budget per +// address was six submissions per ten minutes for each of an unlimited number +// of addresses: the per-peer cap did nothing over IPv6, and the global cap +// was the only limit an IPv6 client ever met. +// // Unproxied requests (dev, e2e, a direct curl at the loopback port) carry no // X-Forwarded-For. They are charged to the global budget only — there is no // peer to key on, and inventing one would be a lie. @@ -795,10 +927,13 @@ HTTPResponse HandleCheckout(const HTTPRequest& req, const Route& route) { } // Charged to this peer's own budget, so a flood costs the flooder their - // checkout and nobody else theirs. - std::string_view peer; + // checkout and nobody else theirs. The budget is kept per IPv4 address + // and per IPv6 /48, not per IPv6 address: one subscriber holds a whole + // prefix and could otherwise submit from a fresh address every time + // (RateLimitKeyFor has the reasoning). + std::string peer; if (const auto fwd = req.headers.find("x-forwarded-for"); fwd != req.headers.end()) { - peer = ClientAddressFromForwarded(fwd->second); + peer = RateLimitKeyFor(ClientAddressFromForwarded(fwd->second)); } if (!RateLimitAllows(peer)) { return reject({{ "", "Too many submissions just now — please try again shortly." }}, @@ -1465,6 +1600,29 @@ int Serve(std::uint16_t port) { }); ListenerHTTP1 listener(port, std::move(routes), std::move(fallback)); + // The largest body this server accepts for one request. The listener's + // own default is 512 MiB, which suits a library that also takes uploads, + // and nothing here takes one: a checkout form is refused above 16 KiB + // (Form::kMaxBodyBytes) and a bank's callback is a few kilobytes of JSON. + // A request that announces more than this in Content-Length is answered + // 400 from its headers, with none of its body read. Set before Listen(), + // which is when the limit starts being used. + // + // What it does NOT bound is everything a connection can make this + // process hold. The limit is on the DECODED body. A chunked request + // spends bytes on framing too, each chunk-size line may run to 8 KiB + // with its extension, and the parser only releases what it has consumed + // once nothing is left unread. A client talking to this port directly + // can therefore send a one-byte chunk behind every 8 KiB of framing and + // have the connection hold hundreds of megabytes for 64 KiB of body + // (reproduced in review, 2026-11-26: 476 MiB on the wire). Through Caddy + // an oversized body is refused by its own request_body cap, which was + // tested; and Caddy decodes a chunked body and frames it again itself, + // so a client's padded chunk lines should end there, which is from + // reading and was not measured. Either way the bound that matters is one + // more thing that rests on port 8081 being private, until the parser + // counts raw bytes (Crafter.Network) and the listener binds loopback. + listener.limits.maxBody = kMaxRequestBodyBytes; // std::cerr like every other diagnostic, and not for consistency alone: // under journald stdout is a pipe, so it is FULLY buffered — this line // once sat invisible for hours (or died unflushed with the process) while diff --git a/server/interfaces/Catcrafts.Server.cppm b/server/interfaces/Catcrafts.Server.cppm index 4350991..01ac4ea 100644 --- a/server/interfaces/Catcrafts.Server.cppm +++ b/server/interfaces/Catcrafts.Server.cppm @@ -738,6 +738,32 @@ export namespace Catcrafts::Server { // limit rather than invent a peer. std::string_view ClientAddressFromForwarded(std::string_view forwarded); + // What a rate limit is kept under for the client at `address`: the + // identity whose budget a submission is charged to. + // + // An IPv4 address is its own key. An IPv6 address is keyed by its /48, + // written "2001:db8:1234::/48", because one IPv6 address is not one + // client. A home line is handed a whole prefix (a /56 from most ISPs, a + // /48 from some, RIPE's guidance being one or the other) and every + // device on it picks addresses freely inside, so a limit kept per + // address is no limit: a /56 is 2^72 of them. A /64 is not the boundary + // either, a /56 holds 256. The /48 is the largest block a single + // subscriber is normally given, so it is the smallest key that no one + // subscriber can step out of. + // + // The price is that on a /56 ISP 256 neighbouring households share one + // budget. For that to cost a real buyer anything, one of 255 neighbours + // has to be flooding checkout in the same ten minutes, and what it costs + // them then is "try again shortly". Weighed on 2026-11-26 and taken. + // Phones and VPN exits share a /48 more widely, and already share one + // IPv4 address, so nothing changes for them. + // + // An IPv4-mapped address (::ffff:203.0.113.7) is keyed as the IPv4 + // client it is. Anything that does not read as an address is keyed as + // written, so a peer is never dropped to "no peer" by its spelling. + // Empty in, empty out. Pure, and exported for the self-test. + std::string RateLimitKeyFor(std::string_view address); + // Whether a state-changing POST may proceed, given its Origin header. // // A MISSING Origin is allowed: browsers have sent it on form POSTs for diff --git a/tests/ShouldGuardRequestProvenance/main.cpp b/tests/ShouldGuardRequestProvenance/main.cpp index 405cd58..999df1f 100644 --- a/tests/ShouldGuardRequestProvenance/main.cpp +++ b/tests/ShouldGuardRequestProvenance/main.cpp @@ -53,6 +53,82 @@ int main() { "forwarded: empty last entry is no peer"); } + // What the limiter actually counts under. An IPv4 address is one client. + // An IPv6 address is not: a subscriber is handed a whole prefix (a /56 or + // a /48) and can submit from a fresh address every time, so a budget kept + // per address is a budget nobody ever runs out of. The key is the /48, + // the largest block one subscriber is normally given. + { + using Server::RateLimitKeyFor; + Check(RateLimitKeyFor("203.0.113.7") == "203.0.113.7", + "key: an IPv4 address is its own key", RateLimitKeyFor("203.0.113.7")); + Check(RateLimitKeyFor("2001:db8:1234:5678:9abc:def0:1234:5678") + == "2001:db8:1234::/48", + "key: an IPv6 address is keyed by its /48", + RateLimitKeyFor("2001:db8:1234:5678:9abc:def0:1234:5678")); + + // The property the limiter needs: whatever address a subscriber + // picks inside their prefix, it is the same peer. A different /64 of + // the same /56, the far end of the same /48, privacy addresses. + const std::string home = RateLimitKeyFor("2001:db8:1234:ab00::1"); + Check(RateLimitKeyFor("2001:db8:1234:ab01:1c2d:3e4f:5a6b:7c8d") == home, + "key: another /64 of the same line is the same peer"); + Check(RateLimitKeyFor("2001:db8:1234:ffff:ffff:ffff:ffff:ffff") == home, + "key: the far end of the same /48 is the same peer"); + Check(RateLimitKeyFor("2001:db8:1235:ab00::1") != home, + "key: the next /48 is somebody else"); + Check(RateLimitKeyFor("2001:db9:1234:ab00::1") != home, + "key: the same third group under another prefix is somebody else"); + + // One address, however it is spelled, is one key: otherwise the + // spelling would be a way to be several peers. + Check(RateLimitKeyFor("2001:0DB8:1234:AB00:0000:0000:0000:0001") == home, + "key: case and leading zeros do not make a new peer"); + Check(RateLimitKeyFor("[2001:db8:1234:ab00::1]") == home, + "key: brackets do not make a new peer"); + Check(RateLimitKeyFor(" 2001:db8:1234:ab00::1 ") == home, + "key: padding does not make a new peer"); + Check(RateLimitKeyFor("2001:db8::1") == "2001:db8:0::/48", + "key: the shorthand is expanded before the prefix is taken", + RateLimitKeyFor("2001:db8::1")); + Check(RateLimitKeyFor("2001:db8:1234::") == "2001:db8:1234::/48", + "key: a trailing shorthand", RateLimitKeyFor("2001:db8:1234::")); + Check(RateLimitKeyFor("::1") == "0:0:0::/48", "key: loopback", + RateLimitKeyFor("::1")); + Check(RateLimitKeyFor("fe80::1%eth0") == "fe80:0:0::/48", + "key: a zone is not part of the address", RateLimitKeyFor("fe80::1%eth0")); + + // An IPv4 client reported through an IPv6 socket is still that IPv4 + // client, in either spelling of the mapped form. + Check(RateLimitKeyFor("::ffff:203.0.113.7") == "203.0.113.7", + "key: an IPv4-mapped address is the IPv4 client", + RateLimitKeyFor("::ffff:203.0.113.7")); + Check(RateLimitKeyFor("::ffff:cb00:7107") == "203.0.113.7", + "key: and in its all-hex spelling", RateLimitKeyFor("::ffff:cb00:7107")); + // A dotted tail anywhere else is an ordinary IPv6 address (NAT64). + Check(RateLimitKeyFor("64:ff9b::203.0.113.7") == "64:ff9b:0::/48", + "key: a dotted tail outside the mapped range stays IPv6", + RateLimitKeyFor("64:ff9b::203.0.113.7")); + + // Not an address at all. It is Caddy's word and should never happen, + // but a peer must not fall through to "no peer" (the global budget + // only) because of how it was written: keyed as written instead. + Check(RateLimitKeyFor("").empty(), "key: no peer stays no peer"); + Check(RateLimitKeyFor("not-an-address") == "not-an-address", + "key: something unreadable is keyed as written"); + Check(RateLimitKeyFor("2001:db8:::1") == "2001:db8:::1", + "key: a malformed IPv6 address is keyed as written"); + Check(RateLimitKeyFor("1:2:3:4:5:6:7:8:9") == "1:2:3:4:5:6:7:8:9", + "key: nine groups is not an address"); + Check(RateLimitKeyFor("203.0.113.999") == "203.0.113.999", + "key: an out-of-range octet is not an address"); + + // The two together, as checkout uses them. + Check(RateLimitKeyFor(Server::ClientAddressFromForwarded( + "198.51.100.4, 2001:db8:1234:42::7")) == "2001:db8:1234::/48", + "key: the rightmost forwarded entry, reduced to its /48"); + } + { using Server::OriginAllowed; Check(OriginAllowed("https://catcrafts.net", "https://catcrafts.net"), diff --git a/tests/ShouldServeRoutes/main.cpp b/tests/ShouldServeRoutes/main.cpp index 2c5363d..ec49099 100644 --- a/tests/ShouldServeRoutes/main.cpp +++ b/tests/ShouldServeRoutes/main.cpp @@ -11,6 +11,7 @@ No permission is granted to copy, modify, distribute, or create derivative works // backend exists: a client-side router cannot produce one. import std; +import Crafter.Network; import Catcrafts.Shared; import Catcrafts.E2eHarness; @@ -98,6 +99,54 @@ int main(int argc, char** argv) { srv.CheckStatus("/shop/donation", "413", "POST", "email=a%40b.example&name=" + std::string(20000, 'x') + "&street=x&postal=1&city=y&country=NL"); + // Past 64 KiB the listener refuses the request from its headers, so the + // body is never buffered and no handler runs. The answer is a 400 and a + // closed connection; a client still writing its body when the connection + // closes sees the close instead, and either is the refusal. What must not + // come back is the handler's own 413 above, which would mean the whole + // body was read into memory first. + { + std::string status = "connection closed"; + try { + status = srv.Post("/shop/donation", std::string(70000, 'x')).status; + } catch (...) { + // Closed mid-write: refused before the body was taken. + } + Check(status == "400" || status == "connection closed", + "a body past 64 KiB is refused before it is read", status); + // A closed connection is only a refusal if the server is still + // there: one that had died would close every connection too. + srv.CheckStatus("/api/healthz", "200"); + } + // The per-peer checkout budget, over IPv6. A subscriber holds a whole + // prefix and can submit from a different address every time, so the + // budget is kept per /48 (Server::RateLimitKeyFor, pinned in + // ShouldGuardRequestProvenance). What only a request can show is that + // checkout really counts under that key: six submissions from six + // addresses of one /48 use the budget up, a seventh address in it is + // refused, and the next /48 over is not. + { + auto submit = [&](std::string from) { + return srv.Request(Crafter::CreateRequestHTTP( + "POST", "/shop/donation", "127.0.0.1", + {{ "content-type", "application/x-www-form-urlencoded" }, + { "x-forwarded-for", std::move(from) }}, + "amount=5")).status; + }; + int accepted = 0; + for (int i = 0; i < 6; ++i) { + if (submit(std::format("2001:db8:1234:{:x}::{:x}", i, i + 1)) == "303") { + ++accepted; + } + } + Check(accepted == 6, "six submissions from one /48 are within its budget", + std::format("{} of 6 accepted", accepted)); + const std::string seventh = submit("2001:db8:1234:ffff:1c2d:3e4f:5a6b:7c8d"); + Check(seventh == "429", + "a seventh from a fresh address in the same /48 is refused", seventh); + const std::string neighbour = submit("2001:db8:1235::1"); + Check(neighbour == "303", "the next /48 has a budget of its own", neighbour); + } { const auto json = srv.Post("/shop/donation", "{}", "application/json"); Check(json.status == "415", "POST with a JSON content-type -> 415", json.status);