Files
SimpleRemoter/server/2015Remote/McpSettingsDlg.cpp
T
yuanyuanxianganddeepseek-flash c4021e1fc9 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
2026-11-01 15:39:54 +01:00

516 lines
23 KiB
C++
Raw 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 "McpSettingsDlg.h"
#include "LangManager.h" // _TR / MessageBoxL
#include "McpServer.h" // GenerateRandomToken
#include "2015Remote.h" // THIS_CFG (GetThisCfg)
#include "BuiltinTlsCert.h" // 设备端是否用内置证书(决定 MCP 证书回落)
#include <atlconv.h>
#include <afxdlgs.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
namespace {
// 构造一个无控件的 DLGTEMPLATE:cdit=0,控件由 OnInitDialog 动态创建。
// (与 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
}
// 把白名单文本规范化为「逗号分隔、逐项去首尾空白、去空项」的存储格式。
// 换行视作分隔符(与逗号等价),便于多行输入。
std::string NormalizeWhitelist(const std::string& raw)
{
std::string norm;
norm.reserve(raw.size());
for (char ch : raw)
norm += (ch == '\r' || ch == '\n') ? ',' : ch;
std::vector<std::string> items;
size_t start = 0;
while (start < norm.size()) {
size_t comma = norm.find(',', start);
std::string item = norm.substr(start, comma == std::string::npos ? std::string::npos : comma - start);
size_t b = item.find_first_not_of(" \t\r\n");
if (b != std::string::npos) {
size_t e = item.find_last_not_of(" \t\r\n");
item = item.substr(b, e - b + 1);
} else {
item.clear();
}
if (!item.empty()) items.push_back(item);
if (comma == std::string::npos) break;
start = comma + 1;
}
std::string out;
for (size_t i = 0; i < items.size(); ++i) {
if (i) out += ",";
out += items[i];
}
return out;
}
// 存储格式(逗号分隔)→ 多行展示(每行一条)。
std::string WhitelistForDisplay(const std::string& stored)
{
std::string disp;
disp.reserve(stored.size());
for (char ch : stored) {
if (ch == ',') disp += "\r\n";
else disp += ch;
}
return disp;
}
} // namespace
BEGIN_MESSAGE_MAP(CMcpSettingsDlg, CDialog)
ON_BN_CLICKED(IDC_MCP_HTTPS, &CMcpSettingsDlg::OnHttpsToggle)
ON_BN_CLICKED(IDC_MCP_CERT_BROWSE, &CMcpSettingsDlg::OnBrowseCert)
ON_BN_CLICKED(IDC_MCP_KEY_BROWSE, &CMcpSettingsDlg::OnBrowseKey)
END_MESSAGE_MAP()
CMcpSettingsDlg::CMcpSettingsDlg(CWnd* parent)
: CDialog((LPCTSTR)NULL, parent)
{
}
INT_PTR CMcpSettingsDlg::DoModal()
{
USES_CONVERSION;
CString title = _TR("MCP设置");
BuildDialogTemplate(m_Template, T2CW(title), 320, 640);
InitModalIndirect((LPCDLGTEMPLATE)m_Template.data());
return CDialog::DoModal();
}
BOOL CMcpSettingsDlg::OnInitDialog()
{
CDialog::OnInitDialog();
CRect cli;
GetClientRect(&cli);
// 占位 rect,真正布局在 LayoutControls 里
CRect r0(0, 0, 10, 10);
m_btnEnable.Create(_TR("启用 MCP"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_ENABLE);
m_lblPort.Create(_TR("端口"), WS_CHILD | WS_VISIBLE, r0, this, (UINT)-1);
m_editPort.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL,
r0, this, IDC_MCP_PORT);
m_lblBind.Create(_TR("绑定地址"), WS_CHILD | WS_VISIBLE, r0, this, (UINT)-1);
m_editBind.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL,
r0, this, IDC_MCP_BIND);
m_lblToken.Create(_TR("Token"), WS_CHILD | WS_VISIBLE, r0, this, (UINT)-1);
m_editToken.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL,
r0, this, IDC_MCP_TOKEN);
m_btnHttps.Create(_TR("启用 HTTPS(本端口同时接受 TLS 连接)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_HTTPS);
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_MCP_CERT);
m_btnCertBrowse.Create(_TR("浏览"), WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
r0, this, IDC_MCP_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_MCP_KEY);
m_btnKeyBrowse.Create(_TR("浏览"), WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
r0, this, IDC_MCP_KEY_BROWSE);
m_btnReadonly.Create(_TR("只读模式(禁命令执行)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_READONLY);
m_btnTerminal.Create(_TR("启用持久终端(全命令,无白名单)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_TERMINAL);
m_btnRemoteControl.Create(_TR("启用远程控制(AI 操控桌面)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_REMOTECONTROL);
m_btnFileTransfer.Create(_TR("启用文件传输(download_file)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_FILETRANSFER);
m_btnFileWrite.Create(_TR("启用文件写入(删除/改名/建目录,不可恢复)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_FILEWRITE);
m_btnManage.Create(_TR("启用管理操作(进程/窗口/服务/电源)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_MANAGE);
m_btnMachine.Create(_TR("启用主机管理(进程/窗口/服务/任务/网络状态)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_MACHINE);
m_btnMachineDangerous.Create(_TR("启用危险主机操作(冻结/解冻进程、停止/重启服务)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_MACHINE_DANGEROUS);
m_btnChat.Create(_TR("启用远程交谈(AI 与用户对话)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_CHAT);
m_btnKeylog.Create(_TR("启用键盘记录(AI 采集击键)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_KEYLOG);
m_lblWhitelist.Create(_TR("命令白名单"), WS_CHILD | WS_VISIBLE, r0, this, (UINT)-1);
m_editWhitelist.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP |
ES_MULTILINE | ES_AUTOVSCROLL | ES_WANTRETURN | WS_VSCROLL,
r0, this, IDC_MCP_WHITELIST);
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_lblPort.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_editPort.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_lblBind.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_editBind.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_lblToken.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_editToken.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnHttps.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_btnReadonly.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnTerminal.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnRemoteControl.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnFileTransfer.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnFileWrite.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnManage.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnMachine.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnMachineDangerous.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnChat.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnKeylog.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_lblWhitelist.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_editWhitelist.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));
}
// 回填配置(首次打开且 token 为空时预填随机值,随保存持久化)
int enabled = THIS_CFG.GetInt("settings", "McpEnabled", 0);
int port = THIS_CFG.GetInt("settings", "McpPort", 6544);
std::string bind = THIS_CFG.GetStr("settings", "McpBind", "127.0.0.1");
std::string tok = THIS_CFG.GetStr("settings", "McpToken", "");
if (tok.empty()) tok = GenerateRandomToken();
int readonly = THIS_CFG.GetInt("settings", "McpReadonly", 1);
int terminal = THIS_CFG.GetInt("settings", "McpTerminal", 0);
int remoteControl = THIS_CFG.GetInt("settings", "McpRemoteControl", 0);
int fileTransfer = THIS_CFG.GetInt("settings", "McpFileTransfer", 0);
int fileWrite = THIS_CFG.GetInt("settings", "McpFileWrite", 0);
int manage = THIS_CFG.GetInt("settings", "McpManage", 0);
int machine = THIS_CFG.GetInt("settings", "McpMachine", 0);
int machineDangerous = THIS_CFG.GetInt("settings", "McpMachineDangerous", 0);
int chat = THIS_CFG.GetInt("settings", "McpChat", 0);
int keylog = THIS_CFG.GetInt("settings", "McpKeylog", 0);
std::string whitelist = THIS_CFG.GetStr("settings", "McpCmdWhitelist", "");
int https = THIS_CFG.GetInt("settings", "McpHttps", 0);
std::string certPath = THIS_CFG.GetStr("settings", "McpCertPath", "");
std::string keyPath = THIS_CFG.GetStr("settings", "McpKeyPath", "");
// 未单独配置 MCP 证书时,按启动逻辑的同一回落规则预填设备端口的 [tls] 路径,
// 用户改或直接用都可以(保存后即成为 MCP 自己的显式配置)。
// 设备端用内置证书(自签)时不回落——公网 MCP 客户端校验会失败。
if (!BuiltinTlsCert::UseBuiltin(THIS_CFG)) {
if (certPath.empty()) certPath = THIS_CFG.GetStr("tls", "CertPath", "");
if (keyPath.empty()) keyPath = THIS_CFG.GetStr("tls", "KeyPath", "");
}
m_btnEnable.SetCheck(enabled ? BST_CHECKED : BST_UNCHECKED);
m_editPort.SetWindowText(CString(std::to_string(port).c_str()));
m_editBind.SetWindowText(CString(bind.c_str()));
m_editToken.SetWindowText(CString(tok.c_str()));
m_btnReadonly.SetCheck(readonly ? BST_CHECKED : BST_UNCHECKED);
m_btnTerminal.SetCheck(terminal ? BST_CHECKED : BST_UNCHECKED);
m_btnRemoteControl.SetCheck(remoteControl ? BST_CHECKED : BST_UNCHECKED);
m_btnFileTransfer.SetCheck(fileTransfer ? BST_CHECKED : BST_UNCHECKED);
m_btnFileWrite.SetCheck(fileWrite ? BST_CHECKED : BST_UNCHECKED);
m_btnManage.SetCheck(manage ? BST_CHECKED : BST_UNCHECKED);
m_btnMachine.SetCheck(machine ? BST_CHECKED : BST_UNCHECKED);
m_btnMachineDangerous.SetCheck(machineDangerous ? BST_CHECKED : BST_UNCHECKED);
m_btnChat.SetCheck(chat ? BST_CHECKED : BST_UNCHECKED);
m_btnKeylog.SetCheck(keylog ? BST_CHECKED : BST_UNCHECKED);
// 白名单存储为逗号分隔,展示为每行一条。
m_editWhitelist.SetWindowText(CString(WhitelistForDisplay(whitelist).c_str()));
m_btnHttps.SetCheck(https ? BST_CHECKED : BST_UNCHECKED);
m_editCert.SetWindowText(CString(certPath.c_str()));
m_editKey.SetWindowText(CString(keyPath.c_str()));
LayoutControls(cli.Width(), cli.Height());
UpdateHttpsState();
return TRUE;
}
void CMcpSettingsDlg::UpdateHttpsState()
{
const BOOL on = (m_btnHttps.GetCheck() == BST_CHECKED);
m_lblCert.EnableWindow(on);
m_editCert.EnableWindow(on);
m_btnCertBrowse.EnableWindow(on);
m_lblKey.EnableWindow(on);
m_editKey.EnableWindow(on);
m_btnKeyBrowse.EnableWindow(on);
}
void CMcpSettingsDlg::OnHttpsToggle()
{
UpdateHttpsState();
}
void CMcpSettingsDlg::OnBrowseCert()
{
CString cur;
m_editCert.GetWindowText(cur);
CFileDialog dlg(TRUE, _T("pem"), cur.IsEmpty() ? nullptr : (LPCTSTR)cur,
OFN_FILEMUSTEXIST | OFN_HIDEREADONLY,
_T("Certificate Files (*.pem;*.crt;*.cer)|*.pem;*.crt;*.cer|All Files (*.*)|*.*||"),
this);
dlg.m_ofn.lpstrTitle = _T("Select Certificate");
if (dlg.DoModal() == IDOK)
m_editCert.SetWindowText(dlg.GetPathName());
}
void CMcpSettingsDlg::OnBrowseKey()
{
CString cur;
m_editKey.GetWindowText(cur);
CFileDialog dlg(TRUE, _T("key"), cur.IsEmpty() ? nullptr : (LPCTSTR)cur,
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 CMcpSettingsDlg::OnOK()
{
CString sPort, sBind, sToken, sWhitelist, sCert, sKey;
m_editPort.GetWindowText(sPort);
m_editBind.GetWindowText(sBind);
m_editToken.GetWindowText(sToken);
m_editWhitelist.GetWindowText(sWhitelist);
m_editCert.GetWindowText(sCert);
m_editKey.GetWindowText(sKey);
bool enabled = (m_btnEnable.GetCheck() == BST_CHECKED);
bool readonly = (m_btnReadonly.GetCheck() == BST_CHECKED);
bool terminal = (m_btnTerminal.GetCheck() == BST_CHECKED);
bool remoteControl = (m_btnRemoteControl.GetCheck() == BST_CHECKED);
bool fileTransfer = (m_btnFileTransfer.GetCheck() == BST_CHECKED);
bool fileWrite = (m_btnFileWrite.GetCheck() == BST_CHECKED);
bool manage = (m_btnManage.GetCheck() == BST_CHECKED);
bool machine = (m_btnMachine.GetCheck() == BST_CHECKED);
bool machineDangerous = (m_btnMachineDangerous.GetCheck() == BST_CHECKED);
bool chat = (m_btnChat.GetCheck() == BST_CHECKED);
bool keylog = (m_btnKeylog.GetCheck() == BST_CHECKED);
bool https = (m_btnHttps.GetCheck() == BST_CHECKED);
// 危险子集依附于主机管理总开关:没开主机管理就没有工具可放开,直接清除并提示。
if (machineDangerous && !machine) {
machineDangerous = false;
m_btnMachineDangerous.SetCheck(BST_UNCHECKED);
MessageBoxL(_TR("危险主机操作依附于主机管理:请先启用主机管理。"), _TR("提示"),
MB_ICONWARNING);
}
// 端口校验:1-65535
int port = atoi(CT2A(sPort));
if (port < 1 || port > 65535) {
MessageBoxL(_TR("端口需为 1-65535 的数字"), _TR("提示"), MB_ICONWARNING);
return;
}
std::string bind = CT2A(sBind);
if (bind.empty()) bind = "127.0.0.1";
std::string token = CT2A(sToken);
if (enabled && token.empty()) {
MessageBoxL(_TR("Token 不能为空"), _TR("提示"), MB_ICONWARNING);
return;
}
// HTTPS:证书与私钥必须都在且存在(启动时加载失败会直接拒绝监听,故此处先挡住)
std::string certPath = CT2A(sCert);
std::string keyPath = CT2A(sKey);
if (https) {
if (certPath.empty()) {
MessageBoxL(_TR("请填写证书路径"), _TR("提示"), MB_ICONWARNING);
return;
}
if (keyPath.empty()) {
MessageBoxL(_TR("请填写私钥路径"), _TR("提示"), MB_ICONWARNING);
return;
}
DWORD ca = GetFileAttributesA(certPath.c_str());
DWORD ka = GetFileAttributesA(keyPath.c_str());
if (ca == INVALID_FILE_ATTRIBUTES || (ca & FILE_ATTRIBUTE_DIRECTORY) ||
ka == INVALID_FILE_ATTRIBUTES || (ka & FILE_ATTRIBUTE_DIRECTORY)) {
MessageBoxL(_TR("证书或私钥文件不存在,请检查路径。"), _TR("提示"), MB_ICONWARNING);
return;
}
}
// 落盘
THIS_CFG.SetInt("settings", "McpEnabled", enabled ? 1 : 0);
THIS_CFG.SetInt("settings", "McpPort", port);
THIS_CFG.SetStr("settings", "McpBind", bind);
THIS_CFG.SetStr("settings", "McpToken", token);
THIS_CFG.SetInt("settings", "McpReadonly", readonly ? 1 : 0);
THIS_CFG.SetInt("settings", "McpTerminal", terminal ? 1 : 0);
THIS_CFG.SetInt("settings", "McpRemoteControl", remoteControl ? 1 : 0);
THIS_CFG.SetInt("settings", "McpFileTransfer", fileTransfer ? 1 : 0);
THIS_CFG.SetInt("settings", "McpFileWrite", fileWrite ? 1 : 0);
THIS_CFG.SetInt("settings", "McpManage", manage ? 1 : 0);
THIS_CFG.SetInt("settings", "McpMachine", machine ? 1 : 0);
THIS_CFG.SetInt("settings", "McpMachineDangerous", machineDangerous ? 1 : 0);
THIS_CFG.SetInt("settings", "McpChat", chat ? 1 : 0);
THIS_CFG.SetInt("settings", "McpKeylog", keylog ? 1 : 0);
std::string whitelist = CT2A(sWhitelist);
whitelist = NormalizeWhitelist(whitelist);
THIS_CFG.SetStr("settings", "McpCmdWhitelist", whitelist);
THIS_CFG.SetInt("settings", "McpHttps", https ? 1 : 0);
THIS_CFG.SetStr("settings", "McpCertPath", certPath);
THIS_CFG.SetStr("settings", "McpKeyPath", keyPath);
// 拆成多段可翻译的单行键,中间用 \r\n 连接(多行键无法在 INI 中表示)
MessageBox(_TR("MCP 设置已保存。") + _T("\r\n") +
_TR("启用/端口/绑定地址/Token/只读/白名单/持久终端/远程控制/文件传输/文件写入/管理操作/主机管理/危险主机操作的改动需重启程序生效。") + _T("\r\n") +
_TR("持久终端、远程控制、管理操作与文件写入仅在只读模式关闭时生效。") + _T("\r\n") +
_TR("文件写入包含删除(不可恢复)、改名与建目录;删除会拒绝盘符根与系统目录。") + _T("\r\n") +
_TR("主机管理的写操作需只读模式关闭;冻结/解冻进程、停止/重启服务还需启用危险主机操作。") + _T("\r\n") +
_TR("远程交谈开关的改动需重启程序生效。") + _T("\r\n") +
_TR("键盘记录开关的改动需重启程序生效。") + _T("\r\n") +
_TR("HTTPS 开关与证书路径的改动需重启程序生效。") + _T("\r\n") +
_TR("证书须为 PEM 格式,私钥须为 PKCS#8 格式。"),
_TR("提示"), MB_ICONINFORMATION);
CDialog::OnOK();
}
void CMcpSettingsDlg::LayoutControls(int cx, int cy)
{
const int margin = 14;
const int labelW = 72;
const int rowH = 24;
const int gap = 10;
const int btnW = 88;
const int btnH = 26;
int y = margin;
m_btnEnable.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
m_lblPort.MoveWindow(margin, y, labelW, rowH);
m_editPort.MoveWindow(margin + labelW, y - 2, 100, rowH);
y += rowH + gap;
m_lblBind.MoveWindow(margin, y, labelW, rowH);
m_editBind.MoveWindow(margin + labelW, y - 2, cx - margin * 2 - labelW, rowH);
y += rowH + gap;
m_lblToken.MoveWindow(margin, y, labelW, rowH);
m_editToken.MoveWindow(margin + labelW, y - 2, cx - margin * 2 - labelW, rowH);
y += rowH + gap;
// HTTPS:勾选后证书/私钥两行才可编辑(未勾选时置灰,值仍保留)。
const int browseW = 64;
int editW = cx - margin * 2 - labelW - browseW - gap;
m_btnHttps.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
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_btnReadonly.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
m_btnTerminal.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
m_btnRemoteControl.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
m_btnFileTransfer.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
m_btnFileWrite.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
m_btnManage.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
m_btnMachine.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
m_btnMachineDangerous.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
m_btnChat.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
m_btnKeylog.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
const int whitelistH = 90;
m_lblWhitelist.MoveWindow(margin, y, labelW, rowH);
m_editWhitelist.MoveWindow(margin + labelW, y - 2, cx - margin * 2 - labelW, whitelistH);
y += whitelistH + 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();
}
}