From d9a1a9ebcb973af671bebdaad6f67241506fdd0c Mon Sep 17 00:00:00 2001 From: yuanyuanxiang <962914132@qq.com> Date: Sun, 25 Oct 2026 14:28:16 +0100 Subject: [PATCH] Fix: Record policy refusals in the MCP audit log Every policy denial - read-only mode, one of the Mcp* switches turned off, or a host that lacks the required capability - answers -32006. The audit log only ever showed CALL_FAIL for those, which lumped them together with parameter errors, offline hosts and timeouts, so after the fact there was no way to tell "nobody called this" from "it was blocked by policy". The hooks all live in one place: the tools/call exit in the HTTP handler now also reads error.code and error.message from the response it already parses, and appends a CALL_DENIED event when the code is -32006. The original CALL_FAIL line is still written, so its statistics keep their old meaning, and the reason text is the fixed English sentence each branch already returns - no tool arguments or user input reach the log. Tool names taken from the request are flattened to a single line first, both in the denied event and in the existing CALL_OK/CALL_FAIL lines, so a crafted name cannot forge extra audit rows. Also refresh the stale note in the design document that still called the client search MAX_PATH overflow unfixed; the source was fixed in 8f718d9, but already-deployed clients still carry it, which is why the smoke test keeps its search cases opt-in. Verified on the Debug instance: with McpFileTransfer temporarily set to 0, download_file returns -32006 and the audit log gains the expected CALL_DENIED line right after its CALL_FAIL; with the switch restored the same call is CALL_OK again and no denied line appears. The read-only smoke test passes 20/20. Co-Authored-By: deepseek-flash --- docs/Mcp_Design.md | 17 ++++++++++++++++- server/2015Remote/McpServer.cpp | 30 ++++++++++++++++++++++++++---- 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/docs/Mcp_Design.md b/docs/Mcp_Design.md index 4d20d1c..75fae34 100644 --- a/docs/Mcp_Design.md +++ b/docs/Mcp_Design.md @@ -483,6 +483,7 @@ void CMcpSettingsDlg::OnBnClickedBtnSave() - `AUTH_FAIL`:UA(截断/清洗)、body 大小、是否因此被封禁。 - `AUTH_BLOCK`:封禁生效。 - `CALL_OK` / `CALL_FAIL`:`tool=`、耗时 `ms=`、响应字节数 `bytes=`。 + - `CALL_DENIED`:被策略拒绝的调用(`-32006`)另记一条,含 `tool=` 与固定原因文本,见 §10.8。 - 审计**不记录** token、密码、哈希、剪贴板内容或工具返回正文。 ### 9.5 N5 列表输出治理 @@ -554,7 +555,7 @@ httplib 默认值对 MCP 场景不合适,改为显式配置: - **超时**:`timeout_ms` 默认 20000(1000–120000)。到点先下发 `COMMAND_FILES_SEARCH_STOP`,再等 5s 收尾;收不到 `FINISH` 也返回已收到的部分结果,`finished=false`。 - **收集上限**:5000 条 / 4 MB 原始包,超出即让客户端停搜并置 `truncated=true`(保护服务端内存,整盘搜索能命中几十万条)。 - **子连接身份校验**:`TOKEN_SEARCH_FILE_LIST` / `TOKEN_SEARCH_FILE_FINISH` 都按 `context*` 比对当前 pending 的子链接,旧搜索(已放弃)的尾包一律不受理,避免迟到的 FINISH 终止新搜索。 -- **已知风险(客户端既有缺陷,未修)**:`client/FileManager.cpp` 的 `SearchFilesRecursive` 用无界 `wsprintf` 往 `char[MAX_PATH]` 里拼路径(`strPath` 第 562 行、`szFullPath` 第 578 行),全程没有长度检查。目录一深(累计路径超过 260)就栈溢出:Debug 客户端弹 `Run-Time Check Failure #2 - Stack around the variable 'strPath' was corrupted` 并挂住搜索线程,Release 客户端静默破坏栈。MFC 文件管理器的「搜索」走同一函数,**与 MCP 无关**(本工具只是让它更容易被触发)。规避:只搜具体的中浅层目录,别从盘符根开始深搜。 +- **已知风险(客户端既有缺陷,仓库内已修)**:`client/FileManager.cpp` 的 `SearchFilesRecursive` 曾用无界 `wsprintf` 往 `char[MAX_PATH]` 里拼路径(`strPath`、`szFullPath`),全程没有长度检查。目录一深(累计路径超过 260)就栈溢出:Debug 客户端弹 `Run-Time Check Failure #2 - Stack around the variable 'strPath' was corrupted` 并挂住搜索线程,Release 客户端静默破坏栈。MFC 文件管理器的「搜索」走同一函数,**与 MCP 无关**。源码已于 2026-10-25 修掉(commit 8f718d9,入口/逐条目长度预判);**已部署的老客户端仍带这个缺陷**,所以 `tools/mcp_smoke.ps1` 的搜索用例仍是 opt-in(`-SearchPath`)。 - **无头路由**:MFC 对话框存在时搜索结果走 `OnReceiveComplete`;只有无头子连接(MCP 调用)才会进 `MessageHandle`,所以这两条 case 只影响 MCP。`TOKEN_SEARCH_FILE_LIST` 分支**绝不 CancelIO**(后面还有 FINISH 与剩余分片)。 - 输出:`{files:[{path,name,dir,size,modified}], finished, truncated, total, totalAll, offset, limit, hasMore}`。 @@ -574,3 +575,17 @@ token 只从 `-Token` / env 读取,不落仓库、不打印;无在线主机 - `get_clipboard`:剪贴板常含口令/令牌/私钥,属"读即泄密",且客户端没有"只读不覆盖"的现成链路;已有 `remote_clipboard` 覆盖写。需要时用 `get_screenshot` + 人工确认。 - `close_window`:`operate_window` 的 `close` 动作已覆盖(同一 `COMMAND_WINDOW_CONTROL` 链路),不重复造工具。 + +### 10.8 D 批:拒绝也入审计 + +动机:所有策略拒绝(只读模式、`Mcp*` 开关关闭、主机不支持某能力)都返回 `-32006`,而审计里只有 `CALL_FAIL`——和「参数错」「主机离线」「超时」混在一起,事后分不清「没人调过」和「被策略拦下」。 + +- 实现放在 `tools/call` 的统一出口(`CMcpServer` 的 HTTP 处理器),不在 24 个 `-32006` 分支里逐个埋点:成功解析响应体后多取 `error.code` / `error.message`,`code == -32006` 就追加一条 + ``` + <时间> CALL_DENIED ip=<来源> tool=<工具名> reason=<固定英文原因> + ``` + 同一调用仍会留下原有的 `CALL_FAIL` 行,所以 `CALL_FAIL` 的统计口径不变。 +- `reason` 全部是各分支写死的英文句子(如 `File transfer is disabled: requires McpFileTransfer=1`),不含调用参数或用户输入,落盘安全;审计依旧不记录 token、参数或返回正文。 +- 其他错误码(`-32602` 参数、`-32002` 主机离线、`-32001` 超时等)不额外记事件,靠 `CALL_FAIL` 行即可。 +- 验证(Debug 实例):把 `McpFileTransfer` 临时置 0 重启后调 `download_file`,审计立刻出现 + `CALL_FAIL ... tool=download_file ms=1 bytes=114` 紧跟 `CALL_DENIED ... reason=File transfer is disabled: requires McpFileTransfer=1`;恢复 `McpFileTransfer=1` 重启后同一调用恢复 `CALL_OK` 且无 `CALL_DENIED`。冒烟脚本 20/20 通过(未指定 `-SearchPath` 时跳过 2 个搜索用例)。 diff --git a/server/2015Remote/McpServer.cpp b/server/2015Remote/McpServer.cpp index c92f162..ebe458f 100644 --- a/server/2015Remote/McpServer.cpp +++ b/server/2015Remote/McpServer.cpp @@ -6528,17 +6528,39 @@ void CMcpServer::HandleMcp(const httplib::Request& req, httplib::Response& res) // 成败以返回体顶层是否有 "error" 成员为准(解析一次,避免正文里出现 "error" 字样时误判) bool failed = false; + int errCode = 0; + std::string errMsg; { Json::Value parsed; Json::CharReaderBuilder rb; std::string perrs; std::istringstream pis(resp); - if (Json::parseFromStream(rb, pis, &parsed, &perrs)) - failed = parsed.isObject() && parsed.isMember("error"); + if (Json::parseFromStream(rb, pis, &parsed, &perrs) && + parsed.isObject() && parsed.isMember("error")) { + failed = true; + const Json::Value& err = parsed["error"]; + if (err.isObject()) { + if (err["code"].isInt()) errCode = err["code"].asInt(); + if (err["message"].isString()) errMsg = err["message"].asString(); + } + } } + // 单行不变量:工具名来自请求参数,控制字符一律换成空格,避免伪造出额外审计行 + auto oneLine = [](std::string v) { + for (char& c : v) + if ((unsigned char)c < 0x20) c = ' '; + return v; + }; + const std::string toolTag = + "tool=" + oneLine(toolName.empty() ? std::string("(empty)") : toolName); AuditMcpEvent(failed ? "CALL_FAIL" : "CALL_OK", clientIp, - "tool=" + (toolName.empty() ? std::string("(empty)") : toolName) + - " ms=" + std::to_string(ms) + " bytes=" + std::to_string(resp.size())); + toolTag + " ms=" + std::to_string(ms) + " bytes=" + std::to_string(resp.size())); + + // 策略拒绝(-32006:只读模式、功能开关关闭、主机不支持)另记一条 CALL_DENIED, + // 事后才分得清「没人调用」和「被策略拦下」。reason 全是固定的英文句式,不含 + // 调用参数或用户输入,可以直接落盘。 + if (errCode == -32006) + AuditMcpEvent("CALL_DENIED", clientIp, toolTag + " reason=" + oneLine(errMsg)); res.set_content(resp, "application/json"); return;