Feature: Add offline hosts, batch reads and MCP hardening

Expose hosts the server already knows about. list_all_hosts enumerates
both live contexts and the historical records in the client list, with
authStatus as a three-state string instead of a boolean. search_hosts
now honours online=false instead of returning an empty list, while the
default stays online-only so existing callers see the same results.
get_host_detail falls back to the last known record for an offline host
rather than failing with -32002.

Let read-only tools take an ids array of up to 50 hosts in one call.
The batch path reuses the single-host dispatcher and pages per host, so
behaviour cannot drift; write tools reject ids with -32602 so a mistake
cannot fan out across machines.

Add get_keylog behind its own McpKeylog switch. It drives the client's
existing keylogger sub-connection, accumulates the streamed text for a
bounded window and byte cap, then closes the sub-connection and returns
UTF-8 lines. The client pushes its buffered history first, so a result
contains both history and fresh keystrokes; the tool description says so.

Harden the endpoint. Failed bearer checks are counted per source IP and
ten failures within a minute block the IP for fifteen minutes. Auth
failures and tool calls append to logs\mcp_audit.log with metadata only:
no token, no arguments, no response bodies, and rotation at 5 MB. Loopback
sources are audited but never blocked, because the built-in frp tunnel
makes every remote request arrive from 127.0.0.1 and banning that address
would lock out legitimate clients along with the attacker.

Give list-style tools one pagination contract (limit/offset plus
total/totalAll/hasMore) and fix the generated schemas so id and ids are
genuine alternatives: the stale required:[id] left over from the
single-host schema would otherwise reject ids-only calls.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-10-25 12:44:45 +01:00
1 parent cc0e4bbd7a
commit ac5b174b5f
12 files changed
+1191 -86

No files matched your search

