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
147 lines
5.6 KiB
C++
147 lines
5.6 KiB
C++
// EmbeddedAnchor.cpp — 生成端:把服务端信任锚写进客户端镜像的锚块。
|
|
//
|
|
// 见 docs/ClientEmbeddedTLS_Design.md §3.3、§4.6。要点:
|
|
// 1. magic 字面量在二进制里不止一份(.rdata 里还有一份),所以不能「找到第一处就写」;
|
|
// 必须扫出全部命中、逐个做结构校验,恰好一个才写,零个报 NoBlock,多个报 Ambiguous。
|
|
// 2. 写之前先读 stub 自己的 capacity 字段——老 stub 没有这个块,我们报错而不是越界。
|
|
// 3. 超长一律报错,绝不截断:截断的 PEM 会让客户端进 fail-closed 且没有恢复通道。
|
|
#include "StdAfx.h"
|
|
#include "EmbeddedAnchor.h"
|
|
#include "ServerTlsSession.h" // ServerTlsIdentity::AnchorPem / IsReady / IsBuiltin
|
|
#include "common/tls_anchor.h"
|
|
|
|
#include <wincrypt.h>
|
|
#include <vector>
|
|
#pragma comment(lib, "crypt32.lib")
|
|
|
|
namespace {
|
|
|
|
// 扫出所有通过结构校验的锚块偏移。命中通常只有 0 或 1 个:payload 里出现的另一处
|
|
// magic 是 .rdata 里的字面量副本,过不了 version/capacity/hash 校验。
|
|
std::vector<size_t> FindAnchorBlocks(const BYTE* payload, DWORD size)
|
|
{
|
|
std::vector<size_t> hits;
|
|
if (!payload || size < sizeof(EmbeddedTlsAnchor))
|
|
return hits;
|
|
|
|
const size_t last = (size_t)size - sizeof(EmbeddedTlsAnchor);
|
|
for (size_t i = 0; i <= last; ++i) {
|
|
const char* p = (const char*)payload + i;
|
|
if (!IsAnchorMagic(p))
|
|
continue;
|
|
EmbeddedTlsAnchor block;
|
|
memcpy(&block, p, sizeof(block)); // 对齐安全:不直接解引用未对齐指针
|
|
if (IsAnchorBlockValid(block))
|
|
hits.push_back(i);
|
|
}
|
|
return hits;
|
|
}
|
|
|
|
bool GetAnchorPem(std::string& pem, std::string& err)
|
|
{
|
|
if (!ServerTlsIdentity::IsReady()) {
|
|
err = "server TLS identity is not ready";
|
|
return false;
|
|
}
|
|
if (!ServerTlsIdentity::AnchorPem(pem) || pem.empty()) {
|
|
err = "server TLS anchor is empty";
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
} // namespace
|
|
|
|
EmbedResult EmbedTlsAnchorInto(BYTE* payload, DWORD size, const std::string& master,
|
|
DWORD& pemLen, std::string& err)
|
|
{
|
|
pemLen = 0;
|
|
|
|
std::vector<size_t> hits = FindAnchorBlocks(payload, size);
|
|
if (hits.empty()) {
|
|
err = "no embedded TLS anchor block in payload (stub not rebuilt?)";
|
|
return EmbedResult::NoBlock;
|
|
}
|
|
if (hits.size() > 1) {
|
|
err = "multiple embedded TLS anchor blocks in payload";
|
|
return EmbedResult::Ambiguous;
|
|
}
|
|
|
|
std::string pem;
|
|
if (!GetAnchorPem(pem, err))
|
|
return EmbedResult::NoAnchor;
|
|
|
|
if (pem.size() > kAnchorCapacity) {
|
|
err = "certificate PEM is " + std::to_string(pem.size()) + " bytes, slot holds " +
|
|
std::to_string(kAnchorCapacity);
|
|
return EmbedResult::TooLong;
|
|
}
|
|
// 主控地址槽位:必须给结尾的 '\0' 留一位,否则客户端 strnlen 读到的地址会被截断。
|
|
constexpr size_t kMasterSlot = sizeof(EmbeddedTlsAnchor::master);
|
|
if (master.size() >= kMasterSlot) {
|
|
err = "master address is " + std::to_string(master.size()) + " bytes, slot holds " +
|
|
std::to_string(kMasterSlot - 1);
|
|
return EmbedResult::TooLong;
|
|
}
|
|
|
|
// 以 stub 里的块为底稿,只改我们负责的字段——magic/capacity 原样保留。
|
|
EmbeddedTlsAnchor block;
|
|
memcpy(&block, payload + hits[0], sizeof(block));
|
|
block.version = kAnchorVersion;
|
|
block.length = (uint32_t)pem.size();
|
|
block.hash = Fnv1a32(pem.data(), pem.size());
|
|
memset(block.master, 0, sizeof(block.master));
|
|
memcpy(block.master, master.c_str(), master.size());
|
|
memset(block.pem, 0, sizeof(block.pem));
|
|
memcpy(block.pem, pem.data(), pem.size());
|
|
|
|
memcpy(payload + hits[0], &block, sizeof(block));
|
|
pemLen = (DWORD)pem.size();
|
|
return EmbedResult::Ok;
|
|
}
|
|
|
|
bool TlsAnchorSummary(std::string& out)
|
|
{
|
|
std::string pem, err;
|
|
if (!GetAnchorPem(pem, err))
|
|
return false;
|
|
|
|
// 只取 PEM 里的第一张证书算指纹:fullchain 时第一张就是服务端自己的叶子证书,
|
|
// 客户端 pin 的也正是它(见 client/TlsChannel.cpp 的 VerifyServerCert)。
|
|
DWORD derLen = 0;
|
|
if (!CryptStringToBinaryA(pem.c_str(), (DWORD)pem.size(), CRYPT_STRING_BASE64HEADER,
|
|
NULL, &derLen, NULL, NULL) || derLen == 0)
|
|
return false;
|
|
std::vector<BYTE> der(derLen);
|
|
if (!CryptStringToBinaryA(pem.c_str(), (DWORD)pem.size(), CRYPT_STRING_BASE64HEADER,
|
|
der.data(), &derLen, NULL, NULL))
|
|
return false;
|
|
|
|
std::string thumb("?"), expiry;
|
|
PCCERT_CONTEXT cert = CertCreateCertificateContext(X509_ASN_ENCODING, der.data(), derLen);
|
|
if (cert) {
|
|
BYTE hash[20] = {};
|
|
DWORD cbHash = sizeof(hash);
|
|
if (CertGetCertificateContextProperty(cert, CERT_SHA1_HASH_PROP_ID, hash, &cbHash) &&
|
|
cbHash >= 6) {
|
|
static const char kHex[] = "0123456789abcdef";
|
|
thumb.clear();
|
|
for (int i = 0; i < 6; ++i) {
|
|
thumb += kHex[hash[i] >> 4];
|
|
thumb += kHex[hash[i] & 0x0F];
|
|
}
|
|
}
|
|
FILETIME utc = cert->pCertInfo->NotAfter, local = {};
|
|
SYSTEMTIME st = {};
|
|
if (FileTimeToLocalFileTime(&utc, &local) && FileTimeToSystemTime(&local, &st)) {
|
|
char buf[16];
|
|
sprintf_s(buf, "%04u-%02u-%02u", st.wYear, st.wMonth, st.wDay);
|
|
expiry = buf;
|
|
}
|
|
CertFreeCertificateContext(cert);
|
|
}
|
|
|
|
out = (ServerTlsIdentity::IsBuiltin() ? "builtin " : "custom ") + expiry + " sha1:" + thumb;
|
|
return true;
|
|
}
|