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
288 lines
11 KiB
C++
288 lines
11 KiB
C++
#include "stdafx.h"
|
||
#include "TlsCertificateDlg.h"
|
||
#include "LangManager.h" // _TR / MessageBoxL
|
||
#include "2015Remote.h" // THIS_CFG (GetThisCfg)
|
||
#include "ServerTlsSession.h" // ServerTlsIdentity::Load / IsLoadError
|
||
#include "BuiltinTlsCert.h" // 内置证书状态与有效期
|
||
#include "common/iniFile.h" // config::GetInt/GetStr/SetInt/SetStr
|
||
#include <atlconv.h>
|
||
#include <afxdlgs.h>
|
||
|
||
#ifdef _DEBUG
|
||
#define new DEBUG_NEW
|
||
#endif
|
||
|
||
namespace {
|
||
|
||
// 构造一个无控件的 DLGTEMPLATE:cdit=0,控件由 OnInitDialog 动态创建。
|
||
// (与 McpSettingsDlg.cpp / ZstaPickerDlg.cpp 内同名函数一致)
|
||
void BuildDialogTemplate(std::vector<BYTE>& out, LPCWSTR caption, short cx, short cy)
|
||
{
|
||
out.clear();
|
||
auto append = [&](const void* p, size_t n) {
|
||
const BYTE* b = (const BYTE*)p;
|
||
out.insert(out.end(), b, b + n);
|
||
};
|
||
auto appendW = [&](WORD v) {
|
||
out.push_back((BYTE)(v & 0xFF));
|
||
out.push_back((BYTE)((v >> 8) & 0xFF));
|
||
};
|
||
auto appendWStr = [&](LPCWSTR s) {
|
||
size_t n = wcslen(s);
|
||
append(s, (n + 1) * sizeof(WCHAR));
|
||
};
|
||
|
||
DLGTEMPLATE dt = { 0 };
|
||
dt.style = DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER |
|
||
WS_POPUP | WS_CAPTION | WS_SYSMENU;
|
||
dt.dwExtendedStyle = 0;
|
||
dt.cdit = 0;
|
||
dt.x = 0; dt.y = 0;
|
||
dt.cx = cx; dt.cy = cy;
|
||
append(&dt, sizeof(dt));
|
||
appendW(0); // no menu
|
||
appendW(0); // default dialog class
|
||
appendWStr(caption); // caption
|
||
appendW(8); // font point size
|
||
appendWStr(L"MS Shell Dlg"); // typeface
|
||
|
||
while (out.size() % 4) out.push_back(0); // DWORD align
|
||
}
|
||
|
||
} // namespace
|
||
|
||
BEGIN_MESSAGE_MAP(CTlsCertificateDlg, CDialog)
|
||
ON_BN_CLICKED(IDC_TLS_CERT_BROWSE, &CTlsCertificateDlg::OnBrowseCert)
|
||
ON_BN_CLICKED(IDC_TLS_KEY_BROWSE, &CTlsCertificateDlg::OnBrowseKey)
|
||
ON_BN_CLICKED(IDC_TLS_BUILTIN, &CTlsCertificateDlg::OnBuiltinToggle)
|
||
END_MESSAGE_MAP()
|
||
|
||
CTlsCertificateDlg::CTlsCertificateDlg(CWnd* parent)
|
||
: CDialog((LPCTSTR)NULL, parent)
|
||
{
|
||
}
|
||
|
||
INT_PTR CTlsCertificateDlg::DoModal()
|
||
{
|
||
USES_CONVERSION;
|
||
CString title = _TR("TLS证书");
|
||
BuildDialogTemplate(m_Template, T2CW(title), 340, 180);
|
||
InitModalIndirect((LPCDLGTEMPLATE)m_Template.data());
|
||
return CDialog::DoModal();
|
||
}
|
||
|
||
BOOL CTlsCertificateDlg::OnInitDialog()
|
||
{
|
||
CDialog::OnInitDialog();
|
||
|
||
CRect cli;
|
||
GetClientRect(&cli);
|
||
|
||
// 占位 rect,真正布局在 LayoutControls 里
|
||
CRect r0(0, 0, 10, 10);
|
||
|
||
m_btnEnable.Create(_TR("启用加密"),
|
||
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
|
||
r0, this, IDC_TLS_ENABLE);
|
||
m_btnBuiltin.Create(_TR("内置证书"),
|
||
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
|
||
r0, this, IDC_TLS_BUILTIN);
|
||
m_lblBuiltinInfo.Create(_T(""), WS_CHILD | WS_VISIBLE | SS_LEFT,
|
||
r0, this, IDC_TLS_BUILTIN_INFO);
|
||
m_lblCert.Create(_TR("证书路径"), WS_CHILD | WS_VISIBLE, r0, this, (UINT)-1);
|
||
m_editCert.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL,
|
||
r0, this, IDC_TLS_CERT);
|
||
m_btnCertBrowse.Create(_TR("浏览"), WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
|
||
r0, this, IDC_TLS_CERT_BROWSE);
|
||
m_lblKey.Create(_TR("私钥路径"), WS_CHILD | WS_VISIBLE, r0, this, (UINT)-1);
|
||
m_editKey.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL,
|
||
r0, this, IDC_TLS_KEY);
|
||
m_btnKeyBrowse.Create(_TR("浏览"), WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
|
||
r0, this, IDC_TLS_KEY_BROWSE);
|
||
m_btnOK.Create(_TR("确定"), WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_DEFPUSHBUTTON,
|
||
r0, this, IDOK);
|
||
m_btnCancel.Create(_TR("取消"), WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
|
||
r0, this, IDCANCEL);
|
||
|
||
// 子控件继承对话框字体 (DS_SETFONT)
|
||
HFONT hFont = (HFONT)::SendMessage(GetSafeHwnd(), WM_GETFONT, 0, 0);
|
||
if (hFont) {
|
||
m_btnEnable.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||
m_btnBuiltin.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||
m_lblBuiltinInfo.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||
m_lblCert.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||
m_editCert.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||
m_btnCertBrowse.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||
m_lblKey.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||
m_editKey.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||
m_btnKeyBrowse.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||
m_btnOK.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||
m_btnCancel.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||
}
|
||
|
||
// 回填配置(Enabled 缺省为启用,与 ServerTlsIdentity::Load 保持一致)
|
||
int enabled = THIS_CFG.GetInt("tls", "Enabled", 1);
|
||
std::string cert = THIS_CFG.GetStr("tls", "CertPath", "");
|
||
std::string key = THIS_CFG.GetStr("tls", "KeyPath", "");
|
||
|
||
m_btnEnable.SetCheck(enabled ? BST_CHECKED : BST_UNCHECKED);
|
||
m_btnBuiltin.SetCheck(BuiltinTlsCert::UseBuiltin(THIS_CFG) ? BST_CHECKED : BST_UNCHECKED);
|
||
m_editCert.SetWindowText(CString(cert.c_str()));
|
||
m_editKey.SetWindowText(CString(key.c_str()));
|
||
|
||
LayoutControls(cli.Width(), cli.Height());
|
||
UpdateBuiltinUi();
|
||
return TRUE;
|
||
}
|
||
|
||
// 勾选/取消「内置证书」:自定义证书/私钥控件随之置灰/恢复。路径本身不清空,
|
||
// 切回自定义证书时原来填的还在。
|
||
void CTlsCertificateDlg::OnBuiltinToggle()
|
||
{
|
||
UpdateBuiltinUi();
|
||
}
|
||
|
||
void CTlsCertificateDlg::UpdateBuiltinUi()
|
||
{
|
||
const BOOL builtin = (m_btnBuiltin.GetCheck() == BST_CHECKED);
|
||
|
||
m_lblCert.EnableWindow(!builtin);
|
||
m_editCert.EnableWindow(!builtin);
|
||
m_btnCertBrowse.EnableWindow(!builtin);
|
||
m_lblKey.EnableWindow(!builtin);
|
||
m_editKey.EnableWindow(!builtin);
|
||
m_btnKeyBrowse.EnableWindow(!builtin);
|
||
|
||
CString info;
|
||
if (builtin) {
|
||
std::string notAfter = BuiltinTlsCert::Describe(THIS_CFG);
|
||
info = notAfter.empty()
|
||
? _TR("首次启用时自动生成")
|
||
: _TR("自签证书,有效期至") + _T(" ") + CString(notAfter.c_str());
|
||
}
|
||
m_lblBuiltinInfo.SetWindowText(info);
|
||
}
|
||
|
||
void CTlsCertificateDlg::OnOK()
|
||
{
|
||
CString sCert, sKey;
|
||
m_editCert.GetWindowText(sCert);
|
||
m_editKey.GetWindowText(sKey);
|
||
bool enabled = (m_btnEnable.GetCheck() == BST_CHECKED);
|
||
bool builtin = (m_btnBuiltin.GetCheck() == BST_CHECKED);
|
||
|
||
std::string cert = CT2A(sCert);
|
||
std::string key = CT2A(sKey);
|
||
|
||
// 校验:启用加密且用自定义证书时,必须填写证书/私钥路径
|
||
if (enabled && !builtin && cert.empty()) {
|
||
MessageBoxL("请填写证书路径", "提示", MB_ICONWARNING);
|
||
return;
|
||
}
|
||
if (enabled && !builtin && key.empty()) {
|
||
MessageBoxL("请填写私钥路径", "提示", MB_ICONWARNING);
|
||
return;
|
||
}
|
||
|
||
// 落盘 [tls] 四键。UseBuiltIn 显式写入,避免「路径非空」推断在清空路径时误判;
|
||
// 用内置证书时 CertPath/KeyPath 原样保留,方便之后切回自定义证书。
|
||
THIS_CFG.SetInt("tls", "Enabled", enabled ? 1 : 0);
|
||
THIS_CFG.SetInt("tls", "UseBuiltIn", builtin ? 1 : 0);
|
||
THIS_CFG.SetStr("tls", "CertPath", cert);
|
||
THIS_CFG.SetStr("tls", "KeyPath", key);
|
||
|
||
// 热重载身份(设计文档 §7.1):开关与证书/私钥路径对新建连接即时生效。
|
||
// 已知窄竞态:Load 内部 FreeIdentity 与「已取 Cred 副本、尚在握手」的连接存在竞态,
|
||
// 未来热切换需引用计数 + 惰性释放(见 ServerTlsSession.cpp FreeIdentity 注释),本次不做。
|
||
ServerTlsIdentity::Load(THIS_CFG);
|
||
|
||
if (ServerTlsIdentity::IsLoadError() && builtin) {
|
||
MessageBoxL("内置证书生成/加载失败,加密功能未生效。请查看日志,或取消勾选「内置证书」后改用本地证书与私钥。",
|
||
"提示", MB_ICONWARNING);
|
||
} else if (ServerTlsIdentity::IsLoadError()) {
|
||
MessageBoxL("证书/私钥加载失败,加密功能未生效。请检查文件路径与格式(证书 PEM、私钥 PKCS#8)。",
|
||
"提示", MB_ICONWARNING);
|
||
} else {
|
||
MessageBox(_TR("TLS 配置已保存。") + _T("\r\n") +
|
||
_TR("改动对新建连接即时生效。"),
|
||
_TR("提示"), MB_ICONINFORMATION);
|
||
}
|
||
|
||
CDialog::OnOK();
|
||
}
|
||
|
||
void CTlsCertificateDlg::OnBrowseCert()
|
||
{
|
||
CFileDialog dlg(TRUE, _T("crt"), nullptr,
|
||
OFN_FILEMUSTEXIST | OFN_HIDEREADONLY,
|
||
_T("Certificate Files (*.crt;*.pem;*.cer;*.cert)|*.crt;*.pem;*.cer;*.cert|All Files (*.*)|*.*||"),
|
||
this);
|
||
dlg.m_ofn.lpstrTitle = _T("Select Certificate");
|
||
|
||
if (dlg.DoModal() == IDOK) {
|
||
m_editCert.SetWindowText(dlg.GetPathName());
|
||
}
|
||
}
|
||
|
||
void CTlsCertificateDlg::OnBrowseKey()
|
||
{
|
||
CFileDialog dlg(TRUE, _T("key"), nullptr,
|
||
OFN_FILEMUSTEXIST | OFN_HIDEREADONLY,
|
||
_T("Key Files (*.key;*.pem)|*.key;*.pem|All Files (*.*)|*.*||"),
|
||
this);
|
||
dlg.m_ofn.lpstrTitle = _T("Select Private Key");
|
||
|
||
if (dlg.DoModal() == IDOK) {
|
||
m_editKey.SetWindowText(dlg.GetPathName());
|
||
}
|
||
}
|
||
|
||
void CTlsCertificateDlg::LayoutControls(int cx, int cy)
|
||
{
|
||
const int margin = 14;
|
||
// 标签宽按英文 "Private Key Path" 取(~80px):72px 时英文标签会折成两行,
|
||
// 中文/繁中都是 4 个字,绰绰有余。
|
||
const int labelW = 84;
|
||
const int rowH = 24;
|
||
const int gap = 10;
|
||
const int browseW = 64;
|
||
const int btnW = 88;
|
||
const int btnH = 26;
|
||
|
||
int y = margin;
|
||
m_btnEnable.MoveWindow(margin, y, cx - margin * 2, 22);
|
||
y += 30;
|
||
|
||
// 「内置证书」与它右侧的说明同排
|
||
const int builtinW = 92;
|
||
m_btnBuiltin.MoveWindow(margin, y, builtinW, 22);
|
||
m_lblBuiltinInfo.MoveWindow(margin + builtinW + 4, y + 4, cx - margin * 2 - builtinW - 4, rowH);
|
||
y += rowH + gap;
|
||
|
||
int editW = cx - margin * 2 - labelW - browseW - gap;
|
||
|
||
m_lblCert.MoveWindow(margin, y, labelW, rowH);
|
||
m_editCert.MoveWindow(margin + labelW, y - 2, editW, rowH);
|
||
m_btnCertBrowse.MoveWindow(cx - margin - browseW, y - 2, browseW, rowH);
|
||
y += rowH + gap;
|
||
|
||
m_lblKey.MoveWindow(margin, y, labelW, rowH);
|
||
m_editKey.MoveWindow(margin + labelW, y - 2, editW, rowH);
|
||
m_btnKeyBrowse.MoveWindow(cx - margin - browseW, y - 2, browseW, rowH);
|
||
y += rowH + gap;
|
||
|
||
// 确定 / 取消按钮紧随私钥路径下方
|
||
m_btnCancel.MoveWindow(cx - margin - btnW, y, btnW, btnH);
|
||
m_btnOK.MoveWindow(cx - margin - btnW * 2 - gap, y, btnW, btnH);
|
||
y += btnH + margin;
|
||
|
||
// 收缩对话框到内容实际高度并重新居中,消除底部空白。
|
||
if (y < cy) {
|
||
CRect wnd;
|
||
GetWindowRect(&wnd);
|
||
SetWindowPos(NULL, 0, 0, wnd.Width(), y + (wnd.Height() - cy),
|
||
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
|
||
CenterWindow();
|
||
}
|
||
}
|