+48
View File
@@ -258,6 +258,7 @@ Json::Value BuildHostJson(context* ctx, _ClientList* clientMap);
| `McpPort` | `6544` | MCP 监听端口;仅当 `McpEnabled=1` 时生效;未配置用默认 `6544` |
| `McpBind` | `127.0.0.1` | 监听地址;默认仅本机;可设 `0.0.0.0`(所有网卡)或内网 IP(如 `192.168.0.92`)以支持远程 |
| `McpToken` | 空(UI 默认随机值) | 静态 token;对话框内「token 必填、默认随机值」——首次打开若为空则预填随机并随保存持久化。运行时优先级:env `YAMA_MCP_TOKEN` → `McpToken` → 皆空则随机生成(见 §3.5) |
| `McpKeylog` | `0` | 键盘记录工具 `get_keylog` 的独立开关(见 §9.3);与 `McpReadonly` 无关,改动需重启生效 |
> 与旧版「`McpPort=0` 即禁用」不同:启用与否改由独立的 `McpEnabled` 开关控制,`McpPort` 回归纯端口语义,二者解耦。
@@ -444,3 +445,50 @@ void CMcpSettingsDlg::OnBnClickedBtnSave()
- ✅ **取数方案**:C(抽公共函数 `BuildHostJson`,MCP 与 WebService 平级复用)。
- ✅ **返回字段**:全量,含实时信息(`rtt` / `activeWindow`),支持 AI 监督场景。
- ✅ **序列化**:`structuredContent` + `outputSchema`,`content` 附带可读摘要。
---
## 9. 增补(2026-10-25:N1–N5)
本轮在既有工具族(P2–P9)之上补齐「能找到主机、能一次查多台、输出不撑爆上下文、认证可追溯」四件事,全部为服务端改动,客户端零改动。
### 9.1 N1 离线主机可见
- 新增工具 `list_all_hosts`(`online` / `offline` 两个布尔过滤,默认都为 `true`),数据源是 `m_ClientMap`(主机列表历史记录,`GetAll()` 快照 + `m_cs` 保护),在线条目复用 `BuildHostJson`,离线条目由 `BuildOfflineHostJson` 生成,字段:`id` / `name` / `remark` / `ip` / `os` / `location` / `online` / `group` / `last_seen` / `install_time` / `authStatus`。
- `search_hosts` 的 `online` 参数:`true` = 仅在线,`false` = 仅离线(修复此前 `online=false` 永远返回空列表的问题),缺省 = 仅在线(与改动前一致,不改变既有调用方看到的结果)。两类都要请用 `list_all_hosts`。
- `authStatus` 是 `ClientValue::Authorized` 的三态枚举(`unauthorized` / `authorized_by_super` / `authorized_by_admin` / `forbidden`),不是布尔值。
- `get_host_detail` 对「在 `m_ClientMap` 里但当前离线」的 id 不再返回 `-32002`,改为返回该主机的最后记录(`online=false`),使 `list_all_hosts` 的结果可直接消费。
### 9.2 N2 批量只读调用
- 只读工具支持 `ids: []`(最多 50 个),与 `id` 二选一(inputSchema 用 `anyOf` 表达)。命中批量的工具:`get_host_detail` / `list_processes` / `list_windows` / `list_services` / `list_files` / `list_registry` / `get_client_log` / `get_activity_history` / `list_network_connections` / 全部 `host_list_*` / `host_get_hosts_file`。
- 写操作工具传 `ids` 直接 `-32602` 拒绝(不逐个执行,避免误操作扩散)。
- 返回:`{tool, total, succeeded, failed, results:[{id, ok, data|error, text}]}`;`content` 里是「共 N 台,成功 X 台,失败 Y 台」+ 最多 ~1200 字节的失败明细。
- `limit` / `offset` 对每台主机各自生效;批量是串行执行,单台超时会占用整批等待时间。
### 9.3 N3 `get_keylog`
- 复用客户端既有键盘记录链路:主连接下发 `COMMAND_KEYBOARD(169)` → 客户端建子连接 → 子连接回 `TOKEN_KEYBOARD_START(293)` 作为就绪包绑定 → 之后每约 1 秒推一包 `TOKEN_KEYBOARD_DATA(294)`。
- 服务端把击键流**累积**(不是一问一答),窗口 `duration_ms`(默认 4000,1000–15000)或字节上限 `max_bytes`(默认 64 KiB,1024–256 KiB)先到者结束;结束时 `EndManagedSession(..., cancelIo=true)` 关闭子连接 —— 与 MFC 关对话框同一路径,客户端据此停止记录。
- 复用 P8 的挂起会话表(新增 `PendingKind::Keylog`,仍受「单设备单飞行」约束),就绪包绑定、迟到包墓碑、子连接断开唤醒全部沿用 P8 逻辑;绑定后服务端回 `COMMAND_NEXT`,让客户端 `WaitForDialogOpen` 立即返回(本工具不开 UI)。
- 返回 `{id, duration_ms, bytes, lines, lineCount, truncated}`,文本按客户端代码页转 UTF-8(`GetClientEncoding`)。**注意**:客户端连上后会先把缓冲区里已有的历史记录推过来,所以结果既含历史也含窗口期内的新击键。
- 独立开关 `McpKeylog`(默认 `0`,不要求只读关)。工具只在开关打开时出现在 `tools/list`,关闭时直接调用返回 `-32006`。
- 隐私:击键内容只进本次响应;审计只记 `CALL_OK tool=get_keylog ms=… bytes=…`,不落任何正文。
### 9.4 N4 认证加固
- 静态 token 校验失败:返回 401,并按来源 IP 计数;60 秒窗口内失败 10 次即封禁该 IP 900 秒,封禁期内返回 429 + `Retry-After`。失败表上限 1024,满时先清理过期项。
- 环回来源(`127.0.0.1` / `::1`)**只记账不封禁**:内置 frpc 把 MCP 端口映射出去时是「本机连本机」,且这条转发没开 Proxy Protocol(httplib 不解析),服务端看到的源地址恒为环回。若按 IP 封禁,一次外部扫描就能把隧道后面所有客户端(包括自己)锁死 15 分钟。审计里这类封禁触发记为 `AUTH_BLOCK ... scope=proxy-source-exempt`。
- 审计文件 `<exe>\logs\mcp_audit.log`(追加写,5 MB 轮转为 `.1`),每行:时间戳(毫秒)、事件、来源 IP、详情。
- `AUTH_FAIL`:UA(截断/清洗)、body 大小、是否因此被封禁。
- `AUTH_BLOCK`:封禁生效。
- `CALL_OK` / `CALL_FAIL`:`tool=`、耗时 `ms=`、响应字节数 `bytes=`。
- 审计**不记录** token、密码、哈希、剪贴板内容或工具返回正文。
### 9.5 N5 列表输出治理
- 列表类工具统一 `limit` / `offset`:默认 `limit=100`,硬上限 `1000`,`offset` 默认 0;非正数按默认值处理。
- `structuredContent` 统一附 `total` / `totalAll` / `offset` / `limit` / `hasMore`,与 `McpMachine.cpp` 既有约定一致(`host_list_*` / `list_network_connections` 本来就是这样)。
- `content` 摘要统一为「共 N <单位>,本次返回第 a-b 条(还有更多,可用 offset 继续取)。」;`hasMore=false` 时不再出现「继续取」的误导提示;`offset` 越界时明确写「offset 超出范围,本次返回 0 条」。
- 实现集中在 `McpInternal.h/.cpp`:`PageWindow` / `ResolvePageWindow` / `ApplyPageWindow` / `WritePageFields` / `AppendPagingProps` / `PageSummary`。
- `list_files` 仍受客户端单次 500 条的硬限制(`total=500` 表示客户端截断,不是服务端分页)。