Feature: Ship a built-in TLS certificate so encryption works out of the box
A fresh install used to require openssl before the server could speak TLS: two empty paths in [tls] meant the identity failed to load and every ClientHello was refused. TLS is now on by default and, when no custom certificate is configured, the server generates its own self-signed one the first time it needs it -- RSA-2048, SHA-256, CN=yama-server, CA:TRUE, valid for ten years from one day before now. Plaintext clients are untouched, since the device port still splits plaintext from TLS by sniffing the first six bytes of a connection. The certificate and its PKCS#8 private key are stored side by side in the config under [tls] BuiltinCert / BuiltinKey as single-line base64 DER. Single line, because the server has two config backends -- the registry for Release, settings.ini for a Debug master -- and only a line without newlines means the same read/write code serves both. That in turn required fixing the registry reader: iniFile::GetStr copied into a 512 byte stack buffer, so a 1.5 KB value came back as a truncated or empty string. The two-phase dynamic read now lives in common/iniFile.h as ReadRegistryValueSz / ReadRegistrySz, and the copy that client/TlsChannel.cpp had been carrying for its own trust anchor is gone. This also makes the built-in certificate self-checking: Ensure() re-reads what it just wrote and fails loudly if the round trip did not survive. Import has to go through NCRYPT_PKCS8_PRIVATE_KEY_BLOB, matching the import path in BuildIdentityFromDer. NCRYPT_PKCS8_PRIV_KEY_INFO_BLOB, which most samples reach for, is not implemented by the Microsoft Software KSP and returns NTE_INVALID_PARAMETER; a probe confirmed it, and the export type that works is the one the importer already expected. Building an identity is now split into a file front-end (PEM, fullchain, PKCS#1 hints) and a shared DER core, so the built-in and file paths cannot drift apart. That key also exposed a second problem worth fixing here. The identity binds its private key to the certificate by name -- CRYPT_KEY_PROV_INFO with pwszContainerName -- and Schannel resolves that name on every handshake through CryptAcquireCertificatePrivateKey. With the fixed name "YamaServerTlsKey", two server processes under the same Windows user shared one key slot: whichever loaded last overwrote it, and the other process's next handshake picked up a private key that does not match its certificate. That is exactly the debug-plus-release pairing used here, and defaulting to a built-in certificate is what makes it reachable, since the debug instance no longer points at the same PEM as the release instance. The name is now the base name plus the first six bytes of the certificate's SHA-1 thumbprint, e.g. YamaServerTlsKey-c0d469eae8a4: different certificates get different keys, instances sharing one certificate still share one key. MCP picks this up too. The effective name goes to the trace log so a collision is visible without a debugger. A stale key from an older build may still sit in the key store under the old name; nothing references it and it is not deleted automatically, since a running instance of an older build could be using it. The trust anchor still has to be pushed. The client pins exactly one root through an exclusive-root chain engine and checks no host name, so a self-signed CA:TRUE leaf chains cleanly to itself -- but only if the client is told about it. That is the existing 启用 TLS / 切换到 WSS command, which now takes the PEM from ServerTlsIdentity::AnchorPem instead of re-reading the configured cert file, so it reports the same certificate the server actually serves for both sources. Losing the stored certificate (cleared registry, new Windows user) regenerates it, and every client must be re-pushed the anchor. Two places that used to fall back to [tls] CertPath now skip that fallback while the built-in certificate is active: the MCP HTTPS front end at startup and the prefill in its settings dialog. A self-signed certificate cannot pass validation at a public MCP client, and the retained CertPath is only a leftover from switching back to a custom certificate, so pretending to use it would fail later with a worse message. MCP HTTPS with empty paths already fails closed with a log line. The TLS dialog gains a 内置证书 checkbox, ticked by default and unticked when certificate paths are present; ticking it greys out the path rows without clearing them, and shows either "generated on first use" or the expiry date read back from the stored certificate. Saving writes four keys -- Enabled, UseBuiltIn, CertPath, KeyPath -- and an explicit UseBuiltIn keeps the paths from being used as an implicit switch. Every reader of [tls] Enabled now defaults to 1, so the menu check, the dialog and the loader agree on a fresh install. The status bar panes on 无 / 有 grew a third state, 内置, and the pane width is measured across all three. Translations were added to en_US, zh_TW and de_DE; skipping the German file would have left the new dialog text in Chinese there, as de_DE is loaded from disk rather than embedded. Verified with the debug server against openssl s_client. Both the generated built-in certificate (CN=yama-server) and an existing custom one (CN=localhost) complete a TLS 1.2 handshake with the pinned certificate, and their log lines show distinct key names, c0d469eae8a4 and 272f2adfb19c. An unmodified client still runs in plaintext without an anchor, an existing custom certificate deployment behaves exactly as before, and client and server both build clean at Debug x64. Co-Authored-By: deepseek-flash
This commit is contained in:
1 parent
4f9bfb0fdc
commit
c4021e1fc9
16 files changed
+697
-131
No files matched your search
@@ -52,6 +52,7 @@
|
||||
#include "McpSettingsDlg.h"
|
||||
#include "TlsCertificateDlg.h"
|
||||
#include "ServerTlsSession.h"
|
||||
#include "BuiltinTlsCert.h"
|
||||
#include "common/md5.h"
|
||||
#include <algorithm>
|
||||
#include <set>
|
||||
@@ -355,7 +356,8 @@ static UINT Indicators[] = {
|
||||
|
||||
// 状态栏短标签分区(TLS/MCP)的宽度:按当前语言下两种取值的实际文本宽度取大者,
|
||||
// 再留出左右边距。硬编码像素在不同语言/DPI 下容易被截断或浪费空间。
|
||||
static int CalcStatusFlagPaneWidth(const CStatusBar& bar, const CString& a, const CString& b)
|
||||
static int CalcStatusFlagPaneWidth(const CStatusBar& bar, const CString& a, const CString& b,
|
||||
const CString& c = CString())
|
||||
{
|
||||
CClientDC dc((CWnd*)&bar);
|
||||
CFont* pOld = nullptr;
|
||||
@@ -377,9 +379,10 @@ static int CalcStatusFlagPaneWidth(const CStatusBar& bar, const CString& a, cons
|
||||
pOld = dc.SelectObject(pFont);
|
||||
CSize szA = dc.GetTextExtent(a);
|
||||
CSize szB = dc.GetTextExtent(b);
|
||||
CSize szC = c.IsEmpty() ? CSize(0, 0) : dc.GetTextExtent(c);
|
||||
if (pOld != nullptr)
|
||||
dc.SelectObject(pOld);
|
||||
return max(szA.cx, szB.cx) + 16;
|
||||
return max(max(szA.cx, szB.cx), szC.cx) + 16;
|
||||
}
|
||||
|
||||
std::string EventName()
|
||||
@@ -1390,7 +1393,7 @@ VOID CMy2015RemoteDlg::CreateSolidMenu()
|
||||
// ID_TOOL_PLUGIN_SETTINGS 二次 InsertMenu,后插者更贴近锚点,故排在 MCP 下方)。
|
||||
if (!SHOULD_HIDE_MENU(HIDE_MENU_TLS_CERTIFICATE, MF_TLS_CERTIFICATE)) {
|
||||
UINT tlsFlags = MF_BYCOMMAND;
|
||||
if (THIS_CFG.GetInt("tls", "Enabled", 0)) {
|
||||
if (THIS_CFG.GetInt("tls", "Enabled", 1)) {
|
||||
tlsFlags |= MF_CHECKED; // 已启用 TLS 则菜单打勾
|
||||
}
|
||||
pExtMenu->InsertMenu(ID_TOOL_PLUGIN_SETTINGS, tlsFlags,
|
||||
@@ -2525,8 +2528,12 @@ BOOL CMy2015RemoteDlg::OnInitDialog()
|
||||
if (THIS_CFG.GetInt("settings", "McpHttps", 0)) {
|
||||
std::string certPath = THIS_CFG.GetStr("settings", "McpCertPath", "");
|
||||
std::string keyPath = THIS_CFG.GetStr("settings", "McpKeyPath", "");
|
||||
if (certPath.empty()) certPath = THIS_CFG.GetStr("tls", "CertPath", "");
|
||||
if (keyPath.empty()) keyPath = THIS_CFG.GetStr("tls", "KeyPath", "");
|
||||
// 设备端用内置证书时,[tls] CertPath 可能只是「切回自定义」保留的历史值,不能再
|
||||
// 拿来给 MCP 兜底:内置证书是自签的,公网 MCP 客户端(Claude 等)校验必然失败。
|
||||
if (!BuiltinTlsCert::UseBuiltin(THIS_CFG)) {
|
||||
if (certPath.empty()) certPath = THIS_CFG.GetStr("tls", "CertPath", "");
|
||||
if (keyPath.empty()) keyPath = THIS_CFG.GetStr("tls", "KeyPath", "");
|
||||
}
|
||||
int internalPort = THIS_CFG.GetInt("settings", "McpInternalPort", 0);
|
||||
if (internalPort <= 0) internalPort = mcpPort + 1;
|
||||
McpServer().SetHttps(true, certPath, keyPath, internalPort);
|
||||
@@ -4125,8 +4132,13 @@ void CMy2015RemoteDlg::UpdateStatusBarStats()
|
||||
|
||||
// === 分区1/2:TLS / MCP 状态 ===
|
||||
// TLS:服务端身份已加载([tls] Enabled 且证书/私钥可用)。与协议切换等处用同一判定,
|
||||
// 避免「菜单显示已启用但证书加载失败」时状态栏给出错误结论。
|
||||
CString strTls = ServerTlsIdentity::IsReady() ? _TR("TLS: 有") : _TR("TLS: 无");
|
||||
// 避免「菜单显示已启用但证书加载失败」时状态栏给出错误结论。三态:无 / 有 / 内置
|
||||
// (内置证书为程序自动生成的自签证书,与用户自备证书区分开)。
|
||||
CString strTls;
|
||||
if (!ServerTlsIdentity::IsReady())
|
||||
strTls = _TR("TLS: 无");
|
||||
else
|
||||
strTls = ServerTlsIdentity::IsBuiltin() ? _TR("TLS: 内置") : _TR("TLS: 有");
|
||||
// MCP:读配置开关。启用后需重启才真正监听,此处反映的是「已启用」这一配置意图;
|
||||
// 启用时一并标出访问协议(McpHttps=1 走 TLS 前端,证书坏了启动时整体 fail-closed)。
|
||||
CString strMcp;
|
||||
@@ -4141,7 +4153,8 @@ void CMy2015RemoteDlg::UpdateStatusBarStats()
|
||||
strMcpWidest = strMcp;
|
||||
}
|
||||
// 宽度取当前状态下的最大取值(关闭时收窄,开启时按最长协议串留足)
|
||||
m_nPaneTlsWidth = CalcStatusFlagPaneWidth(m_StatusBar, _TR("TLS: 有"), _TR("TLS: 无"));
|
||||
m_nPaneTlsWidth = CalcStatusFlagPaneWidth(m_StatusBar, _TR("TLS: 有"), _TR("TLS: 无"),
|
||||
_TR("TLS: 内置"));
|
||||
m_nPaneMcpWidth = CalcStatusFlagPaneWidth(m_StatusBar, strMcp, strMcpWidest);
|
||||
m_StatusBar.SetPaneInfo(1, m_StatusBar.GetItemID(1), SBPS_NORMAL, m_nPaneTlsWidth);
|
||||
m_StatusBar.SetPaneText(1, strTls);
|
||||
@@ -5091,16 +5104,10 @@ void CMy2015RemoteDlg::OnExperimentTlsEnable()
|
||||
"(客户端立即生效并断线重连,正在进行的远程会话会中断)"),
|
||||
_T("提示"), MB_ICONQUESTION | MB_YESNO)) return;
|
||||
|
||||
// 读取服务端证书(信任锚),随启用指令一并下发;客户端写入注册表 settings\tls_cert。
|
||||
std::ifstream certFile(THIS_CFG.GetStr("tls", "CertPath", ""), std::ios::binary);
|
||||
if (!certFile.is_open()) {
|
||||
MessageBoxL(_T("读取服务端 TLS 证书失败,无法下发"), _T("提示"), MB_ICONWARNING);
|
||||
return;
|
||||
}
|
||||
std::ostringstream ss;
|
||||
ss << certFile.rdbuf();
|
||||
std::string certPem = ss.str();
|
||||
if (certPem.empty()) {
|
||||
// 取服务端当前身份的证书(信任锚),随启用指令一并下发;客户端写入注册表
|
||||
// settings\tls_cert。内置证书与自定义证书(fullchain 全部)都从身份模块取。
|
||||
std::string certPem;
|
||||
if (!ServerTlsIdentity::AnchorPem(certPem) || certPem.empty()) {
|
||||
MessageBoxL(_T("读取服务端 TLS 证书失败,无法下发"), _T("提示"), MB_ICONWARNING);
|
||||
return;
|
||||
}
|
||||
@@ -5194,12 +5201,7 @@ VOID CMy2015RemoteDlg::SwitchSelectedProtocol(UINT nID)
|
||||
MessageBoxL(_T("服务端未启用 TLS 证书,无法切换到 WSS"), _T("提示"), MB_ICONWARNING);
|
||||
return;
|
||||
}
|
||||
std::ifstream certFile(THIS_CFG.GetStr("tls", "CertPath", ""), std::ios::binary);
|
||||
if (certFile.is_open()) {
|
||||
std::ostringstream ss;
|
||||
ss << certFile.rdbuf();
|
||||
certPem = ss.str();
|
||||
}
|
||||
ServerTlsIdentity::AnchorPem(certPem);
|
||||
if (certPem.empty()) {
|
||||
MessageBoxL(_T("读取服务端 TLS 证书失败,无法切换到 WSS"), _T("提示"), MB_ICONWARNING);
|
||||
return;
|
||||
@@ -12669,13 +12671,13 @@ void CMy2015RemoteDlg::OnTlsCertificate()
|
||||
CTlsCertificateDlg dlg(this);
|
||||
if (dlg.DoModal() != IDOK) return;
|
||||
|
||||
// 对话框内已写入 [tls] 三键并调 ServerTlsIdentity::Load(THIS_CFG) 热重载,
|
||||
// 对新建连接即时生效(设计文档 §7.1)。
|
||||
// 对话框内已写入 [tls] 四键(Enabled/UseBuiltIn/CertPath/KeyPath)并调
|
||||
// ServerTlsIdentity::Load(THIS_CFG) 热重载,对新建连接即时生效(设计文档 §7.1)。
|
||||
// 菜单在启动时只构建一次(CreateSolidMenu),勾选状态不会自动刷新,
|
||||
// 这里同步「扩展」菜单上「TLS证书」的勾选,使其与 [tls] Enabled 一致。
|
||||
if (CMenu* pExtMenu = m_MainMenu.GetSubMenu(3)) {
|
||||
pExtMenu->CheckMenuItem(ID_TLS_CERTIFICATE, MF_BYCOMMAND |
|
||||
(THIS_CFG.GetInt("tls", "Enabled", 0) ? MF_CHECKED : MF_UNCHECKED));
|
||||
(THIS_CFG.GetInt("tls", "Enabled", 1) ? MF_CHECKED : MF_UNCHECKED));
|
||||
}
|
||||
|
||||
// 状态栏 TLS 分区立即跟随切换结果(对话框内已热重载身份,不等 60s 定时器)
|
||||
|
||||
Reference in new issue
Block a user