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

+50 -7
View File
@@ -52,6 +52,7 @@
#include "McpSettingsDlg.h"
#include "TlsCertificateDlg.h"
#include "ServerTlsSession.h"
#include "EmbeddedAnchor.h"
#include "BuiltinTlsCert.h"
#include "common/md5.h"
#include <algorithm>
@@ -5122,14 +5123,38 @@ void CMy2015RemoteDlg::OnExperimentTlsEnable()
void CMy2015RemoteDlg::OnExperimentTlsDisable()
{
if (!ServerTlsIdentity::IsReady()) {
MessageBoxL(_T("服务端未启用 TLS 证书,无法切换客户端 TLS 传输"),
_T("提示"), MB_ICONWARNING);
return;
// 刻意不再要求 ServerTlsIdentity::IsReady():服务端证书损坏(fail-closed,只认 TLS
// 却握手不了)恰恰是最需要让客户端退回明文的场景,挡住这条指令等于把恢复通道一起关掉。
// 取消 TLS 只是让客户端停止发 ClientHello,服务端本来就一直接受明文。
//
// 先数出选中主机里有多少台靠「生成时内嵌的锚」在加密(CLIENT_CAP_EMBEDDED_ANCHOR):
// 它们与本机的 tls_cert 无关,取消 TLS 后只能靠这条指令写下的抑制标记退出去;离线没
// 收到的那些,下次上线仍会发 ClientHello 撞上明文服务端 → 永久失联,只能重新生成
// 客户端(设计文档 §3.5、§4.9)。
int selected = 0, embedded = 0;
EnterCriticalSection(&m_cs);
for (context* ctx : ResolveCommandTargets()) {
if (!ctx->IsLogin()) continue;
++selected;
if (ctx->UsesEmbeddedAnchor()) ++embedded;
}
if (IDYES != MessageBoxL(_T("确定取消选中主机的 TLS 传输吗?\n"
"(客户端立即生效并断线重连,正在进行的远程会话会中断)"),
_T("提示"), MB_ICONQUESTION | MB_YESNO)) return;
LeaveCriticalSection(&m_cs);
if (selected == 0) return;
// 首发文案沿用原文案(语言文件里已有译文,键含字面 \n 的多行文本,CIniParser 会还原)。
CString msg = _TR("确定取消选中主机的 TLS 传输吗?\n"
"(客户端立即生效并断线重连,正在进行的远程会话会中断)");
if (embedded > 0) {
// 台数用 %d 进模板,不要在外面拼 "%d" + 译句:英文/德文的句首没有空格,
// 拼出来是 "3host(s) use"、"3Host(s) nutzen"。
CString line;
line.Format(_TRF("%d 台主机使用生成时内嵌的信任锚:取消 TLS 后必须重新连上主控"
"才能恢复加密,离线期间不会自行恢复。"), embedded);
msg += "\r\n\r\n" + line;
}
if (IDYES != MessageBox(msg, _TR("提示"),
MB_ICONQUESTION | MB_YESNO |
(embedded > 0 ? MB_DEFBUTTON2 : MB_DEFBUTTON1))) return;
BYTE bToken = COMMAND_TLS_DISABLE; //向被控端发送停用 TLS 传输命令
SendSelectedCommand(&bToken, sizeof(BYTE));
}
@@ -5273,6 +5298,24 @@ BYTE* ReadExeFromResource(DWORD& outSize, int resourceId, const char* resName, i
dwFileSize -= iOffset + sizeof(CONNECT_ADDRESS);
iOffset = MemoryFind(pSearchStart, (char*)g_ConnectAddress.Flag(), dwFileSize, g_ConnectAddress.FlagLen());
}
// 内嵌 TLS 信任锚(设计文档 §4.8):与生成界面共用同一段字节搬运路径,所以在线
// 升级下发的客户端同样可以首连即 TLS。注意用 outSize 而不是 dwFileSize——上面的
// 扫描循环已经把 dwFileSize 递减成了「剩余未扫描长度」。
// NoBlock / NoAnchor —— 静默跳过:目标可能是 Linux/macOS 客户端,或用户自选文件。
// 其余失败 —— 只记日志,绝不因为内嵌失败而中断下发。
{
DWORD anchorLen = 0;
std::string anchorErr;
EmbedResult embed = EmbedTlsAnchorInto(szBuffer, outSize, effectiveIP, anchorLen, anchorErr);
if (embed == EmbedResult::Ok) {
Mprintf("[TLS] embedded trust anchor (%u bytes) for master %s\n",
(unsigned)anchorLen, effectiveIP.c_str());
} else if (embed != EmbedResult::NoBlock && embed != EmbedResult::NoAnchor) {
Mprintf("[TLS] WARN: embedded trust anchor skipped: %s\n", anchorErr.c_str());
}
}
BYTE *buffer = new BYTE[outSize + 1 + sizeofSize];
buffer[0] = cmd;
memcpy(buffer + 1, &outSize, sizeofSize);