Files
SimpleRemoter/server/2015Remote/TlsCertificateDlg.cpp
T
yuanyuanxianganddeepseek-flash cc9ce35c4d Feature: export the built-in TLS certificate from the settings dialog
The built-in certificate lives only inside the server config as base64
DER, so there was no way to take it elsewhere -- to install it as a
custom certificate on another machine, or to hand it to a proxy.

The TLS certificate dialog now has an Export Certificate button next to
the Built-in Certificate checkbox. It is enabled only while that box is
checked. Clicking it opens a save dialog and writes two PEM files: the
chosen .crt and a .key with the same base name in the same directory.
The key is PKCS#8 and unencrypted; the success message says so.

If the certificate has not been generated yet (box checked but the
dialog not applied), the export generates it first, the same way OK
does, then refreshes the expiry text. If the key cannot be written, the
certificate written just before it is deleted, so no half pair is left.

Translations added for en_US, zh_TW and de_DE; en_US and zh_TW are also
embedded resources, so the server was rebuilt.

Verified: Debug x64 server builds clean. Drove the dialog on a running
Debug instance over window messages -- the button, its label and its
enabled state track the checkbox. The PEM writer was checked against
OpenSSL (x509 -subject, pkey -check) using the same CryptoAPI flags.
The save dialog itself was not automated end to end.

Co-Authored-By: deepseek-flash
2026-11-06 12:13:07 +01:00

357 lines
14 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#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
}
// 以二进制写入。路径来自文件对话框(TCHAR),与项目其余文件操作一样走 ANSI 路径。
bool WriteTextFile(const CString& path, const std::string& text)
{
FILE* fp = NULL;
if (_tfopen_s(&fp, path, _T("wb")) != 0 || fp == NULL)
return false;
const size_t n = fwrite(text.data(), 1, text.size(), fp);
fclose(fp);
return n == text.size();
}
} // 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)
ON_BN_CLICKED(IDC_TLS_BUILTIN_EXPORT, &CTlsCertificateDlg::OnExportBuiltin)
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_btnExport.Create(_TR("导出证书"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
r0, this, IDC_TLS_BUILTIN_EXPORT);
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_btnExport.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);
// 导出的是内置证书,没选用它时没有可导出的对象
m_btnExport.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);
}
// 把内置证书导出为 <名字>.crt + <名字>.key(与证书同目录、同主名)。
// 勾了「内置证书」但还没点确定的场合证书可能尚未生成,这里按需生成一次,
// 与 OnOK 走同一个 Ensure 入口。
void CTlsCertificateDlg::OnExportBuiltin()
{
std::string certPem, keyPem;
if (!BuiltinTlsCert::ExportPem(THIS_CFG, certPem, keyPem)) {
if (!BuiltinTlsCert::Ensure(THIS_CFG) ||
!BuiltinTlsCert::ExportPem(THIS_CFG, certPem, keyPem)) {
MessageBoxL("内置证书尚未生成或已损坏,无法导出。", "提示", MB_ICONWARNING);
return;
}
UpdateBuiltinUi(); // 刚生成:说明文本从「首次启用时自动生成」换成有效期
}
CFileDialog dlg(FALSE, _T("crt"), _T("yama-server.crt"),
OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY,
_T("Certificate Files (*.crt)|*.crt|All Files (*.*)|*.*||"), this);
dlg.m_ofn.lpstrTitle = _T("Export Built-in Certificate");
if (dlg.DoModal() != IDOK)
return;
CString certPath = dlg.GetPathName();
CString keyPath = certPath;
int dot = keyPath.ReverseFind(_T('.'));
int slash = keyPath.ReverseFind(_T('\\'));
if (dot > slash)
keyPath = keyPath.Left(dot);
keyPath += _T(".key");
if (!WriteTextFile(certPath, certPem)) {
MessageBoxL("导出失败:无法写入文件,请检查目录是否可写。", "提示", MB_ICONERROR);
return;
}
if (!WriteTextFile(keyPath, keyPem)) {
// 只落一半会被误当成一对完整的证书/私钥,删掉刚写出的证书
DeleteFile(certPath);
MessageBoxL("导出失败:无法写入文件,请检查目录是否可写。", "提示", MB_ICONERROR);
return;
}
CString msg = _TR("证书与私钥已导出:");
msg += _T("\r\n") + certPath;
msg += _T("\r\n") + keyPath;
msg += _T("\r\n\r\n") + _TR("私钥为明文,请妥善保管。");
MessageBox(msg, _TR("提示"), MB_ICONINFORMATION);
}
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;
const int exportW = 96;
m_btnBuiltin.MoveWindow(margin, y, builtinW, 22);
m_btnExport.MoveWindow(cx - margin - exportW, y - 2, exportW, rowH);
m_lblBuiltinInfo.MoveWindow(margin + builtinW + 4, y + 4,
cx - margin * 2 - builtinW - exportW - 12, 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();
}
}