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:
yuanyuanxianganddeepseek-flash committed 2026-11-01 20:40:02 +01:00
1 parent c4021e1fc9
commit 951b4072e5
31 files changed
+1911 -122

No files matched your search

+40 -3
View File
@@ -37,14 +37,32 @@
#include <string>
#include <vector>
// 进程级 TLS 开关:首次调用时加载信任锚(注册表或文件),返回是否启用。线程安全。
// 进程级 TLS 开关(不看目标地址,等价于「允许使用内嵌锚」那一套状态):首次调用时加载
// 信任锚(注册表或文件),返回是否启用。线程安全。
// Windows 版同样是「可热切换」的:TlsReload() 之后本函数立刻反映新状态(不是 call_once)。
// 需要「这条连接会不会走 TLS」时用下面的 TlsEnabledFor(host)——分享/并行实例与主连接的
// 答案可能不同(内嵌锚只对生成时那台主控有效)。
bool TlsEnabled();
// 信任锚已配置但加载失败(损坏/格式错误)时为 true:表示管理员已「颁发」证书,
// 客户端必须拒绝连接(fail-closed),不得静默回退明文。线程安全、幂等。
bool TlsLoadError();
// 按「本连接要连到哪里」给出 TLS 开关与 fail-closed 状态。host 可以是域名、IP,或分号
// 分隔的多地址(与 CONNECT_ADDRESS 的写法一致);为空表示不限定目标(按进程级开关处理)。
//
// 为什么要按连接判定:分享实例、并行的多主控实例都是**同一个进程里的线程**
// (ClientDll.cpp 的 __CreateThread(0,0,StartClientApp,...)),一个进程级布尔量既表达不了
// 「主连接用内嵌锚、分享连接不用」,也不该由先发起连接的那个线程决定(状态首次使用时
// 缓存,谁先连谁说了算)。内嵌锚只在「连的正是生成时那台主控」时生效,判定在 TLS 层内部
// 完成:地址字符串直接相等,或两侧解析出的 IP 相交。
//
// connectHost:本连接实际连到的地址(IOCPClient 的 m_sCurIP,通常是解析后的 IP)。
// configured:配置里的原始写法(可能含分号分隔的多地址/域名),可为空。域名对域名
// 靠它做快路径,不必依赖两次 DNS 查询得到同一个答案。
bool TlsEnabledFor(const std::string& connectHost, const std::string& configured);
bool TlsLoadErrorFor(const std::string& connectHost, const std::string& configured);
// 按当前信任锚位置(注册表 settings\tls_cert → settings.ini → exe 同目录 yama-ca.pem)
// 重建 TLS 上下文并更新开关,让随后建立的新连接立刻走新传输方式(已建立的连接不受
// 影响)。信任锚无效时不做任何改动、返回 false 并给出原因——一次坏下发不该把正在工作
@@ -66,7 +84,10 @@ public:
// 调用方必须关闭 socket(fail-closed)。可重复调用(重连时复用同一对象)。
// sni 非空且为域名时作为 SNI 发送,让反代(nginx)按域名分流到正确的 server 块;
// 证书校验仍只钉信任锚、不校主机名,与直接连主控端口时完全一致。
bool Handshake(SOCKET sock, const char* sni = NULL);
// host/configured:同 TlsEnabledFor,决定证书校验用哪一套信任锚——目标不是生成时
// 那台主控时不能拿内嵌锚去校验,否则必然失败且无法自愈。
bool Handshake(SOCKET sock, const char* sni, const std::string& host,
const std::string& configured);
// 解密读取:返回 >0 的明文字节数;0 表示对端正常关闭;SOCKET_ERROR(-1) 出错。
int Recv(SOCKET sock, char* buf, int len);
@@ -84,6 +105,10 @@ public:
// 握手是否已完成(Send/Recv 可用)。诊断用:区分「本连接已走 TLS」与「裸连接」。
bool IsReady() const { return m_ready; }
// 本连接校验服务端证书时用的是不是内嵌锚。登录上报 CLIENT_CAP_EMBEDDED_ANCHOR 用:
// 只有这种客户端会在服务端关掉 TLS 后失联,操作员据此决定是否先下发取消。
bool AnchorEmbedded() const { return m_anchorEmbedded; }
private:
void CloseHandles();
bool SendAll(SOCKET sock, const void* data, int len);
@@ -94,6 +119,8 @@ private:
bool m_credValid = false; // m_cred 已分配,需 FreeCredentialsHandle
bool m_ctxValid = false; // m_ctx 已分配,需 DeleteSecurityContext
bool m_ready = false; // 握手完成,Send/Recv 可用
bool m_anchorEmbedded = false; // 本次握手用的是内嵌锚(见 AnchorEmbedded)
int m_stateIdx = 1; // 本次握手用的信任锚状态(1=允许内嵌锚;0=不用)
SecPkgContext_StreamSizes m_sizes = {};
@@ -123,6 +150,11 @@ bool TlsEnabled();
// (fail-closed),不得静默回退明文。线程安全、幂等。
bool TlsLoadError();
// Windows 版按目标地址区分「用不用内嵌锚」。Linux 客户端没有内嵌锚概念(生成器只往
// Windows 镜像里写锚块),信任锚一律是配置文件,故这里忽略目标地址,与进程级开关等价。
inline bool TlsEnabledFor(const std::string&, const std::string&) { return TlsEnabled(); }
inline bool TlsLoadErrorFor(const std::string&, const std::string&) { return TlsLoadError(); }
// 服务端下发信任锚(COMMAND_TLS_ENABLE):把 PEM 正文写入
// $XDG_CONFIG_HOME/ghost/yama-ca.pem(默认 ~/.config/ghost/yama-ca.pem,无 HOME 时退回
// 程序目录),原子替换、权限 0600。写入前先解析验证,不是合法证书就整包拒绝。
@@ -153,7 +185,9 @@ public:
// 在已连通的 socket 上完成 TLS 1.2 客户端握手并按信任锚校验服务端证书链。失败返回
// false,调用方必须关闭 socket(fail-closed)。可重复调用(重连时复用同一对象)。
// sni 非空且为域名时作为 SNI 发送(反代按域名分流);证书校验仍只钉信任锚。
bool Handshake(int sock, const char* sni = NULL);
// 后两个参数与 Windows 版同签名,本平台无内嵌锚,忽略。
bool Handshake(int sock, const char* sni, const std::string& host,
const std::string& configured);
// 解密读取:返回 >0 的明文字节数;0 表示对端正常关闭;SOCKET_ERROR(-1) 出错。
int Recv(int sock, char* buf, int len);
@@ -170,6 +204,9 @@ public:
// 握手是否已完成(Send/Recv 可用)。诊断用:区分「本连接已走 TLS」与「裸连接」。
bool IsReady() const { return m_ready; }
// Linux 客户端没有内嵌锚(见上),恒为 false,与 Windows 版签名保持一致。
bool AnchorEmbedded() const { return false; }
private:
void CloseHandles();