Fix: Make the MCP command sentinel robust and fail stalled downloads fast
Re-verified every finding of the 2026-10-25 MCP test report against the source and then end-to-end on the Debug instance, and fixed the ones that live on the server. P1/P3/P4 share one root cause: the sentinel was appended to the command line, so any command that swallows the rest of its line (rem, cmd /c, if, for) swallowed the sentinel too and the call always timed out. On ConPTY clients the command and the sentinel are now sent as two lines, the sentinel prints %errorlevel% (whose echoed text is a literal template, not digits) so folding echo can no longer be mistaken for the sentinel, and FindSentinel returns the real exit code (9009, 1, 0, ...) instead of 0/1. Old non-PTY clients keep the single-line form, since their echo skipping depends on the write length. ConPTY also returns a rendered screen stream rather than a byte stream, so stripped VT sequences leave duplicate text behind; output cleaning now cuts through the echoed command line, strips the echoed sentinel line and erases any leftover sentinel text by its per-command nonce. StripAnsi no longer leaves the backslash of an OSC terminated by ST. A terminal session destroyed by a timeout used to report the same "not found" text as a typo in the session id; a 600s tombstone now says what happened instead. download_file gets a stall watchdog: no data for 60s fails with a clear message and releases the host, where a missing remote path used to hold the whole host for the full 600s default timeout. Also corrects the get_activity_history annotation (it does reach the remote host), completes the -32007/-32008/-32009 error table, documents the sentinel design in Mcp_Design.md 12.1, and corrects the report's claim that the tools blocked during a transfer are local DB reads -- they are remote machine-manager fetches, and purely server-local tools are unaffected. Co-Authored-By: deepseek-flash
This commit is contained in:
1 parent
1c5fab1645
commit
eaa10cc7d3
5 files changed
+486
-71
No files matched your search
@@ -665,8 +665,31 @@ token 只从 `-Token` / env 读取,不落仓库、不打印;无在线主机
|
||||
| `-32004` | Send failed | 命令写入主连接失败(连接刚断) | 重试一次;仍失败按 `-32002` 处理 |
|
||||
| `-32005` | Not supported on this host | 需要 Windows 的工具用在 LNX/MAC/APK 主机上 | 换 Windows 主机,或改用跨平台只读工具(`list_files` 等) |
|
||||
| `-32006` | Policy refused | 只读模式 / 对应 `Mcp*` 开关关闭 / 主机不支持该能力(如 V2 文件传输) | **不要重试**:这是配置决定,需管理员改服务端配置 |
|
||||
| `-32007` | Not in command whitelist | `exec_command` 的命令不在 `McpCmdWhitelist` 里,或词边界不匹配(`dir` 过、`dirx` 拒) | **不要重试**:换成白名单内的命令,或请管理员加白名单项 |
|
||||
| `-32008` | Rejected by validation | 同一码覆盖四类语义:`exec_command` 含 shell 元字符 `&\|<>^` 或控制字符(含 `\r\n`);路径/参数含非法字符;老客户端不支持 V2 文件传输格式;`remote_open` 遇到多显示器 | 按 `message` 修正参数;多显示器/老客户端属能力限制,换目标或换主机 |
|
||||
| `-32009` | Target not found | `kill_network_connection` 的四元组在当前连接表里查不到(`dry_run` 传假四元组最常见) | 先用 `host_list_network_state` 取真实四元组再 `dry_run` 校验 |
|
||||
|
||||
- **命令超时会销毁持久会话**(`terminal_exec`):等服务端收集到哨兵超时返回 `-32001`,会话随即被销毁并留 600 秒「墓碑」;对同一 `session_id` 再发命令返回 `-32002`,文案明确写 `Terminal session was destroyed after this command timed out (waited N ms); call terminal_open again`,与「id 写错」(`Terminal session not found: <id>`)区分开。
|
||||
- **`download_file` 有停滞看门狗**:60 秒没收到任何数据(远程路径不存在/不可访问最典型)即失败,返回 `-32001` 且文案带 `File transfer stalled: no data received for 60s ...`,主机立即释放,不必等 `timeout_ms`。真实的大文件传输只要还在持续收数据就不会触发。
|
||||
|
||||
- `-32006` 会额外在审计日志里记一条 `CALL_DENIED`(§10.8),其余错误只体现在 `CALL_FAIL` 行。
|
||||
- 批量调用(带 `ids[]`)**整体不报错**:每个 id 的结果单独带 `error`,顶层用 `succeeded` / `failed` / `skipped` 汇总;只有整批请求本身非法(超过 50 个 id、写操作传 `ids`)才返回顶层 `-32602`。
|
||||
- 冒烟脚本 `tools/mcp_smoke.ps1` 覆盖了上表的可复现项:`-32601`(未知 method)、`-32602`(未知工具/缺参数/51 个 id)、`-32002`(不存在的主机)、`-32006`(任一开关关闭时自动挑一个关着的功能验证,并断言审计里出现 `CALL_DENIED`;全部开启时跳过)。其余码由各批次的功能验证覆盖(`-32001`/`-32003` 等需要构造竞态或超时,不进冒烟)。
|
||||
- 本次验证(Debug 实例,`McpKeylog` 临时置 0):`get_keylog` 返回 `-32006`,`Bin\logs\mcp_audit.log` 末尾出现 `CALL_DENIED ... tool=get_keylog reason=Keyboard log is disabled (McpKeylog=0)`;此时冒烟 34/34 通过。恢复开关后 `-32006` 与审计两条转为跳过,32/32 通过;带 `-SearchPath` 时 37/37 通过。
|
||||
|
||||
### 12.1 命令哨兵与输出清洗(测试报告 P1/P3/P4 的修复)
|
||||
|
||||
`exec_command` 与 `terminal_exec` 都靠哨兵判断「命令已执行完、退出码是多少」。哨兵有两种形态:
|
||||
|
||||
| 客户端 | 下发内容 | 退出码 |
|
||||
|---|---|---|
|
||||
| ConPTY(`is_pty=true`,新版 Windows 客户端) | 第一行 `@echo off & <cmd>`;第二行单独 `echo __MCP_DONE_<nonce>__%errorlevel%` | 命令的真实退出码 |
|
||||
| 老 ShellManager 管道(`is_pty=false`) | 单行 `<cmd> 2>&1 && echo __MCP_DONE_<nonce>__0 || echo __MCP_DONE_<nonce>__1` | 仅 0 / 非 0 |
|
||||
|
||||
**为什么 PTY 要分两行下发**:`rem hello`、`cmd /c exit 0`、`if`、`for` 这类「吞行」命令会把同一行里的 `&& echo 哨兵` 一起吞掉(`rem`/`cmd /c` 把行内剩余文本当作自己的参数),哨兵永不出现,于是必然超时并销毁会话。哨兵独立成行后由 shell 自己执行,不再受命令行影响。老客户端只能维持单行形态:`client/ShellManager.cpp` 按「写入字节数」跳过回显,多写一行会吃掉上一行的输出。
|
||||
|
||||
**为什么用 `%errorlevel%`**:ConPTY 会把输入整行回显进输出流(80 列会折行)。回显文本里是字面 `%errorlevel%` 而不是数字,而 `FindSentinel` 只认「标记 + 数字」,折行回显再也不可能被误判成哨兵(评审 P3:`ver` 曾因回显里的 `__1` 被判成 `exit_code=1`),同时还能拿到真实退出码(如 `nosuchcmd` 的 9009)。
|
||||
|
||||
**输出清洗顺序**:剥 ANSI(OSC 序列以 `ESC\` 结尾时两字节一起吞,否则会残留 `\`)→ CRLF 归一 → 从缓冲区开头删到「我们下发的命令行回显」结束(顺带清掉 shell 启动画面与提示符)→ 删哨兵行回显 → **按 nonce 擦掉残留的哨兵文本** → 去首尾空行。最后一步是必需的:ConPTY 送回来的是**屏幕渲染流**(带光标移动/擦除序列),剥掉序列后同一行可能重复出现,哨兵会留下副本(实测不擦时 `rem hello` 只剩哨兵、`cmd /c echo abc` 成了 `abc__MCP_DONE_x__0`)。nonce 每条命令随机生成,命令的真实输出不可能包含它,所以按 nonce 擦除不会误伤业务输出。
|
||||
|
||||
**已知边界**:屏幕渲染流里「光标下移空行」会被剥成紧邻行(例如 `ping` 的统计块会贴在最后一条回复后面),不影响语义。
|
||||
@@ -0,0 +1,166 @@
|
||||
# YAMA MCP 服务测试报告
|
||||
|
||||
- 日期:2026-10-25(两轮:本机回环 + 虚拟机复测)
|
||||
- 环境:
|
||||
- 第1轮:Debug 服务端 `Yama_x64d.exe` + 本机被控端 `ghost.exe`(Windows 11,双显示器)
|
||||
- 第2轮:同一 Debug 服务端 + VirtualBox 虚拟机被控端(`DESKTOP-A55C0OI`,Windows 10 19045,单显示器 1718x920,clientType=MDLL)+ 重启后的本机被控端
|
||||
- 配置:`Bin\settings.ini`(McpEnabled=1,McpPort=6545,McpBind=127.0.0.1,McpReadonly=0,全部 `Mcp*` 开关开启)
|
||||
- 方法:Python 直连 `http://127.0.0.1:6545/mcp`(JSON-RPC 2.0),辅以 `tools/mcp_smoke.ps1`、审计日志、`get_client_log`、代码审读交叉验证
|
||||
- 敏感操作约束:删除类操作仅针对本次自建的临时文件/目录(本机 `%TEMP%\yama_mcp_test`、VM 同名目录),测试后已全部清理
|
||||
|
||||
---
|
||||
|
||||
## 0. 复核与处置(同日二次复核)
|
||||
|
||||
复核方式:逐条回到源码确认现象与根因,再在 Debug 实例(`Bin\Yama_x64d.exe` + 本机 `ghost.exe`,Windows 11 双屏 ConPTY 客户端)上端到端复现与验证修复。复核用的客户端配置临时改为直连本机(`x64\Debug\settings.ini`:`master=127.0.0.1`、`ghost=6543`、`UseFrp=0`,原文件备份为 `settings.ini.bak_mcptest`);修复后在 Debug 实例上 `tools/mcp_smoke.ps1 -SearchPath C:\Windows\Fonts` **37/37 通过**。
|
||||
|
||||
| 编号 | 复核结论 | 处置 | 验证证据(修复后实测) |
|
||||
|---|---|---|---|
|
||||
| P1 | 属实 | **已修**。ConPTY 下哨兵改为独立一行(`@echo off & <cmd>` + 单独 `echo __MCP_DONE_<nonce>__%errorlevel%`);会话因超时被销毁后留 600s 墓碑,报错文案区分「被销毁」与「id 写错」。老客户端(非 PTY)保持单行 `&&` 形态,行为不变。 | `rem hello` → exit 0(原 100% 超时);`cmd /c exit 0` → exit 0;`cmd /c echo abc` → `abc`。超时路径:`ping -n 40` 配 `timeout_ms=3000` → `-32001`,随后同一 session → `-32002 "Terminal session was destroyed after this command timed out (waited 3000 ms); call terminal_open again"`;假 id → `-32002 "Terminal session not found: <id> (call terminal_open first)"`;销毁后 `terminal_open` 立即成功 |
|
||||
| P2 | 属实(结论成立),但「10 个纯本地 DB 读取」的**表述有误**——被挡的是经主连接向目标机取数据的远程机器管理工具(`host_list_processes/windows/network_state/scheduled_tasks/services/…`、`host_get_hosts_file` 等,都走 `BeginPending`),属 single-flight 设计;纯服务端本地工具(`get_server_status`、`get_audit_log`、`host_set_remark` 等)不受影响 | **已修**(选了「快速失败」):文件传输加 60s 停滞看门狗,`timeout_ms` 内只要持续有数据就不受影响;默认超时保持 600s(避免误杀大文件)。互斥豁免未做——远程工具之间互斥本身就是有意的。 | 不存在路径 `C:/no_such_dir_zzz_mcp` → **60096ms** 失败,`-32001 "File transfer stalled: no data received for 60s (the remote path is probably missing or inaccessible; verify it with list_files first)"`(原为 `ms=600004`);挂起期间 `get_server_status` 2120ms OK、`get_audit_log` 20ms OK,远程 `list_files` 仍 `-32003`;失败后主机立刻释放,冒烟脚本随即 37/37 通过 |
|
||||
| P3 | 属实 | **已修**。`%errorlevel%` 在回显文本里是字面模板而非数字,`FindSentinel` 改为「从后往前找第一个『标记+数字』」,不再依赖行首。 | `ver` → exit 0(原 1);`nosuchcmd_zzz` → 9009;`cmd /c exit 0` → 0;`set NOVAR` → 1 |
|
||||
| P4 | 属实 | **已修**。清洗改为三段:删到「命令行回显」结束(顺带清掉 shell 启动画面/提示符)→ 删哨兵行回显 → 按 nonce 擦掉渲染残留的哨兵文本;另修 `StripAnsi` 对 `OSC…ESC\` 的收尾(会残留 `\`)。设计见 `docs/Mcp_Design.md` §12.1。 | 上述命令的 stdout 全部无 `@echo off`、无 `__MCP_DONE_*`、无提示符/空行;`type` 报错文本无残留反斜杠 |
|
||||
| P5 | 属实 | **已修**(`McpInternal.cpp` 注解表 `get_activity_history` → `openWorld=true`,附代码注释说明它经 `COMMAND_QUERY_ACTIVITY` 触达远程主机) | 代码审查 + 与 §10.2 口径一致 |
|
||||
| P6 | 属实(`OpenSCManager` 权限不足,客户端失败分支回普通消息包) | **暂搁置**:修它要改客户端(回传带失败标记的 `TOKEN_SERVERLIST`),按「暂不动客户端」原则留待后续批次;服务端当前只能报超时 | 第2轮 VM(提权)成功、第1轮非提权 3/3 超时,反证根因 |
|
||||
| P7 | 属实 | **已修**(文档):`docs/Mcp_Design.md` §12 补齐 `-32007`/`-32008`/`-32009` 并注明 `-32008` 的四类语义 | 文档核对 |
|
||||
| P8 | 属实 | **暂搁置**:服务端收到的响应与「空目录/空键」完全一致,无法区分;需客户端回报错误码,属客户端改动 | 代码审查(两条路径都只搬运客户端结果) |
|
||||
|
||||
**结论**:报告的问题清单与根因分析全部成立(仅 P2 有一处表述需要更正);P1/P3/P4(同一处哨兵机制)与 P5/P7、P2 的「长时间锁定」已在服务端修复并端到端验证,P6/P8 需要客户端配合,按既定原则搁置。
|
||||
|
||||
---
|
||||
|
||||
53 个工具全部可达,冒烟脚本 32/32 通过。功能面整体质量良好;VM 复测轮验证了第1轮受条件所限未能覆盖的远程控制族(11/11)、跨机文件往返、真实 kill 目标校验,并把第1轮两大疑难问题(exec_command 超时、list_services 超时)推进到根因定性。
|
||||
|
||||
最终问题清单:**2 个高优先级**(哨兵机制对吞行命令必然超时并销毁会话;download_file 失败路径长时间锁定主机)、**3 个中优先级**(exit_code 不可靠、stdout 内部实现泄漏、get_activity_history 注解错误)、**3 个低优先级**(list_services 权限失败无解释、错误码缺漏/-32008 复用、路径类工具静默空结果)。每条问题的逐条复核结论、处置与修复后实测证据见 §0。
|
||||
|
||||
## 2. 问题清单
|
||||
|
||||
### P1(高):哨兵机制——「吞行」命令 100% 超时,且销毁持久会话
|
||||
|
||||
哨兵方案:发送 `@echo off & <cmd> 2>&1 && echo __MCP_DONE_<nonce>__0 || echo __MCP_DONE_<nonce>__1`,服务端扫描输出定位哨兵取退出码(`McpServer.cpp:2721/3027` 发送、`FindSentinel :6195` 匹配)。
|
||||
|
||||
缺陷:**任何会消费行内剩余文本的命令都会把哨兵一起「吞掉」**,导致哨兵永远不出现:
|
||||
|
||||
| 命令 | 结果 | 机制 |
|
||||
|---|---|---|
|
||||
| `rem hello` | 超时 | `rem` 把整行剩余部分当注释,`&& echo 哨兵` 不执行 |
|
||||
| `cmd /c exit 0` | 超时(2/2 会话复现) | `cmd /c` 把 `&& echo 哨兵` 一并传给子进程,子进程 `exit` 即退 |
|
||||
| `if`/`for` 同理 | 预期同 | 同类吞行语句 |
|
||||
|
||||
后果链:20s 等待 → `-32001 Timeout waiting for command output`;**持久终端路径上 `WaitTermCommand` 超时直接销毁会话**(`McpServer.cpp:6400` 附近),后续所有 `terminal_exec` 报 `-32002 "Terminal session not found, not ready, or busy"`——报错文案无法区分「会话已被超时销毁」与「id 写错」。
|
||||
|
||||
- 正常对照:`whoami` 35/35 成功(62-217ms)、`set NOVAR`(失败有哨兵)正确返回 exit=1、`cmd /c echo abc`/`cmd /c ver`(子进程有输出)成功。
|
||||
- 建议:
|
||||
1. 哨兵改为独立行下发(先发命令行,再单独发 `echo __MCP_DONE_...__0 || echo ...` 第二行,或用 `(%cmd%) & (echo sentinel)` 子shell包裹);
|
||||
2. 会话被超时销毁后,`terminal_exec` 对该 session_id 返回专门的错误文案(如 "session destroyed after timeout; re-open");
|
||||
3. 文档标注 `exec_command`/`terminal_exec` 不支持 `rem`、`cmd /c` 等吞行命令。
|
||||
|
||||
**复核(2026-10-25)**:属实。已按建议 1、2 修复并验证(PTY 下哨兵独立成行;超时销毁会话留墓碑 + 专用文案),文档见 `docs/Mcp_Design.md` §12.1。老客户端(非 PTY)仍为单行形态,故「吞行命令」限制只适用于老客户端。
|
||||
|
||||
### P2(高):`download_file` 对不存在路径无快速失败,默认 600 秒锁定整台主机
|
||||
|
||||
- 不存在的远程路径会等满默认 `timeout_ms=600000`(实测审计日志 `ms=600004`),期间该主机**所有**远程机器管理工具 `-32003`(single-flight 跨工具互斥),含 `host_list_processes/windows/network_state/scheduled_tasks/services`、`host_get_hosts_file` 等**经主连接向目标机取数据**的工具。一次误路径 = 10 分钟整机不可管理。(初版报告把这批工具写成「10 个纯本地 DB 读取」,属表述错误:它们都要触达目标主机,被互斥挡住是设计;纯服务端本地工具如 `get_server_status` / `get_audit_log` / `host_set_remark` 不受影响,二次复核已实测确认。)
|
||||
- **timeout_ms 参数本身工作正常**(显式 8000 → 实测 8031ms 终止),问题是默认值过长 + 缺路径检测。
|
||||
- 建议任选:客户端枚举路径时快速失败(最优);或下调默认超时(如 60s);或本地读取类工具豁免 BeginPending 互斥。
|
||||
|
||||
### P3(中):`exit_code` 不可靠(哨兵匹配到回显模板)
|
||||
|
||||
- `ver`(成功命令)返回 `exit_code=1`。根因:ConPTY 80 列回显折行使**回显的命令模板**中 `|| echo __MCP_DONE_<nonce>__1` 片段落到行首,`FindSentinel`(`McpServer.cpp:6195`)要求哨兵前是 `\n`/`\r`,于是 rfind 命中的是回显片段而非真实执行的哨兵。
|
||||
- 影响:依赖 exit_code 的自动化会把成功当失败。与 P1 同根(哨兵与回显混在同一输出流)。
|
||||
- 建议:随 P1 一起修(独立行哨兵可同时解决);短期可在 FindSentinel 中排除与已发送命令行重叠的匹配位置。
|
||||
|
||||
**复核(2026-10-25)**:属实。已随 P1 修复:`%errorlevel%` 回显是字面模板、`FindSentinel` 改为从后往前找「标记+数字」,实测 `ver`→0、`nosuchcmd_zzz`→9009。
|
||||
|
||||
### P4(中):`stdout` 泄漏内部实现(回显命令行 + 哨兵文本)
|
||||
|
||||
- `terminal_exec`/`exec_command` 返回的 stdout 中可见 `@echo off & ...` 命令回显、`__MCP_DONE_<nonce>__0/1` 哨兵字样(多例复现,如 `cmd /c echo abc` 的 stdout 含 `__0 || echo __MCP_DONE_2c0fbce0__1\nabc`)。
|
||||
- 原因:ConPTY 回显折行后 `StripEchoedCommand` 的整行匹配失效;哨兵截断点之后的清洗也不覆盖片段。
|
||||
- 影响:输出不可直接展示给最终用户;nonce 泄漏无安全风险(一次性),但属于实现细节泄漏。
|
||||
- 建议:清洗逻辑改为「剔除从行首到哨兵行之前的全部回显块」,而非精确整行匹配。
|
||||
|
||||
**复核(2026-10-25)**:属实。已修:删到命令行回显结束 → 删哨兵行回显 → 按 nonce 擦掉渲染残留的哨兵文本;另修 `StripAnsi` 对 `OSC…ESC\` 收尾会残留 `\` 的问题。设计见 `docs/Mcp_Design.md` §12.1。
|
||||
|
||||
### P5(中):`get_activity_history` 注解登记错误
|
||||
|
||||
- `McpInternal.cpp:333` 登记 `openWorldHint=false`,但该工具经 `ctx->Send2Client(COMMAND_QUERY_ACTIVITY)` 触达远程主机(`McpServer.cpp:2249`),与代码注释及 `docs/Mcp_Design.md` §10.2 口径矛盾。一行修复。
|
||||
|
||||
**复核(2026-10-25)**:属实,已改 `openWorld=true` 并加注释说明理由。
|
||||
|
||||
### P6(低):`list_services` 在非提权被控端上 20s 超时且无解释
|
||||
|
||||
- 第1轮本机被控端(非提权):3/3 超时。客户端日志定位根因:`ServicesManager.cpp:31 Get service list failed`——`OpenSCManager(SC_MANAGER_ALL_ACCESS)` 权限不足,失败分支回传普通消息包而非 `TOKEN_SERVERLIST`,服务端等满 20s。
|
||||
- 第2轮 VM 被控端(权限足够):**成功**(服务列表正常返回)——反证根因即权限。
|
||||
- 建议:客户端失败分支回传带失败标记的 `TOKEN_SERVERLIST`,服务端转译为 `-32005`/明确错误文本;文档标注需要管理员权限。
|
||||
|
||||
**复核(2026-10-25)**:属实(`OpenSCManager` 权限不足 → 客户端失败分支回普通消息包,服务端只能等到超时)。修它要改客户端,按「暂不动客户端」原则搁置。
|
||||
|
||||
### P7(低):错误码表缺 -32007/-32008/-32009,且 -32008 复用多种语义
|
||||
|
||||
- `docs/Mcp_Design.md` §12 只登记到 -32006。-32008 同时用于:元字符、`&|`/控制字符、老客户端格式、多显示器不支持(4 处)。后者语义近 `-32005 Not supported`。
|
||||
|
||||
**复核(2026-10-25)**:属实。`docs/Mcp_Design.md` §12 已补齐 `-32007`/`-32008`/`-32009`,`-32008` 行内注明其四类语义(修正参数 vs 能力限制的处理方式不同)。
|
||||
|
||||
### P8(低):路径类工具对不存在路径静默返回空
|
||||
|
||||
- `list_registry`(注册表,两轮均复现)与 `list_files`(文件列表)对不存在的路径均返回空列表 + `isError:false`,无法区分「为空」与「不存在」。建议返回错误或加 `exists:false`。
|
||||
|
||||
**复核(2026-10-25)**:属实,但服务端拿到的响应与「空目录/空键」完全一致,无法在服务端区分;需客户端回报错误码 → 按「暂不动客户端」原则搁置。
|
||||
|
||||
### 观察项(不计入问题)
|
||||
|
||||
- `host_list_network_state` 的 state 为本地化文本("连接"),按 `ESTABLISHED` 过滤会失配;`kill_network_connection` 内部已归一化(stateName=ESTABLISHED, killable:true),dry_run 对真实四元组校验通过。
|
||||
- `remote_open` 双显示器拒绝(-32008)文案清晰、即时;VM 单屏下全链路正常。
|
||||
- 第1轮 exec_command 11/12 超时在两台被控端重启后均未复现(VM 5/5、重启后本机 5/5+30/30 连发通过);当时环境长时间运行+大量会话开关,疑与资源/状态积累有关,未能复现定位。鉴于 P1/P3 已证哨兵机制脆弱,建议优先落实哨兵改造后观察。
|
||||
|
||||
## 3. 通过项(摘要)
|
||||
|
||||
| 领域 | 结果 |
|
||||
|---|---|
|
||||
| 传输层 | 401/413/404、-32700/-32600/-32601、ping、status 不泄露 token —— 全过 |
|
||||
| 冒烟脚本 | 32/32 PASS |
|
||||
| 主机列表/分页/过滤 | 分页 clamp、越界、group/os/client_type、totalAll 保留 —— 全过 |
|
||||
| 批量工具 | ids>51 拒、写工具拒批量 —— 全过 |
|
||||
| exec 安全门 | 白名单+词边界(`dir` 过/`dirx` 拒/`echo` 拒)、`&`/CRLF -32008、空命令 -32602 —— 全过 |
|
||||
| 文件传输 V2 | 上传 11 项(中文文件名、1MB SHA-256、620 文件递归、overwrite 跳过)、下载 SHA-256、**跨机往返(本机↔VM)SHA 一致** —— 全过 |
|
||||
| search_file | min_size/name_only/子串/非法时间 -32602 —— 全过 |
|
||||
| 服务端本机工具 | audit 分页+过滤、status 一致性、`host_set_remark` GBK 边界(63B 过/66B 拒/emoji 拒)—— 全过 |
|
||||
| 只读主机工具(双端) | get_screenshot(JPEG magic 双端过)、get_keylog、list_registry 子键、list_windows、get_activity_history —— 全过 |
|
||||
| **remote 控制族(VM,第2轮新增)** | open→mouse(move/click/scroll)→keyboard(type/key_press)→clipboard→close→幂等→死会话拒绝 —— **11/11** |
|
||||
| chat(双端) | 本机 6/6 + VM 4/4(open/send/wait timed_out/close)—— 全过 |
|
||||
| 终端持久会话 | open/exec/close 生命周期、echo/whoami/cmd /c echo 等有输出命令 —— 全过(异常见 P1/P3/P4) |
|
||||
| 写工具 | watch_level 1↔0 往返、非法值拒绝 —— 过 |
|
||||
| kill_network_connection | dry_run 假四元组 -32009、**真实四元组校验通过**(VM 实测)—— 过 |
|
||||
|
||||
## 4. 修复优先级建议
|
||||
|
||||
1. **哨兵改造**(P1/P3/P4 同根一次修):独立行哨兵 + 回显块整体剔除 + 超时销毁会话的专用错误文案;
|
||||
2. P2:download 快速失败或默认超时下调 + 本地读取豁免互斥;
|
||||
3. P5:一行注解修复;
|
||||
4. P6:客户端服务枚举失败结构化回传;
|
||||
5. P7/P8 随批次顺手处理。
|
||||
|
||||
**复核后状态**:1 → 已修(§0 P1/P3/P4);2 → 已修「停滞 60s 快速失败」,默认超时未下调、互斥豁免未做(远程工具互斥是有意设计,本地工具本就不受限);3 → 已修;4 → 搁置(需改客户端);5 → P7 已修(文档),P8 搁置(需客户端回报错误码)。
|
||||
|
||||
## 附录 A:错误码实测一览
|
||||
|
||||
| 码 | 场景 | 实测 |
|
||||
|---|---|---|
|
||||
| -32001 | 等待超时 | 吞行命令、非提权 list_services、download 600s/8s 均复现(复核后:吞行命令不再超时;download 停滞 60s 即失败并说明原因) |
|
||||
| -32002 | 离线/不存在 | 不存在 id 复现;会话销毁后 terminal_exec 文案混用(见 P1)→ 复核后已拆成「被超时销毁」与「id 写错」两种文案 |
|
||||
| -32003 | 单设备互斥 | 挂起期间跨工具复现(含远程机器管理工具;**纯服务端本地工具不受影响**,复核已实测) |
|
||||
| -32005 | 不支持 | 代码审查确认(无 LNX/MAC 主机可测) |
|
||||
| -32006 | 策略拒绝 | 冒烟历史覆盖(McpKeylog=0 → CALL_DENIED) |
|
||||
| -32007 | 白名单拒绝 | `echo`/`set` 复现 |
|
||||
| -32008 | 元字符/&\|/老格式/多显示器 | 双屏 `remote_open`、`dir & whoami` 复现 |
|
||||
| -32009 | kill 目标不存在 | dry_run 复现;真实四元组通过 |
|
||||
| -32602 | 参数错误 | 备注 66B、level=99、非法时间等复现 |
|
||||
|
||||
## 附录 B:审计日志行为
|
||||
|
||||
- `CALL_OK`/`CALL_FAIL` 含 `tool= ms= bytes=`;600s 挂起精确记录 `ms=600004`;`get_audit_log` 过滤与实际一致。
|
||||
|
||||
## 附录 C:测试残留与清理
|
||||
|
||||
- 全部测试数据(本机 `%TEMP%\yama_mcp_test\src|vm_target|dl_vm` 与 VM 同名目录)测试后已删除/验证删除。
|
||||
- `settings.ini` 未做修改(本轮未动开关),第1轮已恢复备份。
|
||||
- VM 会话中因超时被销毁的终端已随服务端状态清理;我启动的本机 ghost.exe 已关闭,Debug 服务端保持用户启动状态。
|
||||
@@ -330,7 +330,9 @@ const ToolHints kToolHints[] = {
|
||||
{ "search_hosts", true, false, true, false },
|
||||
{ "list_all_hosts", true, false, true, false },
|
||||
{ "get_host_detail", true, false, true, false },
|
||||
{ "get_activity_history", true, false, true, false },
|
||||
// get_activity_history 虽不含主机 id 之外的写操作,但要经主连接向目标主机发
|
||||
// COMMAND_QUERY_ACTIVITY 取数据(McpServer.cpp:2249),属触达外部主机 → openWorld=true。
|
||||
{ "get_activity_history", true, false, true, true },
|
||||
{ "get_audit_log", true, false, true, false },
|
||||
{ "get_server_status", true, false, true, false },
|
||||
// --- 主机只读 ---
|
||||
|
||||
+267
-65
@@ -1122,7 +1122,7 @@ Json::Value BuildExecCommandOutputSchema() {
|
||||
|
||||
Json::Value exitProp(Json::objectValue);
|
||||
exitProp["type"] = "integer";
|
||||
exitProp["description"] = u8"退出码:0=成功、1=非零退出、-1=未知(进程异常退出)";
|
||||
exitProp["description"] = u8"退出码:ConPTY 客户端为命令的真实退出码;老客户端(非 PTY)仅区分 0/非 0;-1=未知(进程异常退出)";
|
||||
props["exit_code"] = exitProp;
|
||||
|
||||
Json::Value schema(Json::objectValue);
|
||||
@@ -2624,24 +2624,139 @@ static std::string StripAnsi(const std::string& s) {
|
||||
++i; // 吞 ESC
|
||||
if (i < s.size() && s[i] == '[') { // CSI ... 结尾 @–~
|
||||
while (++i < s.size() && !(s[i] >= '@' && s[i] <= '~')) {}
|
||||
} else if (i < s.size() && s[i] == ']') { // OSC ... 结尾 BEL/ESC
|
||||
} else if (i < s.size() && s[i] == ']') { // OSC ... 结尾 BEL/ST(ESC \)
|
||||
while (++i < s.size() && s[i] != '\x07' && s[i] != '\x1b') {}
|
||||
// ST 是两字节 "ESC \":这里停在 ESC 上,须把 '\' 一起吞掉,否则会残留在输出里。
|
||||
if (i + 1 < s.size() && s[i] == '\x1b' && s[i + 1] == '\\') ++i;
|
||||
}
|
||||
// 其它单字节 ESC 序列吞掉当前字节即可(循环 ++i 会跳过它)
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// 去掉 ConPTY 把整行输入回显造成的噪声:echoedLine 是发送的哨兵命令行(含唯一 nonce),
|
||||
// 输出里若出现该行(连同其后换行)则整行剔除。非 PTY 老 ShellManager 已自行跳回显,
|
||||
// 找不到该行即无操作。echoedLine 含随机 nonce,命令真实输出不可能恰好相同。
|
||||
static std::string StripEchoedCommand(const std::string& s, const std::string& echoedLine) {
|
||||
if (echoedLine.empty() || s.empty()) return s;
|
||||
size_t p = s.find(echoedLine);
|
||||
if (p == std::string::npos) return s;
|
||||
size_t q = p + echoedLine.size();
|
||||
if (q < s.size() && s[q] == '\n') ++q; // CRLF 已归一为 \n
|
||||
return s.substr(0, p) + s.substr(q);
|
||||
// 去掉 ConPTY 把整行输入回显造成的噪声:line 是发送过的命令行(含唯一 nonce 或 "@echo off & "
|
||||
// 前缀),输出里若出现这段文本(连同其后的换行)则剔除。回显会被 80 列折行插入换行,
|
||||
// 所以比较时跳过 '\r'/'\n';随机 nonce/固定前缀保证命令真实输出不可能整行命中。
|
||||
// 只删第一处命中(输入回显只发生一次)。
|
||||
static void StripEchoedLine(std::string& s, const std::string& line) {
|
||||
if (line.empty() || s.empty()) return;
|
||||
const size_t n = s.size(), m = line.size();
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
size_t j = 0, k = i;
|
||||
while (j < m && k < n) {
|
||||
const char c = s[k];
|
||||
if (c == '\r' || c == '\n') { ++k; continue; }
|
||||
if (c != line[j]) break;
|
||||
++j; ++k;
|
||||
}
|
||||
if (j != m) continue;
|
||||
while (k < n && (s[k] == '\r' || s[k] == '\n')) ++k; // 连同回显行尾换行一起删
|
||||
s.erase(i, k - i);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 把缓冲区开头一直删到回显行结束(含行尾换行)。ConPTY 起 shell 时会先回放启动画面与
|
||||
// 提示符(一长串空行 + "Microsoft Windows [Version ...]" + "C:\path>"),紧接着才是我们这行
|
||||
// 输入的回显;回显行即「真实输出的起点」,因此删到它结束可把启动噪声一并去掉。
|
||||
// 返回 false 表示没找到回显(例如客户端不回显),此时不动缓冲区。
|
||||
static bool CutThroughEchoedLine(std::string& s, const std::string& line) {
|
||||
if (line.empty() || s.empty()) return false;
|
||||
const size_t n = s.size(), m = line.size();
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
size_t j = 0, k = i;
|
||||
while (j < m && k < n) {
|
||||
const char c = s[k];
|
||||
if (c == '\r' || c == '\n') { ++k; continue; }
|
||||
if (c != line[j]) break;
|
||||
++j; ++k;
|
||||
}
|
||||
if (j != m) continue;
|
||||
while (k < n && (s[k] == '\r' || s[k] == '\n')) ++k;
|
||||
s.erase(0, k);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// 去掉开头的空行(启动画面残留 / 上一行命令尾部的空行)。
|
||||
static void TrimLeadingNewlines(std::string& s) {
|
||||
size_t i = 0;
|
||||
while (i < s.size() && (s[i] == '\r' || s[i] == '\n')) ++i;
|
||||
if (i) s.erase(0, i);
|
||||
}
|
||||
|
||||
// 擦掉输出里**残留**的哨兵文本。ConPTY 送回来的是「屏幕渲染流」而不是字节流:光标重绘
|
||||
// 会把同一行再输出一次,剥掉 VT 序列后同一段文字就重复出现。于是哨兵可能留有副本
|
||||
// (实测 `rem hello` 只剩哨兵、`cmd /c echo abc` 成了 "abc__MCP_DONE_x__0")。
|
||||
// nonce 每条命令随机生成,命令的真实输出不可能包含它,故按 nonce 文本擦除既彻底又安全。
|
||||
// 比较时跳过 '\r'/'\n'(折行回显);`%errorlevel%` 是回显模板本身,一并擦到行尾。
|
||||
static void StripSentinelText(std::string& s, const std::string& nonce) {
|
||||
if (nonce.empty() || s.empty()) return;
|
||||
const std::string marker = "__MCP_DONE_" + nonce + "__";
|
||||
size_t i = 0;
|
||||
while (i < s.size()) {
|
||||
size_t j = 0, k = i;
|
||||
while (j < marker.size() && k < s.size()) {
|
||||
const char c = s[k];
|
||||
if (c == '\r' || c == '\n') { ++k; continue; }
|
||||
if (c != marker[j]) break;
|
||||
++j; ++k;
|
||||
}
|
||||
if (j != marker.size()) { ++i; continue; }
|
||||
size_t end = k;
|
||||
if (end < s.size() && s[end] == '-') ++end;
|
||||
while (end < s.size() && s[end] >= '0' && s[end] <= '9') ++end;
|
||||
if (end < s.size() && s[end] == '%') // 回显模板 ...__%errorlevel%
|
||||
while (end < s.size() && s[end] != '\r' && s[end] != '\n') ++end;
|
||||
size_t begin = i; // 连带前面残留的 "echo "
|
||||
if (begin >= 5 && _strnicmp(s.c_str() + begin - 5, "echo ", 5) == 0) begin -= 5;
|
||||
s.erase(begin, end - begin);
|
||||
i = begin;
|
||||
}
|
||||
}
|
||||
|
||||
// 输入回显清洗(P4):PTY 下删「命令行」与「哨兵行」两处回显。非 PTY 只删哨兵行——
|
||||
// 老 ShellManager 在客户端按写入长度自行跳过回显,删命令行反而可能吃掉命令自身的输出
|
||||
// (如 `echo echo hello`)。
|
||||
static std::string StripEchoedInput(const std::string& s, bool isPty,
|
||||
const std::string& cmdLine, const std::string& sentLine,
|
||||
const std::string& nonce) {
|
||||
std::string out = s;
|
||||
bool cut = isPty && CutThroughEchoedLine(out, cmdLine);
|
||||
if (isPty && !cut) StripEchoedLine(out, cmdLine); // 没回显时退回按整行删
|
||||
StripEchoedLine(out, sentLine);
|
||||
StripSentinelText(out, nonce);
|
||||
TrimLeadingNewlines(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
// 哨兵行有两种形态(见 docs/Mcp_Design.md §12.1):
|
||||
// - ConPTY(is_pty=true):命令与哨兵**分两行**下发。哨兵独立成行执行,于是 rem / cmd / c
|
||||
// exit / if / for 这类「吞行」命令不会连哨兵一起吞掉(P1);哨兵用 %errorlevel% 取真实
|
||||
// 退出码,回显文本里是字面 "%errorlevel%"、不是数字,FindSentinel 只认数字,折行回显再也
|
||||
// 不会被误判成哨兵(P3),也能返回真实退出码而非 0/1。
|
||||
// - 老 ShellManager(is_pty=false):客户端按写入字节数跳过回显,多写一行会吃掉上一行的
|
||||
// 输出,故仍用单行 && / || 形式(老客户端维持既有行为,已知不支持 rem / cmd /c)。
|
||||
static void BuildSentinelLines(bool isPty, const std::string& command, const std::string& nonce,
|
||||
std::string& cmdLine, std::string& sentLine) {
|
||||
if (!isPty) {
|
||||
cmdLine = command + " 2>&1 && echo __MCP_DONE_" + nonce + "__0 || echo __MCP_DONE_" + nonce + "__1";
|
||||
sentLine.clear();
|
||||
return;
|
||||
}
|
||||
cmdLine = "@echo off & " + command;
|
||||
sentLine = "echo __MCP_DONE_" + nonce + "__%errorlevel%";
|
||||
}
|
||||
|
||||
// 组包下发;cmdLine/sentLine 回传给调用方用于剔除输入回显。sentLine 为空表示单行形态。
|
||||
static void SendSentinelLines(context* subCtx, bool isPty, const std::string& command,
|
||||
const std::string& nonce, std::string& cmdLine, std::string& sentLine) {
|
||||
BuildSentinelLines(isPty, command, nonce, cmdLine, sentLine);
|
||||
UINT cp = isPty ? CP_UTF8 : 936;
|
||||
std::string wire = ToAnsi(cmdLine, cp) + "\r\n";
|
||||
if (!sentLine.empty()) wire += ToAnsi(sentLine, cp) + "\r\n";
|
||||
subCtx->Send2Client((BYTE*)wire.data(), (ULONG)wire.size());
|
||||
}
|
||||
|
||||
// 命令是否含控制字符(<0x20,含 \r\n)。\r\n 会把命令拆成多行:一次性 exec 里会绕过
|
||||
@@ -2712,15 +2827,10 @@ std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy
|
||||
|
||||
// 编码:ConPTY(UTF-8) / 老 cmd 管道(GBK)。哨兵为纯 ASCII,两种编码下字节一致。
|
||||
UINT cp = isPty ? CP_UTF8 : 936;
|
||||
// 哨兵命令行:@echo off 仅 ConPTY 需要(抑制回显噪声);老 ShellManager 已自行跳过回显,
|
||||
// 加 @echo off 反而破坏其回显跳过逻辑。&&/|| 取命令真实退出码(%errorlevel% 在复合句中
|
||||
// 是解析期展开、已过期,故用控制操作符)。哨兵为随机串,命令输出不可能恰好包含。
|
||||
std::string line;
|
||||
if (isPty) line += "@echo off & ";
|
||||
line += command;
|
||||
line += " 2>&1 && echo __MCP_DONE_" + nonce + "__0 || echo __MCP_DONE_" + nonce + "__1";
|
||||
std::string wireLine = ToAnsi(line, cp) + "\r\n";
|
||||
subCtx->Send2Client((BYTE*)wireLine.data(), (ULONG)wireLine.size());
|
||||
// 哨兵形态见 BuildSentinelLines:PTY 下命令与哨兵分两行下发(吞行命令不再超时),
|
||||
// 老 ShellManager 保持单行 && / || 形式(其客户端按写入长度跳回显)。
|
||||
std::string cmdLine, sentLine;
|
||||
SendSentinelLines(subCtx, isPty, command, nonce, cmdLine, sentLine);
|
||||
|
||||
std::vector<BYTE> raw;
|
||||
int exitCode = -1;
|
||||
@@ -2740,7 +2850,7 @@ std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy
|
||||
size_t p = 0;
|
||||
while ((p = stdoutStr.find("\r\n", p)) != std::string::npos)
|
||||
stdoutStr.erase(p, 1);
|
||||
stdoutStr = StripEchoedCommand(stdoutStr, line);
|
||||
stdoutStr = StripEchoedInput(stdoutStr, isPty, cmdLine, sentLine, nonce);
|
||||
stdoutStr = TrimRight(stdoutStr);
|
||||
}
|
||||
|
||||
@@ -2983,6 +3093,7 @@ std::string BuildGetServerStatus(const Json::Value& id, CMy2015RemoteDlg* parent
|
||||
// ===== P4:持久远程终端(terminal_open / terminal_exec / terminal_close)=====
|
||||
|
||||
static const int kTermIdleTimeoutSec = 300; // 持久终端 idle 回收超时(秒)
|
||||
static const int kTermTombstoneSec = 600; // 「终端被销毁」墓碑保留时长(秒),供后续报错文案用
|
||||
|
||||
// 共享前置:校验 McpTerminal && !readonly → 解析 id → FindMainContext → 拒绝 LNX/MAC。
|
||||
// 成功返回 true 并输出 devId/ctx;失败时 errJson 已写入对应 JSON 错误串。
|
||||
@@ -3016,24 +3127,19 @@ static bool ResolveTerminalSessionHost(const Json::Value& id, const Json::Value&
|
||||
return true;
|
||||
}
|
||||
|
||||
// 发送哨兵命令行(复用 exec_command 的编码/哨兵逻辑);返回所发送的完整命令行,
|
||||
// 发送哨兵命令行(复用 exec_command 的哨兵逻辑);回传所发送的两行,
|
||||
// 供调用方剔除 ConPTY 把输入整行回显造成的噪声。cp 由 isPty 决定。
|
||||
static std::string SendTerminalCommandLine(context* subCtx, bool isPty, const std::string& command,
|
||||
const std::string& nonce) {
|
||||
UINT cp = isPty ? CP_UTF8 : 936;
|
||||
std::string line;
|
||||
if (isPty) line += "@echo off & ";
|
||||
line += command;
|
||||
line += " 2>&1 && echo __MCP_DONE_" + nonce + "__0 || echo __MCP_DONE_" + nonce + "__1";
|
||||
std::string wireLine = ToAnsi(line, cp) + "\r\n";
|
||||
subCtx->Send2Client((BYTE*)wireLine.data(), (ULONG)wireLine.size());
|
||||
return line;
|
||||
static void SendTerminalCommandLine(context* subCtx, bool isPty, const std::string& command,
|
||||
const std::string& nonce,
|
||||
std::string& cmdLine, std::string& sentLine) {
|
||||
SendSentinelLines(subCtx, isPty, command, nonce, cmdLine, sentLine);
|
||||
}
|
||||
|
||||
// 输出清洗(复用 exec_command 尾部逻辑):raw → UTF-8 → 剥 ANSI → CRLF 归一 →
|
||||
// 去 ConPTY 回显命令行 → TrimRight。
|
||||
static std::string CleanTerminalOutput(const std::vector<BYTE>& raw, UINT cp,
|
||||
const std::string& echoedLine) {
|
||||
// 去输入回显 → TrimRight。
|
||||
static std::string CleanTerminalOutput(const std::vector<BYTE>& raw, UINT cp, bool isPty,
|
||||
const std::string& cmdLine, const std::string& sentLine,
|
||||
const std::string& nonce) {
|
||||
std::string stdoutStr;
|
||||
if (!raw.empty()) {
|
||||
std::string rawStr((const char*)raw.data(), raw.size());
|
||||
@@ -3041,7 +3147,7 @@ static std::string CleanTerminalOutput(const std::vector<BYTE>& raw, UINT cp,
|
||||
size_t p = 0;
|
||||
while ((p = stdoutStr.find("\r\n", p)) != std::string::npos)
|
||||
stdoutStr.erase(p, 1);
|
||||
stdoutStr = StripEchoedCommand(stdoutStr, echoedLine);
|
||||
stdoutStr = StripEchoedInput(stdoutStr, isPty, cmdLine, sentLine, nonce);
|
||||
stdoutStr = TrimRight(stdoutStr);
|
||||
}
|
||||
return stdoutStr;
|
||||
@@ -3124,7 +3230,7 @@ Json::Value BuildTerminalExecOutputSchema() {
|
||||
props["stdout"] = stdoutProp;
|
||||
Json::Value exitProp(Json::objectValue);
|
||||
exitProp["type"] = "integer";
|
||||
exitProp["description"] = u8"退出码:0=成功、1=非零退出、-1=未知(进程异常退出)";
|
||||
exitProp["description"] = u8"退出码:ConPTY 客户端为命令的真实退出码;老客户端(非 PTY)仅区分 0/非 0;-1=未知(进程异常退出)";
|
||||
props["exit_code"] = exitProp;
|
||||
Json::Value schema(Json::objectValue);
|
||||
schema["type"] = "object";
|
||||
@@ -3259,10 +3365,25 @@ std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CM
|
||||
|
||||
context* subCtx = nullptr;
|
||||
bool isPty = false;
|
||||
if (!mcp.BeginTermCommand(devId, sessionId, command, nonce, subCtx, isPty))
|
||||
return BuildError(id, -32002, "Terminal session not found, not ready, or busy: " + sessionId);
|
||||
int begin = mcp.BeginTermCommand(devId, sessionId, command, nonce, subCtx, isPty);
|
||||
if (begin != 0) {
|
||||
// 区分「会话被超时/退出/关闭销毁」与「session_id 写错」「另一条命令在飞」(评审 P1)。
|
||||
std::string destroyed = mcp.DescribeTermDestroyed(devId, sessionId);
|
||||
if (!destroyed.empty())
|
||||
return BuildError(id, -32002, destroyed);
|
||||
if (begin == 4)
|
||||
return BuildError(id, -32003, "Device busy: another terminal_exec is already running for this session");
|
||||
if (begin == 2)
|
||||
return BuildError(id, -32002, "Terminal session_id mismatch: " + sessionId);
|
||||
if (begin == 3)
|
||||
return BuildError(id, -32002, "Terminal session is not ready yet: " + sessionId);
|
||||
if (begin == 5)
|
||||
return BuildError(id, -32002, "Terminal session is already closing: " + sessionId);
|
||||
return BuildError(id, -32002, "Terminal session not found: " + sessionId + " (call terminal_open first)");
|
||||
}
|
||||
|
||||
std::string sentLine = SendTerminalCommandLine(subCtx, isPty, command, nonce);
|
||||
std::string cmdLine, sentLine;
|
||||
SendTerminalCommandLine(subCtx, isPty, command, nonce, cmdLine, sentLine);
|
||||
|
||||
std::vector<BYTE> raw;
|
||||
int exitCode = -1;
|
||||
@@ -3276,7 +3397,8 @@ std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CM
|
||||
subCtx->CancelIO();
|
||||
}
|
||||
|
||||
std::string stdoutStr = CleanTerminalOutput(raw, isPty ? CP_UTF8 : 936, sentLine);
|
||||
std::string stdoutStr = CleanTerminalOutput(raw, isPty ? CP_UTF8 : 936, isPty, cmdLine, sentLine,
|
||||
nonce);
|
||||
|
||||
// 审计:命令执行(不可关闭)。
|
||||
if (parent) {
|
||||
@@ -4508,6 +4630,9 @@ std::string BuildDownloadFile(const Json::Value& id, const Json::Value& args, CM
|
||||
}
|
||||
|
||||
const char* msg = (error == 1002) ? "Timeout waiting for file transfer"
|
||||
: (error == 1004) ? "File transfer stalled: no data received for 60s "
|
||||
"(the remote path is probably missing or inaccessible; "
|
||||
"verify it with list_files first)"
|
||||
: (error == 1001) ? "Path traversal detected in received path"
|
||||
: (error == 1003) ? "Connection lost: the transfer sub-connection closed"
|
||||
: (error == FEV2_HASH_MISMATCH) ? "File SHA-256 verification failed"
|
||||
@@ -6187,11 +6312,14 @@ std::string DispatchSingleHostTool(const Json::Value& id, const std::string& too
|
||||
|
||||
// ===== P3:exec_command 哨兵检测与终端会话 =====
|
||||
|
||||
// 在原始 shell 输出字节流中定位哨兵(纯 ASCII,编码无关)。真实哨兵由 echo 单独输出、独占
|
||||
// 一行(前面是 \n 或缓冲区开头);而 ConPTY 会把整条命令行回显进输出流,哨兵字样嵌在
|
||||
// "&& echo ... || echo ..." 里、前面是空格。据此从后往前找「行首命中」,排除回显行误判:
|
||||
// 否则回显包先于命令输出单独到达时,rfind 会命中回显里的 __1 提前结束、截断真实输出。
|
||||
// 老 ShellManager 已自行跳过回显,输出里只有真实哨兵(仍为行首)。命中 __0 → exit 0;__1 → exit 1。
|
||||
// 在原始 shell 输出字节流中定位哨兵(纯 ASCII,编码无关)。哨兵后紧跟退出码数字(可带负号)。
|
||||
//
|
||||
// ConPTY 会把输入整行回显进输出流,因此「哨兵必须独占行首」这条旧规则反而会把真实哨兵
|
||||
// 排除掉(命令最后一行没有换行时哨兵会接在其后),再往前命中回显里的 &&/|| 片段,得到
|
||||
// 错误的退出码(评审 P3,`ver` → exit_code=1)。现在两种哨兵形态都能安全地不依赖行首:
|
||||
// - 新形态(ConPTY):回显文本里是字面 "%errorlevel%",不是数字,天然不可能命中;
|
||||
// - 老形态(非 PTY):回显由客户端按写入长度跳过,且回显中的片段在真实哨兵之前。
|
||||
// 故从后往前找第一个「标记 + 数字」即可。
|
||||
static bool FindSentinel(const std::vector<BYTE>& buf, const std::string& nonce,
|
||||
size_t& pos, int& exitCode) {
|
||||
std::string marker = "__MCP_DONE_" + nonce + "__";
|
||||
@@ -6201,11 +6329,17 @@ static bool FindSentinel(const std::vector<BYTE>& buf, const std::string& nonce,
|
||||
while (true) {
|
||||
size_t p = s.rfind(marker, from);
|
||||
if (p == std::string::npos) return false;
|
||||
bool lineStart = (p == 0) || (s[p - 1] == '\n') || (s[p - 1] == '\r');
|
||||
size_t digitPos = p + marker.size();
|
||||
if (lineStart && digitPos < s.size() &&
|
||||
(s[digitPos] == '0' || s[digitPos] == '1')) {
|
||||
exitCode = (s[digitPos] == '0') ? 0 : 1;
|
||||
size_t q = p + marker.size();
|
||||
bool neg = false;
|
||||
if (q < s.size() && s[q] == '-') { neg = true; ++q; }
|
||||
size_t digits = q;
|
||||
long long v = 0;
|
||||
while (q < s.size() && s[q] >= '0' && s[q] <= '9' && q - digits < 9) {
|
||||
v = v * 10 + (s[q] - '0');
|
||||
++q;
|
||||
}
|
||||
if (q > digits) {
|
||||
exitCode = (int)(neg ? -v : v);
|
||||
pos = p;
|
||||
return true;
|
||||
}
|
||||
@@ -6356,17 +6490,47 @@ bool CMcpServer::BeginTermOpen(uint64_t device_id, const std::string& sessionId)
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CMcpServer::BeginTermCommand(uint64_t device_id, const std::string& sessionId,
|
||||
const std::string& command, const std::string& nonce,
|
||||
context*& subCtx, bool& isPty) {
|
||||
// 墓碑:记下会话被销毁的原因,供后续 terminal_exec 给出可区分文案。
|
||||
// 调用方必须持有 m_TermMutex。会话不存在时记录是为了让「上一次超时后用户重试」能看懂。
|
||||
void CMcpServer::MarkTermDestroyedLocked(uint64_t device_id, const std::string& sessionId,
|
||||
const std::string& reason) {
|
||||
if (sessionId.empty()) return;
|
||||
TermDestroyedInfo info;
|
||||
info.sessionId = sessionId;
|
||||
info.reason = reason;
|
||||
info.expiry = std::chrono::steady_clock::now() + std::chrono::seconds(kTermTombstoneSec);
|
||||
m_TermDestroyed[device_id] = std::move(info);
|
||||
// 顺手清理过期项(条目极少,线性清一遍即可)
|
||||
auto now = std::chrono::steady_clock::now();
|
||||
for (auto it = m_TermDestroyed.begin(); it != m_TermDestroyed.end(); ) {
|
||||
if (it->second.expiry <= now) it = m_TermDestroyed.erase(it);
|
||||
else ++it;
|
||||
}
|
||||
}
|
||||
|
||||
std::string CMcpServer::DescribeTermDestroyed(uint64_t device_id, const std::string& sessionId) {
|
||||
std::lock_guard<std::mutex> lk(m_TermMutex);
|
||||
auto it = m_TermDestroyed.find(device_id);
|
||||
if (it == m_TermDestroyed.end()) return "";
|
||||
if (std::chrono::steady_clock::now() >= it->second.expiry) {
|
||||
m_TermDestroyed.erase(it);
|
||||
return "";
|
||||
}
|
||||
if (it->second.sessionId != sessionId) return ""; // 是「id 写错」,不是「已销毁」
|
||||
return it->second.reason;
|
||||
}
|
||||
|
||||
int CMcpServer::BeginTermCommand(uint64_t device_id, const std::string& sessionId,
|
||||
const std::string& command, const std::string& nonce,
|
||||
context*& subCtx, bool& isPty) {
|
||||
std::lock_guard<std::mutex> lk(m_TermMutex);
|
||||
auto it = m_TermSessions.find(device_id);
|
||||
if (it == m_TermSessions.end()) return false;
|
||||
if (it == m_TermSessions.end()) return 1; // 不存在(含已销毁)
|
||||
TermSession& s = it->second;
|
||||
if (!s.persistent || s.sessionId != sessionId) return false; // 非持久或 token 不匹配
|
||||
if (!s.started) return false; // 未就绪
|
||||
if (s.busy) return false; // 已有命令在飞
|
||||
if (s.closed) return false; // 已关闭
|
||||
if (!s.persistent || s.sessionId != sessionId) return 2; // 非持久或 token 不匹配
|
||||
if (!s.started) return 3; // 未就绪
|
||||
if (s.busy) return 4; // 已有命令在飞
|
||||
if (s.closed) return 5; // 已关闭
|
||||
s.busy = true;
|
||||
s.command = command;
|
||||
s.nonce = nonce;
|
||||
@@ -6378,7 +6542,7 @@ bool CMcpServer::BeginTermCommand(uint64_t device_id, const std::string& session
|
||||
s.lastActiveAt = time(nullptr);
|
||||
subCtx = s.subCtx;
|
||||
isPty = s.isPty;
|
||||
return true;
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool CMcpServer::WaitTermCommand(uint64_t device_id, std::vector<BYTE>& out,
|
||||
@@ -6392,6 +6556,9 @@ bool CMcpServer::WaitTermCommand(uint64_t device_id, std::vector<BYTE>& out,
|
||||
|
||||
if (!signaled) { // 超时 → 清理会话+路由(调用方负责 CancelIO)
|
||||
context* subCtx = it->second.subCtx;
|
||||
MarkTermDestroyedLocked(device_id, it->second.sessionId,
|
||||
"Terminal session was destroyed after this command timed out (waited "
|
||||
+ std::to_string(timeoutMs) + " ms); call terminal_open again");
|
||||
m_TermContextToDevice.erase(subCtx);
|
||||
m_TermSessions.erase(it);
|
||||
return false;
|
||||
@@ -6402,6 +6569,8 @@ bool CMcpServer::WaitTermCommand(uint64_t device_id, std::vector<BYTE>& out,
|
||||
out = it->second.data;
|
||||
exitCode = -1;
|
||||
closed = true;
|
||||
MarkTermDestroyedLocked(device_id, it->second.sessionId,
|
||||
"Terminal session ended: the shell process exited; call terminal_open again");
|
||||
m_TermContextToDevice.erase(subCtx);
|
||||
m_TermSessions.erase(it);
|
||||
return true;
|
||||
@@ -6429,10 +6598,13 @@ int CMcpServer::CloseTermSession(uint64_t device_id, const std::string& sessionI
|
||||
if (s.busy) {
|
||||
// 有命令在飞:置 closed 唤醒等待线程,由其清理(避免双重擦除)。
|
||||
s.closed = true;
|
||||
MarkTermDestroyedLocked(device_id, sessionId,
|
||||
"Terminal session was closed by terminal_close while a command was running");
|
||||
m_TermCv.notify_all();
|
||||
return 0;
|
||||
}
|
||||
subCtx = s.subCtx;
|
||||
MarkTermDestroyedLocked(device_id, sessionId, "Terminal session was closed by terminal_close");
|
||||
m_TermContextToDevice.erase(s.subCtx);
|
||||
m_TermSessions.erase(it);
|
||||
}
|
||||
@@ -6449,6 +6621,9 @@ int CMcpServer::SweepIdleTerminals(time_t idleTimeoutSec) {
|
||||
TermSession& s = it->second;
|
||||
if (s.persistent && !s.busy && difftime(now, s.lastActiveAt) > (double)idleTimeoutSec) {
|
||||
if (s.subCtx) { m_TermContextToDevice.erase(s.subCtx); toCancel.push_back(s.subCtx); }
|
||||
MarkTermDestroyedLocked(it->first, s.sessionId,
|
||||
"Terminal session was reclaimed after " + std::to_string((int)idleTimeoutSec)
|
||||
+ "s of inactivity; call terminal_open again");
|
||||
it = m_TermSessions.erase(it);
|
||||
} else {
|
||||
++it;
|
||||
@@ -7366,6 +7541,10 @@ std::string GenerateRandomToken() {
|
||||
|
||||
// ===== P6:download_file 文件传输会话(状态机方法)=====
|
||||
|
||||
// 停滞看门狗:超过这么久没收到任何传输包即判失败(远程路径不存在时客户端不发包)。
|
||||
// 60s 足够覆盖极慢链路,又远小于 download_file 默认的 600s 总超时。
|
||||
static const int kFileXferStallMs = 60000;
|
||||
|
||||
bool CMcpServer::IsFileTransferPending(uint64_t device_id) {
|
||||
std::lock_guard<std::mutex> lk(m_FileXferMutex);
|
||||
return m_FileXferSessions.find(device_id) != m_FileXferSessions.end();
|
||||
@@ -7387,6 +7566,7 @@ bool CMcpServer::BeginFileTransferPending(uint64_t device_id, const std::string&
|
||||
s.remotePath = remotePath;
|
||||
s.overwrite = overwrite;
|
||||
s.startAt = time(nullptr);
|
||||
s.lastDataAt = std::chrono::steady_clock::now();
|
||||
m_FileXferSessions[device_id] = std::move(s);
|
||||
return true;
|
||||
}
|
||||
@@ -7402,6 +7582,7 @@ bool CMcpServer::BeginFileUpload(uint64_t device_id) {
|
||||
FileTransferSession s;
|
||||
s.tool = "upload_file";
|
||||
s.startAt = time(nullptr);
|
||||
s.lastDataAt = std::chrono::steady_clock::now();
|
||||
m_FileXferSessions[device_id] = std::move(s);
|
||||
return true;
|
||||
}
|
||||
@@ -7450,6 +7631,7 @@ void CMcpServer::OnFileChunkV2(uint64_t device_id, context* streamSubCtx, const
|
||||
FileTransferSession& s = it->second;
|
||||
if (s.tool != "download_file") return;
|
||||
if (s.done) return; // 已出错/完成,丢弃迟到包
|
||||
s.lastDataAt = std::chrono::steady_clock::now(); // 停滞看门狗:有包就续命
|
||||
|
||||
if (s.streamSubCtx == nullptr) {
|
||||
s.streamSubCtx = streamSubCtx;
|
||||
@@ -7528,6 +7710,7 @@ void CMcpServer::OnFileCompleteV2(uint64_t device_id, const BYTE* buf, ULONG len
|
||||
FileTransferSession& s = it->second;
|
||||
if (s.tool != "download_file") return;
|
||||
if (s.done) return;
|
||||
s.lastDataAt = std::chrono::steady_clock::now(); // 停滞看门狗:有包就续命
|
||||
|
||||
uint32_t fileIndex = pkt->fileIndex;
|
||||
|
||||
@@ -7560,18 +7743,37 @@ bool CMcpServer::WaitFileTransferDone(uint64_t device_id, int timeoutMs,
|
||||
auto it = m_FileXferSessions.find(device_id);
|
||||
if (it == m_FileXferSessions.end()) { error = 1002; return false; }
|
||||
|
||||
bool signaled = m_FileXferCv.wait_for(lk, std::chrono::milliseconds(timeoutMs),
|
||||
[&] { return it->second.done; });
|
||||
// 分段等待 + 停滞看门狗:远程路径不存在时客户端一个包都不发,只靠总超时(默认 600s)
|
||||
// 会把整台主机的单飞互斥占满 10 分钟(评审 P2)。改为「N 秒没有任何数据就判停滞」,
|
||||
// 大文件正常传输时每个 chunk 都会续命,不受影响。
|
||||
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
|
||||
bool signaled = false;
|
||||
while (true) {
|
||||
auto slice = std::chrono::milliseconds(500);
|
||||
auto now = std::chrono::steady_clock::now();
|
||||
if (now + slice > deadline) slice = std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now);
|
||||
if (slice.count() <= 0) break; // 总超时
|
||||
if (m_FileXferCv.wait_for(lk, slice, [&] { return it->second.done; })) {
|
||||
signaled = true;
|
||||
break;
|
||||
}
|
||||
if (std::chrono::steady_clock::now() - it->second.lastDataAt >=
|
||||
std::chrono::milliseconds(kFileXferStallMs)) {
|
||||
it->second.error = 1004; // 停滞
|
||||
it->second.done = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
FileTransferSession& s = it->second;
|
||||
if (!signaled) s.error = 1002; // 超时
|
||||
if (!signaled && !s.done) s.error = 1002; // 总超时
|
||||
|
||||
error = s.error;
|
||||
// 复制已见文件(成功=完整文件;失败=供调用方删半成品)。跳过的既有文件不在此列。
|
||||
for (auto& kv : s.fileEntries) files.push_back(kv.second);
|
||||
skipped = (int)s.skipped.size();
|
||||
|
||||
return signaled && s.error == 0;
|
||||
return s.done && s.error == 0;
|
||||
}
|
||||
|
||||
void CMcpServer::ClearFileTransfer(uint64_t device_id) {
|
||||
|
||||
@@ -186,10 +186,16 @@ public:
|
||||
// 登记持久终端挂起(复用单设备单终端约束;sessionId 由调用方生成)。
|
||||
bool BeginTermOpen(uint64_t device_id, const std::string& sessionId);
|
||||
|
||||
// 复位单条命令字段并置 busy;输出 subCtx/isPty。false = 不存在/不匹配/未就绪/忙碌/已关。
|
||||
bool BeginTermCommand(uint64_t device_id, const std::string& sessionId,
|
||||
const std::string& command, const std::string& nonce,
|
||||
context*& subCtx, bool& isPty);
|
||||
// 复位单条命令字段并置 busy;输出 subCtx/isPty。
|
||||
// 返回:0=ok;1=会话不存在;2=sessionId 不匹配;3=未就绪;4=忙(另一条命令在飞);
|
||||
// 5=shell 已退出。1/2 之外的原因由 DescribeTermDestroyed 提供可读文案。
|
||||
int BeginTermCommand(uint64_t device_id, const std::string& sessionId,
|
||||
const std::string& command, const std::string& nonce,
|
||||
context*& subCtx, bool& isPty);
|
||||
|
||||
// 若该设备上的持久终端最近被销毁(超时/退出/关闭),返回可读原因(英文,含时间);
|
||||
// 否则返回空串。sessionId 不匹配时也返回空串(那是「id 写错」而不是「已销毁」)。
|
||||
std::string DescribeTermDestroyed(uint64_t device_id, const std::string& sessionId);
|
||||
|
||||
// 等待本条命令完成(done || closed || 超时)。done=保持会话;closed/超时=清理会话+路由。
|
||||
bool WaitTermCommand(uint64_t device_id, std::vector<BYTE>& out, int& exitCode,
|
||||
@@ -437,6 +443,10 @@ private:
|
||||
// POST /mcp 处理器:token 校验 + JSON-RPC 分发。
|
||||
void HandleMcp(const httplib::Request& req, httplib::Response& res);
|
||||
|
||||
// 记一条「持久终端已销毁」墓碑(调用方须持有 m_TermMutex)。
|
||||
void MarkTermDestroyedLocked(uint64_t device_id, const std::string& sessionId,
|
||||
const std::string& reason);
|
||||
|
||||
// ===== 鉴权加固 =====
|
||||
// 同一 IP 在窗口期内连续鉴权失败达到阈值即封禁一段时间;封禁期内直接 429,不再比对 token。
|
||||
bool IsAuthBlocked(const std::string& ip);
|
||||
@@ -559,6 +569,15 @@ private:
|
||||
std::condition_variable m_TermCv;
|
||||
std::map<uint64_t, TermSession> m_TermSessions; // device_id → 会话
|
||||
std::map<context*, uint64_t> m_TermContextToDevice; // subCtx → device_id(顶部路由)
|
||||
// 最近一次持久终端被销毁的原因(device → 信息)。终端因超时/退出/关闭被清理后,后续
|
||||
// terminal_exec 无法区分「会话被超时销毁」与「session_id 写错」,只能报同一句
|
||||
// "not found"(评审 P1)。留一条短墓碑,让错误文案能说清是哪种情况。
|
||||
struct TermDestroyedInfo {
|
||||
std::string sessionId;
|
||||
std::string reason; // 英文短句,直接拼进 -32002 文案
|
||||
std::chrono::steady_clock::time_point expiry;
|
||||
};
|
||||
std::map<uint64_t, TermDestroyedInfo> m_TermDestroyed; // device_id → 墓碑(10 分钟内有效)
|
||||
|
||||
// ===== P5:远程控制会话(受 m_ScreenCtrlMutex 保护;单设备单会话)=====
|
||||
struct ScreenCtrlSession {
|
||||
@@ -588,11 +607,14 @@ private:
|
||||
uint32_t directoryCount = 0; // 目录项计数(目录不发 COMPLETE 包)
|
||||
uint32_t filesDone = 0; // 已完成的文件数(含跳过的)
|
||||
bool done = false; // 全部完成或出错
|
||||
int error = 0; // 0=ok;8=哈希不匹配;1001=路径逃逸;1002=超时;1003=流式子连接断线
|
||||
int error = 0; // 0=ok;8=哈希不匹配;1001=路径逃逸;1002=超时;1003=流式子连接断线;1004=停滞(看门狗)
|
||||
std::map<uint32_t, FileTransferEntry> fileEntries; // fileIndex → {path,size,sha256}
|
||||
std::set<uint32_t> skipIndexes; // overwrite=false 跳过的 fileIndex
|
||||
std::vector<FileTransferEntry> skipped; // 跳过的文件(供输出)
|
||||
time_t startAt = 0;
|
||||
// 停滞看门狗:最后一次收到数据的时间。远程路径不存在时客户端一个包都不发,
|
||||
// 旧实现只能干等满 timeout_ms(默认 600s,整台主机被单飞互斥锁住,评审 P2)。
|
||||
std::chrono::steady_clock::time_point lastDataAt;
|
||||
};
|
||||
std::mutex m_FileXferMutex;
|
||||
std::condition_variable m_FileXferCv;
|
||||
|
||||
Reference in new issue
Block a user