diff --git a/include/Void/Net/HttpServer.hpp b/include/Void/Net/HttpServer.hpp index 6ac516e..eb6feaa 100644 --- a/include/Void/Net/HttpServer.hpp +++ b/include/Void/Net/HttpServer.hpp @@ -34,6 +34,15 @@ namespace Void::Net /// once this much framed data is pending. std::size_t duplex_write_buffer_bytes{64ULL * 1024}; int listen_backlog{128}; + + /// Reverse proxies whose forwarding headers are trusted. Entries are + /// exact IP literals ("127.0.0.1", "::1") or CIDR blocks + /// ("10.0.0.0/8", "fd00::/8"). Empty (the default) ignores + /// `X-Forwarded-For` from every peer. When the immediate peer matches + /// an entry, the header is parsed right-to-left and the first hop that + /// is not itself trusted becomes `ServerRequest::client`. Malformed + /// chains are ignored rather than trusted. + std::vector trusted_proxies{}; }; /// Streaming request body reader passed to streaming HTTP route handlers. diff --git a/include/Void/Net/Server.hpp b/include/Void/Net/Server.hpp index acb4582..41feb1e 100644 --- a/include/Void/Net/Server.hpp +++ b/include/Void/Net/Server.hpp @@ -24,6 +24,15 @@ namespace Void::Net using RouteParameters = std::map>; + /// Numeric address of one HTTP peer. `port` is in host byte order and is + /// zero when the address was derived from a forwarding header. + struct PeerInfo { + std::string address; + std::uint16_t port{0}; + + auto operator<=>(const PeerInfo&) const = default; + }; + struct ServerRequest { Method method{Method::Get}; std::string path; @@ -31,6 +40,13 @@ namespace Void::Net std::string body; RouteParameters parameters; std::string query{}; + /// Immediate TCP peer of the connection (numeric address). + PeerInfo peer{}; + /// Effective client address. Equal to `peer` unless the immediate + /// peer is a configured trusted proxy, in which case the rightmost + /// non-trusted `X-Forwarded-For` hop is used. Forwarding headers + /// from untrusted peers are ignored. + PeerInfo client{}; [[nodiscard]] std::optional header(std::string_view name) const noexcept; diff --git a/src/Net/HttpServer.cpp b/src/Net/HttpServer.cpp index 343bbc8..adeadfe 100644 --- a/src/Net/HttpServer.cpp +++ b/src/Net/HttpServer.cpp @@ -74,6 +74,199 @@ namespace Void::Net return s; } + struct IpAddress { + int family{0}; + std::array bytes{}; + + auto operator<=>(const IpAddress&) const = default; + }; + + /// Parses a numeric IPv4/IPv6 literal. IPv4-mapped IPv6 addresses are + /// normalized to IPv4 so a dual-stack listener matches IPv4 CIDRs. + [[nodiscard]] std::optional + parse_ip(std::string_view text) noexcept + { + if (text.empty() || text.size() >= INET6_ADDRSTRLEN + 8) { + return std::nullopt; + } + std::string owned{text}; + IpAddress out; + in_addr v4{}; + if (::inet_pton(AF_INET, owned.c_str(), &v4) == 1) { + out.family = AF_INET; + std::memcpy(out.bytes.data(), &v4, sizeof(v4)); + return out; + } + in6_addr v6{}; + if (::inet_pton(AF_INET6, owned.c_str(), &v6) != 1) { + return std::nullopt; + } + constexpr std::array mapped_prefix{ + std::byte{0}, std::byte{0}, std::byte{0}, std::byte{0}, + std::byte{0}, std::byte{0}, std::byte{0}, std::byte{0}, + std::byte{0}, std::byte{0}, std::byte{0xff}, std::byte{0xff}}; + if (std::memcmp(v6.s6_addr, mapped_prefix.data(), + mapped_prefix.size()) == 0) { + out.family = AF_INET; + std::memcpy(out.bytes.data(), v6.s6_addr + 12, 4); + return out; + } + out.family = AF_INET6; + std::memcpy(out.bytes.data(), &v6, sizeof(v6)); + return out; + } + + struct TrustedRange { + IpAddress network; + int prefix{0}; + }; + + [[nodiscard]] std::optional + parse_trusted_range(std::string_view text) + { + const std::size_t slash = text.find('/'); + const auto parsed = parse_ip(text.substr(0, slash)); + if (!parsed.has_value()) { + return std::nullopt; + } + const int max_prefix = parsed->family == AF_INET ? 32 : 128; + int prefix = max_prefix; + if (slash != std::string_view::npos) { + const std::string_view suffix = text.substr(slash + 1); + int value = 0; + const auto [ptr, ec] = + std::from_chars(suffix.data(), suffix.data() + suffix.size(), + value); + if (ec != std::errc{} || ptr != suffix.data() + suffix.size() || + value < 0 || value > max_prefix) { + return std::nullopt; + } + prefix = value; + } + return TrustedRange{*parsed, prefix}; + } + + [[nodiscard]] bool ip_in_range(const IpAddress& address, + const TrustedRange& range) noexcept + { + if (address.family != range.network.family) { + return false; + } + const int full_bytes = range.prefix / 8; + const int remaining_bits = range.prefix % 8; + if (full_bytes > 0 && + std::memcmp(address.bytes.data(), range.network.bytes.data(), + static_cast(full_bytes)) != 0) { + return false; + } + if (remaining_bits == 0) { + return true; + } + const auto mask = static_cast( + 0xFFu << (8 - remaining_bits)); + const auto a = static_cast( + address.bytes[static_cast(full_bytes)]); + const auto b = static_cast( + range.network.bytes[static_cast(full_bytes)]); + return (a & mask) == (b & mask); + } + + /// True when `address` matches any configured trusted-proxy entry. + /// Unparsable configuration entries are ignored (fail closed). + [[nodiscard]] bool + is_trusted_proxy(std::string_view address, + const std::vector& trusted) noexcept + { + if (trusted.empty() || address.empty()) { + return false; + } + const auto parsed = parse_ip(address); + if (!parsed.has_value()) { + return false; + } + for (const auto& entry : trusted) { + const auto range = parse_trusted_range(entry); + if (range.has_value() && ip_in_range(*parsed, *range)) { + return true; + } + } + return false; + } + + [[nodiscard]] PeerInfo peer_info_of(int fd) noexcept + { + PeerInfo info; + sockaddr_storage ss{}; + socklen_t length = sizeof(ss); + if (::getpeername(fd, reinterpret_cast(&ss), &length) != 0) { + return info; + } + std::array buffer{}; + if (ss.ss_family == AF_INET) { + const auto* v4 = reinterpret_cast(&ss); + info.port = ntohs(v4->sin_port); + if (::inet_ntop(AF_INET, &v4->sin_addr, buffer.data(), + buffer.size()) != nullptr) { + info.address = buffer.data(); + } + } else if (ss.ss_family == AF_INET6) { + const auto* v6 = reinterpret_cast(&ss); + info.port = ntohs(v6->sin6_port); + if (::inet_ntop(AF_INET6, &v6->sin6_addr, buffer.data(), + buffer.size()) != nullptr) { + info.address = buffer.data(); + } + } + return info; + } + + /// Resolves the effective client from the immediate peer and the + /// X-Forwarded-For chain. The header is only consulted when the peer is a + /// configured trusted proxy; malformed hops invalidate the whole chain. + [[nodiscard]] PeerInfo + resolve_client(const PeerInfo& peer, + const std::vector
& headers, + const std::vector& trusted) + { + PeerInfo client = peer; + if (!is_trusted_proxy(peer.address, trusted)) { + return client; + } + std::string chain; + for (const auto& header : headers) { + if (equal_ascii_ci(header.name, "X-Forwarded-For")) { + if (!chain.empty()) { + chain += ','; + } + chain += header.value; + } + } + if (chain.empty()) { + return client; + } + std::vector hops; + std::string_view rest = chain; + while (true) { + const std::size_t comma = rest.find(','); + const std::string_view token = trim_ows(rest.substr(0, comma)); + if (token.empty() || !parse_ip(token).has_value()) { + return client; + } + hops.emplace_back(token); + if (comma == std::string_view::npos) { + break; + } + rest.remove_prefix(comma + 1); + } + std::size_t index = hops.size(); + while (index > 0 && is_trusted_proxy(hops[index - 1], trusted)) { + --index; + } + client.address = hops[index == 0 ? 0 : index - 1]; + client.port = 0; + return client; + } + [[nodiscard]] std::optional parse_method(std::string_view token) noexcept { @@ -2009,6 +2202,7 @@ namespace Void::Net OwnedFd fd_guard{raw_fd}; std::string rx_buf; std::size_t rx_off = 0; + const PeerInfo peer = peer_info_of(fd_guard.get()); while (!stopping.load(std::memory_order_acquire)) { // 1. Read request headers up to \r\n\r\n. @@ -2208,6 +2402,9 @@ namespace Void::Net ws_req.path = std::string{raw_path}; ws_req.headers = std::move(headers); ws_req.query = std::string{raw_query}; + ws_req.peer = peer; + ws_req.client = resolve_client( + peer, ws_req.headers, options.trusted_proxies); auto hs = validate_websocket_upgrade_request( ws_req, ws_match->options); if (!hs.has_value()) { @@ -2373,6 +2570,9 @@ namespace Void::Net req.headers = std::move(headers); req.parameters = std::move(streaming_match->second); req.query = std::string{raw_query}; + req.peer = peer; + req.client = resolve_client( + peer, req.headers, options.trusted_proxies); auto route_res = streaming_match->first(req, body_reader); @@ -2443,6 +2643,9 @@ namespace Void::Net req.headers = std::move(headers); req.body = std::move(body_str); req.query = std::string{raw_query}; + req.peer = peer; + req.client = resolve_client( + peer, req.headers, options.trusted_proxies); auto dispatched = router->dispatch(req); if (!dispatched.has_value()) { diff --git a/tests/standalone/Net/HttpServer.cpp b/tests/standalone/Net/HttpServer.cpp index 75b9d6a..a3e62bd 100644 --- a/tests/standalone/Net/HttpServer.cpp +++ b/tests/standalone/Net/HttpServer.cpp @@ -391,3 +391,92 @@ Void::Testing::Test http_server_limits_smuggling_streaming_and_graceful_drain() Void::Testing::expect_eq(slow_result->body, std::string{"drained"}); } } + +namespace +{ + std::string response_body(const std::string& raw) + { + const std::size_t split = raw.find("\r\n\r\n"); + return split == std::string::npos ? std::string{} : raw.substr(split + 4); + } + + std::string peer_probe(std::uint16_t port, std::string_view forwarded_for) + { + std::string request = "GET /peer HTTP/1.1\r\nHost: 127.0.0.1\r\n"; + if (!forwarded_for.empty()) { + request += "X-Forwarded-For: "; + request += forwarded_for; + request += "\r\n"; + } + request += "Connection: close\r\n\r\n"; + return response_body(raw_http_exchange(port, request)); + } +} // namespace + +Void::Testing::Test http_server_peer_address_and_trusted_proxy_policy() +{ + auto register_probe = [](HttpServer& server) { + Void::Testing::require( + server + .add_route(Method::Get, "/peer", + [](const ServerRequest& req) { + return Void::Result::ok(ServerResponse{ + .status = 200, + .body = req.peer.address + "|" + + req.client.address + "|" + + std::to_string(req.peer.port) + + "|" + + std::to_string(req.client.port)}); + }) + .has_value()); + }; + + // Untrusted peer: forwarding headers are ignored, peer is loopback. + { + HttpServerOptions opts; + opts.bind_host = "127.0.0.1"; + HttpServer server{opts}; + register_probe(server); + Void::Testing::require(server.start().has_value()); + const std::uint16_t port = server.bound_port(); + + const std::string direct = peer_probe(port, {}); + Void::Testing::expect(direct.starts_with("127.0.0.1|127.0.0.1|")); + const std::size_t first = direct.find('|'); + const std::size_t second = direct.find('|', first + 1); + const std::size_t third = direct.find('|', second + 1); + Void::Testing::require(third != std::string::npos); + Void::Testing::expect_eq(direct.substr(second + 1, third - second - 1), + direct.substr(third + 1)); + + const std::string spoofed = peer_probe(port, "203.0.113.7"); + Void::Testing::expect(spoofed.starts_with("127.0.0.1|127.0.0.1|")); + + server.shutdown(std::chrono::seconds{2}); + } + + // Trusted loopback proxy: the rightmost non-trusted hop wins. + { + HttpServerOptions opts; + opts.bind_host = "127.0.0.1"; + opts.trusted_proxies = {"127.0.0.0/8"}; + HttpServer server{opts}; + register_probe(server); + Void::Testing::require(server.start().has_value()); + const std::uint16_t port = server.bound_port(); + + Void::Testing::expect(peer_probe(port, "203.0.113.7") + .starts_with("127.0.0.1|203.0.113.7|")); + Void::Testing::expect( + peer_probe(port, "198.51.100.9, 127.0.0.5") + .starts_with("127.0.0.1|198.51.100.9|")); + Void::Testing::expect(peer_probe(port, "2001:db8::1") + .starts_with("127.0.0.1|2001:db8::1|")); + // Malformed chain: fail closed to the immediate peer. + Void::Testing::expect( + peer_probe(port, "203.0.113.7, not-an-ip") + .starts_with("127.0.0.1|127.0.0.1|")); + + server.shutdown(std::chrono::seconds{2}); + } +}