|
|
@@ -1,5 +1,8 @@
|
|
|
#include "scope_refusal.hpp"
|
|
|
#include "server.hpp"
|
|
|
+#include <openssl/tls1.h>
|
|
|
+#include <openssl/ssl.h>
|
|
|
+#include "cert_store.hpp"
|
|
|
#include "captcha.hpp"
|
|
|
#include "db_errors.hpp"
|
|
|
#include "errors.hpp"
|
|
|
@@ -15,6 +18,86 @@
|
|
|
|
|
|
namespace svapi {
|
|
|
|
|
|
+// --- SNI: choosing the certificate for the name the client asked for --------
|
|
|
+//
|
|
|
+// THE ONLY RAW OPENSSL IN THIS SERVICE. Certificate LOADING goes through
|
|
|
+// cpp-httplib's own tls:: abstraction (cert_store.cpp), because that part has
|
|
|
+// an API; selection does not, so the hook is ours.
|
|
|
+namespace {
|
|
|
+
|
|
|
+/// Called by OpenSSL during the handshake, before any certificate is sent.
|
|
|
+int sniCallback(SSL* ssl, int* al, void*) {
|
|
|
+ if (!ssl) return SSL_TLSEXT_ERR_ALERT_FATAL;
|
|
|
+ const char* requested = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
|
|
|
+
|
|
|
+ // NO SNI AT ALL is refused rather than served a default. A client that
|
|
|
+ // sends no name is either very old or addressing us by IP, and in both
|
|
|
+ // cases there is no right certificate to pick - serving an arbitrary one
|
|
|
+ // produces a name-mismatch error against a RANDOM tenant's hostname, which
|
|
|
+ // is strictly harder to diagnose than a refused handshake. The direct-
|
|
|
+ // address recovery path is for HTTP-level access, not a reason to hand out
|
|
|
+ // somebody's certificate.
|
|
|
+ if (!requested || !*requested) {
|
|
|
+ spdlog::warn("TLS handshake refused: the client sent no SNI hostname, so there is no "
|
|
|
+ "certificate to choose - address this service by name");
|
|
|
+ if (al) *al = SSL_AD_UNRECOGNIZED_NAME;
|
|
|
+ return SSL_TLSEXT_ERR_ALERT_FATAL;
|
|
|
+ }
|
|
|
+
|
|
|
+ // The snapshot is taken ONCE and held for the rest of this handshake, so a
|
|
|
+ // reload landing mid-handshake cannot free the context under us: the
|
|
|
+ // shared_ptr keeps the old snapshot, and with it every SSL_CTX in it, alive
|
|
|
+ // until this function returns.
|
|
|
+ const auto snap = certStore().snapshot();
|
|
|
+ const CertFile* chosen = selectCert(snap->files, requested);
|
|
|
+ if (!chosen) {
|
|
|
+ // Named in the log, because this is the one failure an operator has to
|
|
|
+ // act on and the client sees only a handshake alert.
|
|
|
+ spdlog::warn("TLS handshake refused for '{}': no certificate covers that hostname "
|
|
|
+ "({} loaded). Put <host>.crt and <host>.key in the certificate directory, "
|
|
|
+ "or a wildcard as _.<parent>.crt",
|
|
|
+ requested, snap->files.size());
|
|
|
+ if (al) *al = SSL_AD_UNRECOGNIZED_NAME;
|
|
|
+ return SSL_TLSEXT_ERR_ALERT_FATAL;
|
|
|
+ }
|
|
|
+
|
|
|
+ // Find the context beside the chosen file. `files` and `contexts` are
|
|
|
+ // parallel and built together, so this cannot miss - but it is written as a
|
|
|
+ // search rather than pointer arithmetic so that a later change to either
|
|
|
+ // vector fails safe instead of indexing past the end.
|
|
|
+ for (std::size_t i = 0; i < snap->files.size(); ++i) {
|
|
|
+ if (&snap->files[i] != chosen) continue;
|
|
|
+ if (SSL_set_SSL_CTX(ssl, static_cast<SSL_CTX*>(snap->contexts[i])) == nullptr) {
|
|
|
+ spdlog::error("TLS: could not install the certificate for '{}'", requested);
|
|
|
+ if (al) *al = SSL_AD_INTERNAL_ERROR;
|
|
|
+ return SSL_TLSEXT_ERR_ALERT_FATAL;
|
|
|
+ }
|
|
|
+ // SSL_set_SSL_CTX REPLACES THE CERTIFICATE AND KEY AND NOTHING ELSE -
|
|
|
+ // the options, the minimum protocol version and the verify mode stay
|
|
|
+ // those of the context the connection was accepted on. That is the
|
|
|
+ // documented OpenSSL behaviour and the usual trap here: a per-
|
|
|
+ // certificate context configured more strictly than the base one would
|
|
|
+ // have its strictness silently ignored. We therefore set the same
|
|
|
+ // options on every context (create_server_context does it) rather than
|
|
|
+ // relying on the swap to carry them.
|
|
|
+ return SSL_TLSEXT_ERR_OK;
|
|
|
+ }
|
|
|
+ if (al) *al = SSL_AD_INTERNAL_ERROR;
|
|
|
+ return SSL_TLSEXT_ERR_ALERT_FATAL;
|
|
|
+}
|
|
|
+
|
|
|
+} // namespace
|
|
|
+
|
|
|
+bool installSniHook(void* ctx) {
|
|
|
+ if (!ctx) return false;
|
|
|
+ auto* c = static_cast<SSL_CTX*>(ctx);
|
|
|
+ // Returns 1 on success. Checked, because without the hook every connection
|
|
|
+ // gets whatever certificate the base context holds and the deployment comes
|
|
|
+ // up looking healthy while answering every hostname wrongly.
|
|
|
+ if (SSL_CTX_set_tlsext_servername_callback(c, sniCallback) != 1) return false;
|
|
|
+ return true;
|
|
|
+}
|
|
|
+
|
|
|
std::string projectFor(ServerDeps& d, const httplib::Request& req, size_t group) {
|
|
|
const auto reg = d.settings.hostRegistry();
|
|
|
const bool gatingOn = reg && reg->gating();
|
|
|
@@ -34,7 +117,35 @@ std::string projectFor(ServerDeps& d, const httplib::Request& req, size_t group)
|
|
|
return r.project;
|
|
|
}
|
|
|
|
|
|
-ApiServer::ApiServer(ServerDeps deps) : d_(std::move(deps)) {}
|
|
|
+ApiServer::ApiServer(ServerDeps deps, std::string tlsCertDir) : d_(std::move(deps)) {
|
|
|
+ if (tlsCertDir.empty()) {
|
|
|
+ svr_ = std::make_unique<httplib::Server>();
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ // Load BEFORE the server exists, so a deployment with an unreadable
|
|
|
+ // directory or no usable certificate fails at startup rather than on the
|
|
|
+ // first customer connection. The count is logged either way.
|
|
|
+ const std::size_t loaded = certStore().reload(tlsCertDir);
|
|
|
+ if (loaded == 0)
|
|
|
+ spdlog::error("TLS was requested but NO usable certificate was found in '{}' - every "
|
|
|
+ "handshake will be refused", tlsCertDir);
|
|
|
+
|
|
|
+ // The base context carries the SNI hook; the callback swaps in a
|
|
|
+ // per-certificate context for the name the client asked for. The base
|
|
|
+ // context deliberately holds NO certificate of its own, which is what makes
|
|
|
+ // "no certificate for this name" a refused handshake rather than a wrong
|
|
|
+ // certificate served confidently.
|
|
|
+ svr_ = std::make_unique<httplib::SSLServer>(
|
|
|
+ [](httplib::tls::ctx_t ctx) { return installSniHook(static_cast<void*>(ctx)); });
|
|
|
+ tls_ = true;
|
|
|
+}
|
|
|
+
|
|
|
+bool ApiServer::valid() const {
|
|
|
+ // `SSLServer::is_valid()` is false when the context could not be built, so
|
|
|
+ // this covers both "the hook would not install" and "OpenSSL refused".
|
|
|
+ return svr_ && svr_->is_valid();
|
|
|
+}
|
|
|
|
|
|
static bool keyExpired(const ApiKey& k) {
|
|
|
if (!k.scope) return false;
|
|
|
@@ -136,7 +247,7 @@ void requireCapability(ServerDeps& d, const ApiKey& k, const httplib::Request& r
|
|
|
}
|
|
|
|
|
|
void ApiServer::registerRoutes() {
|
|
|
- svr_.set_exception_handler([](const httplib::Request& req, httplib::Response& res, std::exception_ptr ep) {
|
|
|
+ svr_->set_exception_handler([](const httplib::Request& req, httplib::Response& res, std::exception_ptr ep) {
|
|
|
// RECORD THE SLUG. We build a structured reason for every refusal and
|
|
|
// used to keep NONE of it for a 4xx, so a refused request left only its
|
|
|
// status code behind - and a status code is shared by a dozen causes.
|
|
|
@@ -209,7 +320,7 @@ void ApiServer::registerRoutes() {
|
|
|
// route (e.g. /login, /settings) reaches the server as a 404 (no such static file).
|
|
|
// Serve index.html so React Router can handle it. Excludes API/meta routes and asset
|
|
|
// requests (paths with a file extension), which should keep their real 404.
|
|
|
- svr_.set_error_handler([this](const httplib::Request& req, httplib::Response& res) {
|
|
|
+ svr_->set_error_handler([this](const httplib::Request& req, httplib::Response& res) {
|
|
|
if (res.status == 404 && req.method == "GET" && !d_.webuiDir.empty()
|
|
|
&& req.path.rfind("/api/", 0) != 0
|
|
|
&& req.path.rfind("/ui/", 0) != 0
|
|
|
@@ -232,7 +343,7 @@ void ApiServer::registerRoutes() {
|
|
|
});
|
|
|
|
|
|
// Authenticate /api/* (authorization is per-handler).
|
|
|
- svr_.set_pre_routing_handler([this](const httplib::Request& req, httplib::Response& res) {
|
|
|
+ svr_->set_pre_routing_handler([this](const httplib::Request& req, httplib::Response& res) {
|
|
|
// START of the request: zero the clock and forget the previous
|
|
|
// request's slug. See access_log.hpp on why that ordering matters.
|
|
|
beginRequestTrace();
|
|
|
@@ -288,7 +399,7 @@ void ApiServer::registerRoutes() {
|
|
|
// `code=unauthorized` rather than on every 401 the service emits, and the
|
|
|
// address it acts on is one we resolved under the trusted-proxy rule rather
|
|
|
// than whatever a header claimed.
|
|
|
- svr_.set_logger([this](const httplib::Request& req, const httplib::Response& res) {
|
|
|
+ svr_->set_logger([this](const httplib::Request& req, const httplib::Response& res) {
|
|
|
if (!accessLog().enabled()) return;
|
|
|
auto snap = d_.settings.snapshot();
|
|
|
AccessLogEntry e;
|
|
|
@@ -305,7 +416,7 @@ void ApiServer::registerRoutes() {
|
|
|
accessLog().write(e);
|
|
|
});
|
|
|
|
|
|
- svr_.set_post_routing_handler([this](const httplib::Request& req, httplib::Response& res) {
|
|
|
+ svr_->set_post_routing_handler([this](const httplib::Request& req, httplib::Response& res) {
|
|
|
auto snap = d_.settings.snapshot();
|
|
|
std::string responseOrigin;
|
|
|
if (!snap->corsOrigins.empty() && snap->corsOrigins[0] == "*") {
|
|
|
@@ -320,7 +431,7 @@ void ApiServer::registerRoutes() {
|
|
|
res.set_header("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Captcha-Token, Cache-Control");
|
|
|
res.set_header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS");
|
|
|
});
|
|
|
- svr_.Options(R"(.*)", [](const httplib::Request&, httplib::Response& res) { res.status = 204; });
|
|
|
+ svr_->Options(R"(.*)", [](const httplib::Request&, httplib::Response& res) { res.status = 204; });
|
|
|
|
|
|
registerMetaRoutes(*this);
|
|
|
registerWebuiAuthRoutes(*this);
|
|
|
@@ -344,18 +455,18 @@ void ApiServer::registerRoutes() {
|
|
|
// if cpp-httplib's matching order ever changes.
|
|
|
registerFunctionDispatchRoutes(*this);
|
|
|
|
|
|
- if (!d_.shareDir.empty()) svr_.set_mount_point("/docs", d_.shareDir + "/docs");
|
|
|
- if (!d_.webuiDir.empty()) svr_.set_mount_point("/", d_.webuiDir);
|
|
|
+ if (!d_.shareDir.empty()) svr_->set_mount_point("/docs", d_.shareDir + "/docs");
|
|
|
+ if (!d_.webuiDir.empty()) svr_->set_mount_point("/", d_.webuiDir);
|
|
|
}
|
|
|
|
|
|
void ApiServer::setThreadPoolSize(uint32_t n) {
|
|
|
if (n == 0) return; // leave cpp-httplib's own default alone
|
|
|
- svr_.new_task_queue = [n] { return new httplib::ThreadPool(n); };
|
|
|
+ svr_->new_task_queue = [n] { return new httplib::ThreadPool(n); };
|
|
|
}
|
|
|
|
|
|
-int ApiServer::bindToAnyPort(const std::string& host) { return svr_.bind_to_any_port(host); }
|
|
|
-void ApiServer::listenAfterBind() { svr_.listen_after_bind(); }
|
|
|
-bool ApiServer::listen(const std::string& host, uint16_t port) { return svr_.listen(host, port); }
|
|
|
-void ApiServer::stop() { svr_.stop(); }
|
|
|
+int ApiServer::bindToAnyPort(const std::string& host) { return svr_->bind_to_any_port(host); }
|
|
|
+void ApiServer::listenAfterBind() { svr_->listen_after_bind(); }
|
|
|
+bool ApiServer::listen(const std::string& host, uint16_t port) { return svr_->listen(host, port); }
|
|
|
+void ApiServer::stop() { svr_->stop(); }
|
|
|
|
|
|
} // namespace svapi
|