Feature: Terminate TLS for the MCP endpoint inside YAMA
MCP was served by a plain httplib::Server, so remote clients could only use cleartext HTTP. YAMA now terminates TLS itself: a small front-end owns the MCP port, sniffs the first byte and either runs a Schannel handshake and forwards the decrypted bytes or passes plaintext through, with httplib moving to a loopback-only internal port. No OpenSSL, no frp change, existing local HTTP clients keep working, and an unusable certificate fails closed instead of falling back to cleartext. The identity loader grew the two things a public certificate needs. ECDSA (P-256/P-384/P-521) keys are persisted by importing PKCS#8 with an NCRYPTBUFFER_PKCS_KEY_NAME parameter, the only route MS Software KSP supports for Schannel; RSA keeps its old export-and-repersist path. Fullchains are accepted, and the intermediates are added to the current user's CA store so Schannel, which builds chains only from system stores, actually sends them. The shared handshake also now buffers a full TLS record before the first AcceptSecurityContext, which a partial ClientHello would otherwise poison (SEC_E_UNKNOWN_CREDENTIALS). Session resumption exposed a second trap: when a client resumes a session, ChangeCipherSpec, Finished and the first application record arrive in one segment and AcceptSecurityContext leaves the application record pending in the session. Nothing drained it, because both callers only decrypt when new ciphertext arrives, so the request waited until the peer gave up (the MCP front-end saw no request at all and the client reported "fetch failed (other side closed)"; the device port had the same hole behind its occasional login timeouts). Decrypt now drains pending data on len == 0, and both the front-end and the device port's handshake thread use it before entering their receive loops. Configuration is McpHttps, McpCertPath, McpKeyPath and McpInternalPort, the first three editable in the MCP settings dialog (the certificate rows stay greyed out until HTTPS is enabled and saving rejects missing files). Verified with a real Let's Encrypt ECDSA fullchain (53 tools over TLS, 401 with no or bad token), a local three-level chain whose intermediate was absent from the store, Node 24's fetch on a resumed session (initialize, notifications/initialized and tools/list all complete), and the device port's RSA handshake as a regression check. Details in docs/Mcp_Design.md section 13. Co-Authored-By: deepseek-flash
This commit is contained in:
1 parent
b4cb34fea9
commit
a7dd86ff0f
15 files changed
+1218
-96
No files matched your search
@@ -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 <McpToken>" }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 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 库里会多出这些中间证书(公开信息,留在库里无害)。
|
||||
|
||||
Reference in new issue
Block a user