Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-25 23:44:48 +03:00
1 parent 7a0446b573
commit 3632f2cd43
27 files changed
+3332 -97

No files matched your search

+351
View File
@@ -0,0 +1,351 @@
#include "echoion/web/HttpSecurity.hpp"
#include <boost/asio/ip/address_v6.hpp>
#include <boost/url/parse.hpp>
#include <boost/url/scheme.hpp>
#include <algorithm>
#include <charconv>
#include <cmath>
#include <format>
#include <stdexcept>
namespace Echoion::Web::Security
{
namespace
{
constexpr std::size_t MAX_FORWARDED_HOPS = 64;
constexpr std::size_t MAX_REDIRECT_LENGTH = 8192;
asio::ip::address
normalizeMappedAddress(const asio::ip::address& address)
{
if (address.is_v6() && address.to_v6().is_v4_mapped()) {
return asio::ip::make_address_v4(asio::ip::v4_mapped,
address.to_v6());
}
return address;
}
bool isTrusted(const asio::ip::address& address,
std::span<const CidrBlock>
trustedProxies) noexcept
{
return std::ranges::any_of(trustedProxies,
[&address](const CidrBlock& network) {
return network.contains(address);
});
}
std::string_view trimForwardedToken(std::string_view token) noexcept
{
while (!token.empty() &&
(token.front() == ' ' || token.front() == '\t')) {
token.remove_prefix(1);
}
while (!token.empty() &&
(token.back() == ' ' || token.back() == '\t')) {
token.remove_suffix(1);
}
return token;
}
} // namespace
CidrBlock::CidrBlock(asio::ip::address network, unsigned int prefixLength)
: network_(std::move(network)), prefixLength_(prefixLength)
{
}
bool CidrBlock::contains(const asio::ip::address& address) const noexcept
{
asio::ip::address candidate = address;
if (network_.is_v4() && candidate.is_v6()) {
if (!candidate.to_v6().is_v4_mapped()) {
return false;
}
candidate = asio::ip::make_address_v4(asio::ip::v4_mapped,
candidate.to_v6());
} else if (network_.is_v6() && candidate.is_v4()) {
candidate = asio::ip::make_address_v6(asio::ip::v4_mapped,
candidate.to_v4());
}
if (network_.is_v4() != candidate.is_v4()) {
return false;
}
const auto matches = [this](const auto& lhs, const auto& rhs) {
for (std::size_t index = 0; index < lhs.size(); ++index) {
const auto consumed = static_cast<unsigned int>(index * 8);
const auto remaining =
prefixLength_ > consumed ? prefixLength_ - consumed : 0U;
const auto mask = static_cast<unsigned char>(
remaining >= 8 ? 0xffU
: remaining == 0 ? 0U
: 0xffU << (8 - remaining));
if ((lhs[index] & mask) != (rhs[index] & mask)) {
return false;
}
}
return true;
};
return network_.is_v4() ? matches(network_.to_v4().to_bytes(),
candidate.to_v4().to_bytes())
: matches(network_.to_v6().to_bytes(),
candidate.to_v6().to_bytes());
}
ParsedCidrs parseTrustedProxyCidrs(std::span<const std::string> cidrs)
{
std::vector<CidrBlock> parsed;
parsed.reserve(cidrs.size());
for (std::size_t index = 0; index < cidrs.size(); ++index) {
const std::string_view cidr = cidrs[index];
const auto slash = cidr.find('/');
if (cidr.empty() || slash == 0 ||
(slash != std::string_view::npos &&
(slash + 1 == cidr.size() ||
cidr.find('/', slash + 1) != std::string_view::npos))) {
return std::unexpected(
std::format("trusted proxy CIDR #{} ('{}') is malformed",
index + 1, cidr));
}
const std::string_view addressText = cidr.substr(0, slash);
if (addressText.contains('%')) {
return std::unexpected(std::format(
"trusted proxy CIDR #{} ('{}') must not contain an IPv6 "
"scope identifier",
index + 1, cidr));
}
boost::system::error_code error;
const auto network = asio::ip::make_address(addressText, error);
if (error) {
return std::unexpected(std::format(
"trusted proxy CIDR #{} ('{}') has an invalid address",
index + 1, cidr));
}
const unsigned int maxBits = network.is_v4() ? 32U : 128U;
unsigned int prefixLength = maxBits;
if (slash != std::string_view::npos) {
const std::string_view prefix = cidr.substr(slash + 1);
const auto [end, code] = std::from_chars(
prefix.data(), prefix.data() + prefix.size(), prefixLength);
if (code != std::errc{} ||
end != prefix.data() + prefix.size() ||
prefixLength > maxBits) {
return std::unexpected(std::format(
"trusted proxy CIDR #{} ('{}') has an invalid prefix",
index + 1, cidr));
}
}
parsed.emplace_back(network, prefixLength);
}
return parsed;
}
std::string effectiveClientAddress(const asio::ip::address& immediatePeer,
std::optional<std::string_view>
forwardedFor,
std::span<const CidrBlock>
trustedProxies)
{
const auto directAddress = normalizeMappedAddress(immediatePeer);
if (!forwardedFor || !isTrusted(immediatePeer, trustedProxies)) {
return directAddress.to_string();
}
std::vector<asio::ip::address> hops;
hops.reserve(8);
std::string_view remaining = *forwardedFor;
for (;;) {
if (hops.size() == MAX_FORWARDED_HOPS) {
return directAddress.to_string();
}
const auto comma = remaining.find(',');
const auto token = trimForwardedToken(remaining.substr(0, comma));
if (token.empty() || token.contains('%')) {
return directAddress.to_string();
}
boost::system::error_code error;
auto hop = asio::ip::make_address(token, error);
if (error || (hop.is_v6() && hop.to_v6().scope_id() != 0)) {
return directAddress.to_string();
}
hops.push_back(std::move(hop));
if (comma == std::string_view::npos) {
break;
}
remaining.remove_prefix(comma + 1);
}
asio::ip::address effective = immediatePeer;
for (auto hop = hops.rbegin(); hop != hops.rend(); ++hop) {
if (!isTrusted(effective, trustedProxies)) {
break;
}
effective = *hop;
}
return normalizeMappedAddress(effective).to_string();
}
bool validShortSlug(std::string_view slug) noexcept
{
return slug.size() == 10 &&
std::ranges::all_of(slug, [](unsigned char character) {
return (character >= '0' && character <= '9') ||
(character >= 'A' && character <= 'Z') ||
(character >= 'a' && character <= 'z');
});
}
bool validRedirectLocation(std::string_view location) noexcept
{
if (location.empty() || location.size() > MAX_REDIRECT_LENGTH ||
std::ranges::any_of(location, [](unsigned char character) {
return character <= 0x20U || character >= 0x7fU;
})) {
return false;
}
const auto parsed = boost::urls::parse_uri(location);
if (!parsed) {
return false;
}
const auto& url = *parsed;
if ((url.scheme_id() != boost::urls::scheme::http &&
url.scheme_id() != boost::urls::scheme::https) ||
!url.has_authority() || url.has_userinfo() ||
url.encoded_host().empty()) {
return false;
}
if (url.has_port()) {
const auto port = url.port();
unsigned int number = 0;
const auto [end, code] =
std::from_chars(port.data(), port.data() + port.size(), number);
if (port.empty() || code != std::errc{} ||
end != port.data() + port.size() || number == 0 ||
number > 65535) {
return false;
}
}
return true;
}
ShortLinkRateLimiter::ShortLinkRateLimiter()
: ShortLinkRateLimiter(Config{})
{
}
ShortLinkRateLimiter::ShortLinkRateLimiter(Config config) : config_(config)
{
if (!std::isfinite(config_.globalRate) || config_.globalRate < 0.0 ||
!std::isfinite(config_.globalBurst) || config_.globalBurst < 1.0 ||
!std::isfinite(config_.peerRate) || config_.peerRate < 0.0 ||
!std::isfinite(config_.peerBurst) || config_.peerBurst < 1.0 ||
config_.maxPeers == 0 ||
config_.idleTimeout < Clock::duration::zero() ||
config_.sweepInterval < Clock::duration::zero()) {
throw std::invalid_argument(
"invalid short-link rate limiter settings");
}
peers_.reserve(config_.maxPeers);
}
bool ShortLinkRateLimiter::allow(std::string_view peer)
{
return allow(peer, Clock::now());
}
bool ShortLinkRateLimiter::allow(std::string_view peer, TimePoint now)
{
std::lock_guard lock(mutex_);
evictIdle(now, false);
refill(global_, config_.globalRate, config_.globalBurst, now);
if (global_.tokens < 1.0) {
return false;
}
const std::string peerKey{peer};
auto found = peers_.find(peerKey);
if (found == peers_.end()) {
if (peers_.size() >= config_.maxPeers) {
evictIdle(now, true);
}
if (peers_.size() >= config_.maxPeers) {
return false;
}
found =
peers_
.emplace(peerKey, PeerBucket{.bucket = {}, .lastSeen = now})
.first;
}
found->second.lastSeen = now;
refill(found->second.bucket, config_.peerRate, config_.peerBurst, now);
if (found->second.bucket.tokens < 1.0) {
return false;
}
// Commit both token deductions together. A peer-local rejection never
// consumes global capacity and cannot starve unrelated clients.
global_.tokens -= 1.0;
found->second.bucket.tokens -= 1.0;
return true;
}
void ShortLinkRateLimiter::reset()
{
std::lock_guard lock(mutex_);
global_ = {};
peers_.clear();
nextSweep_ = {};
sweepInitialized_ = false;
}
std::size_t ShortLinkRateLimiter::trackedPeerCount() const
{
std::lock_guard lock(mutex_);
return peers_.size();
}
void ShortLinkRateLimiter::refill(TokenBucket& bucket, double rate,
double burst, TimePoint now) noexcept
{
if (!bucket.initialized) {
bucket.tokens = burst;
bucket.updated = now;
bucket.initialized = true;
return;
}
const auto elapsed =
now > bucket.updated
? std::chrono::duration<double>(now - bucket.updated).count()
: 0.0;
bucket.tokens = std::min(burst, bucket.tokens + elapsed * rate);
bucket.updated = now;
}
void ShortLinkRateLimiter::evictIdle(TimePoint now, bool force)
{
if (!force && sweepInitialized_ && now < nextSweep_) {
return;
}
for (auto peer = peers_.begin(); peer != peers_.end();) {
const bool expired =
now >= peer->second.lastSeen &&
now - peer->second.lastSeen >= config_.idleTimeout;
if (expired) {
peer = peers_.erase(peer);
} else {
++peer;
}
}
nextSweep_ = now + config_.sweepInterval;
sweepInitialized_ = true;
}
} // namespace Echoion::Web::Security
+199 -39
View File
@@ -12,6 +12,10 @@
#include <sstream>
#include <string_view>
#if defined(__unix__) || defined(__APPLE__)
#include <sys/socket.h>
#endif
namespace Echoion::Web
{
namespace websocket = beast::websocket;
@@ -114,19 +118,77 @@ namespace Echoion::Web
from.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignore);
to.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignore);
}
} // namespace
HttpServer::HttpServer() = default;
HttpServer::~HttpServer() { stop(); }
HttpServer::TrustedProxyUpdate HttpServer::validateTrustedProxyCidrs(
const std::vector<std::string>& cidrs)
{
try {
auto parsed = Security::parseTrustedProxyCidrs(cidrs);
if (!parsed) {
return std::unexpected(std::move(parsed.error()));
}
return {};
} catch (const std::exception& exception) {
return std::unexpected(
std::format("failed to validate trusted proxy CIDRs: {}",
exception.what()));
}
}
HttpServer::TrustedProxyUpdate
HttpServer::setTrustedProxyCidrs(const std::vector<std::string>& cidrs)
{
try {
auto parsed = Security::parseTrustedProxyCidrs(cidrs);
if (!parsed) {
return std::unexpected(std::move(parsed.error()));
}
{
std::unique_lock lock(trustedProxyMutex_);
// A trust-policy change changes the peer identity used by the
// limiter. Reset while new address calculations are blocked,
// then publish the already-parsed policy with a no-throw swap.
shortLinkRateLimiter_.reset();
trustedProxyNetworks_.swap(*parsed);
}
return {};
} catch (const std::exception& exception) {
return std::unexpected(std::format(
"failed to update trusted proxy CIDRs: {}", exception.what()));
}
}
bool HttpServer::start(const Config& config)
{
if (running_.exchange(true)) {
if (running_.load()) {
return false;
}
config_ = config;
try {
auto trustedProxies =
Security::parseTrustedProxyCidrs(config.trustedProxyCidrs);
if (!trustedProxies) {
Void::Log::error(
"HttpServer", "{}",
std::format("Failed to start web interface: {}",
trustedProxies.error()));
return false;
}
bool expected = false;
if (!running_.compare_exchange_strong(expected, true)) {
return false;
}
config_ = config;
{
std::unique_lock lock(trustedProxyMutex_);
trustedProxyNetworks_ = std::move(*trustedProxies);
}
shortLinkRateLimiter_.reset();
ioContext_.restart();
asio::ip::tcp::endpoint endpoint(
@@ -272,26 +334,79 @@ namespace Echoion::Web
{
beast::error_code ec;
beast::flat_buffer buffer;
// Serve requests on this connection until the peer closes, an error
// occurs, or the request asks not to keep the connection alive.
while (running_.load()) {
http::request<http::string_body> req;
http::read(*socket, buffer, req, ec);
if (ec) {
return;
}
if (websocket::is_upgrade(req)) {
if (req.target() == "/rpc") {
bridgeRpc(socket, req, buffer);
}
return;
}
if (!serveHttp(*socket, req)) {
// Bound slow clients and parser memory. Every accepted connection
// serves exactly one request; browsers simply open another connection.
#if defined(__unix__) || defined(__APPLE__)
timeval timeout{.tv_sec = 5, .tv_usec = 0};
(void)::setsockopt(socket->native_handle(), SOL_SOCKET, SO_RCVTIMEO,
&timeout, sizeof(timeout));
#endif
http::request_parser<http::string_body> parser;
parser.header_limit(32 * 1024);
parser.body_limit(0);
http::read(*socket, buffer, parser, ec);
if (ec) {
return;
}
auto req = parser.release();
for (const auto& field : req) {
if (field.name_string().size() + field.value().size() > 8 * 1024) {
http::response<http::string_body> response{
http::status::request_header_fields_too_large,
req.version()};
response.set(http::field::server, "Echoion");
response.body() = "Request Header Fields Too Large";
response.prepare_payload();
response.keep_alive(false);
http::write(*socket, response, ec);
return;
}
}
if (websocket::is_upgrade(req)) {
if (req.target() == "/rpc") {
bridgeRpc(socket, req, buffer);
}
return;
}
(void)serveHttp(*socket, req, clientAddress(*socket, req));
}
std::string HttpServer::clientAddress(
const asio::ip::tcp::socket& socket,
const http::request<http::string_body>& req) const
{
boost::system::error_code error;
const auto endpoint = socket.remote_endpoint(error);
if (error) {
return {};
}
std::optional<std::string_view> forwardedFor;
for (const auto& field : req) {
if (!beast::iequals(field.name_string(), "X-Forwarded-For")) {
continue;
}
// Multiple field-lines have ambiguous intermediary semantics.
// Ignore all of them instead of choosing an attacker-controlled
// value.
if (forwardedFor) {
forwardedFor.reset();
break;
}
forwardedFor =
std::string_view{field.value().data(), field.value().size()};
}
std::shared_lock lock(trustedProxyMutex_);
return Security::effectiveClientAddress(
endpoint.address(), forwardedFor, trustedProxyNetworks_);
}
bool HttpServer::allowShortLinkRequest(std::string_view peer)
{
return shortLinkRateLimiter_.allow(peer);
}
void HttpServer::bridgeRpc(std::shared_ptr<asio::ip::tcp::socket> browser,
@@ -315,25 +430,10 @@ namespace Echoion::Web
// Forward the browser's effective IP so the RPC server can offer
// address-based autologin. Never trust a client-supplied value; a
// reverse proxy's X-Forwarded-For (first hop) wins over the socket
// address because the proxy connects from its own host.
// X-Forwarded-For is accepted only from configured proxies and walked
// from right to left, stopping at the nearest untrusted hop.
req.erase("X-Echoion-Client-Ip");
std::string clientIp;
if (auto xff = req.find("X-Forwarded-For"); xff != req.end()) {
clientIp = std::string(xff->value());
if (auto comma = clientIp.find(','); comma != std::string::npos) {
clientIp = clientIp.substr(0, comma);
}
while (!clientIp.empty() && clientIp.front() == ' ') {
clientIp.erase(clientIp.begin());
}
}
if (clientIp.empty()) {
boost::system::error_code epEc;
if (auto ep = browser->remote_endpoint(epEc); !epEc) {
clientIp = ep.address().to_string();
}
}
const std::string clientIp = clientAddress(*browser, req);
if (!clientIp.empty()) {
req.set("X-Echoion-Client-Ip", clientIp);
}
@@ -373,7 +473,8 @@ namespace Echoion::Web
}
bool HttpServer::serveHttp(asio::ip::tcp::socket& socket,
const http::request<http::string_body>& req)
const http::request<http::string_body>& req,
std::string_view requestAddress)
{
beast::error_code ec;
const bool isHead = req.method() == http::verb::head;
@@ -398,7 +499,7 @@ namespace Echoion::Web
if (!location.empty()) {
res.set(http::field::location, location);
}
res.keep_alive(req.keep_alive());
res.keep_alive(false);
// HEAD advertises the real Content-Length but carries no body.
res.content_length(
status == http::status::not_modified ? 0 : body.size());
@@ -468,6 +569,65 @@ namespace Echoion::Web
return !ec && req.keep_alive();
}
constexpr std::string_view kShortPrefix = "/s/";
if (target.starts_with(kShortPrefix)) {
const std::string key = target.substr(kShortPrefix.size());
if (!Security::validShortSlug(key)) {
respond(http::status::not_found, "text/plain", "Not Found",
"no-store");
return false;
}
if (!allowShortLinkRequest(requestAddress)) {
respond(http::status::too_many_requests, "text/plain",
"Too Many Requests", "no-store");
return false;
}
ShortLinkResolver resolver;
{
std::lock_guard lock(shortLinkResolverMutex_);
resolver = shortLinkResolver_;
}
const auto resolution =
resolver ? resolver(key)
: ShortLinkResolution{.status =
ShortLinkStatus::unavailable,
.location = {}};
http::status status = http::status::not_found;
switch (resolution.status) {
case ShortLinkStatus::found:
status = http::status::found;
break;
case ShortLinkStatus::gone:
status = http::status::gone;
break;
case ShortLinkStatus::rateLimited:
status = http::status::too_many_requests;
break;
case ShortLinkStatus::unavailable:
status = http::status::service_unavailable;
break;
case ShortLinkStatus::notFound:
break;
}
http::response<http::string_body> response{status, req.version()};
response.set(http::field::server, "Echoion");
response.set(http::field::cache_control, "no-store");
response.set("Referrer-Policy", "no-referrer");
response.set("X-Robots-Tag", "noindex, nofollow");
response.set("X-Content-Type-Options", "nosniff");
response.set("Content-Security-Policy", "default-src 'none'");
if (status == http::status::found &&
Security::validRedirectLocation(resolution.location)) {
response.set(http::field::location, resolution.location);
} else if (status == http::status::found) {
response.result(http::status::service_unavailable);
}
response.content_length(0);
response.keep_alive(false);
http::write(socket, response, ec);
return false;
}
// User avatar images, resolved through Core's provider (TeamSpeak
// avatar cache). Best-effort: 404 lets the UI fall back to its
// initial-letter avatars; short private caching keeps reloads cheap