diff --git a/docs/Mcp_Design.md b/docs/Mcp_Design.md index d4d49e9..a2c2db9 100644 --- a/docs/Mcp_Design.md +++ b/docs/Mcp_Design.md @@ -260,6 +260,12 @@ Json::Value BuildHostJson(context* ctx, _ClientList* clientMap); | `McpToken` | 空(UI 默认随机值) | 静态 token;对话框内「token 必填、默认随机值」——首次打开若为空则预填随机并随保存持久化。运行时优先级:env `YAMA_MCP_TOKEN` → `McpToken` → 皆空则随机生成(见 §3.5) | | `McpKeylog` | `0` | 键盘记录工具 `get_keylog` 的独立开关(见 §9.3);与 `McpReadonly` 无关,改动需重启生效 | | `McpToolTimeoutMs` | `20000` | 工具等待客户端响应的默认超时(ms),clamp 到 `[1000, 600000]`;各工具自己的 `timeout_ms` 参数优先。**ini-only**(无设置界面控件),改动需重启生效 | +| `McpHttps` | `0` | `1` = 对外端口说 HTTPS(native TLS,见 §13),httplib 退到 `127.0.0.1:McpInternalPort`;`0` = 保持明文。经「MCP设置」对话框的「启用 HTTPS」复选框设置,改动需重启生效 | +| `McpCertPath` | 空(回退 `[tls] CertPath`) | MCP 专用证书(PEM)。面向公网客户端时应为公共 CA 证书(如 Let's Encrypt 的 `fullchain.pem`),不要复用设备端口的自签证书。对话框「证书路径」行可填/浏览;为空时按回退规则预填 `[tls]` 的值 | +| `McpKeyPath` | 空(回退 `[tls] KeyPath`) | 与 `McpCertPath` 配对的私钥,须为 PKCS#8(`-----BEGIN PRIVATE KEY-----`)。对话框「私钥路径」行可填/浏览 | +| `McpInternalPort` | 空(取 `McpPort+1`) | `McpHttps=1` 时 httplib 实际监听的回环端口,仅绑定 `127.0.0.1`。**ini-only**(对话框不暴露,自动取 `McpPort+1`) | + +> 对话框里「证书路径/私钥路径」两行仅在勾选「启用 HTTPS」后可编辑;保存时校验两者非空且文件存在(加载失败会导致 MCP 监听 fail-closed,故提前挡住),格式仍以服务端实际加载为准。 > 与旧版「`McpPort=0` 即禁用」不同:启用与否改由独立的 `McpEnabled` 开关控制,`McpPort` 回归纯端口语义,二者解耦。 @@ -343,6 +349,11 @@ MCP 默认不启用,通过主对话框「扩展 → MCP设置」菜单项打 | 端口 | `McpPort` | `6544` | 数字编辑框,仅当启用时有效 | | 绑定地址 | `McpBind` | `127.0.0.1` | 默认仅本机;可改 `0.0.0.0` / 内网 IP | | Token | `McpToken` | 随机值 | 必填;为空时预填随机 token | +| 「启用 HTTPS」复选框 | `McpHttps` | 未勾选(`0`) | 勾选后本端口同时接受 TLS(§13);未勾选时下面两行置灰 | +| 证书路径 | `McpCertPath` | 空(回退 `[tls] CertPath`) | PEM;带「浏览」按钮。为空时按回退规则预填 `[tls]` 的值 | +| 私钥路径 | `McpKeyPath` | 空(回退 `[tls] KeyPath`) | PKCS#8;带「浏览」按钮 | + +保存时若勾选了 HTTPS,证书/私钥必须非空且文件存在,否则弹提示并留在对话框(身份加载失败会让 MCP 监听 fail-closed,故提前挡住);HTTPS 改动与其它项一样重启生效。 #### 3.8.3 初始化与保存 @@ -698,3 +709,95 @@ token 只从 `-Token` / env 读取,不落仓库、不打印;无在线主机 **输出清洗顺序**:剥 ANSI(OSC 序列以 `ESC\` 结尾时两字节一起吞,否则会残留 `\`)→ CRLF 归一 → 从缓冲区开头删到「我们下发的命令行回显」结束(顺带清掉 shell 启动画面与提示符)→ 删哨兵行回显 → **按 nonce 擦掉残留的哨兵文本** → 去首尾空行。最后一步是必需的:ConPTY 送回来的是**屏幕渲染流**(带光标移动/擦除序列),剥掉序列后同一行可能重复出现,哨兵会留下副本(实测不擦时 `rem hello` 只剩哨兵、`cmd /c echo abc` 成了 `abc__MCP_DONE_x__0`)。nonce 每条命令随机生成,命令的真实输出不可能包含它,所以按 nonce 擦除不会误伤业务输出。 **已知边界**:屏幕渲染流里「光标下移空行」会被剥成紧邻行(例如 `ping` 的统计块会贴在最后一条回复后面),不影响语义。 + +## 13. 增补(2026-10-26:MCP HTTPS / native TLS) + +### 13.1 目标与取舍 + +公网 MCP 客户端(Claude Desktop、WorkBuddy 等)多数只接受 `https://` 端点,而 MCP 一直是明文 `httplib`。三条路里选了第三条: + +| 方案 | 结论 | +|---|---| +| 在 vps 上用 nginx 反代加 TLS | 不行:vps 的 80/443/6544 都由 frps 持有,nginx 只在 8080,且反代会让 token 以明文经过 vps | +| 引入 OpenSSL / cpp-httplib 的 `CPPHTTPLIB_OPENSSL_SUPPORT` | 新增第三方依赖与证书/私钥加载路径,仓库已有 Schannel 实现 | +| **复用仓库既有的 Schannel 入站实现,在 MCP 端口上终结 TLS** | ✅ 零新依赖,`ServerTlsSession`/`ServerTlsIdentity` 已在设备端口跑通 | + +### 13.2 结构:同端口嗅探 + 明文直通 + +``` +客户端 ──TLS──▶ [McpTlsProxy] :McpPort ──明文──▶ httplib 127.0.0.1:McpInternalPort +客户端 ──明文─▶ │ 0x16 0x03 ? (只绑回环,不对外) +``` + +- `McpTlsProxy`(`McpTlsProxy.h/.cpp`)在 `McpBind:McpPort` 上监听,首包用 `MSG_PEEK` 判 TLS(首字节 `0x16` 且次字节 `0x03`,与设备端口 §5.2 同一套路):TLS 走 `ServerTlsSession::HandshakeWithCred` + `Decrypt`/`Encrypt`,否则按字节原样转发。 +- 因此**同一端口两种用法并存**:本机既有的 `http://127.0.0.1:6544/mcp` 不用改,远端可以用 `https://host:6544/mcp`。 +- `McpHttps=0` 时完全不启动前端,行为与改造前一致(httplib 直接监听 `McpBind:McpPort`)。 + +### 13.3 身份:第二份证书,独立 CNG 键名 + +`ServerTlsLoadIdentityFromPem(cert, key, L"YamaMcpTlsKey", id)` 构造进程内第二份入站身份,与设备端口的 `ServerTlsIdentity`(`YamaServerTlsKey`、通常自签 `CN=localhost`)并存:证书/私钥各读各的,持久化私钥用不同键名,互不覆盖。`HandshakeWithCred` 是新增的重载,设备端口仍用 `Handshake`(同一份逻辑,只是取凭据的方式不同)。 + +**fail-closed**:证书/私钥读不出来、CNG 导入失败、端口被占任一项失败,`McpServer::Start` 会把 httplib 一起停掉并返回 false——绝不允许「以为在跑 HTTPS、其实没在监听」。 + +### 13.4 实测(Debug 实例,自签证书) + +| 场景 | 结果 | +|---|---| +| `https://127.0.0.1:6545/mcp`(`--cacert server.crt`)无 token | `401`,证书校验通过 | +| 同一端口 `http://127.0.0.1:6545/mcp` 无 token | `401`(明文直通未受影响) | +| TLS + token:`initialize` / `tools/list` / `tools/call get_server_status` | 正常,53 个工具 | +| 同一条 TLS 连接上连发两个请求(keep-alive) | 两次都 `200`,复用连接 | +| 错误 token | `401`(回环来源的鉴权封禁豁免仍生效) | +| 内部端口 `6546` | 只监听 `127.0.0.1` | +| `McpCertPath` 指向不存在的文件后重启 | MCP 整体不启动,无任何监听(fail-closed) | +| 公共 CA 的 ECDSA 证书(Let's Encrypt P-256 fullchain + PKCS#8 私钥) | 身份加载成功,TLS 无 token `401`、带 token `initialize`/`tools/list` 正常(53 工具) | +| 本地 CA 三级链(叶 + 中间,中间证书不在系统库) | 服务端下发 2 张证书,`openssl s_client -CAfile root.crt` 得 `Verify return code: 0` | +| 设备端口 `6543` TLS(回归) | 握手正常 | +| `McpHttps` 删除后重启(回归) | 明文明监听,无内部端口 | + +### 13.5 Schannel 的一个坑(已修在共用层) + +`ServerTlsSession` 原先把「首次收到的字节」直接喂给 `AcceptSecurityContext`。如果这批字节只是**半条 ClientHello**,Schannel 会先建出一个坏上下文,补齐后再送返回 `SEC_E_UNKNOWN_CREDENTIALS (0x80090301)`,握手必失败。设备端口因为累积了整包才分类、且客户端 ClientHello 通常一次到齐,一直没暴露;MCP 前端按 8 字节嗅探后接手,稳定触发。 + +现在 `HandshakeWithCred` 在首次 ASC 之前先凑齐**一整条 TLS 记录**(5 字节头 + 负载,上限 18432 字节,首字节非 `0x16` 或缺字节超时则 fail-closed),调用方给多少字节都行。这也顺带修好了设备端口在「ClientHello 被 TCP 分片」时的同类隐患。 + +### 13.6 部署公网证书 + +1. 把公共 CA 签发的证书链与私钥(PKCS#8)放到本机,例如 `Bin\certs\mcp-fullchain.pem` / `Bin\certs\mcp-key.pem`。证书支持 RSA 与 ECDSA(P-256/P-384/P-521),可以写成「叶证书 + 中间证书」的 fullchain(见 13.8)。 +2. 「扩展 → MCP设置」勾选「启用 HTTPS」,在两行里填/浏览证书与私钥(也可直接改 ini:`McpHttps=1`、`McpCertPath=<证书>`、`McpKeyPath=<私钥>`),保存后重启 YAMA。注意「端口」填的是对外端口,httplib 自动退到 `127.0.0.1:McpPort+1`。 +3. frp 的 `YAMA-MCP-*` 映射指向本机 `McpPort` 不变——TLS 在 YAMA 内终结,vps 只转发密文。 +4. 证书续期后需重新拷贝 + 重启 YAMA(当前不做热加载)。 + +客户端配置形如: + +```json +{ + "mcpServers": { + "yama": { + "type": "http", + "url": "https://web.just-do-it.icu:6544/mcp", + "headers": { "Authorization": "Bearer " } + } + } +} +``` + +### 13.7 已知限制 + +- **按 IP 的鉴权封禁对远端不生效**:`IsAuthBlocked` 按来源 IP 计数,而经 frp 或本前端转发的请求来源都是 `127.0.0.1`,命中既有的「代理来源豁免」。因此远端的暴力尝试不受「10 次失败 / 60 秒 → 封 15 分钟」约束,真正的防线是 token 熵(32 hex ≈ 128 bit)与审计日志里的 `AUTH_FAIL` 记录。经 frp 暴露时改造前就已如此;但若改造前是把 `McpPort` 直接绑在公网地址(不经 frp),远端 IP 原本会被封禁,开启本前端后一律变成环回、不再封禁——按部署方式评估这一差异。要补需在本前端把真实来源 IP 以受信头注入 httplib 请求,属于后续工作。 +- 证书不热加载:换/续证书需重启 YAMA。 +- 只支持 HTTP/1.1(与 httplib 一致),不做 ALPN h2。 + +### 13.8 证书类型与证书链(2026-10-26 补齐) + +早期实现只认 RSA:私钥一律按 `BCRYPT_RSAFULLPRIVATE_BLOB` 导出后再写入持久化键,遇到 ECDSA 证书(Let's Encrypt 自 2024 年起默认签发 P-256)会在导出处拿 `NTE_BAD_TYPE (0x8009000a)` 并报错退出。现在按**证书公钥类型**分两路落盘(`ServerTlsSession.cpp` 的 `BuildIdentity`): + +| 证书公钥 | 落盘方式 | +|---|---| +| RSA | 导入 PKCS#8 为临时键 → 导出 `BCRYPT_RSAFULLPRIVATE_BLOB` → `NCryptCreatePersistedKey` + `NCryptSetProperty` + `NCryptFinalizeKey` | +| ECDSA(P-256/P-384/P-521) | 导入 PKCS#8 时在参数表里给出键名(`NCRYPTBUFFER_PKCS_KEY_NAME`),MS Software KSP 直接持久化 | + +ECDSA 这条是 MS Software KSP 唯一可行的一条,其余几条均已实测不通:`NCryptCreatePersistedKey` 后写 EC 私钥 BLOB,`SetProperty` 返回 0 但 `Finalize` 给 `NTE_INVALID_PARAMETER (0x80090027)`;导入后再 `NCryptSetProperty(NCRYPT_NAME_PROPERTY)` 给 `NTE_NOT_SUPPORTED (0x80090029)`(不带键名即匿名临时键,Schannel 用不上);把临时键句柄经 `CERT_KEY_CONTEXT_PROP_ID` 挂到证书上,Schannel 报 `SEC_E_NO_CREDENTIALS (0x8009030e)`。`NCRYPTBUFFER_PKCS_KEY_NAME` 的值必须**含结尾 NUL**,少了同样报 0x80090027。曲线只支持具名 P-256/P-384/P-521,显式参数形式的曲线会带明确报错退出。 + +**证书链**:Schannel 的握手在进程外完成,建链时只查系统证书库——fullchain 里的中间证书塞进叶证书自带的内存库或 `paCred` 数组都不会被下发(实测只发叶证书,缺中间证书的客户端建链失败)。因此加载身份时把 fullchain 第 2 张起的证书补进「当前用户\中间证书颁发机构」库(`Cert:\CurrentUser\CA`,已在库中则跳过;.NET 的 `SslStreamCertificateContext` 也是这么做的),Schannel 建好链后随握手下发。证书文件因此可以、也建议写成「叶证书 + 中间证书」的 fullchain(Let's Encrypt 的 `fullchain.pem` 即如此)。副作用:进程所在账户的 CA 库里会多出这些中间证书(公开信息,留在库里无害)。 + diff --git a/server/2015Remote/2015RemoteDlg.cpp b/server/2015Remote/2015RemoteDlg.cpp index 6d8ed22..fa544e7 100644 --- a/server/2015Remote/2015RemoteDlg.cpp +++ b/server/2015Remote/2015RemoteDlg.cpp @@ -2434,6 +2434,19 @@ BOOL CMy2015RemoteDlg::OnInitDialog() McpServer().SetKeylogEnabled(THIS_CFG.GetInt("settings", "McpKeylog", 0) != 0); // 工具默认等待超时(ini-only 键,无设置界面):默认 20000ms,clamp 在 SetToolTimeoutMs 内。 McpServer().SetToolTimeoutMs(THIS_CFG.GetInt("settings", "McpToolTimeoutMs", 20000)); + // HTTPS(native TLS):McpHttps=1 时对外端口说 TLS,httplib 退到回环内部端口。 + // 证书/私钥为空时回落到 [tls] 那一对(对话框里同样按此规则预填)。 + 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", ""); + int internalPort = THIS_CFG.GetInt("settings", "McpInternalPort", 0); + if (internalPort <= 0) internalPort = mcpPort + 1; + McpServer().SetHttps(true, certPath, keyPath, internalPort); + Mprintf("[MCP] HTTPS enabled: %s:%d -> 127.0.0.1:%d (cert=%s)\n", + mcpBind.c_str(), mcpPort, internalPort, certPath.c_str()); + } if (!McpServer().Start(mcpBind, mcpPort)) { Mprintf("McpServer start failed on %s:%d\n", mcpBind.c_str(), mcpPort); } else { diff --git a/server/2015Remote/2015Remote_vs2015.vcxproj b/server/2015Remote/2015Remote_vs2015.vcxproj index a56d4e1..1fe680a 100644 --- a/server/2015Remote/2015Remote_vs2015.vcxproj +++ b/server/2015Remote/2015Remote_vs2015.vcxproj @@ -328,6 +328,7 @@ + @@ -400,6 +401,7 @@ + diff --git a/server/2015Remote/2015Remote_vs2015.vcxproj.filters b/server/2015Remote/2015Remote_vs2015.vcxproj.filters index 54a34a6..ae97cbe 100644 --- a/server/2015Remote/2015Remote_vs2015.vcxproj.filters +++ b/server/2015Remote/2015Remote_vs2015.vcxproj.filters @@ -22,6 +22,7 @@ + @@ -161,6 +162,7 @@ + diff --git a/server/2015Remote/IOCPServer.cpp b/server/2015Remote/IOCPServer.cpp index 9e21c15..22d8250 100644 --- a/server/2015Remote/IOCPServer.cpp +++ b/server/2015Remote/IOCPServer.cpp @@ -931,11 +931,38 @@ DWORD WINAPI IOCPServer::TlsHandshakeThreadProc(LPVOID lParam) bool ok = (ctx->tls != NULL) && ctx->tls->Handshake(ctx->sClientSocket, initial.data(), (int)initial.size()); + // 握手结束时会话里可能已经躺着首条应用数据:客户端复用 TLS 会话时会把 + // ChangeCipherSpec + Finished + 首个业务包挤在同一批字节里,握手只消费前两个。 + // 必须在交还 IOCP 之前取出来喂给解析路径——接收路径只在有新密文到达时才调 + // Decrypt,等客户端再发一包就是等一个永远不来的包(客户端正等我们回应), + // 表现为随机登录超时/重连。明文连接从未有此问题。 + std::vector pendingPlain; + if (ok && ctx->tls->Decrypt(NULL, 0, pendingPlain) < 0) + ok = false; + if (ok) { + // 响应必须走加密通道,故先置 Ready 再解析首包。 ctx->tlsState.store(TLS_Ready, std::memory_order_release); } - // 先释放握手线程持有的引用,再触发任何可能 RemoveStaleContext 的动作(#215 顺序)。 + // 注意顺序:解析仍在本线程持有引用期间完成(对象不会在这段窗口里被回收); + // 释放引用之后才允许任何可能 RemoveStaleContext 的动作(#215)。 + if (ok && !pendingPlain.empty()) { + // 与工作线程同样的解压上下文,只是现建现用(首包只解析这一批)。 + ZSTD_DCtx* dctx = ZSTD_createDCtx(); + z_stream z = {}; + inflateInit2(&z, 15); + ok = ctx->IsRemoved.load(std::memory_order_acquire) ? TRUE + : ParseReceivedData(ctx, pendingPlain.data(), (DWORD)pendingPlain.size(), + This->m_NotifyProc, dctx, &z); + inflateEnd(&z); + ZSTD_freeDCtx(dctx); + if (!ok) { + Mprintf("[TLS] pending first packet parse failed for %s (closing)\n", + ctx->GetPeerName().c_str()); + } + } + ctx->IoRefCount.fetch_sub(1); if (ok) { diff --git a/server/2015Remote/McpServer.cpp b/server/2015Remote/McpServer.cpp index 6b7e050..40e1f88 100644 --- a/server/2015Remote/McpServer.cpp +++ b/server/2015Remote/McpServer.cpp @@ -6860,17 +6860,40 @@ bool CMcpServer::Start(const std::string& bind, int port) { m_bind = bind; m_port = port; - m_thread = std::thread([this, bind, port]() { - m_server.listen(bind, port); + // HTTPS 时 httplib 只监听回环内部端口,对外端口由 McpTlsProxy 占据。 + const bool https = m_httpsEnabled; + const int backendPort = (https && m_internalPort > 0) ? m_internalPort : (https ? port + 1 : port); + // 只在 HTTPS 下记住内部端口:明文模式下把它写成 port,会让「先明文启动、再改 HTTPS + // 重启」这条路径拿到 backendPort == port,后端和前端抢同一个端口、MCP 直接起不来。 + if (https) m_internalPort = backendPort; + const std::string backendBind = https ? "127.0.0.1" : bind; + + m_thread = std::thread([this, backendBind, backendPort]() { + m_server.listen(backendBind, backendPort); }); // 给 listen 一点时间绑定端口;httplib::Server::is_running() 在 listen 内部置位。 std::this_thread::sleep_for(std::chrono::milliseconds(100)); m_running.store(m_server.is_running()); - return m_running.load(); + if (!m_running.load()) return false; + + if (https) { + // fail-closed:TLS 前端起不来(证书/私钥坏、端口被占)就整体停掉, + // 绝不让 MCP 以「以为在跑 HTTPS 其实没在监听」的状态存在。 + if (!m_tlsProxy.Start(bind, port, backendPort, m_certPath, m_keyPath)) { + Mprintf("[MCP] HTTPS front-end failed to start; MCP server disabled\n"); + m_server.stop(); + if (m_thread.joinable()) m_thread.join(); + m_running.store(false); + return false; + } + } + return true; } void CMcpServer::Stop() { + // 先停前端:不再接入新连接,再停后端。Stop 内部会 join 前端线程。 + m_tlsProxy.Stop(); m_server.stop(); if (m_thread.joinable()) { m_thread.join(); diff --git a/server/2015Remote/McpServer.h b/server/2015Remote/McpServer.h index 3c0ee99..7bbffa1 100644 --- a/server/2015Remote/McpServer.h +++ b/server/2015Remote/McpServer.h @@ -27,6 +27,8 @@ #define min(a,b) (((a) < (b)) ? (a) : (b)) #endif +#include "McpTlsProxy.h" + #pragma comment(lib, "ws2_32.lib") class CMy2015RemoteDlg; @@ -58,6 +60,18 @@ public: void SetParentDlg(CMy2015RemoteDlg* pDlg) { m_parent = pDlg; } void SetToken(const std::string& token) { m_token = token; } + // HTTPS(native TLS):开启后 httplib 退到 127.0.0.1:internalPort,对外由 McpTlsProxy + // 在 bind:port 上同端口嗅探(TLS 解密 / 明文直通)。internalPort <= 0 时取 port+1。 + void SetHttps(bool enabled, const std::string& certPath, const std::string& keyPath, + int internalPort) { + m_httpsEnabled = enabled; + m_certPath = certPath; + m_keyPath = keyPath; + m_internalPort = internalPort; + } + bool IsHttps() const { return m_httpsEnabled; } + int GetInternalPort() const { return m_internalPort; } + bool Start(const std::string& bind, int port); void Stop(); bool IsRunning() const { return m_running.load(); } @@ -501,11 +515,16 @@ private: PendingKind kind, context* mainCtx); httplib::Server m_server; + McpTlsProxy m_tlsProxy; // HTTPS 前端(仅在 m_httpsEnabled 时启动) std::thread m_thread; std::atomic m_running{false}; std::string m_token; std::string m_bind; // Start 传入的监听地址 int m_port = 0; // Start 传入的监听端口 + bool m_httpsEnabled = false; // SetHttps 设置(默认明文) + std::string m_certPath; // MCP TLS 证书(PEM) + std::string m_keyPath; // MCP TLS 私钥(PEM, PKCS#8) + int m_internalPort = 0; // httplib 实际监听的回环端口 CMy2015RemoteDlg* m_parent = nullptr; // 挂起请求注册表(受 m_PendingMutex 保护,键 = device_id)。 diff --git a/server/2015Remote/McpSettingsDlg.cpp b/server/2015Remote/McpSettingsDlg.cpp index 82f972e..469bdd2 100644 --- a/server/2015Remote/McpSettingsDlg.cpp +++ b/server/2015Remote/McpSettingsDlg.cpp @@ -4,6 +4,7 @@ #include "McpServer.h" // GenerateRandomToken #include "2015Remote.h" // THIS_CFG (GetThisCfg) #include +#include #ifdef _DEBUG #define new DEBUG_NEW @@ -95,6 +96,9 @@ std::string WhitelistForDisplay(const std::string& stored) } // 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) @@ -106,7 +110,7 @@ INT_PTR CMcpSettingsDlg::DoModal() { USES_CONVERSION; CString title = _TR("MCP设置"); - BuildDialogTemplate(m_Template, T2CW(title), 320, 540); + BuildDialogTemplate(m_Template, T2CW(title), 320, 640); InitModalIndirect((LPCDLGTEMPLATE)m_Template.data()); return CDialog::DoModal(); } @@ -133,6 +137,19 @@ BOOL CMcpSettingsDlg::OnInitDialog() 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); @@ -179,6 +196,13 @@ BOOL CMcpSettingsDlg::OnInitDialog() 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)); @@ -210,6 +234,13 @@ BOOL CMcpSettingsDlg::OnInitDialog() 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 自己的显式配置)。 + 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())); @@ -227,17 +258,66 @@ BOOL CMcpSettingsDlg::OnInitDialog() // 白名单存储为逗号分隔,展示为每行一条。 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; + 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); @@ -248,6 +328,7 @@ void CMcpSettingsDlg::OnOK() 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) { @@ -273,6 +354,27 @@ void CMcpSettingsDlg::OnOK() 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); @@ -290,6 +392,9 @@ void CMcpSettingsDlg::OnOK() 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") + @@ -297,7 +402,9 @@ void CMcpSettingsDlg::OnOK() _TR("持久终端、远程控制与管理操作仅在只读模式关闭时生效。") + _T("\r\n") + _TR("主机管理的写操作需只读模式关闭;冻结/解冻进程、停止/重启服务还需启用危险主机操作。") + _T("\r\n") + _TR("远程交谈开关的改动需重启程序生效。") + _T("\r\n") + - _TR("键盘记录开关的改动需重启程序生效。"), + _TR("键盘记录开关的改动需重启程序生效。") + _T("\r\n") + + _TR("HTTPS 开关与证书路径的改动需重启程序生效。") + _T("\r\n") + + _TR("证书须为 PEM 格式,私钥须为 PKCS#8 格式。"), _TR("提示"), MB_ICONINFORMATION); CDialog::OnOK(); @@ -328,6 +435,22 @@ void CMcpSettingsDlg::LayoutControls(int cx, int cy) 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; diff --git a/server/2015Remote/McpSettingsDlg.h b/server/2015Remote/McpSettingsDlg.h index 8bf3107..09f4674 100644 --- a/server/2015Remote/McpSettingsDlg.h +++ b/server/2015Remote/McpSettingsDlg.h @@ -4,7 +4,7 @@ #include #include -// 「MCP设置」配置对话框:启用 MCP / 端口 / 绑定地址 / Token。 +// 「MCP设置」配置对话框:启用 MCP / 端口 / 绑定地址 / Token / HTTPS 与证书。 // 因 2015Remote.rc 为 UTF-16 编码、不宜手工编辑,参照 ZstaPickerDlg 用 // InitModalIndirect + 内存 DLGTEMPLATE 程序化创建(见 docs/Mcp_Design.md §3.8)。 class CMcpSettingsDlg : public CDialog @@ -18,6 +18,10 @@ protected: virtual BOOL OnInitDialog(); virtual void OnOK(); + afx_msg void OnHttpsToggle(); + afx_msg void OnBrowseCert(); + afx_msg void OnBrowseKey(); + DECLARE_MESSAGE_MAP() private: @@ -36,6 +40,11 @@ private: IDC_MCP_MACHINE_DANGEROUS = 1012, // 「启用危险主机操作」复选框(冻结/停止/重启) IDC_MCP_CHAT = 1013, // 「启用远程交谈」复选框(chat_* 工具族,不要求只读关) IDC_MCP_KEYLOG = 1014, // 「启用键盘记录」复选框(get_keylog,不要求只读关) + IDC_MCP_HTTPS = 1015, // 「启用 HTTPS」复选框(MCP 端口同时接受 TLS) + IDC_MCP_CERT = 1016, // 证书路径编辑框(PEM) + IDC_MCP_KEY = 1017, // 私钥路径编辑框(PKCS#8) + IDC_MCP_CERT_BROWSE = 1018, // 证书路径「浏览」按钮 + IDC_MCP_KEY_BROWSE = 1019, // 私钥路径「浏览」按钮 }; CButton m_btnEnable; @@ -52,9 +61,14 @@ private: CButton m_btnKeylog; CStatic m_lblWhitelist; CEdit m_editWhitelist; + CButton m_btnHttps; + CStatic m_lblCert, m_lblKey; + CEdit m_editCert, m_editKey; + CButton m_btnCertBrowse, m_btnKeyBrowse; CButton m_btnOK, m_btnCancel; std::vector m_Template; // 内存 DLGTEMPLATE 字节 void LayoutControls(int cx, int cy); + void UpdateHttpsState(); // 勾选 HTTPS 才允许编辑证书/私钥 }; diff --git a/server/2015Remote/McpTlsProxy.cpp b/server/2015Remote/McpTlsProxy.cpp new file mode 100644 index 0000000..3d37f42 --- /dev/null +++ b/server/2015Remote/McpTlsProxy.cpp @@ -0,0 +1,440 @@ +// McpTlsProxy.cpp — MCP 端口的 TLS 前端实现(Schannel 入站,同端口嗅探) +#include "StdAfx.h" +#include "McpTlsProxy.h" + +#include + +namespace +{ +// MCP 身份在 CNG KSP 里的键名,与设备端口的 YamaServerTlsKey 区分,避免互相覆盖。 +const wchar_t* kMcpKeyName = L"YamaMcpTlsKey"; + +const size_t kMaxConns = 64; // 并发连接上限(MCP 客户端数量很少,防资源耗尽) +const DWORD kSniffTimeoutMs = 10000; // 首字节嗅探超时:连上不说话的直接断开 +} + +bool McpTlsProxy::WaitReady(SOCKET sock, bool forRead, int timeoutMs) +{ + fd_set fds; + FD_ZERO(&fds); + FD_SET(sock, &fds); + timeval tv; + tv.tv_sec = timeoutMs / 1000; + tv.tv_usec = (timeoutMs % 1000) * 1000; + return select(0, forRead ? &fds : NULL, forRead ? NULL : &fds, NULL, &tv) > 0; +} + +bool McpTlsProxy::SendAll(SOCKET sock, const void* data, int len) +{ + const char* p = (const char*)data; + int sent = 0; + while (sent < len) + { + int n = send(sock, p + sent, len - sent, 0); + if (n == SOCKET_ERROR) + { + if (WSAGetLastError() == WSAEWOULDBLOCK) + { + if (!WaitReady(sock, false, 30000)) + return false; + continue; + } + return false; + } + if (n <= 0) + return false; + sent += n; + } + return true; +} + +SOCKET McpTlsProxy::ConnectLoopback(int port) +{ + SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (s == INVALID_SOCKET) + return INVALID_SOCKET; + + sockaddr_in addr = {}; + addr.sin_family = AF_INET; + addr.sin_port = htons((u_short)port); + addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + + if (connect(s, (sockaddr*)&addr, sizeof(addr)) != 0) + { + closesocket(s); + return INVALID_SOCKET; + } + u_long nb = 1; + ioctlsocket(s, FIONBIO, &nb); // 连接建立后转非阻塞,交给 select 驱动 + return s; +} + +bool McpTlsProxy::Start(const std::string& bind, int listenPort, int backendPort, + const std::string& certPath, const std::string& keyPath) +{ + if (m_running.load()) + return true; + if (listenPort <= 0 || backendPort <= 0) + return false; + + // 身份必须先加载成功:证书坏了就 fail-closed,绝不以明文对外监听。 + if (!ServerTlsLoadIdentityFromPem(certPath, keyPath, kMcpKeyName, m_identity)) + { + Mprintf("[McpTls] FATAL: cannot load MCP TLS identity (cert=%s key=%s); " + "refusing to start MCP listener\n", certPath.c_str(), keyPath.c_str()); + return false; + } + m_identityLoaded = true; + m_backendPort = backendPort; + + addrinfo hints = {}; + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + addrinfo* res = nullptr; + char portStr[16] = {}; + sprintf_s(portStr, "%d", listenPort); + const char* node = (bind.empty() || bind == "0.0.0.0") ? "0.0.0.0" : bind.c_str(); + + if (getaddrinfo(node, portStr, &hints, &res) != 0 || res == nullptr) + { + Mprintf("[McpTls] FATAL: cannot resolve bind address %s\n", node); + ServerTlsFreeIdentity(m_identity); + m_identityLoaded = false; + return false; + } + + SOCKET ls = socket(res->ai_family, res->ai_socktype, res->ai_protocol); + if (ls == INVALID_SOCKET) + { + freeaddrinfo(res); + ServerTlsFreeIdentity(m_identity); + m_identityLoaded = false; + return false; + } + BOOL reuse = TRUE; + setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)); + u_long nb = 1; + ioctlsocket(ls, FIONBIO, &nb); // 非阻塞监听,accept 用 select 驱动 + + if (::bind(ls, res->ai_addr, (int)res->ai_addrlen) != 0 || + listen(ls, SOMAXCONN) != 0) + { + Mprintf("[McpTls] FATAL: bind/listen %s:%d failed (%d)\n", node, listenPort, WSAGetLastError()); + freeaddrinfo(res); + closesocket(ls); + ServerTlsFreeIdentity(m_identity); + m_identityLoaded = false; + return false; + } + freeaddrinfo(res); + + m_listen = ls; + m_running.store(true); + m_acceptThread = std::thread(&McpTlsProxy::AcceptLoop, this); + Mprintf("[McpTls] listening on %s:%d (TLS + plaintext passthrough) -> 127.0.0.1:%d\n", + node, listenPort, backendPort); + return true; +} + +void McpTlsProxy::Stop() +{ + if (!m_running.exchange(false) && m_listen == INVALID_SOCKET && !m_acceptThread.joinable()) + { + // 从未启动或已停止 + if (m_identityLoaded) + { + ServerTlsFreeIdentity(m_identity); + m_identityLoaded = false; + } + return; + } + + SOCKET ls = m_listen; + m_listen = INVALID_SOCKET; + if (ls != INVALID_SOCKET) + { + shutdown(ls, SD_BOTH); // 唤醒阻塞 accept + closesocket(ls); + } + if (m_acceptThread.joinable()) + m_acceptThread.join(); + + std::vector> all; + { + std::lock_guard lk(m_connMtx); + all.swap(m_conns); + } + for (auto& c : all) + { + if (c->done.load()) + continue; // 已自行收尾,句柄可能已关闭,勿再触碰 + SOCKET cl = c->client.load(); + if (cl != INVALID_SOCKET) + shutdown(cl, SD_BOTH); + SOCKET b = c->backend.load(); + if (b != INVALID_SOCKET) + shutdown(b, SD_BOTH); + } + for (auto& c : all) + { + if (c->th.joinable()) + c->th.join(); + } + + if (m_identityLoaded) + { + ServerTlsFreeIdentity(m_identity); + m_identityLoaded = false; + } + Mprintf("[McpTls] stopped\n"); +} + +void McpTlsProxy::SweepFinished() +{ + std::vector> finished; + { + std::lock_guard lk(m_connMtx); + for (auto it = m_conns.begin(); it != m_conns.end();) + { + if ((*it)->done.load()) + { + finished.push_back(*it); + it = m_conns.erase(it); + } + else + { + ++it; + } + } + } + for (auto& c : finished) + { + if (c->th.joinable()) + c->th.join(); + } +} + +void McpTlsProxy::AcceptLoop() +{ + while (m_running.load()) + { + if (!WaitReady(m_listen, true, 500)) + continue; // 超时轮询 m_running,便于 Stop 及时退出 + + SOCKET cs = accept(m_listen, NULL, NULL); + if (cs == INVALID_SOCKET) + { + if (!m_running.load()) + break; + int e = WSAGetLastError(); + if (e == WSAEWOULDBLOCK) + continue; + Mprintf("[McpTls] accept failed (%d); listener stops\n", e); + break; + } + + SweepFinished(); + + std::lock_guard lk(m_connMtx); + if (m_conns.size() >= kMaxConns) + { + closesocket(cs); + continue; + } + u_long nb = 1; + ioctlsocket(cs, FIONBIO, &nb); // 嗅探/泵送全部走 select + + auto c = std::make_shared(); + c->client.store(cs); + m_conns.push_back(c); + c->th = std::thread([this, c]() { ServeConn(c); }); + } +} + +void McpTlsProxy::CloseConn(Conn& c) +{ + SOCKET cl = c.client.exchange(INVALID_SOCKET); + if (cl != INVALID_SOCKET) + { + shutdown(cl, SD_BOTH); + closesocket(cl); + } + SOCKET b = c.backend.exchange(INVALID_SOCKET); + if (b != INVALID_SOCKET) + { + shutdown(b, SD_BOTH); + closesocket(b); + } + c.done.store(true); +} + +void McpTlsProxy::ServeConn(std::shared_ptr sp) +{ + Conn& c = *sp; + SOCKET client = c.client.load(); + + // ---- 1) 首字节嗅探(同设备端口 §5.2):0x16 0x03 = TLS ClientHello ---- + BYTE peek[8] = {}; + int pn = 0; + DWORD start = GetTickCount(); + for (;;) + { + int r = recv(client, (char*)peek, sizeof(peek), MSG_PEEK); + if (r > 0) + { + pn = r; + break; + } + if (r == 0) + { + CloseConn(c); // 对端直接关闭 + return; + } + if (WSAGetLastError() != WSAEWOULDBLOCK) + { + CloseConn(c); + return; + } + if (GetTickCount() - start > kSniffTimeoutMs || !m_running.load()) + { + CloseConn(c); // 连上不说话的,直接断开 + return; + } + WaitReady(client, true, 200); + } + const bool isTls = (peek[0] == 0x16) && (pn < 2 || peek[1] == 0x03); + + // ---- 2) 后端:httplib 只监听 127.0.0.1 的内部端口 ---- + SOCKET backend = ConnectLoopback(m_backendPort); + if (backend == INVALID_SOCKET) + { + Mprintf("[McpTls] backend 127.0.0.1:%d not reachable\n", m_backendPort); + CloseConn(c); + return; + } + c.backend.store(backend); + + // ---- 3) 分流 ---- + if (isTls) + { + // 嗅探用的是 MSG_PEEK(不消费),ClientHello 原样留在内核缓冲里;交多少字节 + // HandshakeWithCred 都能自己补齐,这里直接让它从 socket 读完整首条记录。 + ServerTlsSession sess; + if (!sess.HandshakeWithCred(client, NULL, 0, m_identity.cred)) + { + Mprintf("[McpTls] TLS handshake failed; closing connection\n"); + CloseConn(c); + return; + } + PumpTls(c, sess); + } + else + { + PumpRaw(c); // 本机 http://127.0.0.1:port 的既有用法原样透传 + } + CloseConn(c); +} + +void McpTlsProxy::PumpRaw(Conn& c) +{ + char buf[16384]; + const SOCKET client = c.client.load(); + const SOCKET backend = c.backend.load(); + + for (;;) + { + fd_set rd; + FD_ZERO(&rd); + FD_SET(client, &rd); + FD_SET(backend, &rd); + int n = select(0, &rd, NULL, NULL, NULL); + if (n <= 0) + break; + + if (FD_ISSET(client, &rd)) + { + int r = recv(client, buf, sizeof(buf), 0); + if (r == 0) break; + if (r < 0) + { + if (WSAGetLastError() == WSAEWOULDBLOCK) continue; + break; + } + if (!SendAll(backend, buf, r)) break; + } + if (FD_ISSET(backend, &rd)) + { + int r = recv(backend, buf, sizeof(buf), 0); + if (r == 0) break; + if (r < 0) + { + if (WSAGetLastError() == WSAEWOULDBLOCK) continue; + break; + } + if (!SendAll(client, buf, r)) break; + } + } +} + +void McpTlsProxy::PumpTls(Conn& c, ServerTlsSession& sess) +{ + char buf[16384]; + const SOCKET client = c.client.load(); + const SOCKET backend = c.backend.load(); + std::vector plain; + std::vector wire; + + // 握手阶段已经收到的明文要先送给后端:客户端复用 TLS 会话时会把 ChangeCipherSpec + + // Finished + 首条请求挤在同一批字节里,握手只会消费前两个,请求留在会话缓冲里。 + // 不在这里取走,后端就一个字节也收不到,5s 后按 keep-alive 超时关连接,客户端看到的是 + // “fetch failed (other side closed)”(实测 undici/Node 24 稳定复现)。 + { + std::vector head; + if (sess.Decrypt(NULL, 0, head) < 0) + return; + if (!head.empty() && !SendAll(backend, head.data(), (int)head.size())) + return; + } + + for (;;) + { + fd_set rd; + FD_ZERO(&rd); + FD_SET(client, &rd); + FD_SET(backend, &rd); + int n = select(0, &rd, NULL, NULL, NULL); + if (n <= 0) + break; + + if (FD_ISSET(client, &rd)) + { + int r = recv(client, buf, sizeof(buf), 0); + if (r == 0) break; + if (r < 0) + { + if (WSAGetLastError() == WSAEWOULDBLOCK) continue; + break; + } + plain.clear(); + if (sess.Decrypt((const BYTE*)buf, r, plain) < 0) + break; // 对端 close_notify / 解密失败 + if (!plain.empty() && !SendAll(backend, plain.data(), (int)plain.size())) + break; + } + if (FD_ISSET(backend, &rd)) + { + int r = recv(backend, buf, sizeof(buf), 0); + if (r == 0) break; + if (r < 0) + { + if (WSAGetLastError() == WSAEWOULDBLOCK) continue; + break; + } + wire.clear(); + if (sess.Encrypt((const BYTE*)buf, r, wire) < 0) + break; + if (!wire.empty() && !SendAll(client, wire.data(), (int)wire.size())) + break; + } + } +} diff --git a/server/2015Remote/McpTlsProxy.h b/server/2015Remote/McpTlsProxy.h new file mode 100644 index 0000000..3849f38 --- /dev/null +++ b/server/2015Remote/McpTlsProxy.h @@ -0,0 +1,77 @@ +// McpTlsProxy.h — MCP 端口的 TLS 前端(同端口嗅探:TLS 解密 / 明文直通) +// +// 背景:CMcpServer 用的 httplib::Server 是明文 HTTP。要让 MCP 客户端经公网用 https +// 访问,又不引入 OpenSSL 依赖,这里在 MCP 前面加一层基于 Schannel 的 TLS 前端: +// +// 客户端 → :McpPort(本类)→ 127.0.0.1:<内部端口>(httplib) +// +// 首字节嗅探与设备端口(IOCPServer.cpp §5.2)同一套路:首字节 0x16 且次字节 0x03 +// 视为 TLS ClientHello,走 ServerTlsSession 入站握手;否则按明文原样转发。因此本机 +// 现有的 http://127.0.0.1:6544 用法不需要改动,远端可同时用 https。 +// +// 身份:独立于设备端口的 [tls] 证书(MCP 面向公网客户端,需公共 CA 证书), +// 由 ServerTlsLoadIdentityFromPem 加载,CNG 键名 YamaMcpTlsKey,与设备端口互不覆盖。 +#pragma once + +#include + +#include +#include +#include +#include +#include +#include + +#include "ServerTlsSession.h" + +class ServerTlsSession; + +class McpTlsProxy +{ +public: + McpTlsProxy() {} + ~McpTlsProxy() { Stop(); } + + McpTlsProxy(const McpTlsProxy&) = delete; + McpTlsProxy& operator=(const McpTlsProxy&) = delete; + + // 监听 bind:listenPort,把解密后的字节转发到 127.0.0.1:backendPort。 + // certPath/keyPath 为 PEM(证书 + PKCS#8 私钥)。任一环节失败返回 false(fail-closed)。 + bool Start(const std::string& bind, int listenPort, int backendPort, + const std::string& certPath, const std::string& keyPath); + void Stop(); + + bool IsRunning() const { return m_running.load(); } + +private: + // 单条前端连接:客户端套接字 + 连到 httplib 的后端套接字。 + // Stop() 需要能打断正在 select/recv 的线程,故后端套接字放在原子量里随时可取。 + struct Conn + { + std::atomic client{ INVALID_SOCKET }; + std::atomic backend{ INVALID_SOCKET }; + std::atomic done{ false }; + std::thread th; + }; + + void AcceptLoop(); + void ServeConn(std::shared_ptr c); + void PumpRaw(Conn& c); + void PumpTls(Conn& c, ServerTlsSession& sess); + void SweepFinished(); + void CloseConn(Conn& c); + + static SOCKET ConnectLoopback(int port); + static bool WaitReady(SOCKET sock, bool forRead, int timeoutMs); + static bool SendAll(SOCKET sock, const void* data, int len); + + SOCKET m_listen = INVALID_SOCKET; + std::thread m_acceptThread; + std::atomic m_running{ false }; + int m_backendPort = 0; + ServerTlsExtraIdentity m_identity; + bool m_identityLoaded = false; + + std::mutex m_connMtx; + std::vector> m_conns; +}; diff --git a/server/2015Remote/ServerTlsSession.cpp b/server/2015Remote/ServerTlsSession.cpp index b09e230..34eb013 100644 --- a/server/2015Remote/ServerTlsSession.cpp +++ b/server/2015Remote/ServerTlsSession.cpp @@ -75,6 +75,31 @@ KeyFmt DetectKeyFormat(const std::string& keyPem) return KF_PKCS1; return KF_UNKNOWN; } + +// 证书文件里可能有多个 PEM 块(fullchain:叶证书 + 中间证书)。逐块切出来解码, +// 顺序即文件顺序。单证书文件也走这里(返回 1 块)。 +std::vector> PemToDerList(const std::string& pem) +{ + static const std::string kBegin = "-----BEGIN CERTIFICATE-----"; + static const std::string kEnd = "-----END CERTIFICATE-----"; + std::vector> out; + size_t pos = 0; + while (true) + { + size_t b = pem.find(kBegin, pos); + if (b == std::string::npos) + break; + size_t e = pem.find(kEnd, b); + if (e == std::string::npos) + break; + e += kEnd.size(); + std::vector der; + if (PemToDer(pem.substr(b, e - b), der) && !der.empty()) + out.push_back(std::move(der)); + pos = e; + } + return out; +} } // ===================================================================================== @@ -143,7 +168,35 @@ bool ServerTlsIdentity::Load(config& cfg) return true; } -bool ServerTlsIdentity::LoadIdentity(const std::string& certPath, const std::string& keyPath) +namespace +{ +// 用证书上下文换入站凭据:显式指定服务端证书,不请求客户端证书(单向 TLS)。 +// 单独成函数,因为 EC 键的几种绑定方式都要靠「凭据能否建立」来验证。 +SECURITY_STATUS AcquireInboundCredFor(PCCERT_CONTEXT cert, CredHandle& cred) +{ + SCHANNEL_CRED sc = {}; + sc.dwVersion = SCHANNEL_CRED_VERSION; + sc.cCreds = 1; + sc.paCred = &cert; + sc.grbitEnabledProtocols = SP_PROT_TLS1_2_SERVER; + // NO_DEFAULT_CREDS 避免回退到系统默认凭据,确保只用我们提供的证书/私钥。 + //(单向 TLS 不请求客户端证书,故无需 SCH_CRED_MANUAL_CRED_VALIDATION。) + sc.dwFlags = SCH_CRED_NO_DEFAULT_CREDS; + + cred = {}; + TimeStamp tsExpiry = {}; + return AcquireCredentialsHandleA( + NULL, (SEC_CHAR*)"Microsoft Unified Security Protocol Provider", SECPKG_CRED_INBOUND, + NULL, &sc, NULL, NULL, &cred, &tsExpiry); +} + +// 按给定 PEM(证书链 + PKCS#8 私钥)与 CNG 持久化键名构造一份入站身份。 +// 设备端口(ServerTlsIdentity,键名 YamaServerTlsKey)与 MCP 前端(独立键名)共用这段 +// 逻辑;键名不同则两份身份可并存,互不覆盖。 +// 成功时 outCred / outCert / outKey 均有效,生命周期由调用方释放。 +bool BuildIdentity(const std::string& certPath, const std::string& keyPath, + const wchar_t* keyName, + CredHandle& outCred, PCCERT_CONTEXT& outCert, NCRYPT_KEY_HANDLE& outKey) { std::string certPem, keyPem; if (!ReadFileText(certPath, certPem)) @@ -157,28 +210,100 @@ bool ServerTlsIdentity::LoadIdentity(const std::string& certPath, const std::str return false; } - // 1) 证书:PEM → DER → PCCERT_CONTEXT。 - std::vector certDer; - if (!PemToDer(certPem, certDer)) + // 1) 证书:PEM → DER → PCCERT_CONTEXT(第一块为叶证书)。 + std::vector> certDers = PemToDerList(certPem); + if (certDers.empty()) { Mprintf("[TLS] FATAL: cert file %s is not a valid PEM\n", certPath.c_str()); return false; } PCCERT_CONTEXT cert = CertCreateCertificateContext(X509_ASN_ENCODING, - certDer.data(), (DWORD)certDer.size()); + certDers[0].data(), (DWORD)certDers[0].size()); if (cert == NULL) { Mprintf("[TLS] FATAL: CertCreateCertificateContext failed (%u)\n", GetLastError()); return false; } + // fullchain 里剩下的中间证书要补进「当前用户\中间证书颁发机构」库里:Schannel 的 + // 握手在进程外完成,建链时只查系统证书库——塞进叶证书自带的内存库或 paCred 数组都 + // 不会被下发(实测只发叶证书,缺中间证书的客户端建链失败)。补进库里之后 Schannel + // 会随握手把整条链下发,这与 .NET SslStreamCertificateContext 的做法一致。 + // 已经是公开信息,留在库里无害;已在库中则跳过。 + for (size_t i = 1; i < certDers.size(); ++i) + { + PCCERT_CONTEXT chainCert = CertCreateCertificateContext( + X509_ASN_ENCODING, certDers[i].data(), (DWORD)certDers[i].size()); + if (chainCert == NULL) + { + Mprintf("[TLS] WARN: chain cert #%u in %s is unreadable (%u); " + "handshake will only send the certificates already in the store\n", + (unsigned)i, certPath.c_str(), GetLastError()); + continue; + } + static HCERTSTORE s_caStore = NULL; // 进程级;关掉反而让 Schannel 后续取不到 + if (s_caStore == NULL) + s_caStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, 0, + CERT_SYSTEM_STORE_CURRENT_USER, L"CA"); + bool inStore = s_caStore != NULL && + CertFindCertificateInStore(s_caStore, X509_ASN_ENCODING, 0, + CERT_FIND_EXISTING, chainCert, NULL) != NULL; + if (!inStore && + (s_caStore == NULL || + !CertAddEncodedCertificateToStore(s_caStore, X509_ASN_ENCODING, + certDers[i].data(), (DWORD)certDers[i].size(), + CERT_STORE_ADD_USE_EXISTING, NULL))) + { + Mprintf("[TLS] WARN: cannot add chain cert #%u from %s to the user CA store (%u); " + "handshake may not send the full chain\n", + (unsigned)i, certPath.c_str(), GetLastError()); + } + CertFreeCertificateContext(chainCert); + } // 2) 私钥:PEM → DER → 持久化到 CNG KSP(仅支持 PKCS#8;PKCS#1 给出可操作的转换提示)。 // // 关键:Schannel 入站凭据(AcquireCredentialsHandle)需要「能按名重开」的持久化私钥。 - // NCryptImportKey 产出的是匿名临时键,绑定 CERT_NCRYPT_KEY_HANDLE_PROP_ID 后 Schannel 仍 - // 拿不到(AcquireCredentialsHandle 返回 SEC_E_NO_CREDENTIALS 0x8009030e)。因此先把 - // PKCS#8 导入为临时键、导出为裸 RSA 私钥 BLOB(NCryptSetProperty 只认裸 BLOB,不认 - // PKCS#8),再写入持久化键并 finalize,最后用 CERT_KEY_PROV_INFO_PROP_ID 按名引用。 + // 匿名临时键不行:绑定 CERT_NCRYPT_KEY_HANDLE_PROP_ID 或 CERT_KEY_CONTEXT_PROP_ID + // 后 Schannel 仍拿不到(AcquireCredentialsHandle 返回 SEC_E_NO_CREDENTIALS 0x8009030e)。 + // 最后由 CERT_KEY_PROV_INFO_PROP_ID 按名引用持久化键。 + // + // 私钥类型沿用证书公钥类型(早期版本写死 RSA,对 Let's Encrypt 现默认的 ECDSA 证书 + // 导裸 BLOB 会拿 NTE_BAD_TYPE 0x8009000a,必须按 EC BLOB 导出)。判断用证书而不是 + // NCryptGetProperty(BCRYPT_ALGORITHM_NAME):导入的临时键不支持该属性(实测 + // NTE_NOT_SUPPORTED 0x80090029);且私钥本就该与证书匹配。 + const char* certKeyOid = cert->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId; + const bool certKeyIsRsa = certKeyOid && strcmp(certKeyOid, szOID_RSA_RSA) == 0; + const bool certKeyIsEc = certKeyOid && strcmp(certKeyOid, szOID_ECC_PUBLIC_KEY) == 0; + if (!certKeyIsRsa && !certKeyIsEc) + { + Mprintf("[TLS] FATAL: cert %s uses unsupported public key type (%s); " + "RSA and ECDSA (P-256/P-384/P-521) are supported\n", + certPath.c_str(), certKeyOid ? certKeyOid : "unknown"); + CertFreeCertificateContext(cert); + return false; + } + + // ECDSA 只支持具名曲线:曲线在证书公钥参数里是 DER 编码的曲线 OID,先核对一遍, + // 好给出比 KSP 报错更清楚的提示(显式参数形式的曲线 KSP 也不吃)。 + if (certKeyIsEc) + { + static const BYTE kP256[] = { 0x06,0x08,0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x07 }; + static const BYTE kP384[] = { 0x06,0x05,0x2B,0x81,0x04,0x00,0x22 }; + static const BYTE kP521[] = { 0x06,0x05,0x2B,0x81,0x04,0x00,0x23 }; + const CRYPT_OBJID_BLOB& parm = cert->pCertInfo->SubjectPublicKeyInfo.Algorithm.Parameters; + auto isCurve = [&](const BYTE* der, DWORD len) { + return parm.cbData == len && parm.pbData && memcmp(parm.pbData, der, len) == 0; + }; + if (!isCurve(kP256, sizeof(kP256)) && !isCurve(kP384, sizeof(kP384)) && + !isCurve(kP521, sizeof(kP521))) + { + Mprintf("[TLS] FATAL: cert %s uses an ECDSA curve other than P-256/P-384/P-521 " + "(or explicit curve parameters); convert it to an RSA or named-curve key\n", + certPath.c_str()); + CertFreeCertificateContext(cert); + return false; + } + } std::vector keyDer; NCRYPT_KEY_HANDLE persistedKey = 0; if (DetectKeyFormat(keyPem) == KF_PKCS8) @@ -201,37 +326,67 @@ bool ServerTlsIdentity::LoadIdentity(const std::string& certPath, const std::str return false; } - // 2a) PKCS#8 → 临时键。 - NCRYPT_KEY_HANDLE tmp = 0; - st = NCryptImportKey(hProv, NULL, NCRYPT_PKCS8_PRIVATE_KEY_BLOB, NULL, - &tmp, keyDer.data(), (DWORD)keyDer.size(), 0); - if (st == ERROR_SUCCESS) + // EC 与 RSA 的落盘路径不同: + // - EC:MS Software KSP 唯一支持的「导入私钥并落盘」方式,是在导入参数表里给出 + // 键名(NCRYPTBUFFER_PKCS_KEY_NAME)——不带键名一律按匿名临时键处理。同为导入 + // 后的持久化,CreatePersistedKey 后写私钥 BLOB 虽然 SetProperty 返回 0,Finalize + // 却给 NTE_INVALID_PARAMETER(0x80090027);导入后再 + // NCryptSetProperty(NCRYPT_NAME_PROPERTY) 给 NTE_NOT_SUPPORTED(0x80090029)。 + // - RSA:导入为临时键 → 导出裸私钥 BLOB(NCryptSetProperty 只认裸 BLOB,不认 + // PKCS#8)→ 写入持久化键 → finalize。 + if (certKeyIsEc) { - // 2b) 允许明文导出,导出为裸 RSA 私钥 BLOB。 - DWORD policy = NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG | NCRYPT_ALLOW_EXPORT_FLAG; - NCryptSetProperty(tmp, NCRYPT_EXPORT_POLICY_PROPERTY, (PBYTE)&policy, sizeof(policy), 0); + std::wstring nameW(keyName); + NCryptBuffer nameBuf = {}; + nameBuf.cbBuffer = (ULONG)((nameW.size() + 1) * sizeof(WCHAR)); + nameBuf.BufferType = NCRYPTBUFFER_PKCS_KEY_NAME; + nameBuf.pvBuffer = (PVOID)nameW.c_str(); + NCryptBufferDesc desc = {}; + desc.ulVersion = NCRYPTBUFFER_VERSION; + desc.cBuffers = 1; + desc.pBuffers = &nameBuf; - std::vector raw; - DWORD rawLen = 0; - st = NCryptExportKey(tmp, NULL, BCRYPT_RSAFULLPRIVATE_BLOB, NULL, NULL, 0, &rawLen, 0); + st = NCryptImportKey(hProv, NULL, NCRYPT_PKCS8_PRIVATE_KEY_BLOB, &desc, + &persistedKey, keyDer.data(), (DWORD)keyDer.size(), + NCRYPT_OVERWRITE_KEY_FLAG); + } + else + { + NCRYPT_KEY_HANDLE tmp = 0; + st = NCryptImportKey(hProv, NULL, NCRYPT_PKCS8_PRIVATE_KEY_BLOB, NULL, + &tmp, keyDer.data(), (DWORD)keyDer.size(), 0); if (st == ERROR_SUCCESS) { - raw.resize(rawLen); + DWORD policy = NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG | NCRYPT_ALLOW_EXPORT_FLAG; + NCryptSetProperty(tmp, NCRYPT_EXPORT_POLICY_PROPERTY, + (PBYTE)&policy, sizeof(policy), 0); + + std::vector raw; + DWORD rawLen = 0; st = NCryptExportKey(tmp, NULL, BCRYPT_RSAFULLPRIVATE_BLOB, NULL, - raw.data(), rawLen, &rawLen, 0); + NULL, 0, &rawLen, 0); + if (st == ERROR_SUCCESS) + { + raw.resize(rawLen); + st = NCryptExportKey(tmp, NULL, BCRYPT_RSAFULLPRIVATE_BLOB, NULL, + raw.data(), rawLen, &rawLen, 0); + } + if (st == ERROR_SUCCESS) + { + st = NCryptCreatePersistedKey(hProv, &persistedKey, BCRYPT_RSA_ALGORITHM, + keyName, AT_KEYEXCHANGE, + NCRYPT_OVERWRITE_KEY_FLAG); + } + if (st == ERROR_SUCCESS) + { + st = NCryptSetProperty(persistedKey, BCRYPT_RSAFULLPRIVATE_BLOB, + raw.data(), (DWORD)raw.size(), 0); + } + if (st == ERROR_SUCCESS) + st = NCryptFinalizeKey(persistedKey, 0); + + NCryptFreeObject(tmp); } - - // 2c) 写入持久化键并 finalize(落到 KSP,可被 Schannel 按名重开)。 - if (st == ERROR_SUCCESS) - st = NCryptCreatePersistedKey(hProv, &persistedKey, BCRYPT_RSA_ALGORITHM, - g_keyName, AT_KEYEXCHANGE, NCRYPT_OVERWRITE_KEY_FLAG); - if (st == ERROR_SUCCESS) - st = NCryptSetProperty(persistedKey, BCRYPT_RSAFULLPRIVATE_BLOB, - raw.data(), (DWORD)raw.size(), 0); - if (st == ERROR_SUCCESS) - st = NCryptFinalizeKey(persistedKey, 0); - - NCryptFreeObject(tmp); } NCryptFreeObject(hProv); @@ -257,54 +412,55 @@ bool ServerTlsIdentity::LoadIdentity(const std::string& certPath, const std::str // 3) 绑定私钥到证书上下文:按名引用持久化键。Schannel 经 CryptAcquireCertificatePrivateKey // 在 MS_KEY_STORAGE_PROVIDER 里用 pwszContainerName 重开该键。 + // 4) 换入站凭据(单向 TLS,不请求客户端证书)。 CRYPT_KEY_PROV_INFO provInfo = {}; - provInfo.pwszContainerName = (LPWSTR)g_keyName; + provInfo.pwszContainerName = (LPWSTR)keyName; provInfo.pwszProvName = (LPWSTR)MS_KEY_STORAGE_PROVIDER; provInfo.dwProvType = 0; // 0 = CNG(无 CAPI provider type) - provInfo.dwKeySpec = AT_KEYEXCHANGE; + provInfo.dwKeySpec = certKeyIsEc ? 0 : AT_KEYEXCHANGE; // ECDSA 键无 legacy key spec + + CredHandle cred = {}; + SECURITY_STATUS st = SEC_E_NO_CREDENTIALS; if (!CertSetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID, 0, &provInfo)) { + st = (SECURITY_STATUS)HRESULT_FROM_WIN32(GetLastError()); Mprintf("[TLS] FATAL: CertSetCertificateContextProperty(CERT_KEY_PROV_INFO_PROP_ID) " - "failed (%u)\n", GetLastError()); - NCryptDeleteKey(persistedKey, 0); // 删除并释放句柄 - CertFreeCertificateContext(cert); - return false; + "failed 0x%08x\n", (unsigned)st); + } + else + { + st = AcquireInboundCredFor(cert, cred); } - // 绑定后持久化键句柄交进程级 g_persistedKey,随 FreeIdentity 删除(覆盖旧键,避免残留)。 - g_persistedKey = persistedKey; - - // 4) 入站凭据:显式指定服务端证书,不请求客户端证书(单向 TLS)。 - SCHANNEL_CRED sc = {}; - sc.dwVersion = SCHANNEL_CRED_VERSION; - sc.cCreds = 1; - sc.paCred = &cert; - sc.grbitEnabledProtocols = SP_PROT_TLS1_2_SERVER; - // NO_DEFAULT_CREDS 避免回退到系统默认凭据,确保只用我们提供的证书/私钥。 - //(单向 TLS 不请求客户端证书,故无需 SCH_CRED_MANUAL_CRED_VALIDATION。) - sc.dwFlags = SCH_CRED_NO_DEFAULT_CREDS; - - TimeStamp tsExpiry = {}; - SECURITY_STATUS st = AcquireCredentialsHandleA( - NULL, (SEC_CHAR*)"Microsoft Unified Security Protocol Provider", SECPKG_CRED_INBOUND, - NULL, &sc, NULL, NULL, &g_cred, &tsExpiry); if (st != SEC_E_OK) { Mprintf("[TLS] FATAL: AcquireCredentialsHandle(SECPKG_CRED_INBOUND) failed 0x%08x\n", (unsigned)st); CertFreeCertificateContext(cert); // 无凭据引用,安全释放 - g_cred = {}; - if (g_persistedKey) // 回滚:删除已持久化的私钥,避免残留 - { - NCryptDeleteKey(g_persistedKey, 0); // 删除并释放句柄 - g_persistedKey = 0; - } + NCryptDeleteKey(persistedKey, 0); // 回滚:删除已持久化的私钥,避免残留 return false; } + outCert = cert; + outKey = persistedKey; + outCred = cred; + return true; +} +} // namespace + +bool ServerTlsIdentity::LoadIdentity(const std::string& certPath, const std::string& keyPath) +{ + CredHandle cred = {}; + PCCERT_CONTEXT cert = NULL; + NCRYPT_KEY_HANDLE key = 0; + if (!BuildIdentity(certPath, keyPath, g_keyName, cred, cert, key)) + return false; + // 成功:把证书上下文生命周期交给进程级 g_cert,随 FreeIdentity 释放, // 保证在 FreeCredentialsHandle 之前私钥一直可用。 + g_cred = cred; g_cert = cert; + g_persistedKey = key; g_credValid = true; return true; } @@ -385,25 +541,89 @@ bool ServerTlsSession::SendAll(SOCKET sock, const void* data, int len) } bool ServerTlsSession::Handshake(SOCKET sock, const BYTE* initial, int initialLen) +{ + return HandshakeWithCred(sock, initial, initialLen, ServerTlsIdentity::Cred()); +} + +bool ServerTlsSession::HandshakeWithCred(SOCKET sock, const BYTE* initial, int initialLen, + CredHandle cred) { std::lock_guard lk(m_mtx); if (m_ctxValid) CloseHandles(); // 防御:会话应只握手一次 - CredHandle cred = ServerTlsIdentity::Cred(); - // 单向 TLS:服务端不请求客户端证书,故无需 ASC_REQ_MANUAL_CRED_VALIDATION //(该标志只在 mTLS 校验客户端证书时有意义;SDK 的 ASC 命名空间里亦无此常量)。 DWORD req = ASC_REQ_SEQUENCE_DETECT | ASC_REQ_REPLAY_DETECT | ASC_REQ_CONFIDENTIALITY | ASC_REQ_ALLOCATE_MEMORY | ASC_REQ_STREAM; - std::vector hs(initial, initial + initialLen); + std::vector hs; + if (initial != NULL && initialLen > 0) + hs.assign(initial, initial + initialLen); CtxtHandle ctx = {}; bool ctxValid = false; TimeStamp tsExpiry = {}; ULONG attrs = 0; SECURITY_STATUS sc = SEC_I_CONTINUE_NEEDED; + // 握手期间同步收字节:非阻塞套接字上等可读再收,避免误判为致命错误。 + auto RecvMore = [&](std::vector& buf) -> bool + { + char raw[8192]; + int r; + for (;;) + { + r = recv(sock, raw, sizeof(raw), 0); + if (r == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK) + { + if (!WaitSocketReady(sock, true, 15000)) + { + r = SOCKET_ERROR; + break; // 等可读超时 + } + continue; + } + break; + } + if (r <= 0) + { + Mprintf("[TLS] handshake recv failed/EOF (r=%d err=%d)\n", r, WSAGetLastError()); + return false; + } + buf.insert(buf.end(), (BYTE*)raw, (BYTE*)raw + r); + return true; + }; + + // 首次 AcceptSecurityContext 之前必须凑齐一整条 TLS 记录(5 字节头 + 负载)。 + // 实测(2026-10-26):用「半条 ClientHello」做首次调用,Schannel 会建出一个坏上下文, + // 之后补齐数据再送返回 SEC_E_UNKNOWN_CREDENTIALS(0x80090301),握手必失败。设备端口 + // 一直整包到达所以没暴露;MCP TLS 前端按 8 字节嗅探后接手,稳定触发。故在此统一兜底: + // 调用方给多少都行,缺的字节由本函数从 socket 补齐。 + for (;;) + { + if (hs.size() < 5) + { + if (!RecvMore(hs)) + return false; + continue; + } + if (hs[0] != 0x16) + { + Mprintf("[TLS] handshake: first byte 0x%02x is not a handshake record; fail-closed\n", hs[0]); + return false; + } + const size_t recLen = 5 + (((size_t)hs[3] << 8) | (size_t)hs[4]); + if (recLen > 18432) // TLS 记录上限 16384 + 允许的额外开销 + { + Mprintf("[TLS] handshake: absurd record length %u; fail-closed\n", (unsigned)recLen); + return false; + } + if (hs.size() >= recLen) + break; + if (!RecvMore(hs)) + return false; + } + for (;;) { SecBuffer inBufs[2] = { @@ -454,29 +674,11 @@ bool ServerTlsSession::Handshake(SOCKET sock, const BYTE* initial, int initialLe break; // 真正的失败 } - char raw[8192]; - int r; - for (;;) + if (!RecvMore(hs)) { - r = recv(sock, raw, sizeof(raw), 0); - if (r == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK) - { - if (!WaitSocketReady(sock, true, 15000)) - { - r = SOCKET_ERROR; - break; // 等可读超时 - } - continue; // 非阻塞套接字暂无数据:等可读后重试 - } - break; - } - if (r <= 0) - { - Mprintf("[TLS] handshake recv failed/EOF (r=%d err=%d)\n", r, WSAGetLastError()); sc = SEC_E_INTERNAL_ERROR; break; } - hs.insert(hs.end(), (BYTE*)raw, (BYTE*)raw + r); } if (sc != SEC_E_OK) @@ -512,11 +714,14 @@ int ServerTlsSession::Decrypt(const BYTE* cipher, int len, std::vector& pl std::lock_guard lk(m_mtx); if (!m_ready) return -1; - if (len <= 0) + // len == 0 表示「只取残留」:握手结束时会话里可能已经躺着紧随 Finished 的首条 + // 应用数据(见 HandshakeWithCred 末尾),调用方必须在进入收发循环前取一次, + // 否则这份数据要等下一条密文到达才会被解出来。 + if (len > 0) + m_raw.insert(m_raw.end(), cipher, cipher + len); + if (m_raw.empty()) return 0; - m_raw.insert(m_raw.end(), cipher, cipher + len); - for (;;) { SecBuffer bufs[4] = { @@ -602,3 +807,42 @@ void CONTEXT_OBJECT::FreeTls() delete tls; tls = NULL; } + +// ===================================================================================== +// 额外入站身份(MCP 等第二套证书) +// ===================================================================================== + +bool ServerTlsLoadIdentityFromPem(const std::string& certPath, const std::string& keyPath, + const wchar_t* keyName, ServerTlsExtraIdentity& out) +{ + CredHandle cred = {}; + PCCERT_CONTEXT cert = NULL; + NCRYPT_KEY_HANDLE key = 0; + if (!BuildIdentity(certPath, keyPath, keyName, cred, cert, key)) + return false; + + out.cred = cred; + out.cert = cert; + out.key = (ULONG_PTR)key; + return true; +} + +void ServerTlsFreeIdentity(ServerTlsExtraIdentity& id) +{ + // 顺序同 ServerTlsIdentity::FreeIdentity:凭据 → 证书 → 持久化私钥。 + if (id.cred.dwLower || id.cred.dwUpper) + { + FreeCredentialsHandle(&id.cred); + id.cred = {}; + } + if (id.cert) + { + CertFreeCertificateContext(id.cert); + id.cert = NULL; + } + if (id.key) + { + NCryptDeleteKey((NCRYPT_KEY_HANDLE)id.key, 0); + id.key = 0; + } +} diff --git a/server/2015Remote/ServerTlsSession.h b/server/2015Remote/ServerTlsSession.h index 46cabdd..1482680 100644 --- a/server/2015Remote/ServerTlsSession.h +++ b/server/2015Remote/ServerTlsSession.h @@ -54,6 +54,27 @@ private: static bool LoadIdentity(const std::string& certPath, const std::string& keyPath); }; +// ---- 额外入站身份(MCP 等第二套证书)---- +// +// 进程级身份 ServerTlsIdentity 只服务设备端口,证书由 [tls] 指定(通常是自签 +// CN=localhost)。MCP 要暴露给公网客户端,必须用公共 CA 签发的证书,故需要第二份 +// 身份。两者可并存:证书/私钥各自加载,持久化私钥用不同的键名(keyName)分开存放, +// 不会互相覆盖。调用方负责在停止时调用 ServerTlsFreeIdentity。 +struct ServerTlsExtraIdentity +{ + CredHandle cred = {}; // AcquireCredentialsHandle 产出的入站凭据 + PCCERT_CONTEXT cert = NULL; // 凭据按名引用的证书上下文 + ULONG_PTR key = 0; // NCrypt 持久化私钥句柄(NCRYPT_KEY_HANDLE) +}; + +// 从 PEM(证书链 + PKCS#8 私钥)构造一份独立入站身份。keyName 为 CNG 持久化键名, +// 须与其它身份不同(例如 L"YamaServerTlsKey" / L"YamaMcpTlsKey")。 +bool ServerTlsLoadIdentityFromPem(const std::string& certPath, const std::string& keyPath, + const wchar_t* keyName, ServerTlsExtraIdentity& out); + +// 释放 ServerTlsLoadIdentityFromPem 构造的身份(先凭据、再证书、最后删除持久化私钥)。 +void ServerTlsFreeIdentity(ServerTlsExtraIdentity& id); + // ---- 单连接服务端 TLS 会话(握手 + 加解密)---- class ServerTlsSession { @@ -69,7 +90,13 @@ public: // 成功返回 true,失败 false(调用方关闭连接,fail-closed)。 bool Handshake(SOCKET sock, const BYTE* initial, int initialLen); + // 同上,但使用调用方提供的入站凭据(MCP TLS 前端用独立的第二份身份, + // 见 ServerTlsLoadIdentityFromPem)。 + bool HandshakeWithCred(SOCKET sock, const BYTE* initial, int initialLen, CredHandle cred); + // 解密:把本次 WSARecv 收到的密文 cipher[0..len] 喂入,把能解出的明文追加到 plain。 + // len == 0 表示只解出会话里已缓存的密文(握手结束后必须先取一次,否则紧随 Finished + // 到达的首条应用数据会一直躺着,直到客户端再发一包)。 // 返回 0 = 成功(可能无明文);-1 = 错误 / 对端 close_notify(调用方关闭连接)。 int Decrypt(const BYTE* cipher, int len, std::vector& plain); diff --git a/server/2015Remote/lang/en_US.ini b/server/2015Remote/lang/en_US.ini index 3d50fe6..015cd7e 100644 --- a/server/2015Remote/lang/en_US.ini +++ b/server/2015Remote/lang/en_US.ini @@ -2019,6 +2019,10 @@ MCPԶ Զ³̽»̸¿ª¹صĸ͝ÐèÖØÆô³ÌÐòÉúЧ¡£=Changes to the remote chat switch take effect after restart. ÆôÓüüÅ̼Ǽ£¨AI ²ɼ¯»÷¼ü£©=Enable keylogger (AI keystroke capture) ¼üÅ̼Ǽ¿ª¹صĸ͝ÐèÖØÆô³ÌÐòÉúЧ¡£=Changes to the keylogger switch take effect after restart. +ÆôÓà HTTPS£¨±¾¶˿Úͬʱ½ÓÊÜ TLS Á¬½ӣ©=Enable HTTPS (this port also accepts TLS connections) +HTTPS ¿ª¹ØÓë֤Êé·¾¶µĸ͝ÐèÖØÆô³ÌÐòÉúЧ¡£=Changes to the HTTPS switch and certificate paths take effect after restart. +֤Êé»ò˽ԿÎļþ²»´æÔڣ¬Çë¼ì²é·¾¶¡£=Certificate or private key file not found; check the path. +֤ÊéÐëΪ PEM ¸ñʽ£¬˽ԿÐëΪ PKCS#8 ¸ñʽ¡£=Certificate must be PEM; private key must be PKCS#8. Ö÷»ú¹ÜÀíµÄд²Ù×÷Ðèֻ¶Áģʽ¹رգ»¶³½á/½ⶳ½ø³̡¢ֹͣ/ÖØÆô·þÎñ»¹ÐèÆôÓÃΣÏÕÖ÷»ú²Ù×÷¡£=Host management write operations require read-only mode to be off; freezing/thawing processes and stopping/restarting services also require dangerous host operations. µÚ %d ¸öǮ°üµØַ²»ºϷ¨!=Wallet address #%d is invalid! %d ÐÂÁ¬½Ó\r\n=%d New connection\r\n diff --git a/server/2015Remote/lang/zh_TW.ini b/server/2015Remote/lang/zh_TW.ini index b1e938d..0b7fe96 100644 --- a/server/2015Remote/lang/zh_TW.ini +++ b/server/2015Remote/lang/zh_TW.ini @@ -2010,6 +2010,10 @@ MCPԶ Զ³̽»̸¿ª¹صĸ͝ÐèÖØÆô³ÌÐòÉúЧ¡£=ßh¶˽»Մé_êPµÄ׃¸üÐèÖØÐ†¢„ӳÌʽááÉúЧ¡£ ÆôÓüüÅ̼Ǽ£¨AI ²ɼ¯»÷¼ü£©=†¢ÓÃæI±Pӛ䛣¨AI ”Xȡ°´æI£© ¼üÅ̼Ǽ¿ª¹صĸ͝ÐèÖØÆô³ÌÐòÉúЧ¡£=æI±Pӛä›é_êPµĸĄÓÐèÖØÐ†¢„ӳÌʽ·½¿ÉÉúЧ¡£ +ÆôÓà HTTPS£¨±¾¶˿Úͬʱ½ÓÊÜ TLS Á¬½ӣ©=†¢Óà HTTPS£¨±¾ßB½Ӳºͬ•r½ÓÊÜ TLS ßB¾€£© +HTTPS ¿ª¹ØÓë֤Êé·¾¶µĸ͝ÐèÖØÆô³ÌÐòÉúЧ¡£=HTTPS é_êPÅc‘{×C·�½µĸĄÓÐèÖ؆¢³ÌʽÉúЧ¡£ +֤Êé»ò˽ԿÎļþ²»´æÔڣ¬Çë¼ì²é·¾¶¡£=‘{×C»ò˽耙n°¸²»´æÔڣ¬Ո™z²é·�½¡£ +֤ÊéÐëΪ PEM ¸ñʽ£¬˽ԿÐëΪ PKCS#8 ¸ñʽ¡£=‘{×C횞é PEM ¸ñʽ£¬˽è€횞é PKCS#8 ¸ñʽ¡£ Ö÷»ú¹ÜÀíµÄд²Ù×÷Ðèֻ¶Áģʽ¹رգ»¶³½á/½ⶳ½ø³̡¢ֹͣ/ÖØÆô·þÎñ»¹ÐèÆôÓÃΣÏÕÖ÷»ú²Ù×÷¡£=Ö÷™C¹ÜÀíµČ‘Èë²Ù×÷ÐèêPé]Ψ×xģʽ£»ƒö½Y/½âƒö̎Àí³ÌÐò¡¢ֹͣ/ÖØÐ†¢„ӷþ„Õ߀Ð膢ÓÃΣëUÖ÷™C²Ù×÷¡£ µÚ %d ¸öǮ°üµØַ²»ºϷ¨!=µÚ %d ‚€åX°üλַ²»ºϷ¨! %d ÐÂÁ¬½Ó\r\n=%d ÐÂßB¾€\r\n